index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/properties/ExponentialBackOffTriggerProperties.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.properties; import com.netflix.genie.common.internal.util.ExponentialBackOffTrigger; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.time.Duration; /** * Properties for {@link com.netflix.genie.common.internal.util.ExponentialBackOffTrigger} used in various places. * <p> * Notice this class is not tagged as {@link org.springframework.boot.context.properties.ConfigurationProperties} * since it's not a root property class. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class ExponentialBackOffTriggerProperties { private ExponentialBackOffTrigger.DelayType delayType = ExponentialBackOffTrigger.DelayType.FROM_PREVIOUS_EXECUTION_COMPLETION; private Duration minDelay = Duration.ofMillis(100); private Duration maxDelay = Duration.ofSeconds(3); private float factor = 1.2f; }
2,200
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/properties/package-info.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Property classes used by both agent and web modules. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.properties; import javax.annotation.ParametersAreNonnullByDefault;
2,201
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/configs/AwsAutoConfiguration.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.configs; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.AwsRegionProvider; import com.amazonaws.regions.DefaultAwsRegionProviderChain; import com.amazonaws.regions.Regions; import com.netflix.genie.common.internal.aws.s3.S3ClientFactory; import com.netflix.genie.common.internal.aws.s3.S3ProtocolResolver; import com.netflix.genie.common.internal.aws.s3.S3ProtocolResolverRegistrar; import com.netflix.genie.common.internal.services.JobArchiver; import com.netflix.genie.common.internal.services.impl.S3JobArchiverImpl; import io.awspring.cloud.autoconfigure.context.ContextCredentialsAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextInstanceDataAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextRegionProviderAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextResourceLoaderAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextStackAutoConfiguration; import io.awspring.cloud.autoconfigure.context.properties.AwsRegionProperties; import io.awspring.cloud.autoconfigure.context.properties.AwsS3ResourceLoaderProperties; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.core.io.ProtocolResolver; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * Spring Boot auto configuration for AWS related beans for the Genie Agent. Should be configured after all the * Spring Cloud AWS context configurations are complete. * * @author tgianos * @since 4.0.0 */ @Configuration @EnableConfigurationProperties @AutoConfigureAfter( { ContextCredentialsAutoConfiguration.class, ContextInstanceDataAutoConfiguration.class, ContextRegionProviderAutoConfiguration.class, ContextResourceLoaderAutoConfiguration.class, ContextStackAutoConfiguration.class } ) @ConditionalOnBean(AWSCredentialsProvider.class) @Slf4j public class AwsAutoConfiguration { /** * Constant for the precedence of the S3 job archive implementation for others to reference if need be. * * @see Ordered */ public static final int S3_JOB_ARCHIVER_PRECEDENCE = Ordered.HIGHEST_PRECEDENCE + 10; /** * Get an AWS region provider instance. The rules for this basically follow what Spring Cloud AWS does but uses * the interface from the AWS SDK instead and provides a sensible default. * <p> * See: <a href="https://tinyurl.com/y9edl6yr">Spring Cloud AWS Region Documentation</a> * * @param awsRegionProperties The cloud.aws.region.* properties * @return A region provider based on whether static was set by user, else auto, else default of us-east-1 */ @Bean @ConditionalOnMissingBean(AwsRegionProvider.class) public AwsRegionProvider awsRegionProvider(final AwsRegionProperties awsRegionProperties) { final String staticRegion = awsRegionProperties.getStatic(); if (StringUtils.isNotBlank(staticRegion)) { // Make sure we have a valid region. Will throw runtime exception if not. final Regions region = Regions.fromName(staticRegion); return new AwsRegionProvider() { /** * Always return the static configured region. * * {@inheritDoc} */ @Override public String getRegion() throws SdkClientException { return region.getName(); } }; } else { return new DefaultAwsRegionProviderChain(); } } /** * Provide a lazy {@link S3ClientFactory} instance if one is needed by the system. * * @param awsCredentialsProvider The {@link AWSCredentialsProvider} to use * @param awsRegionProvider The {@link AwsRegionProvider} to use * @param environment The Spring application {@link Environment} to bind properties from * @return A {@link S3ClientFactory} instance */ @Bean @ConditionalOnMissingBean(S3ClientFactory.class) public S3ClientFactory s3ClientFactory( final AWSCredentialsProvider awsCredentialsProvider, final AwsRegionProvider awsRegionProvider, final Environment environment ) { return new S3ClientFactory(awsCredentialsProvider, awsRegionProvider, environment); } /** * Provide a configuration properties bean for Spring Cloud resource loader properties if for whatever reason * the {@link ContextResourceLoaderAutoConfiguration} isn't applied by the agent app. * * @return A {@link AwsS3ResourceLoaderProperties} instance with the bindings from cloud.aws.loader values */ @Bean @ConditionalOnMissingBean(AwsS3ResourceLoaderProperties.class) @ConfigurationProperties(ContextResourceLoaderAutoConfiguration.AWS_LOADER_PROPERTY_PREFIX) public AwsS3ResourceLoaderProperties awsS3ResourceLoaderProperties() { return new AwsS3ResourceLoaderProperties(); } /** * Provide an protocol resolver which will allow resources with s3:// prefixes to be resolved by the * application {@link org.springframework.core.io.ResourceLoader} provided this bean is eventually added to the * context via the * {@link org.springframework.context.ConfigurableApplicationContext#addProtocolResolver(ProtocolResolver)} * method. * * @param resourceLoaderProperties The {@link AwsS3ResourceLoaderProperties} instance to use * @param s3ClientFactory The {@link S3ClientFactory} instance to use * @return A {@link S3ProtocolResolver} instance */ @Bean @ConditionalOnMissingBean(S3ProtocolResolver.class) public S3ProtocolResolver s3ProtocolResolver( final AwsS3ResourceLoaderProperties resourceLoaderProperties, final S3ClientFactory s3ClientFactory ) { final ThreadPoolTaskExecutor s3TaskExecutor = new ThreadPoolTaskExecutor(); s3TaskExecutor.setCorePoolSize(resourceLoaderProperties.getCorePoolSize()); s3TaskExecutor.setMaxPoolSize(resourceLoaderProperties.getMaxPoolSize()); s3TaskExecutor.setQueueCapacity(resourceLoaderProperties.getQueueCapacity()); s3TaskExecutor.setThreadGroupName("Genie-S3-Resource-Loader-Thread-Pool"); s3TaskExecutor.setThreadNamePrefix("S3-resource-loader-thread"); return new S3ProtocolResolver(s3ClientFactory, s3TaskExecutor); } /** * Configurer bean which will add the {@link S3ProtocolResolver} to the set of {@link ProtocolResolver} in the * application context. * * @param s3ProtocolResolver The implementation of {@link S3ProtocolResolver} to use * @return A {@link S3ProtocolResolverRegistrar} instance */ @Bean @ConditionalOnMissingBean(S3ProtocolResolverRegistrar.class) public S3ProtocolResolverRegistrar s3ProtocolResolverRegistrar(final S3ProtocolResolver s3ProtocolResolver) { return new S3ProtocolResolverRegistrar(s3ProtocolResolver); } /** * Provide an implementation of {@link JobArchiver} to handle archiving * to S3. * * @param s3ClientFactory The factory for creating S3 clients * @return A {@link S3JobArchiverImpl} instance */ @Bean @Order(S3_JOB_ARCHIVER_PRECEDENCE) public S3JobArchiverImpl s3JobArchiver(final S3ClientFactory s3ClientFactory) { return new S3JobArchiverImpl(s3ClientFactory); } }
2,202
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/configs/CommonServicesAutoConfiguration.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.configs; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.properties.RegexDirectoryManifestProperties; import com.netflix.genie.common.internal.services.JobArchiveService; import com.netflix.genie.common.internal.services.JobArchiver; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import com.netflix.genie.common.internal.services.impl.FileSystemJobArchiverImpl; import com.netflix.genie.common.internal.services.impl.JobArchiveServiceImpl; import com.netflix.genie.common.internal.services.impl.JobDirectoryManifestCreatorServiceImpl; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.common.internal.util.RegexDirectoryManifestFilter; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import java.nio.file.Path; import java.util.List; import java.util.concurrent.TimeUnit; /** * Auto configuration of any services that are common to both the agent and the server. * * @author tgianos * @since 4.0.0 */ @Configuration @EnableConfigurationProperties( { RegexDirectoryManifestProperties.class } ) public class CommonServicesAutoConfiguration { /** * Constant allowing developers to reference the precedence in their own configuration files. * * @see Ordered */ public static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE = Ordered.LOWEST_PRECEDENCE - 20; /** * Provide a {@link JobArchiver} implementation that will copy from one place on the filesystem to another. * * @return A {@link FileSystemJobArchiverImpl} instance */ @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) public FileSystemJobArchiverImpl fileSystemJobArchiver() { return new FileSystemJobArchiverImpl(); } /** * Provide a default {@link JobArchiveService} if no override is defined. * * @param jobArchivers The ordered available {@link JobArchiver} implementations in the system * @param directoryManifestFactory the job directory manifest factory * @return A {@link JobArchiveServiceImpl} instance */ @Bean @ConditionalOnMissingBean(JobArchiveService.class) public JobArchiveService jobArchiveService( final List<JobArchiver> jobArchivers, final DirectoryManifest.Factory directoryManifestFactory ) { return new JobArchiveServiceImpl(jobArchivers, directoryManifestFactory); } /** * Provide a {@link JobDirectoryManifestCreatorService} if no override is defined. * The manifest produced by this service do not include checksum for entries and caches manifests recently created. * * @param directoryManifestFactory the factory to produce the manifest if needed * @param cache the cache to use * @return a {@link JobDirectoryManifestCreatorService} */ @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) public JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService( final DirectoryManifest.Factory directoryManifestFactory, @Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache ) { return new JobDirectoryManifestCreatorServiceImpl(directoryManifestFactory, cache, false); } /** * Provide a {@code Cache<Path, DirectoryManifest>} named "jobDirectoryManifestCache" if no override is defined. * * @return a {@link Cache} */ @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") public Cache<Path, DirectoryManifest> jobDirectoryManifestCache() { // TODO hardcoded configuration values return Caffeine.newBuilder() .maximumSize(100) .expireAfterWrite(30, TimeUnit.SECONDS) .build(); } /** * Provide a {@link DirectoryManifest.Factory} if no override is defined. * * @param directoryManifestFilter the filter used during manifest creation * @return a directory manifest factory */ @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) public DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ) { return new DirectoryManifest.Factory(directoryManifestFilter); } /** * Provide a {@link DirectoryManifest.Filter} that filters files and/or prunes directories based on a set of * regular expression patterns provided via properties. * * @param properties the properties * @return a directory manifest filter */ @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) public DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties) { return new RegexDirectoryManifestFilter(properties); } /** * Provide a {@link PropertiesMapCache.Factory} if no override is defined. * * @param environment the environment * @return a properties map cache factory */ @Bean @ConditionalOnMissingBean(PropertiesMapCache.Factory.class) public PropertiesMapCache.Factory propertiesMapCacheFactory(final Environment environment) { return new PropertiesMapCache.Factory(environment); } }
2,203
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/configs/ProtoConvertersAutoConfiguration.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.configs; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter; import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Auto configuration of components common to both the agent and the server. * * @author mprimi * @since 4.0.0 */ @Configuration public class ProtoConvertersAutoConfiguration { /** * Provide a bean for proto conversion of job service objects if one isn't already defined. * * @return A {@link JobServiceProtoConverter} instance. */ @Bean @ConditionalOnMissingBean(JobServiceProtoConverter.class) public JobServiceProtoConverter jobServiceProtoConverter() { return new JobServiceProtoConverter(); } /** * Provide a bean for proto conversion of agent job directory manifest objects if one isn't already defined. * * @return A {@link JobDirectoryManifestProtoConverter} instance. */ @Bean @ConditionalOnMissingBean(JobDirectoryManifestProtoConverter.class) public JobDirectoryManifestProtoConverter jobDirectoryManifestProtoConverter() { return new JobDirectoryManifestProtoConverter(GenieObjectMapper.getMapper()); } }
2,204
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/configs/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Common Spring Auto Configuration classes for use in both Agent and Server. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.configs; import javax.annotation.ParametersAreNonnullByDefault;
2,205
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/BucketProperties.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.aws.s3; import com.amazonaws.regions.Regions; import io.awspring.cloud.core.naming.AmazonResourceName; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import java.util.Optional; /** * A property class which holds information about how to interact with a specific S3 Bucket. * * @author tgianos * @since 4.0.0 */ @Validated @Getter @Setter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class BucketProperties { /* * See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces */ private static final String IAM_SERVICE_NAMESPACE = "iam"; private AmazonResourceName roleARN; private Regions region; /** * Get the {@link Regions} this bucket is in. * * @return The {@link Regions#getName()} wrapped in an {@link Optional}. If the optional is empty it indicates that * the default or current region should be used */ public Optional<String> getRegion() { if (this.region == null) { return Optional.empty(); } else { return Optional.of(this.region.getName()); } } /** * Set the AWS region from a string name representation e.g. us-east-1. * * @param region The name of the region to use * @see Regions#fromName(String) */ public void setRegion(@Nullable final String region) { if (region != null) { this.region = Regions.fromName(region); } else { this.region = null; } } /** * Get the ARN of the role to assume from this instance when working with the given bucket. * * @return The ARN wrapped in an {@link Optional}. If the {@link Optional} is empty no role should be assumed when * working with this bucket */ public Optional<String> getRoleARN() { if (this.roleARN == null) { return Optional.empty(); } else { return Optional.of(this.roleARN.toString()); } } /** * Set the ARN of the role to assume from this instance when working with the given bucket. * * @param roleARN The valid role ARN or null if no role assumption is needed. * @throws IllegalArgumentException If the {@code roleARN} is not null and the value isn't a valid role ARN format */ public void setRoleARN(@Nullable final String roleARN) { if (roleARN != null) { final AmazonResourceName arn = AmazonResourceName.fromString(roleARN); final String awsService = arn.getService(); if (awsService.equals(IAM_SERVICE_NAMESPACE)) { this.roleARN = arn; } else { throw new IllegalArgumentException( "ARN (" + roleARN + ") is valid format but incorrect service. Expected " + IAM_SERVICE_NAMESPACE + " but got " + awsService ); } } } }
2,206
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/S3ClientFactory.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.aws.s3; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider; import com.amazonaws.regions.AwsRegionProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.google.common.annotations.VisibleForTesting; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.Environment; import javax.annotation.Nullable; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * An {@link AmazonS3} client factory class. Given {@link AmazonS3URI} instances and the configuration of the system * this factory is expected to return a valid client instance for the S3 URI which can then be used to access that URI. * * @author tgianos * @since 4.0.0 */ @Slf4j public class S3ClientFactory { @VisibleForTesting static final String BUCKET_PROPERTIES_ROOT_KEY = "genie.aws.s3.buckets"; private final AWSCredentialsProvider awsCredentialsProvider; private final Map<String, S3ClientKey> bucketToClientKey; private final ConcurrentHashMap<S3ClientKey, AmazonS3> clientCache; private final ConcurrentHashMap<AmazonS3, TransferManager> transferManagerCache; private final Map<String, BucketProperties> bucketProperties; private final AWSSecurityTokenService stsClient; private final Regions defaultRegion; /** * Constructor. * * @param awsCredentialsProvider The base AWS credentials provider to use for the generated S3 clients * @param regionProvider How this factory should determine the default {@link Regions} * @param environment The Spring application {@link Environment} */ public S3ClientFactory( final AWSCredentialsProvider awsCredentialsProvider, final AwsRegionProvider regionProvider, final Environment environment ) { this.awsCredentialsProvider = awsCredentialsProvider; /* * Use the Spring property binder to dynamically map properties under a common root into a map of key to object. * * In this case we're trying to get bucketName -> BucketProperties * * So if there were properties like: * genie.aws.s3.buckets.someBucket1.roleARN = blah * genie.aws.s3.buckets.someBucket2.region = us-east-1 * genie.aws.s3.buckets.someBucket2.roleARN = blah * * The result of this should be two entries in the map "bucket1" and "bucket2" mapping to property binding * object instances of BucketProperties with the correct property set or null if option wasn't specified. */ this.bucketProperties = Binder .get(environment) .bind( BUCKET_PROPERTIES_ROOT_KEY, Bindable.mapOf(String.class, BucketProperties.class) ) .orElse(Collections.emptyMap()); // Set the initial size to the number of special cases defined in properties + 1 for the default client // NOTE: Should we proactively create all necessary clients or be lazy about it? For now, lazy. final int initialCapacity = this.bucketProperties.size() + 1; this.clientCache = new ConcurrentHashMap<>(initialCapacity); this.transferManagerCache = new ConcurrentHashMap<>(initialCapacity); String tmpRegion; try { tmpRegion = regionProvider.getRegion(); } catch (final SdkClientException e) { tmpRegion = Regions.getCurrentRegion() != null ? Regions.getCurrentRegion().getName() : Regions.US_EAST_1.getName(); log.warn( "Couldn't determine the AWS region from the provider ({}) supplied. Defaulting to {}", regionProvider.toString(), tmpRegion ); } this.defaultRegion = Regions.fromName(tmpRegion); // Create a token service client to use if we ever need to assume a role // TODO: Perhaps this should be just set to null if the bucket properties are empty as we'll never need it? this.stsClient = AWSSecurityTokenServiceClientBuilder .standard() .withRegion(this.defaultRegion) .withCredentials(this.awsCredentialsProvider) .build(); this.bucketToClientKey = new ConcurrentHashMap<>(); } /** * Get an {@link AmazonS3} client instance appropriate for the given {@link AmazonS3URI}. * * @param s3URI The URI of the S3 resource this client is expected to access. * @return A S3 client instance which should be used to access the S3 resource */ public AmazonS3 getClient(final AmazonS3URI s3URI) { final String bucketName = s3URI.getBucket(); final S3ClientKey s3ClientKey; /* * The purpose of the dual maps is to make sure we don't create an unnecessary number of S3 clients. * If we made the client cache just bucketName -> client directly we'd have no way to make know if an already * created instance for another bucket could be re-used for this bucket since it could be same region/role * combination. This way we first map the bucket name to a key of role/region and then use that key * to find a re-usable client for those dimensions. */ s3ClientKey = this.bucketToClientKey.computeIfAbsent( bucketName, key -> { // We've never seen this bucket before. Calculate the key. /* * Region Resolution rules: * 1. Is it part of the S3 URI already? Use that * 2. Is it part of the properties passed in by admin/user Use that * 3. Fall back to whatever the default is for this process */ final Regions bucketRegion; final String uriBucketRegion = s3URI.getRegion(); if (StringUtils.isNotBlank(uriBucketRegion)) { bucketRegion = Regions.fromName(uriBucketRegion); } else { final String propertyBucketRegion = this.bucketProperties.containsKey(key) ? this.bucketProperties.get(key).getRegion().orElse(null) : null; if (StringUtils.isNotBlank(propertyBucketRegion)) { bucketRegion = Regions.fromName(propertyBucketRegion); } else { bucketRegion = this.defaultRegion; } } // Anything special in the bucket we need to reference final String roleARN = this.bucketProperties.containsKey(key) ? this.bucketProperties.get(key).getRoleARN().orElse(null) : null; return new S3ClientKey(bucketRegion, roleARN); } ); return this.clientCache.computeIfAbsent(s3ClientKey, this::buildS3Client); } /** * Get a {@link TransferManager} instance for use with the given {@code s3URI}. * * @param s3URI The S3 URI this transfer manager will be interacting with * @return An instance of {@link TransferManager} backed by an appropriate S3 client for the given URI */ public TransferManager getTransferManager(final AmazonS3URI s3URI) { return this.transferManagerCache.computeIfAbsent(this.getClient(s3URI), this::buildTransferManager); } private AmazonS3 buildS3Client(final S3ClientKey s3ClientKey) { // TODO: Do something about allowing ClientConfiguration to be passed in return AmazonS3ClientBuilder .standard() .withRegion(s3ClientKey.getRegion()) .withForceGlobalBucketAccessEnabled(true) .withCredentials( s3ClientKey .getRoleARN() .map( roleARN -> { // TODO: Perhaps rename with more detailed info? final String roleSession = "Genie-Agent-" + UUID.randomUUID().toString(); return (AWSCredentialsProvider) new STSAssumeRoleSessionCredentialsProvider .Builder(roleARN, roleSession) .withStsClient(this.stsClient) .build(); } ) .orElse(this.awsCredentialsProvider) ) .build(); } private TransferManager buildTransferManager(final AmazonS3 s3Client) { // TODO: Perhaps want to supply more options? return TransferManagerBuilder.standard().withS3Client(s3Client).build(); } /** * A simple class used as a key to see if we already have a S3Client created for the combination of properties * that make up this class. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) private static class S3ClientKey { private final Regions region; private final String roleARN; /** * Constructor. * * @param region The region the S3 client is configured to access. * @param roleARN The role the S3 client is configured to assume if any. Null if no assumption is necessary. */ S3ClientKey(final Regions region, @Nullable final String roleARN) { this.region = region; this.roleARN = roleARN; } Optional<String> getRoleARN() { return Optional.ofNullable(this.roleARN); } } }
2,207
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/S3ProtocolResolverRegistrar.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.aws.s3; import io.awspring.cloud.core.io.s3.SimpleStorageProtocolResolver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.io.ProtocolResolver; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; /** * A class which takes an instance of {@link S3ProtocolResolver} and adds it to the Spring {@link ApplicationContext} * set of {@link ProtocolResolver}. This class will also search for any existing instances of * {@link SimpleStorageProtocolResolver} within the current protocol resolver set. Since the protocol resolvers are * iterated in the order they're added, due to being backed by {@link java.util.LinkedHashMap}, any call to * {@link ApplicationContext#getResource(String)} would always use {@link SimpleStorageProtocolResolver} for S3 * resources if it was already in the set before this class is invoked. * * @author tgianos * @since 4.0.0 */ @Slf4j public class S3ProtocolResolverRegistrar implements ApplicationContextAware { private final S3ProtocolResolver s3ProtocolResolver; /** * Constructor. * * @param s3ProtocolResolver the resolver that this class will register with the application context */ public S3ProtocolResolverRegistrar(final S3ProtocolResolver s3ProtocolResolver) { this.s3ProtocolResolver = s3ProtocolResolver; } /** * {@inheritDoc} * <p> * Add the {@link S3ProtocolResolver} to the set of protocol resolvers in the application context. Remove any * instances of {@link SimpleStorageProtocolResolver}. */ @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof ConfigurableApplicationContext) { final ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext; if (configurableApplicationContext instanceof AbstractApplicationContext) { final AbstractApplicationContext abstractApplicationContext = (AbstractApplicationContext) configurableApplicationContext; final Collection<ProtocolResolver> protocolResolvers = abstractApplicationContext.getProtocolResolvers(); final Set<ProtocolResolver> simpleStorageProtocolResolvers = protocolResolvers .stream() .filter(SimpleStorageProtocolResolver.class::isInstance) .collect(Collectors.toSet()); protocolResolvers.removeAll(simpleStorageProtocolResolvers); } log.info( "Adding instance of {} to the set of protocol resolvers", this.s3ProtocolResolver.getClass().getCanonicalName() ); configurableApplicationContext.addProtocolResolver(this.s3ProtocolResolver); } } }
2,208
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/S3ProtocolResolver.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.aws.s3; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3URI; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.springframework.core.io.ProtocolResolver; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.task.TaskExecutor; import javax.annotation.Nullable; import java.io.IOException; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class implements the {@link ProtocolResolver} interface. When an instance of this class is added to a * Spring Application context list of Protocol Resolvers via * {@link org.springframework.context.ConfigurableApplicationContext#addProtocolResolver(ProtocolResolver)} allows * valid S3 resources to be loaded using the Spring {@link ResourceLoader} abstraction. * <p> * Leverages some work done by Spring Cloud AWS. * * @author tgianos * @since 4.0.0 */ @Slf4j public class S3ProtocolResolver implements ProtocolResolver { private static final String S3N_PROTOCOL = "s3n:"; private static final String S3A_PROTOCOL = "s3a:"; private static final String S3_REGEX = "s3.:"; private static final String S3_REPLACEMENT = "s3:"; private static final Pair<Integer, Integer> NULL_RANGE = ImmutablePair.of(null, null); private static final Pattern RANGE_HEADER_PATTERN = Pattern.compile("bytes=(\\d*)-(\\d*)"); private final S3ClientFactory s3ClientFactory; private final TaskExecutor s3TaskExecutor; /** * Constructor. * * @param s3ClientFactory The S3 client factory to use to get S3 client instances * @param s3TaskExecutor A task executor to use for uploading files to S3 */ public S3ProtocolResolver( final S3ClientFactory s3ClientFactory, final TaskExecutor s3TaskExecutor ) { this.s3ClientFactory = s3ClientFactory; this.s3TaskExecutor = s3TaskExecutor; } /** * TODO: It would be nice to use Spring's HttpRange for this parsing, but this module does not * currently depend on spring-web. And this class cannot be moved to genie-web since it is used by * {@link S3ProtocolResolver} which is shared with the genie-agent module. */ static Pair<Integer, Integer> parseRangeHeader(@Nullable final String rangeHeader) { if (StringUtils.isBlank(rangeHeader)) { return NULL_RANGE; } final Matcher matcher = RANGE_HEADER_PATTERN.matcher(rangeHeader); if (!matcher.matches()) { return NULL_RANGE; } final String rangeStartString = matcher.group(1); final String rangeEndString = matcher.group(2); Integer rangeStart = null; Integer rangeEnd = null; if (!StringUtils.isBlank(rangeStartString)) { rangeStart = Integer.parseInt(rangeStartString); } if (!StringUtils.isBlank(rangeEndString)) { rangeEnd = Integer.parseInt(rangeEndString); } return ImmutablePair.of(rangeStart, rangeEnd); } /** * {@inheritDoc} */ @Override public Resource resolve(final String location, final ResourceLoader resourceLoader) { log.debug("Attempting to resolve if {} is a S3 resource or not", location); final String normalizedLocation; // Rewrite s3n:// and s3a:// URIs as s3:// for backward compatibility if (location.startsWith(S3N_PROTOCOL) || location.startsWith(S3A_PROTOCOL)) { normalizedLocation = location.replaceFirst(S3_REGEX, S3_REPLACEMENT); } else { normalizedLocation = location; } final AmazonS3URI s3URI; final URI uri; try { s3URI = new AmazonS3URI(normalizedLocation); uri = URI.create(location); } catch (final IllegalArgumentException iae) { log.debug("{} is not a valid S3 resource (Error message: {}).", normalizedLocation, iae.getMessage()); return null; } // Remove the fragment portion of the URI path (which stores the range requested, if any) final int fragmentIndex = s3URI.getKey().lastIndexOf("#"); final String normalizedKey; if (fragmentIndex == -1) { normalizedKey = s3URI.getKey(); } else { normalizedKey = s3URI.getKey().substring(0, fragmentIndex); } final String rangeHeader = uri.getFragment(); final Pair<Integer, Integer> range = parseRangeHeader(rangeHeader); final AmazonS3 client = this.s3ClientFactory.getClient(s3URI); log.debug("{} is a valid S3 resource.", location); // TODO: This implementation from Spring Cloud AWS always wraps the passed in client with a proxy that follows // redirects. I'm not sure if we want that or not. Probably ok for now but maybe revisit later? try { return new SimpleStorageRangeResource( client, s3URI.getBucket(), normalizedKey, s3URI.getVersionId(), this.s3TaskExecutor, range ); } catch (IOException e) { log.error("Failed to create S3 resource: " + location + ": " + e.getMessage()); return null; } } }
2,209
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/package-info.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * This package contains classes and utilities for working with the AWS S3 service. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.aws.s3; import javax.annotation.ParametersAreNonnullByDefault;
2,210
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/aws/s3/SimpleStorageRangeResource.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.aws.s3; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.GetObjectRequest; import io.awspring.cloud.core.io.s3.AmazonS3ProxyFactory; import io.awspring.cloud.core.io.s3.SimpleStorageResource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.Pair; import org.springframework.core.task.TaskExecutor; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * This class extends {@link SimpleStorageResource} in order to efficiently handle range requests. * Rather than fetching the entire object and let the web tier skip, it only downloads the relevant object region and * returns a composite input stream that skips the unrequested bytes. * * @author mprimi * @since 4.0.0 */ @Slf4j public final class SimpleStorageRangeResource extends SimpleStorageResource { private final AmazonS3 client; private final String bucket; private final String key; private final String versionId; private final Pair<Integer, Integer> range; private final long contentLength; SimpleStorageRangeResource( final AmazonS3 client, final String bucket, final String key, final String versionId, final TaskExecutor s3TaskExecutor, final Pair<Integer, Integer> range ) throws IOException { super(client, bucket, key, s3TaskExecutor, versionId, null); this.client = AmazonS3ProxyFactory.createProxy(client); this.bucket = bucket; this.key = key; this.versionId = versionId; this.range = range; long tempContentLength = -1; try { tempContentLength = super.contentLength(); } catch (FileNotFoundException e) { // S3 object does not exist. // Upstream code will handle this correctly by checking exists(), contentLength(), etc. log.warn("Returning non-existent S3 resource {}/{}", bucket, key); } this.contentLength = tempContentLength; final Integer lower = this.range.getLeft(); final Integer upper = this.range.getRight(); if ((lower != null && upper != null && lower > upper) || (lower != null && lower > contentLength)) { throw new IllegalArgumentException( "Invalid range " + lower + "-" + upper + " for S3 object of size " + contentLength ); } } /** * {@inheritDoc} */ @Override public InputStream getInputStream() throws IOException { if (!this.exists()) { throw new FileNotFoundException("No such object: " + this.bucket + "/" + key); } // Index of first and last byte to fetch (inclusive) final long rangeStart; final long rangeEnd; if (this.range.getLeft() == null && this.range.getRight() == null) { // Full object rangeStart = 0; rangeEnd = Math.max(0, this.contentLength - 1); } else if (this.range.getLeft() == null && this.range.getRight() != null) { // Object suffix rangeStart = Math.max(0, this.contentLength - this.range.getRight()); rangeEnd = Math.max(0, this.contentLength - 1); } else if (this.range.getLeft() != null && this.range.getRight() == null) { // From offset to end rangeStart = this.range.getLeft(); rangeEnd = Math.max(0, this.contentLength - 1); } else { // Range start and end are provided rangeStart = this.range.getLeft(); rangeEnd = Math.min(this.range.getRight(), this.contentLength - 1); } log.debug( "Resource {}/{} requested range: {}-{}, actual range: {}-{}", this.bucket, this.key, this.range.getLeft(), this.range.getRight(), rangeStart, rangeEnd ); final long skipBytes = Math.max(0, rangeStart); final InputStream inputStream; if (rangeEnd - rangeStart < 0 || (rangeEnd == 0 && rangeStart == 0)) { inputStream = new EmptyInputStream(); } else { final GetObjectRequest getObjectRequest = new GetObjectRequest(this.bucket, this.key) .withRange(rangeStart, rangeEnd) .withVersionId(this.versionId); inputStream = this.client.getObject(getObjectRequest).getObjectContent(); } return new SkipInputStream(skipBytes, inputStream); } @Override public boolean exists() { if (this.contentLength == -1) { return false; } return super.exists(); } /** * An input stream that skips some amount of bytes because they are ignored by the web tier when sending back * the response content. */ private static class SkipInputStream extends InputStream { private final InputStream objectRangeInputStream; private long skipBytesLeft; SkipInputStream(final long bytesToSkip, final InputStream objectRangeInputStream) { this.objectRangeInputStream = objectRangeInputStream; this.skipBytesLeft = bytesToSkip; } @Override public int read() throws IOException { // Overriding other read(...) methods and hoping nobody is using this one directly. throw new NotImplementedException("Not implemented"); } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException("Invalid read( b[" + b.length + "], " + off + ", " + len + ")"); } // Efficiently skip over range of bytes that should be ignored if (this.skipBytesLeft > 0) { final long skippedBytesRead = Math.min(this.skipBytesLeft, len); this.skipBytesLeft -= skippedBytesRead; return Math.toIntExact(skippedBytesRead); } return this.objectRangeInputStream.read(b, off, len); } @Override public long skip(final long n) throws IOException { long skipped = 0; if (this.skipBytesLeft > 0) { skipped = Math.min(n, this.skipBytesLeft); this.skipBytesLeft -= skipped; } if (skipped < n) { skipped += this.objectRangeInputStream.skip(n - skipped); } return skipped; } @Override public void close() throws IOException { super.close(); this.objectRangeInputStream.close(); } } private static class EmptyInputStream extends InputStream { @Override public int read() throws IOException { return -1; } } }
2,211
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/jobs/JobConstants.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.jobs; import java.util.TimeZone; /** * A class holding some constants to be used everywhere. * * @author amsharma * @author tgianos * @author mprimi * @since 3.0.0 */ public final class JobConstants { /** * The header to use to mark a forwarded from another Genie node. */ public static final String GENIE_FORWARDED_FROM_HEADER = "Genie-Forwarded-From"; /** * The launcher script name that genie creates to setup a job for running. **/ public static final String GENIE_JOB_LAUNCHER_SCRIPT = "run"; /** * File Path prefix to be used while creating paths for dependency files downloaded by Genie to local dir. **/ public static final String DEPENDENCY_FILE_PATH_PREFIX = "dependencies"; /** * File Path prefix to be used while creating paths for config files downloaded by Genie to local dir. **/ public static final String CONFIG_FILE_PATH_PREFIX = "config"; /** * Stderr Filename generated by Genie after running a job. **/ public static final String STDERR_LOG_FILE_NAME = "stderr"; /** * Stdout Filename generated by Genie after running a job. **/ public static final String STDOUT_LOG_FILE_NAME = "stdout"; /** * Filename for logfile generated during setup (sourcing of entities setup files). */ public static final String GENIE_SETUP_LOG_FILE_NAME = "setup.log"; /** * Filename for environment variables dumped after setup. */ public static final String GENIE_AGENT_ENV_FILE_NAME = "env.log"; /** * Genie Agent log file name (after it is relocated inside the job directory). */ public static final String GENIE_AGENT_LOG_FILE_NAME = "agent.log"; /** * File Path prefix to be used while creating directories for application files to local dir. **/ public static final String APPLICATION_PATH_VAR = "applications"; /** * File Path prefix to be used while creating directories for command files to local dir. **/ public static final String COMMAND_PATH_VAR = "command"; /** * File Path prefix to be used while creating directories for cluster files to local dir. **/ public static final String CLUSTER_PATH_VAR = "cluster"; /** * File Path prefix to be used while creating working directory for jobs. **/ public static final String GENIE_PATH_VAR = "genie"; /** * File Path prefix to be used while creating working directory for jobs. **/ public static final String LOGS_PATH_VAR = "logs"; /** * Environment variable for Genie job working directory. **/ public static final String GENIE_JOB_DIR_ENV_VAR = "GENIE_JOB_DIR"; /** * Environment variable for Genie cluster directory. **/ public static final String GENIE_CLUSTER_DIR_ENV_VAR = "GENIE_CLUSTER_DIR"; /** * Environment variable for Genie cluster id. */ public static final String GENIE_CLUSTER_ID_ENV_VAR = "GENIE_CLUSTER_ID"; /** * Environment variable for the Genie cluster name. */ public static final String GENIE_CLUSTER_NAME_ENV_VAR = "GENIE_CLUSTER_NAME"; /** * Environment variable for the Genie cluster tags. */ public static final String GENIE_CLUSTER_TAGS_ENV_VAR = "GENIE_CLUSTER_TAGS"; /** * Environment variable for Genie command directory. **/ public static final String GENIE_COMMAND_DIR_ENV_VAR = "GENIE_COMMAND_DIR"; /** * Environment variable for Genie command id. */ public static final String GENIE_COMMAND_ID_ENV_VAR = "GENIE_COMMAND_ID"; /** * Environment variable for the Genie command name. */ public static final String GENIE_COMMAND_NAME_ENV_VAR = "GENIE_COMMAND_NAME"; /** * Environment variable for the Genie command tags. */ public static final String GENIE_COMMAND_TAGS_ENV_VAR = "GENIE_COMMAND_TAGS"; /** * Environment variable for Genie application directory. **/ public static final String GENIE_APPLICATION_DIR_ENV_VAR = "GENIE_APPLICATION_DIR"; /** * Environment variable for Genie Job ID. */ public static final String GENIE_JOB_ID_ENV_VAR = "GENIE_JOB_ID"; /** * Environment variable for Genie Job Name. */ public static final String GENIE_JOB_NAME_ENV_VAR = "GENIE_JOB_NAME"; /** * Environment variable for Genie Job Memory. */ public static final String GENIE_JOB_MEMORY_ENV_VAR = "GENIE_JOB_MEMORY"; /** * Environment variable for Genie job tags provided by the user. */ public static final String GENIE_JOB_TAGS_ENV_VAR = "GENIE_JOB_TAGS"; /** * Environment variable for Genie Job grouping. */ public static final String GENIE_JOB_GROUPING_ENV_VAR = "GENIE_JOB_GROUPING"; /** * Environment variable for Genie Job grouping instance. */ public static final String GENIE_JOB_GROUPING_INSTANCE_ENV_VAR = "GENIE_JOB_GROUPING_INSTANCE"; /** * Environment variable for the Genie command tags in the job request. */ public static final String GENIE_REQUESTED_COMMAND_TAGS_ENV_VAR = "GENIE_REQUESTED_COMMAND_TAGS"; /** * Environment variable for the Genie cluster criteria tags in the job request. */ public static final String GENIE_REQUESTED_CLUSTER_TAGS_ENV_VAR = "GENIE_REQUESTED_CLUSTER_TAGS"; /** * Environment variable for Genie version. */ public static final String GENIE_VERSION_ENV_VAR = "GENIE_VERSION"; /** * Environment variable for the Genie username the job request. */ public static final String GENIE_USER_ENV_VAR = "GENIE_USER"; /** * Environment variable for the Genie user group the job request. */ public static final String GENIE_USER_GROUP_ENV_VAR = "GENIE_USER_GROUP"; /** * UTC timezone. */ public static final TimeZone UTC = TimeZone.getTimeZone("UTC"); /** * The property name to check whether new job submissions should be allowed. */ public static final String JOB_SUBMISSION_ENABLED_PROPERTY_KEY = "genie.jobs.submission.enabled"; /** * The property name to check for the message to send back to the request user if jobs are currently disabled. */ public static final String JOB_SUBMISSION_DISABLED_MESSAGE_KEY = "genie.jobs.submission.disabledMessage"; /** * The default message to send back to users when the jobs are disabled if there was none other set. */ public static final String JOB_SUBMISSION_DISABLED_DEFAULT_MESSAGE = "Job submission is currently disabled. Please try again later."; /** * The name of the setup file (for entities that have one) when downloaded in the job directory. */ public static final String GENIE_ENTITY_SETUP_SCRIPT_FILE_NAME = "genie_setup.sh"; /** * The name of the file left behind if the runfile fails during setup (sourcing entities setup scripts). */ public static final String GENIE_SETUP_ERROR_FILE_NAME = "setup_failed.txt"; /** * Protected constructor for utility class. */ protected JobConstants() { } }
2,212
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/jobs/package-info.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Common job classes shared by agent and server. * * @author mprimi * @since 4.0.0 */ package com.netflix.genie.common.internal.jobs;
2,213
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/JobDirectoryManifestCreatorService.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import java.io.IOException; import java.nio.file.Path; /** * Factory-like service that produces {@link DirectoryManifest} for Genie jobs directories. * Implementations can have behaviors such as remotely fetching, or caching. * * @author mprimi * @since 4.0.0 */ // TODO: Move this into the Agent codebase once v3 embedded execution no longer needed on server public interface JobDirectoryManifestCreatorService { /** * Produces a {@link DirectoryManifest} for the given job. * * @param jobDirectoryPath the job directory * @return a {@link DirectoryManifest} * @throws IOException if the manifest cannot be created. */ DirectoryManifest getDirectoryManifest( Path jobDirectoryPath ) throws IOException; /** * If the implementation caches manifests to avoid excessive I/O, then demand the given cache entry be dropped, * thus forcing a re-creation of manifest from scratch. * * @param jobDirectoryPath the job directory */ void invalidateCachedDirectoryManifest(Path jobDirectoryPath); }
2,214
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/JobArchiveService.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import java.net.URI; import java.nio.file.Path; /** * A service which is responsible for taking the files related to running a Genie job and backing them up to a different * location. * * @author standon * @author tgianos * @since 4.0.0 */ // TODO: Move this to the agent codebase once v3 embedded execution removed from server public interface JobArchiveService { /** * The subdirectory within the job directory where the manifest will be placed. */ String MANIFEST_DIRECTORY = "genie"; /** * The name of job manifest file generated by the system. */ String MANIFEST_NAME = "manifest.json"; /** * Backup the contents of the given directory to the target location. This will recursively backup ALL the files * and sub-directories within the given directory to the target. * * @param directory {@link Path} to the directory to archive * @param targetURI target {@link URI} for the root archive location * @throws JobArchiveException if archival fails */ void archiveDirectory(Path directory, URI targetURI) throws JobArchiveException; }
2,215
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/JobArchiver.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import org.springframework.core.io.WritableResource; import java.io.File; import java.net.URI; import java.nio.file.Path; import java.util.List; /** * Implementations of this interface should be able to a write job files to a {@link WritableResource} root location. * * @author tgianos * @since 4.0.0 */ // TODO: Move this to the agent codebase once v3 embedded execution is removed from the server public interface JobArchiver { /** * Attempt to archive a directory located at {@code directory} to the {@code target}. All existing data "under" * {@code target} should be assumed to be overwritten/replaced. * * @param directory The directory to archive * @param filesList The list of files to archive * @param target The root of a writable location to archive to. * @return {@code false} if this implementation doesn't support archiving to {@code target}. {@code true} if does * support archiving to {@code target} and the archival was successful * @throws JobArchiveException If an exception happened during archival */ boolean archiveDirectory(Path directory, List<File> filesList, URI target) throws JobArchiveException; }
2,216
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Any service interfaces and implementations shared between the Agent and the Server codebases. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.services; import javax.annotation.ParametersAreNonnullByDefault;
2,217
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/impl/FileSystemJobArchiverImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services.impl; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import com.netflix.genie.common.internal.services.JobArchiver; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; /** * An implementation of {@link JobArchiver} which attempts to copy the job directory somewhere else on the file * system for backup. A convenient example of this would be a NFS mounted to the Genie host. * * @author tgianos * @since 4.0.0 */ @Slf4j public class FileSystemJobArchiverImpl implements JobArchiver { private static final String FILE_SCHEME = "file"; private static final CopyOption[] COPY_OPTIONS = new CopyOption[]{ StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING, }; /** * {@inheritDoc} */ @Override public boolean archiveDirectory( final Path directory, final List<File> filesList, final URI target ) throws JobArchiveException { if (!target.getScheme().equalsIgnoreCase(FILE_SCHEME)) { return false; } final Path targetDirectoryPath = Paths.get(target.getPath()); // If the source doesn't exist or isn't a directory, then throw an exception if (!Files.exists(directory) || !Files.isDirectory(directory)) { throw new JobArchiveException(directory + " doesn't exist or isn't a directory. Unable to copy"); } // If the destination base directory exists and isn't a directory, then throw an exception if (Files.exists(targetDirectoryPath) && !Files.isDirectory(targetDirectoryPath)) { throw new JobArchiveException(targetDirectoryPath + " exist and isn't a directory. Unable to copy"); } for (final File file : filesList) { final Path sourceFilePath = file.toPath(); final Path sourceFileRelativePath = directory.relativize(sourceFilePath); final Path destinationFilePath = targetDirectoryPath.resolve(sourceFileRelativePath); try { final Path parentDirectory = destinationFilePath.getParent(); if (parentDirectory != null) { log.info("Creating parent directory for {}", destinationFilePath); Files.createDirectories(parentDirectory); } log.info("Copying {} to {}", sourceFilePath, destinationFilePath); Files.copy(sourceFilePath, destinationFilePath, COPY_OPTIONS); } catch (IOException e) { log.warn("Failed to archive file {} to {}: {}", sourceFilePath, destinationFilePath, e.getMessage(), e); } } return true; } }
2,218
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/impl/S3JobArchiverImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services.impl; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.services.s3.transfer.MultipleFileUpload; import com.amazonaws.services.s3.transfer.TransferManager; import com.netflix.genie.common.internal.aws.s3.S3ClientFactory; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import com.netflix.genie.common.internal.services.JobArchiveService; import com.netflix.genie.common.internal.services.JobArchiver; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotNull; import java.io.File; import java.net.URI; import java.nio.file.Path; import java.util.List; /** * Implementation of {@link JobArchiveService} for S3 destinations. * * @author standon * @author tgianos * @since 4.0.0 */ @Slf4j public class S3JobArchiverImpl implements JobArchiver { private final S3ClientFactory s3ClientFactory; /** * Constructor. * * @param s3ClientFactory The factory to use to get S3 client instances for a given S3 bucket. */ public S3JobArchiverImpl(final S3ClientFactory s3ClientFactory) { this.s3ClientFactory = s3ClientFactory; } /** * {@inheritDoc} */ @Override public boolean archiveDirectory( @NotNull final Path directory, final List<File> filesList, @NotNull final URI target ) throws JobArchiveException { final String uriString = target.toString(); final AmazonS3URI s3URI; try { s3URI = new AmazonS3URI(target); } catch (final IllegalArgumentException iae) { log.debug("{} is not a valid S3 URI", uriString); return false; } final String directoryString = directory.toString(); log.debug( "{} is a valid S3 location. Proceeding to archive {} to location: {}", uriString, directoryString, uriString ); try { final TransferManager transferManager = this.s3ClientFactory.getTransferManager(s3URI); final MultipleFileUpload upload = transferManager.uploadFileList( s3URI.getBucket(), s3URI.getKey(), directory.toFile(), filesList ); upload.waitForCompletion(); return true; } catch (final Exception e) { log.error("Error archiving to S3 location: {} ", uriString, e); throw new JobArchiveException("Error archiving " + directoryString, e); } } }
2,219
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/impl/JobDirectoryManifestCreatorServiceImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services.impl; import com.github.benmanes.caffeine.cache.Cache; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.nio.file.Path; /** * Implementation of {@link JobDirectoryManifestCreatorService} that caches manifests produced by the factory for a few * seconds, thus avoiding re-calculating the same for subsequent requests (e.g. a user navigating a tree true the UI). * * @author mprimi * @since 4.0.0 */ @Slf4j public class JobDirectoryManifestCreatorServiceImpl implements JobDirectoryManifestCreatorService { private final Cache<Path, DirectoryManifest> cache; private final DirectoryManifest.Factory factory; private final boolean includeChecksum; /** * Constructor. * * @param factory the directory manifest factory * @param cache the loading cache to use * @param includeChecksum whether to produce manifests that include checksums */ public JobDirectoryManifestCreatorServiceImpl( final DirectoryManifest.Factory factory, final Cache<Path, DirectoryManifest> cache, final boolean includeChecksum ) { this.factory = factory; this.cache = cache; this.includeChecksum = includeChecksum; } /** * {@inheritDoc} */ @Override public DirectoryManifest getDirectoryManifest(final Path jobDirectoryPath) throws IOException { try { return cache.get( jobDirectoryPath.normalize().toAbsolutePath(), path -> { try { return this.factory.getDirectoryManifest(path, this.includeChecksum); } catch (IOException e) { throw new RuntimeException("Failed to create manifest", e); } } ); } catch (RuntimeException e) { if (e.getCause() != null && e.getCause() instanceof IOException) { // Unwrap and throw the original IOException throw (IOException) e.getCause(); } throw e; } } /** * {@inheritDoc} */ @Override public void invalidateCachedDirectoryManifest(final Path jobDirectoryPath) { this.cache.invalidate(jobDirectoryPath); } }
2,220
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/impl/JobArchiveServiceImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.services.impl; import com.google.common.collect.ImmutableList; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import com.netflix.genie.common.internal.services.JobArchiveService; import com.netflix.genie.common.internal.services.JobArchiver; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; /** * Default implementation of the {@link JobArchiveService}. * * @author tgianos * @since 4.0.0 */ @Slf4j public class JobArchiveServiceImpl implements JobArchiveService { private final ImmutableList<JobArchiver> jobArchivers; private final DirectoryManifest.Factory directoryManifestFactory; /** * Constructor. * * @param jobArchivers The ordered list of {@link JobArchiver} implementations to use. Not empty. * @param directoryManifestFactory The job directory manifest factory */ public JobArchiveServiceImpl( final List<JobArchiver> jobArchivers, final DirectoryManifest.Factory directoryManifestFactory ) { this.jobArchivers = ImmutableList.copyOf(jobArchivers); this.directoryManifestFactory = directoryManifestFactory; } /** * {@inheritDoc} */ @Override public void archiveDirectory(final Path directory, final URI target) throws JobArchiveException { // TODO: This relies highly on convention. Might be nicer to better abstract with database // record that points directly to where the manifest is or other solution? final DirectoryManifest manifest; final Path manifestPath; try { manifest = directoryManifestFactory.getDirectoryManifest(directory, true); final Path manifestDirectoryPath = StringUtils.isBlank(JobArchiveService.MANIFEST_DIRECTORY) ? directory : directory.resolve(JobArchiveService.MANIFEST_DIRECTORY); if (Files.notExists(manifestDirectoryPath)) { Files.createDirectories(manifestDirectoryPath); } else if (!Files.isDirectory(manifestDirectoryPath)) { throw new JobArchiveException( manifestDirectoryPath + " is not a directory. Unable to create job manifest. Unable to archive" ); } manifestPath = manifestDirectoryPath.resolve(JobArchiveService.MANIFEST_NAME); Files.write(manifestPath, GenieObjectMapper.getMapper().writeValueAsBytes(manifest)); log.debug("Wrote job directory manifest to {}", manifestPath); } catch (final IOException ioe) { throw new JobArchiveException("Unable to create job directory manifest. Unable to archive", ioe); } // Attempt to archive the job directory, now including the manifest file, using available implementations final String uriString = target.toString(); final List<File> filesList = ImmutableList.<File>builder() .add(manifestPath.toFile()) .addAll( manifest.getFiles() .stream() .map(fileEntry -> Paths.get(fileEntry.getPath())) .map(directory::resolve) .map(Path::toAbsolutePath) .filter(path -> Files.exists(path)) .map(Path::toFile) .collect(Collectors.toSet()) ) .build(); for (final JobArchiver archiver : this.jobArchivers) { // TODO: Perhaps we should pass the manifest down to the archive implementations if they want to use it? if (archiver.archiveDirectory(directory, filesList, target)) { log.debug( "Successfully archived job directory {} to {} using {} ({} files)", directory.toString(), uriString, archiver.getClass().getSimpleName(), filesList.size() ); return; } } // For now archival is not considered critical so just log warning log.warn( "Failed to archive job directory {} to {} using any of the available implementations", directory.toString(), uriString ); } }
2,221
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/services/impl/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implementations of service interfaces found in {@link com.netflix.genie.common.internal.services}. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.services.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,222
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/spring
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/spring/autoconfigure/CommonTracingAutoConfiguration.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.internal.spring.autoconfigure; import brave.Tracer; import com.netflix.genie.common.internal.tracing.TracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter; import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTracingCleanup; import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents; import com.netflix.genie.common.internal.tracing.brave.impl.DefaultBraveTagAdapterImpl; import com.netflix.genie.common.internal.tracing.brave.impl.EnvVarBraveTracePropagatorImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import zipkin2.reporter.AsyncReporter; import java.util.Set; /** * Auto configuration for common tracing components within Genie server and agent. * * @author tgianos * @since 4.0.0 */ @Configuration public class CommonTracingAutoConfiguration { /** * Provide an implementation of {@link TracePropagator} if no other has been defined. * * @return instance of {@link EnvVarBraveTracePropagatorImpl} */ @Bean @ConditionalOnMissingBean(BraveTracePropagator.class) public EnvVarBraveTracePropagatorImpl braveTracePropagator() { return new EnvVarBraveTracePropagatorImpl(); } /** * Provide a {@link BraveTracingCleanup} based on the context. * * @param reporters Any {@link AsyncReporter} instances configured * @return A {@link BraveTracingCleanup} instance */ @Bean @ConditionalOnMissingBean(BraveTracingCleanup.class) public BraveTracingCleanup braveTracingCleaner(final Set<AsyncReporter<?>> reporters) { return new BraveTracingCleanup(reporters); } /** * Provide a {@link BraveTagAdapter} instance if no other has been provided. * * @return A {@link DefaultBraveTagAdapterImpl} instance which just directly applies the tags to the span */ @Bean @ConditionalOnMissingBean(BraveTagAdapter.class) public DefaultBraveTagAdapterImpl braveTagAdapter() { return new DefaultBraveTagAdapterImpl(); } /** * Provide a {@link BraveTracingComponents} instance based on Brave if no other has been provided. * * @param tracer The {@link Tracer} instance to use * @param tracePropagator The {@link BraveTracePropagator} to use * @param tracingCleanup The {@link BraveTracingCleanup} to use * @param tagAdapter The {@link BraveTagAdapter} instance to use * @return A {@link BraveTracingComponents} instance */ @Bean @ConditionalOnMissingBean(BraveTracingComponents.class) public BraveTracingComponents braveTracingComponents( final Tracer tracer, final BraveTracePropagator tracePropagator, final BraveTracingCleanup tracingCleanup, final BraveTagAdapter tagAdapter ) { return new BraveTracingComponents(tracer, tracePropagator, tracingCleanup, tagAdapter); } }
2,223
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/spring
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/spring/autoconfigure/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Auto configuration classes for modules within this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.spring.autoconfigure; import javax.annotation.ParametersAreNonnullByDefault;
2,224
0
Create_ds/genie/genie-swagger/src/test/java/com/netflix/genie/swagger/spring
Create_ds/genie/genie-swagger/src/test/java/com/netflix/genie/swagger/spring/autoconfigure/SwaggerAutoConfigurationTest.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.swagger.spring.autoconfigure; import io.swagger.v3.oas.models.OpenAPI; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springdoc.core.GroupedOpenApi; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; /** * Unit tests for the {@link SwaggerAutoConfiguration} class. * * @author tgianos * @since 3.0.0 */ class SwaggerAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( SwaggerAutoConfiguration.class ) ); @Test void expectedBeansExist() { this.contextRunner.run( context -> { Assertions.assertThat(context).hasSingleBean(GroupedOpenApi.class); Assertions.assertThat(context).hasSingleBean(OpenAPI.class); } ); } }
2,225
0
Create_ds/genie/genie-swagger/src/test/java/com/netflix/genie/swagger/spring
Create_ds/genie/genie-swagger/src/test/java/com/netflix/genie/swagger/spring/autoconfigure/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Tests for auto-configurations in this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.swagger.spring.autoconfigure; import javax.annotation.ParametersAreNonnullByDefault;
2,226
0
Create_ds/genie/genie-swagger/src/main/java/com/netflix/genie/swagger/spring
Create_ds/genie/genie-swagger/src/main/java/com/netflix/genie/swagger/spring/autoconfigure/SwaggerAutoConfiguration.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.swagger.spring.autoconfigure; import io.swagger.v3.oas.models.ExternalDocumentation; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springdoc.core.GroupedOpenApi; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Spring configuration for Swagger via Spring Doc. * * @author tgianos * @see <a href="https://springdoc.org/">Spring Doc</a> * @since 4.2.0 */ @Configuration public class SwaggerAutoConfiguration { /** * Bean for the V3 API documentation. * * @return Instance of {@link GroupedOpenApi} for the V3 endpoints */ @Bean @ConditionalOnMissingBean(name = "genieV3ApiGroup") public GroupedOpenApi genieV3ApiGroup() { return GroupedOpenApi.builder() .group("V3") .pathsToMatch("/api/v3/**") .build(); } /** * Configure OpenAPI specification. * * @return The {@link OpenAPI} instance and description */ @Bean @ConditionalOnMissingBean(OpenAPI.class) public OpenAPI springShopOpenAPI() { return new OpenAPI() .info( new Info() .title("Genie REST API") .description("Spring shop sample application") .version("v4.2.x") .license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0")) ) .externalDocs( new ExternalDocumentation() .description("Documentation Site") .url("https://netflix.github.io/genie") ); } }
2,227
0
Create_ds/genie/genie-swagger/src/main/java/com/netflix/genie/swagger/spring
Create_ds/genie/genie-swagger/src/main/java/com/netflix/genie/swagger/spring/autoconfigure/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Auto configuration for Spring applications relating to Swagger. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.swagger.spring.autoconfigure; import javax.annotation.ParametersAreNonnullByDefault;
2,228
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/CommandTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Tests for the {@link Command} class. * * @author tgianos * @since 3.0.0 */ class CommandTest { private static final String NAME = UUID.randomUUID().toString(); private static final String USER = UUID.randomUUID().toString(); private static final String VERSION = UUID.randomUUID().toString(); private static final long CHECK_DELAY = 12380L; private static final ArrayList<String> EXECUTABLE_AND_ARGS = Lists.newArrayList("foo-cli", "--verbose"); private static final String EXECUTABLE = StringUtils.join(EXECUTABLE_AND_ARGS, " "); private static final int MEMORY = 10_255; @SuppressWarnings("deprecation") @Test void canBuildCommand() { final Command command = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS).build(); Assertions.assertThat(command.getName()).isEqualTo(NAME); Assertions.assertThat(command.getUser()).isEqualTo(USER); Assertions.assertThat(command.getVersion()).isEqualTo(VERSION); Assertions.assertThat(command.getStatus()).isEqualTo(CommandStatus.ACTIVE); Assertions.assertThat(command.getExecutable()).isEqualTo(EXECUTABLE); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(EXECUTABLE_AND_ARGS); Assertions.assertThat(command.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(command.getConfigs()).isEmpty(); Assertions.assertThat(command.getDependencies()).isEmpty(); Assertions.assertThat(command.getCreated().isPresent()).isFalse(); Assertions.assertThat(command.getDescription().isPresent()).isFalse(); Assertions.assertThat(command.getId().isPresent()).isFalse(); Assertions.assertThat(command.getTags()).isEmpty(); Assertions.assertThat(command.getUpdated().isPresent()).isFalse(); Assertions.assertThat(command.getMemory().isPresent()).isFalse(); Assertions.assertThat(command.getClusterCriteria()).isEmpty(); Assertions.assertThat(command.getCheckDelay()).isEqualTo(Command.DEFAULT_CHECK_DELAY); Assertions.assertThat(command.getRuntime()).isNotNull(); } @SuppressWarnings("deprecation") @Test void canBuildCommandWithDeprecatedCheckDelayConstructor() { final Command command = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, CHECK_DELAY).build(); Assertions.assertThat(command.getName()).isEqualTo(NAME); Assertions.assertThat(command.getUser()).isEqualTo(USER); Assertions.assertThat(command.getVersion()).isEqualTo(VERSION); Assertions.assertThat(command.getStatus()).isEqualTo(CommandStatus.ACTIVE); Assertions.assertThat(command.getExecutable()).isEqualTo(EXECUTABLE); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(EXECUTABLE_AND_ARGS); Assertions.assertThat(command.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(command.getConfigs()).isEmpty(); Assertions.assertThat(command.getDependencies()).isEmpty(); Assertions.assertThat(command.getCreated().isPresent()).isFalse(); Assertions.assertThat(command.getDescription().isPresent()).isFalse(); Assertions.assertThat(command.getId().isPresent()).isFalse(); Assertions.assertThat(command.getTags()).isEmpty(); Assertions.assertThat(command.getUpdated().isPresent()).isFalse(); Assertions.assertThat(command.getMemory().isPresent()).isFalse(); Assertions.assertThat(command.getClusterCriteria()).isEmpty(); Assertions.assertThat(command.getCheckDelay()).isEqualTo(Command.DEFAULT_CHECK_DELAY); Assertions.assertThat(command.getRuntime()).isNotNull(); } @SuppressWarnings("deprecation") @Test void canBuildCommandWithDeprecatedExecutableConstructor() { final Command command = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE, CHECK_DELAY).build(); Assertions.assertThat(command.getName()).isEqualTo(NAME); Assertions.assertThat(command.getUser()).isEqualTo(USER); Assertions.assertThat(command.getVersion()).isEqualTo(VERSION); Assertions.assertThat(command.getStatus()).isEqualTo(CommandStatus.ACTIVE); Assertions.assertThat(command.getExecutable()).isEqualTo(EXECUTABLE); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(EXECUTABLE_AND_ARGS); Assertions.assertThat(command.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(command.getConfigs()).isEmpty(); Assertions.assertThat(command.getDependencies()).isEmpty(); Assertions.assertThat(command.getCreated().isPresent()).isFalse(); Assertions.assertThat(command.getDescription().isPresent()).isFalse(); Assertions.assertThat(command.getId().isPresent()).isFalse(); Assertions.assertThat(command.getTags()).isEmpty(); Assertions.assertThat(command.getUpdated().isPresent()).isFalse(); Assertions.assertThat(command.getMemory().isPresent()).isFalse(); Assertions.assertThat(command.getClusterCriteria()).isEmpty(); Assertions.assertThat(command.getCheckDelay()).isEqualTo(Command.DEFAULT_CHECK_DELAY); Assertions.assertThat(command.getRuntime()).isNotNull(); } @SuppressWarnings("deprecation") @Test void canBuildCommandWithOptionals() { final Command.Builder builder = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS); final String setupFile = UUID.randomUUID().toString(); builder.withSetupFile(setupFile); final Set<String> configs = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withConfigs(configs); final Set<String> dependencies = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withDependencies(dependencies); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); builder.withMemory(MEMORY - 1); builder.withCheckDelay(CHECK_DELAY); final List<Criterion> clusterCriteria = Lists.newArrayList( new Criterion.Builder().withId(UUID.randomUUID().toString()).build(), new Criterion.Builder().withName(UUID.randomUUID().toString()).build(), new Criterion.Builder().withStatus(UUID.randomUUID().toString()).build(), new Criterion.Builder().withVersion(UUID.randomUUID().toString()).build(), new Criterion.Builder().withTags(Sets.newHashSet(UUID.randomUUID().toString())).build() ); builder.withClusterCriteria(clusterCriteria); final Map<String, ContainerImage> images = new HashMap<>(); final Runtime runtime = new Runtime.Builder() .withResources( new RuntimeResources.Builder() .withCpu(8) .withMemoryMb((long) MEMORY) .withDiskMb(18_333L) .withGpu(3) .withNetworkMbps(512L) .build() ) .withImages(images) .build(); builder.withRuntime(runtime); final Command command = builder.build(); Assertions.assertThat(command.getName()).isEqualTo(NAME); Assertions.assertThat(command.getUser()).isEqualTo(USER); Assertions.assertThat(command.getVersion()).isEqualTo(VERSION); Assertions.assertThat(command.getStatus()).isEqualTo(CommandStatus.ACTIVE); Assertions.assertThat(command.getExecutable()).isEqualTo(EXECUTABLE); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(EXECUTABLE_AND_ARGS); Assertions.assertThat(command.getCheckDelay()).isEqualTo(Command.DEFAULT_CHECK_DELAY); Assertions.assertThat(command.getSetupFile()).isPresent().contains(setupFile); Assertions.assertThat(command.getConfigs()).isEqualTo(configs); Assertions.assertThat(command.getDependencies()).isEqualTo(dependencies); Assertions.assertThat(command.getCreated()).isPresent().contains(created); Assertions.assertThat(command.getDescription()).isPresent().contains(description); Assertions.assertThat(command.getId()).isPresent().contains(id); Assertions.assertThat(command.getTags()).isEqualTo(tags); Assertions.assertThat(command.getUpdated()).isPresent().contains(updated); Assertions.assertThat(command.getMemory()).isPresent().contains(MEMORY); Assertions.assertThat(command.getClusterCriteria()).isEqualTo(clusterCriteria); Assertions.assertThat(command.getRuntime()).isEqualTo(runtime); } @SuppressWarnings("deprecation") @Test void canBuildCommandNullOptionals() { final Command.Builder builder = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS); builder.withSetupFile(null); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(null); builder.withTags(null); builder.withUpdated(null); builder.withMemory(null); builder.withClusterCriteria(null); builder.withCheckDelay(null); builder.withRuntime(null); final Command command = builder.build(); Assertions.assertThat(command.getName()).isEqualTo(NAME); Assertions.assertThat(command.getUser()).isEqualTo(USER); Assertions.assertThat(command.getVersion()).isEqualTo(VERSION); Assertions.assertThat(command.getStatus()).isEqualTo(CommandStatus.ACTIVE); Assertions.assertThat(command.getExecutable()).isEqualTo(EXECUTABLE); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(EXECUTABLE_AND_ARGS); Assertions.assertThat(command.getSetupFile()).isNotPresent(); Assertions.assertThat(command.getConfigs()).isEmpty(); Assertions.assertThat(command.getDependencies()).isEmpty(); Assertions.assertThat(command.getCreated()).isNotPresent(); Assertions.assertThat(command.getDescription()).isNotPresent(); Assertions.assertThat(command.getId()).isNotPresent(); Assertions.assertThat(command.getTags()).isEmpty(); Assertions.assertThat(command.getUpdated()).isNotPresent(); Assertions.assertThat(command.getMemory()).isNotPresent(); Assertions.assertThat(command.getClusterCriteria()).isEmpty(); Assertions.assertThat(command.getRuntime()).isNotNull(); } @Test void canFindEquality() { final Command.Builder builder = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS); builder.withSetupFile(null); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Command command1 = builder.build(); final Command command2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Command command3 = builder.build(); Assertions.assertThat(command1).isEqualTo(command2); Assertions.assertThat(command1).isNotEqualTo(command3); } @Test void canUseHashCode() { final Command.Builder builder = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS); builder.withSetupFile(null); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Command command1 = builder.build(); final Command command2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Command command3 = builder.build(); Assertions.assertThat(command1.hashCode()).isEqualTo(command2.hashCode()); Assertions.assertThat(command1.hashCode()).isNotEqualTo(command3.hashCode()); } @Test void cantBuildWithoutExecutable() { Assertions .assertThatIllegalArgumentException() .isThrownBy(() -> new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE).build()); } @SuppressWarnings("deprecation") @Test void canBuildWithConflictingExecutableFields() { final ArrayList<String> expectedExecutable = Lists.newArrayList("exec", "arg1", "arg2"); final Command command = new Command.Builder(NAME, USER, VERSION, CommandStatus.ACTIVE, EXECUTABLE_AND_ARGS, CHECK_DELAY) .withExecutable("foo") .withExecutableAndArguments(expectedExecutable) .build(); Assertions.assertThat(command.getExecutableAndArguments()).isEqualTo(expectedExecutable); Assertions.assertThat(command.getExecutable()).isEqualTo(StringUtils.join(expectedExecutable, ' ')); } }
2,229
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/ApplicationStatusTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the ApplicationStatus enum. * * @author tgianos * @since 2.0.0 */ class ApplicationStatusTest { /** * Tests whether a valid application status is parsed correctly. * * @throws GeniePreconditionException If any precondition isn't met. */ @Test void testValidApplicationStatus() throws GeniePreconditionException { Assertions .assertThat(ApplicationStatus.parse(ApplicationStatus.ACTIVE.name().toLowerCase())) .isEqualByComparingTo(ApplicationStatus.ACTIVE); Assertions .assertThat(ApplicationStatus.parse(ApplicationStatus.DEPRECATED.name().toLowerCase())) .isEqualByComparingTo(ApplicationStatus.DEPRECATED); Assertions .assertThat(ApplicationStatus.parse(ApplicationStatus.INACTIVE.name().toLowerCase())) .isEqualByComparingTo(ApplicationStatus.INACTIVE); } /** * Tests whether an invalid application status throws exception. */ @Test void testInvalidApplicationStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> ApplicationStatus.parse("DOES_NOT_EXIST")); } /** * Tests whether an invalid application status throws exception. */ @Test void testBlankApplicationStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> ApplicationStatus.parse(" ")); } }
2,230
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/JobTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Set; import java.util.UUID; /** * Unit tests for the Job class. * * @author tgianos * @since 3.0.0 */ class JobTest { private static final String NAME = UUID.randomUUID().toString(); private static final String USER = UUID.randomUUID().toString(); private static final String VERSION = UUID.randomUUID().toString(); private static final List<String> COMMAND_ARGS = Lists.newArrayList(UUID.randomUUID().toString()); /** * Test to make sure can build a valid Job using the builder. */ @Test @SuppressWarnings("deprecation") void canBuildJobDeprecatedConstructor() { final Job job = new Job.Builder(NAME, USER, VERSION, StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)).build(); Assertions.assertThat(job.getName()).isEqualTo(NAME); Assertions.assertThat(job.getUser()).isEqualTo(USER); Assertions.assertThat(job.getVersion()).isEqualTo(VERSION); Assertions .assertThat(job.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions.assertThat(job.getArchiveLocation().isPresent()).isFalse(); Assertions.assertThat(job.getClusterName().isPresent()).isFalse(); Assertions.assertThat(job.getCommandName().isPresent()).isFalse(); Assertions.assertThat(job.getFinished().isPresent()).isFalse(); Assertions.assertThat(job.getStarted().isPresent()).isFalse(); Assertions.assertThat(job.getStatus()).isEqualTo(JobStatus.INIT); Assertions.assertThat(job.getStatusMsg().isPresent()).isFalse(); Assertions.assertThat(job.getCreated().isPresent()).isFalse(); Assertions.assertThat(job.getDescription().isPresent()).isFalse(); Assertions.assertThat(job.getId().isPresent()).isFalse(); Assertions.assertThat(job.getTags()).isEmpty(); Assertions.assertThat(job.getUpdated().isPresent()).isFalse(); Assertions.assertThat(job.getRuntime()).isEqualTo(Duration.ZERO); Assertions.assertThat(job.getGrouping().isPresent()).isFalse(); Assertions.assertThat(job.getGroupingInstance().isPresent()).isFalse(); } /** * Test to make sure can build a valid Job using the builder. */ @Test void canBuildJob() { final Job job = new Job.Builder(NAME, USER, VERSION).build(); Assertions.assertThat(job.getName()).isEqualTo(NAME); Assertions.assertThat(job.getUser()).isEqualTo(USER); Assertions.assertThat(job.getVersion()).isEqualTo(VERSION); Assertions.assertThat(job.getCommandArgs().isPresent()).isFalse(); Assertions.assertThat(job.getArchiveLocation().isPresent()).isFalse(); Assertions.assertThat(job.getClusterName().isPresent()).isFalse(); Assertions.assertThat(job.getCommandName().isPresent()).isFalse(); Assertions.assertThat(job.getFinished().isPresent()).isFalse(); Assertions.assertThat(job.getStarted().isPresent()).isFalse(); Assertions.assertThat(job.getStatus()).isEqualTo(JobStatus.INIT); Assertions.assertThat(job.getStatusMsg().isPresent()).isFalse(); Assertions.assertThat(job.getCreated().isPresent()).isFalse(); Assertions.assertThat(job.getDescription().isPresent()).isFalse(); Assertions.assertThat(job.getId().isPresent()).isFalse(); Assertions.assertThat(job.getTags()).isEmpty(); Assertions.assertThat(job.getUpdated().isPresent()).isFalse(); Assertions.assertThat(job.getRuntime()).isEqualTo(Duration.ZERO); Assertions.assertThat(job.getGrouping().isPresent()).isFalse(); Assertions.assertThat(job.getGroupingInstance().isPresent()).isFalse(); } /** * Test to make sure can build a valid Job with optional parameters. */ @Test @SuppressWarnings("deprecation") void canBuildJobWithOptionalsDeprecated() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); final String archiveLocation = UUID.randomUUID().toString(); builder.withArchiveLocation(archiveLocation); final String clusterName = UUID.randomUUID().toString(); builder.withClusterName(clusterName); final String commandName = UUID.randomUUID().toString(); builder.withCommandName(commandName); final Instant finished = Instant.now(); builder.withFinished(finished); final Instant started = Instant.now(); builder.withStarted(started); builder.withStatus(JobStatus.SUCCEEDED); final String statusMsg = UUID.randomUUID().toString(); builder.withStatusMsg(statusMsg); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final String grouping = UUID.randomUUID().toString(); builder.withGrouping(grouping); final String groupingInstance = UUID.randomUUID().toString(); builder.withGroupingInstance(groupingInstance); final Job job = builder.build(); Assertions.assertThat(job.getName()).isEqualTo(NAME); Assertions.assertThat(job.getUser()).isEqualTo(USER); Assertions.assertThat(job.getVersion()).isEqualTo(VERSION); Assertions .assertThat(job.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions .assertThat(job.getArchiveLocation().orElseThrow(IllegalArgumentException::new)) .isEqualTo(archiveLocation); Assertions.assertThat(job.getClusterName().orElseThrow(IllegalArgumentException::new)).isEqualTo(clusterName); Assertions.assertThat(job.getCommandName().orElseThrow(IllegalArgumentException::new)).isEqualTo(commandName); Assertions.assertThat(job.getFinished().orElseThrow(IllegalArgumentException::new)).isEqualTo(finished); Assertions.assertThat(job.getStarted().orElseThrow(IllegalArgumentException::new)).isEqualTo(started); Assertions.assertThat(job.getStatus()).isEqualTo(JobStatus.SUCCEEDED); Assertions.assertThat(job.getStatusMsg().orElseThrow(IllegalArgumentException::new)).isEqualTo(statusMsg); Assertions.assertThat(job.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions.assertThat(job.getDescription().orElseThrow(IllegalArgumentException::new)).isEqualTo(description); Assertions.assertThat(job.getId().orElseThrow(IllegalArgumentException::new)).isEqualTo(id); Assertions.assertThat(job.getTags()).isEqualTo(tags); Assertions.assertThat(job.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); Assertions .assertThat(job.getRuntime()) .isEqualByComparingTo(Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli())); Assertions.assertThat(job.getGrouping().orElseThrow(IllegalArgumentException::new)).isEqualTo(grouping); Assertions .assertThat(job.getGroupingInstance().orElseThrow(IllegalArgumentException::new)) .isEqualTo(groupingInstance); } /** * Test to make sure can build a valid Job with optional parameters. */ @Test void canBuildJobWithOptionals() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs(COMMAND_ARGS); final String archiveLocation = UUID.randomUUID().toString(); builder.withArchiveLocation(archiveLocation); final String clusterName = UUID.randomUUID().toString(); builder.withClusterName(clusterName); final String commandName = UUID.randomUUID().toString(); builder.withCommandName(commandName); final Instant finished = Instant.now(); builder.withFinished(finished); final Instant started = Instant.now(); builder.withStarted(started); builder.withStatus(JobStatus.SUCCEEDED); final String statusMsg = UUID.randomUUID().toString(); builder.withStatusMsg(statusMsg); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final String grouping = UUID.randomUUID().toString(); builder.withGrouping(grouping); final String groupingInstance = UUID.randomUUID().toString(); builder.withGroupingInstance(groupingInstance); final Job job = builder.build(); Assertions.assertThat(job.getName()).isEqualTo(NAME); Assertions.assertThat(job.getUser()).isEqualTo(USER); Assertions.assertThat(job.getVersion()).isEqualTo(VERSION); Assertions .assertThat(job.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions .assertThat(job.getArchiveLocation().orElseThrow(IllegalArgumentException::new)) .isEqualTo(archiveLocation); Assertions.assertThat(job.getClusterName().orElseThrow(IllegalArgumentException::new)).isEqualTo(clusterName); Assertions.assertThat(job.getCommandName().orElseThrow(IllegalArgumentException::new)).isEqualTo(commandName); Assertions.assertThat(job.getFinished().orElseThrow(IllegalArgumentException::new)).isEqualTo(finished); Assertions.assertThat(job.getStarted().orElseThrow(IllegalArgumentException::new)).isEqualTo(started); Assertions.assertThat(job.getStatus()).isEqualTo(JobStatus.SUCCEEDED); Assertions.assertThat(job.getStatusMsg().orElseThrow(IllegalArgumentException::new)).isEqualTo(statusMsg); Assertions.assertThat(job.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions.assertThat(job.getDescription().orElseThrow(IllegalArgumentException::new)).isEqualTo(description); Assertions.assertThat(job.getId().orElseThrow(IllegalArgumentException::new)).isEqualTo(id); Assertions.assertThat(job.getTags()).isEqualTo(tags); Assertions.assertThat(job.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); Assertions .assertThat(job.getRuntime()) .isEqualByComparingTo(Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli())); Assertions.assertThat(job.getGrouping().orElseThrow(IllegalArgumentException::new)).isEqualTo(grouping); Assertions .assertThat(job.getGroupingInstance().orElseThrow(IllegalArgumentException::new)) .isEqualTo(groupingInstance); } /** * Test to make sure a Job can be successfully built when nulls are inputted. */ @Test void canBuildJobWithNulls() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs((List<String>) null); builder.withArchiveLocation(null); builder.withClusterName(null); builder.withCommandName(null); builder.withFinished(null); builder.withStarted(null); builder.withStatus(JobStatus.INIT); builder.withStatusMsg(null); builder.withCreated(null); builder.withDescription(null); builder.withId(null); builder.withTags(null); builder.withUpdated(null); final Job job = builder.build(); Assertions.assertThat(job.getName()).isEqualTo(NAME); Assertions.assertThat(job.getUser()).isEqualTo(USER); Assertions.assertThat(job.getVersion()).isEqualTo(VERSION); Assertions.assertThat(job.getCommandArgs().isPresent()).isFalse(); Assertions.assertThat(job.getArchiveLocation().isPresent()).isFalse(); Assertions.assertThat(job.getClusterName().isPresent()).isFalse(); Assertions.assertThat(job.getCommandName().isPresent()).isFalse(); Assertions.assertThat(job.getFinished().isPresent()).isFalse(); Assertions.assertThat(job.getStarted().isPresent()).isFalse(); Assertions.assertThat(job.getStatus()).isEqualTo(JobStatus.INIT); Assertions.assertThat(job.getStatusMsg().isPresent()).isFalse(); Assertions.assertThat(job.getCreated().isPresent()).isFalse(); Assertions.assertThat(job.getDescription().isPresent()).isFalse(); Assertions.assertThat(job.getId().isPresent()).isFalse(); Assertions.assertThat(job.getTags()).isEmpty(); Assertions.assertThat(job.getUpdated().isPresent()).isFalse(); Assertions.assertThat(job.getRuntime()).isEqualTo(Duration.ZERO); } /** * Test equals. */ @Test void canFindEquality() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs((List<String>) null); builder.withArchiveLocation(null); builder.withClusterName(null); builder.withCommandName(null); builder.withFinished(null); builder.withStarted(null); builder.withStatus(JobStatus.INIT); builder.withStatusMsg(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Job job1 = builder.build(); final Job job2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Job job3 = builder.build(); Assertions.assertThat(job1).isEqualTo(job2); Assertions.assertThat(job1).isNotEqualTo(job3); } /** * Test hash code. */ @Test void canUseHashCode() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); builder.withCommandArgs((List<String>) null); builder.withArchiveLocation(null); builder.withClusterName(null); builder.withCommandName(null); builder.withFinished(null); builder.withStarted(null); builder.withStatus(JobStatus.INIT); builder.withStatusMsg(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Job job1 = builder.build(); final Job job2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Job job3 = builder.build(); Assertions.assertThat(job1.hashCode()).isEqualTo(job2.hashCode()); Assertions.assertThat(job1.hashCode()).isNotEqualTo(job3.hashCode()); } /** * Test to prove a bug with command args splitting with trailing whitespace was corrected. */ @Test void testCommandArgsEdgeCases() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); } }
2,231
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/JobStatusTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the JobStatus enum. * * @author tgianos * @since 2.0.0 */ class JobStatusTest { /** * Tests whether a valid job status is parsed correctly. * * @throws GeniePreconditionException If any precondition isn't met. */ @Test void testValidJobStatus() throws GeniePreconditionException { Assertions .assertThat(JobStatus.parse(JobStatus.RUNNING.name().toLowerCase())) .isEqualByComparingTo(JobStatus.RUNNING); Assertions .assertThat(JobStatus.parse(JobStatus.FAILED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.FAILED); Assertions .assertThat(JobStatus.parse(JobStatus.KILLED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.KILLED); Assertions .assertThat(JobStatus.parse(JobStatus.INIT.name().toLowerCase())) .isEqualByComparingTo(JobStatus.INIT); Assertions .assertThat(JobStatus.parse(JobStatus.SUCCEEDED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.SUCCEEDED); Assertions .assertThat(JobStatus.parse(JobStatus.RESERVED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.RESERVED); Assertions .assertThat(JobStatus.parse(JobStatus.RESOLVED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.RESOLVED); Assertions .assertThat(JobStatus.parse(JobStatus.CLAIMED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.CLAIMED); Assertions .assertThat(JobStatus.parse(JobStatus.ACCEPTED.name().toLowerCase())) .isEqualByComparingTo(JobStatus.ACCEPTED); } /** * Tests whether an invalid job status returns null. */ @Test void testInvalidJobStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> JobStatus.parse("DOES_NOT_EXIST")); } /** * Tests whether an invalid application status throws exception. */ @Test void testBlankJobStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> JobStatus.parse(" ")); } /** * Test to make sure isActive is working properly. */ @Test void testIsActive() { Assertions.assertThat(JobStatus.RUNNING.isActive()).isTrue(); Assertions.assertThat(JobStatus.INIT.isActive()).isTrue(); Assertions.assertThat(JobStatus.FAILED.isActive()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isActive()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isActive()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isActive()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isActive()).isTrue(); Assertions.assertThat(JobStatus.RESOLVED.isActive()).isTrue(); Assertions.assertThat(JobStatus.CLAIMED.isActive()).isTrue(); Assertions.assertThat(JobStatus.ACCEPTED.isActive()).isTrue(); } /** * Test to make sure isFinished is working properly. */ @Test void testIsFinished() { Assertions.assertThat(JobStatus.RUNNING.isFinished()).isFalse(); Assertions.assertThat(JobStatus.INIT.isFinished()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.INVALID.isFinished()).isTrue(); Assertions.assertThat(JobStatus.KILLED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.SUCCEEDED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.RESERVED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.RESOLVED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.CLAIMED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isFinished()).isFalse(); } /** * Test to make sure isResolvable is working properly. */ @Test void testIsResolvable() { Assertions.assertThat(JobStatus.RUNNING.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.INIT.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isResolvable()).isTrue(); Assertions.assertThat(JobStatus.RESOLVED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.CLAIMED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isResolvable()).isFalse(); } /** * Test to make sure isClaimable is working properly. */ @Test void testIsClaimable() { Assertions.assertThat(JobStatus.RUNNING.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.INIT.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.RESOLVED.isClaimable()).isTrue(); Assertions.assertThat(JobStatus.CLAIMED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isClaimable()).isTrue(); } /** * Make sure all the active statuses are present in the set. */ @Test void testGetActivesStatuses() { Assertions .assertThat(JobStatus.getActiveStatuses()) .containsExactlyInAnyOrder( JobStatus.INIT, JobStatus.RUNNING, JobStatus.RESERVED, JobStatus.RESOLVED, JobStatus.CLAIMED, JobStatus.ACCEPTED ); } /** * Make sure all the finished statuses are present in the set. */ @Test void testGetFinishedStatuses() { Assertions .assertThat(JobStatus.getFinishedStatuses()) .containsExactlyInAnyOrder(JobStatus.INVALID, JobStatus.FAILED, JobStatus.KILLED, JobStatus.SUCCEEDED); } /** * Make sure all the claimable status are present in the set. */ @Test void testGetResolvableStatuses() { Assertions.assertThat(JobStatus.getResolvableStatuses()).containsExactlyInAnyOrder(JobStatus.RESERVED); } /** * Make sure all the claimable status are present in the set. */ @Test void testGetClaimableStatuses() { Assertions .assertThat(JobStatus.getClaimableStatuses()) .containsExactlyInAnyOrder(JobStatus.RESOLVED, JobStatus.ACCEPTED); } }
2,232
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/ClusterStatusTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the ClusterStatus enum. * * @author tgianos * @since 2.0.0 */ class ClusterStatusTest { /** * Tests whether a valid cluster status is parsed correctly. * * @throws GeniePreconditionException if any precondition isn't met. */ @Test void testValidClusterStatus() throws GeniePreconditionException { Assertions .assertThat(ClusterStatus.parse(ClusterStatus.UP.name().toLowerCase())) .isEqualByComparingTo(ClusterStatus.UP); Assertions .assertThat(ClusterStatus.parse(ClusterStatus.OUT_OF_SERVICE.name().toLowerCase())) .isEqualByComparingTo(ClusterStatus.OUT_OF_SERVICE); Assertions .assertThat(ClusterStatus.parse(ClusterStatus.TERMINATED.name().toLowerCase())) .isEqualByComparingTo(ClusterStatus.TERMINATED); } /** * Tests whether an invalid cluster status throws exception. */ @Test void testInvalidClusterStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> ClusterStatus.parse("DOES_NOT_EXIST")); } /** * Tests whether an invalid cluster status throws exception. */ @Test void testBlankClusterStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> ClusterStatus.parse(" ")); } }
2,233
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/BaseDTOTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.external.util.GenieObjectMapper; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.UUID; /** * Unit tests for the BaseDTO class. * * @author tgianos * @since 3.0.0 */ class BaseDTOTest { /** * Test to make sure we can create a valid JSON string from a DTO object. */ @Test void canCreateValidJsonString() { final Application application = new Application.Builder( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ApplicationStatus.ACTIVE ).build(); final String json = application.toString(); Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException(); } }
2,234
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/JobRequestTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Stream; /** * Unit tests for the {@link JobRequest} class. * * @author tgianos * @since 3.0.0 */ class JobRequestTest { private static final String NAME = UUID.randomUUID().toString(); private static final String USER = UUID.randomUUID().toString(); private static final String VERSION = UUID.randomUUID().toString(); private static final List<String> COMMAND_ARGS = Lists.newArrayList(UUID.randomUUID().toString()); private static final List<ClusterCriteria> CLUSTER_CRITERIA = Lists.newArrayList( new ClusterCriteria( Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()) ), new ClusterCriteria( Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()) ), new ClusterCriteria( Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()) ) ); private static final Set<String> COMMAND_CRITERION = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString() ); private static Stream<Arguments> provideCommandArgsConstructorCases() { return Stream.of( Arguments.of(null, null, null), Arguments.of("", null, null), Arguments.of(null, Lists.newArrayList(), null), Arguments.of("foo bar", null, "foo bar"), Arguments.of(null, Lists.newArrayList("foo", "bar"), "foo bar"), Arguments.of("...", Lists.newArrayList("foo", "bar"), "foo bar") ); } @SuppressWarnings("deprecation") @Test void canBuildJobRequestDeprecated() { final JobRequest request = new JobRequest.Builder( NAME, USER, VERSION, StringUtils.join(COMMAND_ARGS, StringUtils.SPACE), CLUSTER_CRITERIA, COMMAND_CRITERION ).build(); Assertions.assertThat(request.getName()).isEqualTo(NAME); Assertions.assertThat(request.getUser()).isEqualTo(USER); Assertions.assertThat(request.getVersion()).isEqualTo(VERSION); Assertions .assertThat(request.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions.assertThat(request.getClusterCriterias()).isEqualTo(CLUSTER_CRITERIA); Assertions.assertThat(request.getCommandCriteria()).isEqualTo(COMMAND_CRITERION); Assertions.assertThat(request.getCpu().isPresent()).isFalse(); Assertions.assertThat(request.isDisableLogArchival()).isFalse(); Assertions.assertThat(request.getEmail().isPresent()).isFalse(); Assertions.assertThat(request.getConfigs()).isEmpty(); Assertions.assertThat(request.getDependencies()).isEmpty(); Assertions.assertThat(request.getGroup().isPresent()).isFalse(); Assertions.assertThat(request.getMemory().isPresent()).isFalse(); Assertions.assertThat(request.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(request.getCreated().isPresent()).isFalse(); Assertions.assertThat(request.getDescription().isPresent()).isFalse(); Assertions.assertThat(request.getId().isPresent()).isFalse(); Assertions.assertThat(request.getTags()).isEmpty(); Assertions.assertThat(request.getUpdated().isPresent()).isFalse(); Assertions.assertThat(request.getApplications()).isEmpty(); Assertions.assertThat(request.getTimeout().isPresent()).isFalse(); Assertions.assertThat(request.getGrouping().isPresent()).isFalse(); Assertions.assertThat(request.getGroupingInstance().isPresent()).isFalse(); } @SuppressWarnings("deprecation") @Test void canBuildJobRequest() { final JobRequest request = new JobRequest.Builder(NAME, USER, VERSION, CLUSTER_CRITERIA, COMMAND_CRITERION).build(); Assertions.assertThat(request.getName()).isEqualTo(NAME); Assertions.assertThat(request.getUser()).isEqualTo(USER); Assertions.assertThat(request.getVersion()).isEqualTo(VERSION); Assertions.assertThat(request.getCommandArgs().isPresent()).isFalse(); Assertions.assertThat(request.getClusterCriterias()).isEqualTo(CLUSTER_CRITERIA); Assertions.assertThat(request.getCommandCriteria()).isEqualTo(COMMAND_CRITERION); Assertions.assertThat(request.getCpu()).isNotPresent(); Assertions.assertThat(request.isDisableLogArchival()).isEqualTo(false); Assertions.assertThat(request.getEmail().isPresent()).isFalse(); Assertions.assertThat(request.getConfigs()).isEmpty(); Assertions.assertThat(request.getDependencies()).isEmpty(); Assertions.assertThat(request.getGroup().isPresent()).isFalse(); Assertions.assertThat(request.getMemory()).isNotPresent(); Assertions.assertThat(request.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(request.getCreated().isPresent()).isFalse(); Assertions.assertThat(request.getDescription().isPresent()).isFalse(); Assertions.assertThat(request.getId().isPresent()).isFalse(); Assertions.assertThat(request.getTags()).isEmpty(); Assertions.assertThat(request.getUpdated().isPresent()).isFalse(); Assertions.assertThat(request.getApplications()).isEmpty(); Assertions.assertThat(request.getTimeout().isPresent()).isFalse(); Assertions.assertThat(request.getGrouping().isPresent()).isFalse(); Assertions.assertThat(request.getGroupingInstance().isPresent()).isFalse(); Assertions.assertThat(request.getRuntime()).isNotNull(); } @SuppressWarnings("deprecation") @Test void canBuildJobRequestWithOptionalsDeprecated() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, CLUSTER_CRITERIA, COMMAND_CRITERION); builder.withCommandArgs(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); final int cpu = 5; builder.withCpu(cpu - 1); final boolean disableLogArchival = true; builder.withDisableLogArchival(disableLogArchival); final String email = UUID.randomUUID().toString() + "@netflix.com"; builder.withEmail(email); final Set<String> configs = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withConfigs(configs); final Set<String> dependencies = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withDependencies(dependencies); final String group = UUID.randomUUID().toString(); builder.withGroup(group); final int memory = 2048; builder.withMemory(memory - 1); final String setupFile = UUID.randomUUID().toString(); builder.withSetupFile(setupFile); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final List<String> applications = Lists.newArrayList( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withApplications(applications); final int timeout = 8970243; builder.withTimeout(timeout); final String grouping = UUID.randomUUID().toString(); builder.withGrouping(grouping); final String groupingInstance = UUID.randomUUID().toString(); builder.withGroupingInstance(groupingInstance); final Map<String, ContainerImage> images = new HashMap<>(); images.put( UUID.randomUUID().toString(), new ContainerImage.Builder() .withName(UUID.randomUUID().toString()) .withTag(UUID.randomUUID().toString()) .withArguments(Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString())) .build() ); final Runtime runtime = new Runtime.Builder() .withResources( new RuntimeResources.Builder() .withCpu(cpu) .withGpu(7) .withMemoryMb((long) memory) .withDiskMb(10_342L) .withNetworkMbps(512L) .build() ) .withImages(images) .build(); builder.withRuntime(runtime); final JobRequest request = builder.build(); Assertions.assertThat(request.getName()).isEqualTo(NAME); Assertions.assertThat(request.getUser()).isEqualTo(USER); Assertions.assertThat(request.getVersion()).isEqualTo(VERSION); Assertions .assertThat(request.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions.assertThat(request.getClusterCriterias()).isEqualTo(CLUSTER_CRITERIA); Assertions.assertThat(request.getCommandCriteria()).isEqualTo(COMMAND_CRITERION); Assertions.assertThat(request.getCpu().orElseThrow(IllegalArgumentException::new)).isEqualTo(cpu); Assertions.assertThat(request.isDisableLogArchival()).isEqualTo(disableLogArchival); Assertions.assertThat(request.getEmail().orElseThrow(IllegalArgumentException::new)).isEqualTo(email); Assertions.assertThat(request.getConfigs()).isEqualTo(configs); Assertions.assertThat(request.getDependencies()).isEqualTo(dependencies); Assertions.assertThat(request.getGroup().orElseThrow(IllegalArgumentException::new)).isEqualTo(group); Assertions.assertThat(request.getMemory().orElseThrow(IllegalArgumentException::new)).isEqualTo(memory); Assertions.assertThat(request.getSetupFile().orElseThrow(IllegalArgumentException::new)).isEqualTo(setupFile); Assertions.assertThat(request.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions .assertThat(request.getDescription().orElseThrow(IllegalArgumentException::new)) .isEqualTo(description); Assertions.assertThat(request.getId().orElseThrow(IllegalArgumentException::new)).isEqualTo(id); Assertions.assertThat(request.getTags()).isEqualTo(tags); Assertions.assertThat(request.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); Assertions.assertThat(request.getApplications()).isEqualTo(applications); Assertions.assertThat(request.getTimeout().orElseThrow(IllegalArgumentException::new)).isEqualTo(timeout); Assertions.assertThat(request.getGrouping().orElseThrow(IllegalArgumentException::new)).isEqualTo(grouping); Assertions .assertThat(request.getGroupingInstance().orElseThrow(IllegalArgumentException::new)) .isEqualTo(groupingInstance); Assertions.assertThat(request.getRuntime()).isEqualTo(runtime); } @SuppressWarnings("deprecation") @Test void canBuildJobRequestWithOptionals() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, CLUSTER_CRITERIA, COMMAND_CRITERION); builder.withCommandArgs(COMMAND_ARGS); final int cpu = 5; final boolean disableLogArchival = true; builder.withDisableLogArchival(disableLogArchival); final String email = UUID.randomUUID().toString() + "@netflix.com"; builder.withEmail(email); final Set<String> configs = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withConfigs(configs); final Set<String> dependencies = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withDependencies(dependencies); final String group = UUID.randomUUID().toString(); builder.withGroup(group); final int memory = 2048; final String setupFile = UUID.randomUUID().toString(); builder.withSetupFile(setupFile); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final List<String> applications = Lists.newArrayList( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); builder.withApplications(applications); final int timeout = 8970243; builder.withTimeout(timeout); final String grouping = UUID.randomUUID().toString(); builder.withGrouping(grouping); final String groupingInstance = UUID.randomUUID().toString(); builder.withGroupingInstance(groupingInstance); final Map<String, ContainerImage> images = new HashMap<>(); images.put( UUID.randomUUID().toString(), new ContainerImage.Builder() .withName(UUID.randomUUID().toString()) .withTag(UUID.randomUUID().toString()) .withArguments(Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString())) .build() ); final Runtime runtime = new Runtime.Builder() .withResources( new RuntimeResources.Builder() .withCpu(cpu) .withGpu(3) .withMemoryMb((long) memory) .withDiskMb(10_345L) .withNetworkMbps(1_243L) .build() ) .withImages(images) .build(); builder.withRuntime(runtime); final JobRequest request = builder.build(); Assertions.assertThat(request.getName()).isEqualTo(NAME); Assertions.assertThat(request.getUser()).isEqualTo(USER); Assertions.assertThat(request.getVersion()).isEqualTo(VERSION); Assertions .assertThat(request.getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)); Assertions.assertThat(request.getClusterCriterias()).isEqualTo(CLUSTER_CRITERIA); Assertions.assertThat(request.getCommandCriteria()).isEqualTo(COMMAND_CRITERION); Assertions.assertThat(request.getCpu().orElseThrow(IllegalArgumentException::new)).isEqualTo(cpu); Assertions.assertThat(request.isDisableLogArchival()).isEqualTo(disableLogArchival); Assertions.assertThat(request.getEmail().orElseThrow(IllegalArgumentException::new)).isEqualTo(email); Assertions.assertThat(request.getConfigs()).isEqualTo(configs); Assertions.assertThat(request.getDependencies()).isEqualTo(dependencies); Assertions.assertThat(request.getGroup().orElseThrow(IllegalArgumentException::new)).isEqualTo(group); Assertions.assertThat(request.getMemory().orElseThrow(IllegalArgumentException::new)).isEqualTo(memory); Assertions.assertThat(request.getSetupFile().orElseThrow(IllegalArgumentException::new)).isEqualTo(setupFile); Assertions.assertThat(request.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions .assertThat(request.getDescription().orElseThrow(IllegalArgumentException::new)) .isEqualTo(description); Assertions.assertThat(request.getId().orElseThrow(IllegalArgumentException::new)).isEqualTo(id); Assertions.assertThat(request.getTags()).isEqualTo(tags); Assertions.assertThat(request.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); Assertions.assertThat(request.getApplications()).isEqualTo(applications); Assertions.assertThat(request.getTimeout().orElseThrow(IllegalArgumentException::new)).isEqualTo(timeout); Assertions.assertThat(request.getGrouping().orElseThrow(IllegalArgumentException::new)).isEqualTo(grouping); Assertions .assertThat(request.getGroupingInstance().orElseThrow(IllegalArgumentException::new)) .isEqualTo(groupingInstance); Assertions.assertThat(request.getRuntime()).isEqualTo(runtime); } @Test void canBuildJobRequestWithNulls() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); builder.withCommandArgs((List<String>) null); builder.withEmail(null); builder.withConfigs(null); builder.withDependencies(null); builder.withGroup(null); builder.withSetupFile(null); builder.withCreated(null); builder.withDescription(null); builder.withId(null); builder.withTags(null); builder.withUpdated(null); builder.withApplications(null); builder.withRuntime(null); final JobRequest request = builder.build(); Assertions.assertThat(request.getName()).isEqualTo(NAME); Assertions.assertThat(request.getUser()).isEqualTo(USER); Assertions.assertThat(request.getVersion()).isEqualTo(VERSION); Assertions.assertThat(request.getCommandArgs().isPresent()).isFalse(); Assertions.assertThat(request.getClusterCriterias()).isEmpty(); Assertions.assertThat(request.getCommandCriteria()).isEmpty(); Assertions.assertThat(request.getCpu().isPresent()).isFalse(); Assertions.assertThat(request.isDisableLogArchival()).isFalse(); Assertions.assertThat(request.getEmail().isPresent()).isFalse(); Assertions.assertThat(request.getDependencies()).isEmpty(); Assertions.assertThat(request.getDependencies()).isEmpty(); Assertions.assertThat(request.getGroup().isPresent()).isFalse(); Assertions.assertThat(request.getMemory().isPresent()).isFalse(); Assertions.assertThat(request.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(request.getCreated().isPresent()).isFalse(); Assertions.assertThat(request.getDescription().isPresent()).isFalse(); Assertions.assertThat(request.getId().isPresent()).isFalse(); Assertions.assertThat(request.getTags()).isEmpty(); Assertions.assertThat(request.getUpdated().isPresent()).isFalse(); Assertions.assertThat(request.getApplications()).isEmpty(); Assertions.assertThat(request.getTimeout().isPresent()).isFalse(); Assertions.assertThat(request.getRuntime()).isNotNull(); } /** * Test equals. */ @Test void canFindEquality() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); builder.withEmail(null); builder.withConfigs(null); builder.withDependencies(null); builder.withGroup(null); builder.withSetupFile(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); builder.withApplications(null); final JobRequest jobRequest1 = builder.build(); final JobRequest jobRequest2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobRequest jobRequest3 = builder.build(); Assertions.assertThat(jobRequest1).isEqualTo(jobRequest2); Assertions.assertThat(jobRequest1).isNotEqualTo(jobRequest3); } /** * Test hash code. */ @Test void canUseHashCode() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); builder.withEmail(null); builder.withConfigs(null); builder.withDependencies(null); builder.withGroup(null); builder.withSetupFile(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); builder.withApplications(null); final JobRequest jobRequest1 = builder.build(); final JobRequest jobRequest2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobRequest jobRequest3 = builder.build(); Assertions.assertThat(jobRequest1.hashCode()).isEqualTo(jobRequest2.hashCode()); Assertions.assertThat(jobRequest1.hashCode()).isNotEqualTo(jobRequest3.hashCode()); } /** * Test to prove a bug with command args splitting with trailing whitespace was corrected. */ @Test void testCommandArgsEdgeCases() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); } /** * Test edge cases of building a job request with two overlapping fields: the legacy commandArgs (String) and the * new commandArguments (List of String). */ @ParameterizedTest @MethodSource("provideCommandArgsConstructorCases") void testCommandArgsConstructorEdgeCases( @Nullable final String commandArgs, @Nullable final List<String> commandArguments, @Nullable final String expectedCommandArgs ) { final JobRequest jobRequest = new JobRequest.Builder( "NAME", "USER", "VERSION", Lists.newArrayList(), Sets.newHashSet(), commandArgs, commandArguments ).build(); final String message = String.format( "Unexpected result when constructing JobRequest with commandArgs: %s and commandArguments: %s", commandArgs, commandArguments ); Assertions .assertThat(jobRequest.getCommandArgs().orElse(null)) .withFailMessage(message) .isEqualTo(expectedCommandArgs); } }
2,235
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/UserResourcesSummaryTest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Test UserResourcesSummary DTO. */ class UserResourcesSummaryTest { /** * Test constructor, accessors, equality. */ @Test void testUserJobCount() { final UserResourcesSummary dto = new UserResourcesSummary("foo", 3, 1024); Assertions.assertThat(dto.getUser()).isEqualTo("foo"); Assertions.assertThat(dto.getRunningJobsCount()).isEqualTo(3); Assertions.assertThat(dto.getUsedMemory()).isEqualTo(1024); Assertions.assertThat(dto).isEqualTo(new UserResourcesSummary("foo", 3, 1024)); Assertions.assertThat(dto).isNotEqualTo(new UserResourcesSummary("bar", 3, 1024)); Assertions.assertThat(dto).isNotEqualTo(new UserResourcesSummary("foo", 4, 1024)); Assertions.assertThat(dto).isNotEqualTo(new UserResourcesSummary("foo", 3, 2048)); Assertions.assertThat(dto.hashCode()).isEqualTo(new UserResourcesSummary("foo", 3, 1024).hashCode()); Assertions.assertThat(dto.hashCode()).isNotEqualTo(new UserResourcesSummary("bar", 3, 1024).hashCode()); Assertions.assertThat(dto.hashCode()).isNotEqualTo(new UserResourcesSummary("foo", 4, 1024).hashCode()); Assertions.assertThat(dto.hashCode()).isNotEqualTo(new UserResourcesSummary("foo", 3, 2048).hashCode()); } }
2,236
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/ApplicationTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Sets; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.test.suppliers.RandomSuppliers; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.time.Instant; import java.util.Set; import java.util.UUID; /** * Tests for the Application DTO. * * @author tgianos * @since 3.0.0 */ class ApplicationTest { private static final String NAME = UUID.randomUUID().toString(); private static final String USER = UUID.randomUUID().toString(); private static final String VERSION = UUID.randomUUID().toString(); /** * Test to make sure we can build an application using the default builder constructor. */ @Test void canBuildApplication() { final Application application = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE).build(); Assertions.assertThat(application.getName()).isEqualTo(NAME); Assertions.assertThat(application.getUser()).isEqualTo(USER); Assertions.assertThat(application.getVersion()).isEqualTo(VERSION); Assertions.assertThat(application.getStatus()).isEqualTo(ApplicationStatus.ACTIVE); Assertions.assertThat(application.getDependencies()).isEmpty(); Assertions.assertThat(application.getType().isPresent()).isFalse(); Assertions.assertThat(application.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(application.getConfigs()).isEmpty(); Assertions.assertThat(application.getCreated().isPresent()).isFalse(); Assertions.assertThat(application.getDescription().isPresent()).isFalse(); Assertions.assertThat(application.getId().isPresent()).isFalse(); Assertions.assertThat(application.getTags()).isEmpty(); Assertions.assertThat(application.getUpdated().isPresent()).isFalse(); Assertions.assertThat(application.getMetadata().isPresent()).isFalse(); } /** * Test to make sure we can build an application with all optional parameters. */ @Test void canBuildApplicationWithOptionals() { final Application.Builder builder = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE); final Set<String> dependencies = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withDependencies(dependencies); final String type = UUID.randomUUID().toString(); builder.withType(type); final String setupFile = UUID.randomUUID().toString(); builder.withSetupFile(setupFile); final Set<String> configs = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withConfigs(configs); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final Application application = builder.build(); Assertions.assertThat(application.getName()).isEqualTo(NAME); Assertions.assertThat(application.getUser()).isEqualTo(USER); Assertions.assertThat(application.getVersion()).isEqualTo(VERSION); Assertions.assertThat(application.getStatus()).isEqualTo(ApplicationStatus.ACTIVE); Assertions.assertThat(application.getDependencies()).isEqualTo(dependencies); Assertions.assertThat(application.getType().orElseGet(RandomSuppliers.STRING)).isEqualTo(type); Assertions.assertThat(application.getSetupFile().orElseGet(RandomSuppliers.STRING)).isEqualTo(setupFile); Assertions.assertThat(application.getConfigs()).isEqualTo(configs); Assertions.assertThat(application.getCreated().orElseGet(RandomSuppliers.INSTANT)).isEqualTo(created); Assertions .assertThat(application.getDescription().orElseThrow(IllegalArgumentException::new)) .isEqualTo(description); Assertions .assertThat(application.getId().orElseThrow(IllegalArgumentException::new)) .isEqualTo(id); Assertions .assertThat(application.getTags()) .isEqualTo(tags); Assertions .assertThat(application.getUpdated().orElseThrow(IllegalArgumentException::new)) .isEqualTo(updated); } /** * Make sure we can use both builder methods for metadata and that trying to use invalid JSON throws exception. * * @throws IOException on JSON error * @throws GeniePreconditionException on Invalid JSON */ @Test void canBuildWithMetadata() throws IOException, GeniePreconditionException { final ObjectMapper objectMapper = GenieObjectMapper.getMapper(); final String metadata = "{\"key1\":\"value1\",\"key2\":3}"; final JsonNode metadataNode = objectMapper.readTree(metadata); final Application.Builder builder = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE); builder.withMetadata(metadata); Assertions .assertThat( objectMapper.writeValueAsString( builder.build().getMetadata().orElseThrow(IllegalArgumentException::new) ) ) .isEqualTo(metadata); builder.withMetadata(metadataNode); Assertions .assertThat(builder.build().getMetadata().orElseThrow(IllegalArgumentException::new)) .isEqualTo(metadataNode); builder.withMetadata((JsonNode) null); Assertions.assertThat(builder.build().getMetadata().isPresent()).isFalse(); Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> builder.withMetadata("{I'm Not valid Json}")); } /** * Test to make sure we can build an application with null collection parameters. */ @Test void canBuildApplicationNullOptionals() { final Application.Builder builder = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE); builder.withDependencies(null); builder.withType(null); builder.withSetupFile(null); builder.withConfigs(null); builder.withCreated(null); builder.withDescription(null); builder.withId(null); builder.withTags(null); builder.withUpdated(null); final Application application = builder.build(); Assertions.assertThat(application.getName()).isEqualTo(NAME); Assertions.assertThat(application.getUser()).isEqualTo(USER); Assertions.assertThat(application.getVersion()).isEqualTo(VERSION); Assertions.assertThat(application.getStatus()).isEqualTo(ApplicationStatus.ACTIVE); Assertions.assertThat(application.getDependencies()).isEmpty(); Assertions.assertThat(application.getType().isPresent()).isFalse(); Assertions.assertThat(application.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(application.getConfigs()).isEmpty(); Assertions.assertThat(application.getCreated().isPresent()).isFalse(); Assertions.assertThat(application.getDescription().isPresent()).isFalse(); Assertions.assertThat(application.getId().isPresent()).isFalse(); Assertions.assertThat(application.getTags()).isEmpty(); Assertions.assertThat(application.getUpdated().isPresent()).isFalse(); } /** * Test equals. */ @Test void testEqualityAndHashCode() { final Application.Builder builder = new Application.Builder(NAME, USER, VERSION, ApplicationStatus.ACTIVE); builder.withDependencies(null); builder.withType(null); builder.withSetupFile(null); builder.withConfigs(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Application app1 = builder.build(); final Application app2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Application app3 = builder.build(); Assertions.assertThat(app1).isEqualTo(app2); Assertions.assertThat(app1).isNotEqualTo(app3); Assertions.assertThat(app1.hashCode()).isEqualTo(app2.hashCode()); Assertions.assertThat(app1.hashCode()).isNotEqualTo(app3.hashCode()); } }
2,237
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/ClusterCriteriaTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.Sets; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.Set; import java.util.UUID; /** * Tests for ClusterCriteria. * * @author tgianos * @since 2.0.0 */ class ClusterCriteriaTest { /** * Make sure the constructor create sets properly. */ @Test void canConstruct() { final Set<String> tags = Sets.newHashSet("tag1", "tag2"); final ClusterCriteria cc = new ClusterCriteria(tags); Assertions.assertThat(cc.getTags()).isEqualTo(tags); } /** * Test to make sure clients can't modify the internal state. */ @Test void cantModifyTags() { final Set<String> tags = Sets.newHashSet("tag1", "tag2"); final ClusterCriteria cc = new ClusterCriteria(tags); Assertions .assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> cc.getTags().add("this should fail")); } /** * Make sure we can use equals. */ @Test void canGetEquality() { final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); final ClusterCriteria clusterCriteria1 = new ClusterCriteria(tags); final ClusterCriteria clusterCriteria2 = new ClusterCriteria(tags); tags.add(UUID.randomUUID().toString()); final ClusterCriteria clusterCriteria3 = new ClusterCriteria(tags); Assert.assertEquals(clusterCriteria1, clusterCriteria2); Assert.assertNotEquals(clusterCriteria1, clusterCriteria3); } /** * Make sure we can use equals. */ @Test void canGetHashCode() { final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); final ClusterCriteria clusterCriteria1 = new ClusterCriteria(tags); final ClusterCriteria clusterCriteria2 = new ClusterCriteria(tags); tags.add(UUID.randomUUID().toString()); final ClusterCriteria clusterCriteria3 = new ClusterCriteria(tags); Assert.assertEquals(clusterCriteria1.hashCode(), clusterCriteria2.hashCode()); Assert.assertNotEquals(clusterCriteria1.hashCode(), clusterCriteria3.hashCode()); } }
2,238
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/JobMetadataTest.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.UUID; /** * Unit tests for the JobMetadata class. * * @author tgianos * @since 3.0.0 */ class JobMetadataTest { /** * Test to make sure we can successfully build a JobMetadata class. */ @Test void canBuild() { final String clientHost = UUID.randomUUID().toString(); final String userAgent = UUID.randomUUID().toString(); final int numAttachments = 38; final long totalSizeOfAttachments = 3809234L; final long stdOutSize = 80283L; final long stdErrSize = 8002343L; final JobMetadata metadata = new JobMetadata .Builder() .withClientHost(clientHost) .withUserAgent(userAgent) .withNumAttachments(numAttachments) .withTotalSizeOfAttachments(totalSizeOfAttachments) .withStdOutSize(stdOutSize) .withStdErrSize(stdErrSize) .build(); Assertions .assertThat(metadata.getClientHost().orElseThrow(IllegalArgumentException::new)) .isEqualTo(clientHost); Assertions.assertThat(metadata.getUserAgent().orElseThrow(IllegalArgumentException::new)).isEqualTo(userAgent); Assertions .assertThat(metadata.getNumAttachments().orElseThrow(IllegalArgumentException::new)) .isEqualTo(numAttachments); Assertions .assertThat(metadata.getTotalSizeOfAttachments().orElseThrow(IllegalArgumentException::new)) .isEqualTo(totalSizeOfAttachments); Assertions .assertThat(metadata.getStdOutSize().orElseThrow(IllegalArgumentException::new)) .isEqualTo(stdOutSize); Assertions .assertThat(metadata.getStdErrSize().orElseThrow(IllegalArgumentException::new)) .isEqualTo(stdErrSize); } /** * Test to make sure we can successfully find equality. */ @Test void canFindEquality() { final String clientHost = UUID.randomUUID().toString(); final String userAgent = UUID.randomUUID().toString(); final int numAttachments = 38; final long totalSizeOfAttachments = 3809234L; final JobMetadata.Builder builder = new JobMetadata .Builder() .withId(UUID.randomUUID().toString()) .withClientHost(clientHost) .withUserAgent(userAgent) .withNumAttachments(numAttachments) .withTotalSizeOfAttachments(totalSizeOfAttachments); final JobMetadata one = builder.build(); final JobMetadata two = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobMetadata three = builder.build(); Assertions.assertThat(one).isEqualTo(two); Assertions.assertThat(one).isNotEqualTo(three); Assertions.assertThat(one).isNotEqualTo(new Object()); } /** * Test to make sure we can successfully find equality. */ @Test void canUseHashCode() { final String clientHost = UUID.randomUUID().toString(); final String userAgent = UUID.randomUUID().toString(); final int numAttachments = 38; final long totalSizeOfAttachments = 3809234L; final JobMetadata.Builder builder = new JobMetadata .Builder() .withId(UUID.randomUUID().toString()) .withClientHost(clientHost) .withUserAgent(userAgent) .withNumAttachments(numAttachments) .withTotalSizeOfAttachments(totalSizeOfAttachments); final JobMetadata one = builder.build(); final JobMetadata two = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobMetadata three = builder.build(); Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode()); Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode()); } }
2,239
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/CommandStatusTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for the CommandStatus enum. * * @author tgianos * @since 2.0.0 */ class CommandStatusTest { /** * Tests whether a valid command status is parsed correctly. * * @throws GeniePreconditionException If any precondition isn't met. */ @Test void testValidCommandStatus() throws GeniePreconditionException { Assertions .assertThat(CommandStatus.parse(CommandStatus.ACTIVE.name().toLowerCase())) .isEqualByComparingTo(CommandStatus.ACTIVE); Assertions .assertThat(CommandStatus.parse(CommandStatus.DEPRECATED.name().toLowerCase())) .isEqualByComparingTo(CommandStatus.DEPRECATED); Assertions .assertThat(CommandStatus.parse(CommandStatus.INACTIVE.name().toLowerCase())) .isEqualByComparingTo(CommandStatus.INACTIVE); } /** * Tests whether an invalid command status throws exception. */ @Test void testInvalidCommandStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> CommandStatus.parse("DOES_NOT_EXIST")); } /** * Tests whether an invalid application status throws exception. */ @Test void testBlankCommandStatus() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy(() -> CommandStatus.parse(" ")); } }
2,240
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/JobExecutionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Unit tests for the JobExecution class. * * @author tgianos * @since 3.0.0 */ class JobExecutionTest { private static final String HOST_NAME = UUID.randomUUID().toString(); private static final long CHECK_DELAY = 280843L; private static final int PROCESS_ID = 134234; private static final Instant TIMEOUT = Instant.now(); private static final int MEMORY = 1_024; /** * Test to make sure can build a valid JobExecution using the builder. */ @Test void canBuildJob() { final JobExecution execution = new JobExecution.Builder(HOST_NAME).build(); Assertions.assertThat(execution.getHostName()).isEqualTo(HOST_NAME); Assertions.assertThat(execution.getProcessId().isPresent()).isFalse(); Assertions.assertThat(execution.getCheckDelay().isPresent()).isFalse(); Assertions.assertThat(execution.getTimeout().isPresent()).isFalse(); Assertions.assertThat(execution.getExitCode().isPresent()).isFalse(); Assertions.assertThat(execution.getCreated().isPresent()).isFalse(); Assertions.assertThat(execution.getId().isPresent()).isFalse(); Assertions.assertThat(execution.getUpdated().isPresent()).isFalse(); Assertions.assertThat(execution.getMemory().isPresent()).isFalse(); Assertions.assertThat(execution.getArchiveStatus().isPresent()).isFalse(); Assertions.assertThat(execution.getLauncherExt().isPresent()).isFalse(); Assertions.assertThat(execution.getRuntime()).isNotNull(); } /** * Test to make sure can build a valid JobExecution with optional parameters. */ @Test void canBuildJobWithOptionals() { final JobExecution.Builder builder = new JobExecution.Builder(HOST_NAME); builder.withCheckDelay(CHECK_DELAY); builder.withProcessId(PROCESS_ID); builder.withTimeout(TIMEOUT); builder.withMemory(MEMORY - 1); builder.withArchiveStatus(ArchiveStatus.ARCHIVED); final int exitCode = 0; builder.withExitCode(exitCode); final Instant created = Instant.now(); builder.withCreated(created); final String id = UUID.randomUUID().toString(); builder.withId(id); final Instant updated = Instant.now(); builder.withUpdated(updated); final JsonNode launcherExt = JsonNodeFactory.instance.objectNode(); builder.withLauncherExt(launcherExt); final Map<String, ContainerImage> images = new HashMap<>(); images.put( UUID.randomUUID().toString(), new ContainerImage.Builder().withName(UUID.randomUUID().toString()).build() ); final Runtime runtime = new Runtime.Builder() .withResources( new RuntimeResources.Builder() .withCpu(5) .withGpu(98) .withMemoryMb((long) MEMORY) .withDiskMb(324L) .withNetworkMbps(255L) .build() ) .withImages(images) .build(); builder.withRuntime(runtime); final JobExecution execution = builder.build(); Assertions.assertThat(execution.getHostName()).isEqualTo(HOST_NAME); Assertions .assertThat(execution.getProcessId().orElseThrow(IllegalArgumentException::new)) .isEqualTo(PROCESS_ID); Assertions .assertThat(execution.getCheckDelay().orElseThrow(IllegalArgumentException::new)) .isEqualTo(CHECK_DELAY); Assertions.assertThat(execution.getTimeout().orElseThrow(IllegalArgumentException::new)).isEqualTo(TIMEOUT); Assertions.assertThat(execution.getExitCode().orElseThrow(IllegalArgumentException::new)).isEqualTo(exitCode); Assertions.assertThat(execution.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions.assertThat(execution.getId().orElseThrow(IllegalArgumentException::new)).isEqualTo(id); Assertions.assertThat(execution.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); Assertions.assertThat(execution.getMemory().orElseThrow(IllegalArgumentException::new)).isEqualTo(MEMORY); Assertions.assertThat(execution.getArchiveStatus().orElseThrow(IllegalArgumentException::new)) .isEqualTo(ArchiveStatus.ARCHIVED); Assertions.assertThat(execution.getLauncherExt().orElseThrow(IllegalArgumentException::new)) .isEqualTo(launcherExt); Assertions.assertThat(execution.getRuntime()).isEqualTo(runtime); } /** * Test to make sure a JobExecution can be successfully built when nulls are inputted. */ @Test void canBuildJobWithNulls() { final JobExecution.Builder builder = new JobExecution.Builder(HOST_NAME); builder.withExitCode(null); builder.withProcessId(null); builder.withCheckDelay(null); builder.withTimeout(null); builder.withMemory(null); builder.withCreated(null); builder.withId(null); builder.withUpdated(null); builder.withArchiveStatus(null); builder.withLauncherExt(null); final JobExecution execution = builder.build(); Assertions.assertThat(execution.getHostName()).isEqualTo(HOST_NAME); Assertions.assertThat(execution.getProcessId().isPresent()).isFalse(); Assertions.assertThat(execution.getCheckDelay().isPresent()).isFalse(); Assertions.assertThat(execution.getTimeout().isPresent()).isFalse(); Assertions.assertThat(execution.getExitCode().isPresent()).isFalse(); Assertions.assertThat(execution.getCreated().isPresent()).isFalse(); Assertions.assertThat(execution.getId().isPresent()).isFalse(); Assertions.assertThat(execution.getUpdated().isPresent()).isFalse(); Assertions.assertThat(execution.getMemory().isPresent()).isFalse(); Assertions.assertThat(execution.getArchiveStatus().isPresent()).isFalse(); Assertions.assertThat(execution.getLauncherExt().isPresent()).isFalse(); } /** * Test equals. */ @Test void canFindEquality() { final JobExecution.Builder builder = new JobExecution.Builder(HOST_NAME); builder.withCreated(null); builder.withId(UUID.randomUUID().toString()); builder.withUpdated(null); final JobExecution jobExecution1 = builder.build(); final JobExecution jobExecution2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobExecution jobExecution3 = builder.build(); Assertions.assertThat(jobExecution1).isEqualTo(jobExecution2); Assertions.assertThat(jobExecution1).isNotEqualTo(jobExecution3); } /** * Test hash code. */ @Test void canUseHashCode() { final JobExecution.Builder builder = new JobExecution.Builder(HOST_NAME); builder.withCreated(null); builder.withId(UUID.randomUUID().toString()); builder.withUpdated(null); final JobExecution jobExecution1 = builder.build(); final JobExecution jobExecution2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final JobExecution jobExecution3 = builder.build(); Assertions.assertThat(jobExecution1.hashCode()).isEqualTo(jobExecution2.hashCode()); Assertions.assertThat(jobExecution1.hashCode()).isNotEqualTo(jobExecution3.hashCode()); } }
2,241
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Tests for DTOs. * * @author tgianos */ package com.netflix.genie.common.dto;
2,242
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/ClusterTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.Sets; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Set; import java.util.UUID; /** * Tests for the {@link Cluster} DTO. * * @author tgianos * @since 3.0.0 */ class ClusterTest { private static final String NAME = UUID.randomUUID().toString(); private static final String USER = UUID.randomUUID().toString(); private static final String VERSION = UUID.randomUUID().toString(); /** * Test to make sure we can build a cluster using the default builder constructor. */ @Test void canBuildCluster() { final Cluster cluster = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP).build(); Assertions.assertThat(cluster.getName()).isEqualTo(NAME); Assertions.assertThat(cluster.getUser()).isEqualTo(USER); Assertions.assertThat(cluster.getVersion()).isEqualTo(VERSION); Assertions.assertThat(cluster.getStatus()).isEqualTo(ClusterStatus.UP); Assertions.assertThat(cluster.getConfigs()).isEmpty(); Assertions.assertThat(cluster.getDependencies()).isEmpty(); Assertions.assertThat(cluster.getCreated().isPresent()).isFalse(); Assertions.assertThat(cluster.getDescription().isPresent()).isFalse(); Assertions.assertThat(cluster.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(cluster.getId().isPresent()).isFalse(); Assertions.assertThat(cluster.getTags()).isEmpty(); Assertions.assertThat(cluster.getUpdated().isPresent()).isFalse(); } /** * Test to make sure we can build a cluster with all optional parameters. */ @Test void canBuildClusterWithOptionals() { final Cluster.Builder builder = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP); final Set<String> configs = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withConfigs(configs); final Set<String> dependencies = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withDependencies(dependencies); final Instant created = Instant.now(); builder.withCreated(created); final String description = UUID.randomUUID().toString(); builder.withDescription(description); final String id = UUID.randomUUID().toString(); builder.withId(id); final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString()); builder.withTags(tags); final Instant updated = Instant.now(); builder.withUpdated(updated); final Cluster cluster = builder.build(); Assertions.assertThat(cluster.getName()).isEqualTo(NAME); Assertions.assertThat(cluster.getUser()).isEqualTo(USER); Assertions.assertThat(cluster.getVersion()).isEqualTo(VERSION); Assertions.assertThat(cluster.getStatus()).isEqualTo(ClusterStatus.UP); Assertions.assertThat(cluster.getConfigs()).isEqualTo(configs); Assertions.assertThat(cluster.getDependencies()).isEqualTo(dependencies); Assertions.assertThat(cluster.getCreated().orElseThrow(IllegalArgumentException::new)).isEqualTo(created); Assertions .assertThat(cluster.getDescription().orElseThrow(IllegalArgumentException::new)) .isEqualTo(description); Assertions .assertThat(cluster.getId().orElseThrow(IllegalArgumentException::new)) .isEqualTo(id); Assertions.assertThat(cluster.getTags()).isEqualTo(tags); Assertions.assertThat(cluster.getUpdated().orElseThrow(IllegalArgumentException::new)).isEqualTo(updated); } /** * Test to make sure we can build a cluster with null collection parameters. */ @Test void canBuildClusterNullOptionals() { final Cluster.Builder builder = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(null); builder.withTags(null); builder.withUpdated(null); final Cluster cluster = builder.build(); Assertions.assertThat(cluster.getName()).isEqualTo(NAME); Assertions.assertThat(cluster.getUser()).isEqualTo(USER); Assertions.assertThat(cluster.getVersion()).isEqualTo(VERSION); Assertions.assertThat(cluster.getStatus()).isEqualTo(ClusterStatus.UP); Assertions.assertThat(cluster.getConfigs()).isEmpty(); Assertions.assertThat(cluster.getDependencies()).isEmpty(); Assertions.assertThat(cluster.getCreated().isPresent()).isFalse(); Assertions.assertThat(cluster.getDescription().isPresent()).isFalse(); Assertions.assertThat(cluster.getSetupFile().isPresent()).isFalse(); Assertions.assertThat(cluster.getId().isPresent()).isFalse(); Assertions.assertThat(cluster.getTags()).isEmpty(); Assertions.assertThat(cluster.getUpdated().isPresent()).isFalse(); } /** * Test equals. */ @Test void canFindEquality() { final Cluster.Builder builder = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.UP); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Cluster cluster1 = builder.build(); final Cluster cluster2 = builder.build(); builder.withDescription(UUID.randomUUID().toString()); final Cluster cluster3 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Cluster cluster4 = builder.build(); Assertions.assertThat(cluster1).isEqualTo(cluster2); Assertions.assertThat(cluster1).isEqualTo(cluster3); Assertions.assertThat(cluster1).isNotEqualTo(cluster4); } /** * Test hash code. */ @Test void canUseHashCode() { final Cluster.Builder builder = new Cluster.Builder(NAME, USER, VERSION, ClusterStatus.TERMINATED); builder.withConfigs(null); builder.withDependencies(null); builder.withCreated(null); builder.withDescription(null); builder.withId(UUID.randomUUID().toString()); builder.withTags(null); builder.withUpdated(null); final Cluster cluster1 = builder.build(); final Cluster cluster2 = builder.build(); builder.withId(UUID.randomUUID().toString()); final Cluster cluster3 = builder.build(); Assertions.assertThat(cluster1.hashCode()).isEqualTo(cluster2.hashCode()); Assertions.assertThat(cluster1.hashCode()).isNotEqualTo(cluster3.hashCode()); } }
2,243
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/search/BaseSearchResultTest.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto.search; import com.netflix.genie.common.external.util.GenieObjectMapper; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.UUID; /** * Unit tests for the BaseSearchResult class. * * @author tgianos * @since 3.0.0 */ class BaseSearchResultTest { /** * Make sure the constructor and getters work properly. */ @Test void canConstruct() { final String id = UUID.randomUUID().toString(); final String name = UUID.randomUUID().toString(); final String user = UUID.randomUUID().toString(); final BaseSearchResult searchResult = new BaseSearchResult(id, name, user); Assertions.assertThat(searchResult.getId()).isEqualTo(id); Assertions.assertThat(searchResult.getName()).isEqualTo(name); Assertions.assertThat(searchResult.getUser()).isEqualTo(user); } /** * Make sure the equals function only acts on id. */ @Test void canFindEquality() { final String id = UUID.randomUUID().toString(); final BaseSearchResult searchResult1 = new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString()); final BaseSearchResult searchResult2 = new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString()); final BaseSearchResult searchResult3 = new BaseSearchResult( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); Assertions.assertThat(searchResult1).isEqualTo(searchResult2); Assertions.assertThat(searchResult1).isNotEqualTo(searchResult3); Assertions.assertThat(searchResult1.hashCode()).isEqualTo(searchResult2.hashCode()); Assertions.assertThat(searchResult1.hashCode()).isNotEqualTo(searchResult3.hashCode()); } /** * Test to make sure we can create a valid JSON string from a DTO object. */ @Test void canCreateValidJsonString() { final BaseSearchResult searchResult = new BaseSearchResult( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString() ); final String json = searchResult.toString(); Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException(); } }
2,244
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/search/JobSearchResultTest.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto.search; import com.netflix.genie.common.dto.JobStatus; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; import java.util.UUID; /** * Tests for the {@link JobSearchResult} DTO. * * @author tgianos * @since 3.0.0 */ class JobSearchResultTest { /** * Make sure constructor works. */ @Test void canConstruct() { final String id = UUID.randomUUID().toString(); final String name = UUID.randomUUID().toString(); final String user = UUID.randomUUID().toString(); final JobStatus status = JobStatus.FAILED; final Instant started = Instant.now(); final Instant finished = Instant.now(); final String clusterName = UUID.randomUUID().toString(); final String commandName = UUID.randomUUID().toString(); final JobSearchResult searchResult = new JobSearchResult(id, name, user, status, started, finished, clusterName, commandName); Assertions.assertThat(searchResult.getId()).isEqualTo(id); Assertions.assertThat(searchResult.getName()).isEqualTo(name); Assertions.assertThat(searchResult.getUser()).isEqualTo(user); Assertions.assertThat(searchResult.getStatus()).isEqualTo(status); Assertions.assertThat(searchResult.getStarted().orElseThrow(IllegalArgumentException::new)).isEqualTo(started); Assertions .assertThat(searchResult.getFinished().orElseThrow(IllegalArgumentException::new)) .isEqualTo(finished); Assertions .assertThat(searchResult.getClusterName().orElseThrow(IllegalArgumentException::new)) .isEqualTo(clusterName); Assertions .assertThat(searchResult.getCommandName().orElseThrow(IllegalArgumentException::new)) .isEqualTo(commandName); Assertions .assertThat(searchResult.getRuntime()) .isEqualByComparingTo(Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli())); final JobSearchResult searchResult2 = new JobSearchResult(id, name, user, status, null, null, null, null); Assertions.assertThat(searchResult2.getId()).isEqualTo(id); Assertions.assertThat(searchResult2.getName()).isEqualTo(name); Assertions.assertThat(searchResult.getUser()).isEqualTo(user); Assertions.assertThat(searchResult2.getStatus()).isEqualTo(status); Assertions.assertThat(searchResult2.getStarted().isPresent()).isFalse(); Assertions.assertThat(searchResult2.getFinished().isPresent()).isFalse(); Assertions.assertThat(searchResult2.getClusterName().isPresent()).isFalse(); Assertions.assertThat(searchResult2.getCommandName().isPresent()).isFalse(); Assertions.assertThat(searchResult2.getRuntime()).isEqualTo(Duration.ZERO); } }
2,245
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/dto/search/package-info.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Tests for search DTOs. * * @author tgianos * @since 3.0.0 */ package com.netflix.genie.common.dto.search;
2,246
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/util/JsonUtilsTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.util; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.collect.Lists; import com.netflix.genie.common.exceptions.GenieException; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; /** * Unit tests for the JsonUtils class. * * @author tgianos * @since 3.0.0 */ class JsonUtilsTest { /** * Test the constructor. */ @Test void canConstructInPackage() { Assertions.assertThat(new JsonUtils()).isNotNull(); } /** * Test to make sure we can marshall an Object to a JSON string. * * @throws GenieException On marshalling error */ @Test void canMarshall() throws GenieException { final List<String> strings = Lists.newArrayList("one", "two", "three"); Assertions.assertThat(JsonUtils.marshall(strings)).isEqualTo("[\"one\",\"two\",\"three\"]"); } /** * Test to make sure can successfully un-marshall a collection. * * @throws GenieException for any problems during the process */ @Test void canUnmarshall() throws GenieException { final String source = "[\"one\",\"two\",\"three\"]"; final TypeReference<List<String>> list = new TypeReference<List<String>>() { }; Assertions .assertThat(JsonUtils.unmarshall(source, list)) .isEqualTo(Lists.newArrayList("one", "two", "three")); Assertions.assertThat(JsonUtils.unmarshall(null, list)).isEqualTo(Lists.newArrayList()); } }
2,247
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/util/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes that test the Genie common utility classes. * * @author tgianos */ package com.netflix.genie.common.util;
2,248
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/util/TimeUtilsTest.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.util; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; /** * Unit tests for TimeUtils. * * @author tgianos * @since 3.0.0 */ class TimeUtilsTest { /** * Can get the duration for various cases. */ @Test void canGetDuration() { final long durationMillis = 50823L; final Duration duration = Duration.ofMillis(durationMillis); final Instant started = Instant.now(); final Instant finished = started.plusMillis(durationMillis); Assertions.assertThat(TimeUtils.getDuration(null, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(Instant.EPOCH, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(started, null)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, Instant.EPOCH)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, finished)).isEqualByComparingTo(duration); } }
2,249
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieNotFoundExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieNotFoundException}. * * @author tgianos * @since 2.0.0 */ class GenieNotFoundExceptionTest { private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GenieNotFoundException.class) .isThrownBy( () -> { throw new GenieNotFoundException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GenieNotFoundException.class) .isThrownBy( () -> { throw new GenieNotFoundException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } }
2,250
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GeniePreconditionExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GeniePreconditionException}. * * @author tgianos * @since 2.0.0 */ class GeniePreconditionExceptionTest { private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy( () -> { throw new GeniePreconditionException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_PRECON_FAILED)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GeniePreconditionException.class) .isThrownBy( () -> { throw new GeniePreconditionException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_PRECON_FAILED)); } }
2,251
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieBadRequestExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieBadRequestException}. * * @author tgianos * @since 2.0.0 */ class GenieBadRequestExceptionTest { private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GenieBadRequestException.class) .isThrownBy( () -> { throw new GenieBadRequestException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GenieBadRequestException.class) .isThrownBy( () -> { throw new GenieBadRequestException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST)); } }
2,252
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieException}. * * @author tgianos * @since 2.0.0 */ class GenieExceptionTest { private static final int ERROR_CODE = 404; private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testThreeArgConstructor() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } /** * Test the constructor. */ @Test void testTwoArgConstructorWithMessage() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } }
2,253
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieTimeoutExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieTimeoutException}. * * @author tgianos * @since 3.0.0 */ class GenieTimeoutExceptionTest { private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GenieTimeoutException.class) .isThrownBy( () -> { throw new GenieTimeoutException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_CLIENT_TIMEOUT)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GenieTimeoutException.class) .isThrownBy( () -> { throw new GenieTimeoutException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_CLIENT_TIMEOUT)); } }
2,254
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieServerExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieServerException}. * * @author tgianos * @since 2.0.0 */ class GenieServerExceptionTest { private static final String ERROR_MESSAGE = "Not Found"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GenieServerException.class) .isThrownBy( () -> { throw new GenieServerException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GenieServerException.class) .isThrownBy( () -> { throw new GenieServerException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR)); } }
2,255
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/GenieServerUnavailableExceptionTest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.HttpURLConnection; /** * Test the constructors of the {@link GenieServerUnavailableException}. * * @author tgianos * @since 2.0.0 */ class GenieServerUnavailableExceptionTest { private static final String ERROR_MESSAGE = "Cannot Run Jobs"; private static final IOException IOE = new IOException("IOException"); /** * Test the constructor. */ @Test void testTwoArgConstructor() { Assertions .assertThatExceptionOfType(GenieServerUnavailableException.class) .isThrownBy( () -> { throw new GenieServerUnavailableException(ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE)); } /** * Test the constructor. */ @Test void testMessageArgConstructor() { Assertions .assertThatExceptionOfType(GenieServerUnavailableException.class) .isThrownBy( () -> { throw new GenieServerUnavailableException(ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE)); } }
2,256
0
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/test/java/com/netflix/genie/common/exceptions/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes that test the Genie exception code. * * @author tgianos */ package com.netflix.genie.common.exceptions;
2,257
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ClusterStatus.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.apache.commons.lang3.StringUtils; /** * The possible statuses for a cluster. * * @author tgianos */ public enum ClusterStatus { /** * Cluster is UP, and accepting jobs. */ UP, /** * Cluster may be running, but not accepting job submissions. */ OUT_OF_SERVICE, /** * Cluster is no-longer running, and is terminated. */ TERMINATED; /** * Parse cluster status. * * @param value string to parse/convert into cluster status * @return UP, OUT_OF_SERVICE, TERMINATED if match * @throws GeniePreconditionException on invalid value */ public static ClusterStatus parse(final String value) throws GeniePreconditionException { if (StringUtils.isNotBlank(value)) { for (final ClusterStatus status : ClusterStatus.values()) { if (value.equalsIgnoreCase(status.toString())) { return status; } } } throw new GeniePreconditionException( "Unacceptable cluster status. Must be one of {UP, OUT_OF_SERVICE, TERMINATED}" ); } }
2,258
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/CommandStatus.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.apache.commons.lang3.StringUtils; /** * The available statuses for Commands. * * @author tgianos */ public enum CommandStatus { /** * Command is active, and in-use. */ ACTIVE, /** * Command is deprecated, and will be made inactive in the future. */ DEPRECATED, /** * Command is inactive, and not in-use. */ INACTIVE; /** * Parse command status. * * @param value string to parse/convert into command status * @return ACTIVE, DEPRECATED, INACTIVE if match * @throws GeniePreconditionException on invalid value */ public static CommandStatus parse(final String value) throws GeniePreconditionException { if (StringUtils.isNotBlank(value)) { for (final CommandStatus status : CommandStatus.values()) { if (value.equalsIgnoreCase(status.toString())) { return status; } } } throw new GeniePreconditionException( "Unacceptable command status. Must be one of {ACTIVE, DEPRECATED, INACTIVE}" ); } }
2,259
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Application.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.util.Optional; /** * Application DTO. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = Application.Builder.class) public class Application extends ExecutionEnvironmentDTO { private static final long serialVersionUID = 212266105066344180L; @NotNull(message = "An application status is required") private final ApplicationStatus status; private final String type; /** * Constructor only accessible via builder build() method. * * @param builder The builder to get data from */ protected Application(final Builder builder) { super(builder); this.status = builder.bStatus; this.type = builder.bType; } /** * Get the type of this application. * * @return The type as an Optional */ public Optional<String> getType() { return Optional.ofNullable(this.type); } /** * A builder to create applications. * * @author tgianos * @since 3.0.0 */ public static class Builder extends ExecutionEnvironmentDTO.Builder<Builder> { private final ApplicationStatus bStatus; private String bType; /** * Constructor which has required fields. * * @param name The name to use for the Application * @param user The user to use for the Application * @param version The version to use for the Application * @param status The status of the Application */ public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final ApplicationStatus status ) { super(name, user, version); this.bStatus = status; } /** * Set the type of this application. * * @param type The type (e.g. Hadoop, Spark, etc) for grouping applications * @return The builder */ public Builder withType(@Nullable final String type) { this.bType = type; return this; } /** * Build the application. * * @return Create the final read-only Application instance */ public Application build() { return new Application(this); } } }
2,260
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Criterion.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Representation of various criterion options available. Used for determining which cluster and command are used to * execute a job. * * @author tgianos * @since 4.3.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @JsonDeserialize(builder = Criterion.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class Criterion implements Serializable { private static final long serialVersionUID = -8382495858646428806L; private final String id; private final String name; private final String version; private final String status; private final ImmutableSet< @NotEmpty(message = "A tag can't be an empty string") @Size(max = 255, message = "A tag can't be longer than 255 characters") String> tags; /** * Copy the contents of the given {@link Criterion} but use the supplied status. * * @param criterion The {@link Criterion} to copy * @param status The status to use */ public Criterion(final Criterion criterion, final String status) { this.id = criterion.id; this.name = criterion.name; this.version = criterion.version; this.status = status; this.tags = ImmutableSet.copyOf(criterion.getTags()); } private Criterion(final Builder builder) throws IllegalArgumentException { this.id = builder.bId; this.name = builder.bName; this.version = builder.bVersion; this.status = builder.bStatus; this.tags = builder.bTags == null ? ImmutableSet.of() : ImmutableSet.copyOf(builder.bTags); if ( StringUtils.isBlank(this.id) && StringUtils.isBlank(this.name) && StringUtils.isBlank(this.version) && StringUtils.isBlank(this.status) && this.tags.isEmpty() ) { throw new IllegalArgumentException("Invalid criterion. One of the fields must have a valid value"); } } /** * Get the id of the resource desired if it exists. * * @return {@link Optional} wrapping the id */ public Optional<String> getId() { return Optional.ofNullable(this.id); } /** * Get the name of the resource desired if it exists. * * @return {@link Optional} wrapping the name */ public Optional<String> getName() { return Optional.ofNullable(this.name); } /** * Get the version of the resource desired if it exists. * * @return {@link Optional} wrapping the version */ public Optional<String> getVersion() { return Optional.ofNullable(this.version); } /** * Get the desired status of the resource if it has been set by the creator. * * @return {@link Optional} wrapping the status */ public Optional<String> getStatus() { return Optional.ofNullable(this.status); } /** * Get the set of tags the creator desires the resource to have if any were set. * * @return An immutable set of strings. Any attempt at modification will throw an exception. */ public Set<String> getTags() { return this.tags; } /** * Builder for creating a Criterion instance. * * @author tgianos * @since 4.0.0 */ public static class Builder { private String bId; private String bName; private String bVersion; private String bStatus; private ImmutableSet<String> bTags; /** * Set the id of the resource (cluster, command, etc) to use. * * @param id The id * @return The builder */ public Builder withId(@Nullable final String id) { this.bId = StringUtils.isBlank(id) ? null : id; return this; } /** * Set the name of the resource (cluster, command, etc) to search for. * * @param name The name of the resource * @return The builder */ public Builder withName(@Nullable final String name) { this.bName = StringUtils.isBlank(name) ? null : name; return this; } /** * Set the version of the resource (cluster, command, etc) to search for. * * @param version The version of the resource * @return The builder */ public Builder withVersion(@Nullable final String version) { this.bVersion = StringUtils.isBlank(version) ? null : version; return this; } /** * Set the status to search for. Overrides default status of resource in search algorithm. * * @param status The status to override the default with * @return The builder */ public Builder withStatus(@Nullable final String status) { this.bStatus = StringUtils.isBlank(status) ? null : status; return this; } /** * Set the tags to use in the search. * * @param tags The tags. Any blanks will be removed * @return The builder */ public Builder withTags(@Nullable final Set<String> tags) { this.bTags = tags == null ? ImmutableSet.of() : ImmutableSet.copyOf( tags .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toSet())); return this; } /** * Build an immutable Criterion. A precondition exception will be thrown if all of the fields are empty. * * @return A criterion which is completely immutable. * @throws IllegalArgumentException A valid Criterion must have at least one field populated */ public Criterion build() throws IllegalArgumentException { return new Criterion(this); } } }
2,261
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/JobStatusMessages.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; /** * Constant strings for status message attached to a job after it terminates. * * @author mprimi * @since 3.0.7 */ public final class JobStatusMessages { //TODO this class could go away and we could fold this into JobStatus /** * The message for when the agent is preparing to launch the job. */ public static final String JOB_INITIALIZING = "Preparing to launch job"; /** * The status message while a job is actively running. */ public static final String JOB_RUNNING = "Job is Running."; /** * Job killed because maximum run time was exceeded. */ public static final String JOB_EXCEEDED_TIMEOUT = "Job exceeded timeout."; /** * Job killed because a limit related to the size of the directory was exceeded. */ public static final String JOB_EXCEEDED_FILES_LIMIT = "Job files exceeded limit."; /** * Job killed by user. */ public static final String JOB_KILLED_BY_USER = "Job was killed by user."; /** * Job killed by system. */ public static final String JOB_KILLED_BY_SYSTEM = "Job was killed by system."; /** * Job completed successfully. */ public static final String JOB_FINISHED_SUCCESSFULLY = "Job finished successfully."; /** * Job terminated with non-zero exit code. */ public static final String JOB_FAILED = "Job failed."; /** * Job failed in in the setup portion of the run script (setting environment or running resources setup scripts). */ public static final String JOB_SETUP_FAILED = "Job script failed during setup. See setup log for details"; /** * Agent failed to claim job id, job record does not exist, it is not in a state where it can be claimed. */ public static final String FAILED_TO_CLAIM_JOB = "Failed to claim job"; /** * The agent failed to create a directory for the job. */ public static final String FAILED_TO_CREATE_JOB_DIRECTORY = "Failed to create job directory"; /** * The agent failed to compose or write a job script. */ public static final String FAILED_TO_CREATE_JOB_SCRIPT = "Failed to create job script"; /** * The agent failed to download dependencies. They may not exist, or the agent may not have the required permission * to read them or write them on local disk. */ public static final String FAILED_TO_DOWNLOAD_DEPENDENCIES = "Failed to download dependencies"; /** * The server refused to let the agent run a job, refusal is based on agent version or hostname. */ public static final String FAILED_AGENT_SERVER_HANDSHAKE = "Failed agent/server handshake"; /** * The agent encountered an error while attempting to launch the job process. */ public static final String FAILED_TO_LAUNCH_JOB = "Failed to launch job"; /** * The agent failed to reserve the job id, possibly because it is already in use. */ public static final String FAILED_TO_RESERVE_JOB_ID = "Failed to reserve job id"; /** * The agent encountered an unhandled error while waiting for the job process to complete. */ public static final String FAILED_TO_WAIT_FOR_JOB_COMPLETION = "Failed to wait for job completion"; /** * The agent could not determine what state the job is in. */ public static final String UNKNOWN_JOB_STATE = "Unknown job state"; /** * The agent failed to update the persisted job status via server. */ public static final String FAILED_TO_UPDATE_STATUS = "Failed to update job status"; /** * The agent failed to start up (before any job-specific action is taken). */ public static final String FAILED_AGENT_STARTUP = "Failed to initialize agent"; /** * The agent could not retrieve the job specifications. * Could mean it does not exist or cannot be resolved. */ public static final String FAILED_TO_OBTAIN_JOB_SPECIFICATION = "Failed to obtain job specification"; /** * The agent failed to initialize a required runtime service (file stream, heartbeat, kill). */ public static final String FAILED_TO_START_SERVICE = "Failed to start service"; /** * The agent failed to configure itself, probably due to invalid command-line arguments. */ public static final String FAILED_AGENT_CONFIGURATION = "Failed to configure execution"; /** * Could not resolve the job. */ public static final String FAILED_TO_RESOLVE_JOB = "Failed to resolve job given original request and available resources"; /** * While job was running, server status was set to something else (probably marked failed by the leader after * the agent was disconnected for too long). */ public static final String JOB_MARKED_FAILED = "The job status changed server-side while the job was running"; /** * Job resolution fails due to runtime error (i.e. NOT due to unsatisfiable constraints). */ public static final String RESOLUTION_RUNTIME_ERROR = "Runtime error during job resolution"; /** * Private constructor, this class is not meant to be instantiated. */ private JobStatusMessages() { } }
2,262
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ExecutionEnvironmentDTO.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.google.common.collect.ImmutableSet; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Size; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * Base class DTO for DTOs which require a setup file. * * @author tgianos * @since 3.0.0 */ @Getter public abstract class ExecutionEnvironmentDTO extends CommonDTO { private static final long serialVersionUID = 2116254045303538065L; private final Set<String> configs; private final Set<String> dependencies; @Size(max = 1024, message = "Max length of the setup file is 1024 characters") private final String setupFile; /** * Constructor. * * @param builder The builder to use */ @SuppressWarnings("unchecked") ExecutionEnvironmentDTO(@Valid final Builder builder) { super(builder); this.setupFile = builder.bSetupFile; this.configs = ImmutableSet.copyOf(builder.bConfigs); this.dependencies = ImmutableSet.copyOf(builder.bDependencies); } /** * Get the setup file. * * @return The setup file location as an Optional */ public Optional<String> getSetupFile() { return Optional.ofNullable(this.setupFile); } /** * A builder for helping to create instances. * * @param <T> The type of builder that extends this builder for final implementation * @author tgianos * @since 3.0.0 */ // NOTE: These abstract class builders are marked public not protected due to a JDK bug from 1999 which caused // issues with Clojure clients which use reflection to make the Java API calls. // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4283544 // Setting them to public seems to have solved the issue at the expense of "proper" code design @SuppressWarnings("unchecked") public abstract static class Builder<T extends Builder> extends CommonDTO.Builder<T> { private final Set<String> bConfigs = new HashSet<>(); private final Set<String> bDependencies = new HashSet<>(); private String bSetupFile; /** * Constructor with required fields. * * @param name The name to use for the resource * @param user The user to user for the resource * @param version The version to use for the resource */ protected Builder(final String name, final String user, final String version) { super(name, user, version); } /** * The setup file to use with the resource if desired. * * @param setupFile The setup file location * @return The builder */ public T withSetupFile(@Nullable final String setupFile) { this.bSetupFile = setupFile; return (T) this; } /** * The configs to use with the resource if desired. * * @param configs The configuration file locations * @return The builder */ public T withConfigs(@Nullable final Set<String> configs) { this.bConfigs.clear(); if (configs != null) { this.bConfigs.addAll(configs); } return (T) this; } /** * Set the dependencies for the entity if desired. * * @param dependencies The dependencies * @return The builder */ public T withDependencies(@Nullable final Set<String> dependencies) { this.bDependencies.clear(); if (dependencies != null) { this.bDependencies.addAll(dependencies); } return (T) this; } } }
2,263
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Job.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.netflix.genie.common.util.JsonUtils; import com.netflix.genie.common.util.TimeUtils; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; /** * Read only data transfer object representing a Job in the Genie system. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = Job.Builder.class) public class Job extends CommonDTO { private static final long serialVersionUID = -4218933066048954819L; @NotNull(message = "A valid job status is required") private final JobStatus status; @Size(max = 255, message = "Max length of the status message is 255 characters") private final String statusMsg; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant started; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant finished; @Size(max = 1024, message = "Max character length is 1024 characters for the archive location") private final String archiveLocation; @Size(max = 255, message = "Max character length is 255 characters for the cluster name") private final String clusterName; @Size(max = 255, message = "Max character length is 255 characters for the command name") private final String commandName; @NotNull @JsonSerialize(using = ToStringSerializer.class) private final Duration runtime; @Size(max = 10_000, message = "The maximum number of characters for the command arguments is 10,000") private final String commandArgs; private final String grouping; private final String groupingInstance; /** * Constructor used by the builder. * * @param builder The builder to use */ protected Job(@Valid final Builder builder) { super(builder); this.commandArgs = builder.bCommandArgs; this.status = builder.bStatus; this.statusMsg = builder.bStatusMsg; this.started = builder.bStarted; this.finished = builder.bFinished; this.archiveLocation = builder.bArchiveLocation; this.clusterName = builder.bClusterName; this.commandName = builder.bCommandName; this.grouping = builder.bGrouping; this.groupingInstance = builder.bGroupingInstance; this.runtime = TimeUtils.getDuration(this.started, this.finished); } /** * Get the arguments to be put on the command line along with the command executable. * * @return The command arguments */ public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } /** * Get the current status message. * * @return The status message as an optional */ public Optional<String> getStatusMsg() { return Optional.ofNullable(this.statusMsg); } /** * Get the archive location for the job if there is one. * * @return The archive location */ public Optional<String> getArchiveLocation() { return Optional.ofNullable(this.archiveLocation); } /** * Get the name of the cluster running the job if there currently is one. * * @return The name of the cluster where the job is running */ public Optional<String> getClusterName() { return Optional.ofNullable(this.clusterName); } /** * Get the name of the command running this job if there currently is one. * * @return The name of the command */ public Optional<String> getCommandName() { return Optional.ofNullable(this.commandName); } /** * Get the grouping for this job if there currently is one. * * @return The grouping * @since 3.3.0 */ public Optional<String> getGrouping() { return Optional.ofNullable(this.grouping); } /** * Get the grouping instance for this job if there currently is one. * * @return The grouping instance * @since 3.3.0 */ public Optional<String> getGroupingInstance() { return Optional.ofNullable(this.groupingInstance); } /** * Get the time the job started. * * @return The started time or null if not set */ public Optional<Instant> getStarted() { return Optional.ofNullable(this.started); } /** * Get the time the job finished. * * @return The finished time or null if not set */ public Optional<Instant> getFinished() { return Optional.ofNullable(this.finished); } /** * A builder to create jobs. * * @author tgianos * @since 3.0.0 */ public static class Builder extends CommonDTO.Builder<Builder> { private String bCommandArgs; private JobStatus bStatus = JobStatus.INIT; private String bStatusMsg; private Instant bStarted; private Instant bFinished; private String bArchiveLocation; private String bClusterName; private String bCommandName; private String bGrouping; private String bGroupingInstance; /** * Constructor which has required fields. * * @param name The name to use for the Job * @param user The user to use for the Job * @param version The version to use for the Job * @since 3.3.0 */ @JsonCreator public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version ) { super(name, user, version); } /** * Constructor which has required fields. * <p> * Deprecated: Command args is optional. Use new constructor. Will be removed in 4.0.0 * * @param name The name to use for the Job * @param user The user to use for the Job * @param version The version to use for the Job * @param commandArgs The command arguments used for this job. Max length 10,000 characters * @see #Builder(String, String, String) */ @Deprecated public Builder( final String name, final String user, final String version, @Nullable final String commandArgs ) { super(name, user, version); this.bCommandArgs = StringUtils.isBlank(commandArgs) ? null : commandArgs; } /** * The command arguments to use in conjunction with the command executable selected for this job. * <p> * DEPRECATED: This API will be removed in 4.0.0 in favor of the List based method for improved control over * escaping of arguments. * * @param commandArgs The command args. The max length is 10,000 characters * @return The builder * @since 3.3.0 * @deprecated See {@link #withCommandArgs(List)} */ @Deprecated public Builder withCommandArgs(@Nullable final String commandArgs) { this.bCommandArgs = StringUtils.isBlank(commandArgs) ? null : commandArgs; return this; } /** * The command arguments to use in conjunction with the command executable selected for this job. * * @param commandArgs The command args. The maximum combined size of the command args plus 1 space character * between each argument must be less than or equal to 10,000 characters * @return The builder * @since 3.3.0 */ public Builder withCommandArgs(@Nullable final List<String> commandArgs) { if (commandArgs != null) { this.bCommandArgs = StringUtils.join(commandArgs, StringUtils.SPACE); if (StringUtils.isBlank(this.bCommandArgs)) { this.bCommandArgs = null; } } else { this.bCommandArgs = null; } return this; } /** * Set the execution cluster name for this job. * * @param clusterName The execution cluster name * @return The builder */ public Builder withClusterName(@Nullable final String clusterName) { this.bClusterName = clusterName; return this; } /** * Set the name of the command used to run this job. * * @param commandName The name of the command * @return The builder */ public Builder withCommandName(@Nullable final String commandName) { this.bCommandName = commandName; return this; } /** * Set the status of the job. * * @param status The status * @return The builder * @see JobStatus */ public Builder withStatus(final JobStatus status) { this.bStatus = status; return this; } /** * Set the detailed status message of the job. * * @param statusMsg The status message * @return The builder */ public Builder withStatusMsg(@Nullable final String statusMsg) { this.bStatusMsg = statusMsg; return this; } /** * Set the started time of the job. * * @param started The started time of the job * @return The builder */ public Builder withStarted(@Nullable final Instant started) { this.bStarted = started; return this; } /** * Set the finished time of the job. * * @param finished The time the job finished * @return The builder */ public Builder withFinished(@Nullable final Instant finished) { this.bFinished = finished; return this; } /** * Set the archive location of the job. * * @param archiveLocation The location where the job results are archived * @return The builder */ public Builder withArchiveLocation(@Nullable final String archiveLocation) { this.bArchiveLocation = archiveLocation; return this; } /** * Set the grouping to use for this job. * * @param grouping The grouping * @return The builder * @since 3.3.0 */ public Builder withGrouping(@Nullable final String grouping) { this.bGrouping = grouping; return this; } /** * Set the grouping instance to use for this job. * * @param groupingInstance The grouping instance * @return The builder * @since 3.3.0 */ public Builder withGroupingInstance(@Nullable final String groupingInstance) { this.bGroupingInstance = groupingInstance; return this; } /** * Build the job. * * @return Create the final read-only Job instance */ public Job build() { return new Job(this); } } }
2,264
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/UserResourcesSummary.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * A summary of the resources used by a given user. * * @author mprimi * @since 4.0.0 */ @AllArgsConstructor @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class UserResourcesSummary { private final String user; private final long runningJobsCount; private final long usedMemory; }
2,265
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Command.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * A command data transfer object. After creation, it is read-only. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = Command.Builder.class) public class Command extends ExecutionEnvironmentDTO { /** * The default amount of time to wait between job process checks. */ public static final long DEFAULT_CHECK_DELAY = 10000L; private static final long serialVersionUID = -3559641165667609041L; @NotNull(message = "A valid command status is required") private final CommandStatus status; @NotEmpty(message = "An executable is required") @Size(max = 1024, message = "Executable path can't be longer than 1024 characters") private final String executable; @NotEmpty(message = "An executable is required") private final List<@NotEmpty @Size(max = 1024) String> executableAndArguments; @Deprecated private final long checkDelay; @Min( value = 1, message = "The minimum amount of memory if desired is 1 MB. Probably should be much more than that" ) @Deprecated private final Integer memory; private final List<Criterion> clusterCriteria; private final Runtime runtime; /** * Constructor used by the builder. * * @param builder The builder to get data from */ protected Command(@Valid final Builder builder) { super(builder); this.status = builder.bStatus; this.checkDelay = DEFAULT_CHECK_DELAY; if (!builder.bExecutableAndArguments.isEmpty()) { this.executableAndArguments = Collections.unmodifiableList( new ArrayList<>(builder.bExecutableAndArguments) ); this.executable = StringUtils.join(builder.bExecutableAndArguments, ' '); } else if (builder.bExecutable != null && !builder.bExecutable.isEmpty()) { this.executable = builder.bExecutable; this.executableAndArguments = Collections.unmodifiableList( Arrays.asList(StringUtils.split(builder.bExecutable, ' ')) ); } else { throw new IllegalArgumentException("Cannot build command without 'executable' OR 'executableAndArguments'"); } this.clusterCriteria = Collections.unmodifiableList(new ArrayList<>(builder.bClusterCriteria)); this.runtime = new Runtime.Builder() .withResources(builder.bRuntimeResources.build()) .withImages(builder.bImages) .build(); this.memory = this.runtime .getResources() .getMemoryMb() .flatMap(mem -> Optional.of(mem.intValue())) .orElse(null); } /** * Get the default amount of memory (in MB) to use for jobs which use this command. * * @return Optional of the amount of memory as it could be null if none set * @deprecated Use runtime instead */ @Deprecated public Optional<Integer> getMemory() { return Optional.ofNullable(this.memory); } /** * A builder to create commands. * * @author tgianos * @since 3.0.0 */ public static class Builder extends ExecutionEnvironmentDTO.Builder<Builder> { private final CommandStatus bStatus; private final List<String> bExecutableAndArguments = new ArrayList<>(); private final List<Criterion> bClusterCriteria = new ArrayList<>(); private String bExecutable; private final RuntimeResources.Builder bRuntimeResources = new RuntimeResources.Builder(); private final Map<String, ContainerImage> bImages = new HashMap<>(); /** * Constructor which has required fields. * * @param name The name to use for the Command * @param user The user to use for the Command * @param version The version to use for the Command * @param status The status of the Command * @param executable The executable for the command * @param ignoredCheckDelay Ignored. Here for backwards compatibility. * @deprecated Use {@link #Builder(String, String, String, CommandStatus, List)} */ @Deprecated public Builder( final String name, final String user, final String version, final CommandStatus status, final String executable, final long ignoredCheckDelay ) { super(name, user, version); this.bStatus = status; this.bExecutable = executable; } /** * Constructor with required fields. * * @param name The name to use for the Command * @param user The user to use for the Command * @param version The version to use for the Command * @param status The status of the Command * @param executableAndArguments The executable for the command and its fixed arguments * @param ignoredCheckDelay Ignored. Here for backwards compatibility. * @deprecated Use {@link #Builder(String, String, String, CommandStatus, List)} */ @Deprecated public Builder( final String name, final String user, final String version, final CommandStatus status, final List<String> executableAndArguments, final long ignoredCheckDelay ) { super(name, user, version); this.bStatus = status; this.bExecutableAndArguments.addAll(executableAndArguments); } /** * Constructor with required fields. * * @param name The name to use for the Command * @param user The user to use for the Command * @param version The version to use for the Command * @param status The status of the Command * @param executableAndArguments The executable for the command and its fixed arguments */ public Builder( final String name, final String user, final String version, final CommandStatus status, final List<String> executableAndArguments ) { super(name, user, version); this.bStatus = status; this.bExecutableAndArguments.addAll(executableAndArguments); } /* * This constructor is provided just for JSON deserialization and considers both the old 'executable' and the * new 'executableAndArguments' fields optional for API backward compatibility. */ @JsonCreator Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final CommandStatus status ) { super(name, user, version); this.bStatus = status; } /** * Set the amount of memory (in MB) to default jobs run with this command to use. * * @param memory The default amount of memory (in MB) for jobs to use * @return The builder * @deprecated Use {@link #withRuntime(Runtime)} instead */ @Deprecated public Builder withMemory(@Nullable final Integer memory) { this.bRuntimeResources.withMemoryMb(memory == null ? null : memory.longValue()); return this; } /** * Set the executable and its fixed arguments for this command. * Note that this string is tokenized with a naive strategy (split on space) to break apart the executable from * its fixed arguments. Escape characters and quotes are ignored in this process. To avoid this tokenization, * use {@link #withExecutableAndArguments(List)} * * @param executable the executable, possibly followed by arguments * @return The builder * @deprecated this setter is provided transitionally to make both 'executable' and 'executableAndArguments' * optional for API backward compatibility. The proper way to construct a Command is via the constructor * {@link #Builder(String, String, String, CommandStatus, List, long)}. */ @Deprecated public Builder withExecutable(final String executable) { this.bExecutable = executable; return this; } /** * Set the executable and its fixed arguments for this command. * * @param executableAndArguments the executable and its argument * @return The builder * @deprecated this setter is provided transitionally to make both 'executable' and 'executableAndArguments' * optional for API backward compatibility. The proper way to construct a Command is via the constructor * {@link #Builder(String, String, String, CommandStatus, List, long)}. */ @Deprecated public Builder withExecutableAndArguments(@Nullable final List<String> executableAndArguments) { this.bExecutableAndArguments.clear(); if (executableAndArguments != null) { this.bExecutableAndArguments.addAll(executableAndArguments); } return this; } /** * The check delay for pre-4.x.x Genie backends. This no longer has any impact on the system and is here * to maintain backwards compatibility. Will always be set to -1. * * @param ignoredCheckDelay The check delay but this value is ignored * @return The current {@link Builder} instance */ @Deprecated public Builder withCheckDelay(@Nullable final Long ignoredCheckDelay) { // No-Op for backwards compatibility return this; } /** * Set the ordered list of {@link Criterion} that should be used to resolve which clusters this command * can run on at any given time. * * @param clusterCriteria The {@link Criterion} in priority order * @return The builder */ public Builder withClusterCriteria(@Nullable final List<Criterion> clusterCriteria) { this.bClusterCriteria.clear(); if (clusterCriteria != null) { this.bClusterCriteria.addAll(clusterCriteria); } return this; } /** * Set the runtime for any jobs that use this command. * * @param runtime The {@link Runtime} or {@literal null} * @return The builder instance */ public Builder withRuntime(@Nullable final Runtime runtime) { this.bImages.clear(); if (runtime == null) { this.bRuntimeResources .withCpu(null) .withGpu(null) .withMemoryMb(null) .withDiskMb(null) .withNetworkMbps(null); } else { final RuntimeResources resources = runtime.getResources(); this.bRuntimeResources .withCpu(resources.getCpu().orElse(null)) .withGpu(resources.getGpu().orElse(null)) .withMemoryMb(resources.getMemoryMb().orElse(null)) .withDiskMb(resources.getDiskMb().orElse(null)) .withNetworkMbps(resources.getNetworkMbps().orElse(null)); this.bImages.putAll(runtime.getImages()); } return this; } /** * Build the command. * * @return Create the final read-only Command instance */ public Command build() { return new Command(this); } } }
2,266
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Cluster.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Getter; import javax.validation.constraints.NotNull; /** * Cluster DTO object. Read only after construction. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = Cluster.Builder.class) public class Cluster extends ExecutionEnvironmentDTO { private static final long serialVersionUID = 8562447832504925029L; @NotNull(message = "A valid cluster status is required") private final ClusterStatus status; /** * Constructor used only by the build() method of the builder. * * @param builder The builder to get data from */ protected Cluster(final Builder builder) { super(builder); this.status = builder.bStatus; } /** * A builder to create clusters. * * @author tgianos * @since 3.0.0 */ public static class Builder extends ExecutionEnvironmentDTO.Builder<Builder> { private final ClusterStatus bStatus; /** * Constructor which has required fields. * * @param name The name to use for the Cluster * @param user The user to use for the Cluster * @param version The version to use for the Cluster * @param status The status of the Cluster */ public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final ClusterStatus status ) { super(name, user, version); this.bStatus = status; } /** * Build the cluster. * * @return Create the final read-only Cluster instance */ public Cluster build() { return new Cluster(this); } } }
2,267
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/JobRequest.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Email; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; /** * All information needed to make a request to run a new job. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = JobRequest.Builder.class) public class JobRequest extends ExecutionEnvironmentDTO { /** * The default number of seconds from start before a job times out. */ public static final int DEFAULT_TIMEOUT_DURATION = 604800; private static final long serialVersionUID = 3163971970144435277L; @Size(max = 10_000, message = "The maximum number of characters for the command arguments is 10,000") private final String commandArgs; @Valid @NotEmpty(message = "At least one cluster criteria is required") private final List<ClusterCriteria> clusterCriterias; @NotEmpty(message = "At least one valid (e.g. non-blank) command criteria is required") private final Set<String> commandCriteria; @Size(max = 255, message = "Max length of the group is 255 characters") private final String group; private final boolean disableLogArchival; @Size(max = 255, message = "Max length of the email 255 characters") @Email(message = "Must be a valid email address") private final String email; @Min(value = 1, message = "Must have at least 1 CPU") @Deprecated private final Integer cpu; @Min(value = 1, message = "Must have at least 1 MB of memory. Preferably much more.") @Deprecated private final Integer memory; @Min(value = 1, message = "The timeout must be at least 1 second, preferably much more.") private final Integer timeout; private final List<String> applications; private final String grouping; private final String groupingInstance; private final Runtime runtime; /** * Constructor used by the builder build() method. * * @param builder The builder to use */ JobRequest(@Valid final Builder builder) { super(builder); this.commandArgs = builder.bCommandArgs; this.clusterCriterias = ImmutableList.copyOf(builder.bClusterCriterias); this.commandCriteria = ImmutableSet.copyOf(builder.bCommandCriteria); this.group = builder.bGroup; this.disableLogArchival = builder.bDisableLogArchival; this.email = builder.bEmail; this.timeout = builder.bTimeout; this.applications = ImmutableList.copyOf(builder.bApplications); this.grouping = builder.bGrouping; this.groupingInstance = builder.bGroupingInstance; this.runtime = new Runtime.Builder() .withResources(builder.bRuntimeResources.build()) .withImages(builder.bImages) .build(); this.cpu = this.runtime.getResources().getCpu().orElse(null); this.memory = this.runtime.getResources() .getMemoryMb() .map(Long::intValue) .orElse(null); } /** * Get the arguments to be put on the command line along with the command executable. * * @return The command arguments */ public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } /** * Get the group the user should be a member of. * * @return The group as an optional */ public Optional<String> getGroup() { return Optional.ofNullable(this.group); } /** * Get the email for the user. * * @return The email address as an Optional */ public Optional<String> getEmail() { return Optional.ofNullable(this.email); } /** * Get the number of CPU's requested to run this job. * * @return The number of CPU's as an Optional * @deprecated Use runtime instead * @since 4.3.0 */ @Deprecated public Optional<Integer> getCpu() { return Optional.ofNullable(this.cpu); } /** * Get the amount of memory (in MB) requested to run this job with. * * @return The amount of memory as an Optional * @deprecated Use runtime instead * @since 4.3.0 */ @Deprecated public Optional<Integer> getMemory() { return Optional.ofNullable(this.memory); } /** * Get the amount of time requested (in seconds) before this job is timed out on the server. * * @return The timeout as an Optional */ public Optional<Integer> getTimeout() { return Optional.ofNullable(this.timeout); } /** * Get the grouping for this job if there currently is one. * * @return The grouping * @since 3.3.0 */ public Optional<String> getGrouping() { return Optional.ofNullable(this.grouping); } /** * Get the grouping instance for this job if there currently is one. * * @return The grouping instance * @since 3.3.0 */ public Optional<String> getGroupingInstance() { return Optional.ofNullable(this.groupingInstance); } /** * A builder to create job requests. * * @author tgianos * @since 3.0.0 */ public static class Builder extends ExecutionEnvironmentDTO.Builder<Builder> { private final List<ClusterCriteria> bClusterCriterias = new ArrayList<>(); private final Set<String> bCommandCriteria = new HashSet<>(); private final List<String> bApplications = new ArrayList<>(); private String bCommandArgs; private String bGroup; private boolean bDisableLogArchival; private String bEmail; private Integer bTimeout; private String bGrouping; private String bGroupingInstance; private final RuntimeResources.Builder bRuntimeResources = new RuntimeResources.Builder(); private final Map<String, ContainerImage> bImages = new HashMap<>(); /** * Constructor which has required fields. * * @param name The name to use for the Job * @param user The user to use for the Job * @param version The version to use for the Job * @param clusterCriterias The list of cluster criteria for the Job * @param commandCriteria The list of command criteria for the Job * @since 3.3.0 */ public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "clusterCriterias", required = true) final List<ClusterCriteria> clusterCriterias, @JsonProperty(value = "commandCriteria", required = true) final Set<String> commandCriteria ) { super(name, user, version); this.bClusterCriterias.addAll(clusterCriterias); commandCriteria.forEach( criteria -> { if (StringUtils.isNotBlank(criteria)) { this.bCommandCriteria.add(criteria); } } ); } /** * Constructor which has required fields plus two optional ways of passing arguments. * * @param name The name to use for the Job * @param user The user to use for the Job * @param version The version to use for the Job * @param clusterCriterias The list of cluster criteria for the Job * @param commandCriteria The list of command criteria for the Job * @since 4.0.0 */ @JsonCreator Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "clusterCriterias", required = true) final List<ClusterCriteria> clusterCriterias, @JsonProperty(value = "commandCriteria", required = true) final Set<String> commandCriteria, @JsonProperty(value = "commandArgs") @Nullable final String commandArgs, @JsonProperty(value = "commandArguments") @Nullable final List<String> commandArguments ) { this(name, user, version, clusterCriterias, commandCriteria); if (commandArgs == null && commandArguments == null) { // Neither fields are set. this.withCommandArgs(Lists.newArrayList()); } else if (commandArguments != null && !commandArguments.isEmpty()) { this.withCommandArgs(commandArguments); } else if (commandArgs != null && !commandArgs.isEmpty()) { this.withCommandArgs(commandArgs); } else { // Either is present but both are empty this.withCommandArgs(Lists.newArrayList()); } } /** * Constructor which has required fields. * <p> * DEPRECATED: Will be removed in 4.0.0 as command args are optional and should be a List now * * @param name The name to use for the Job * @param user The user to use for the Job * @param version The version to use for the Job * @param commandArgs The command line arguments for the Job * @param clusterCriterias The list of cluster criteria for the Job * @param commandCriteria The list of command criteria for the Job * @deprecated Use {@link #Builder(String, String, String, List, Set)} */ @Deprecated public Builder( final String name, final String user, final String version, @Nullable final String commandArgs, final List<ClusterCriteria> clusterCriterias, final Set<String> commandCriteria ) { super(name, user, version); this.bCommandArgs = StringUtils.isBlank(commandArgs) ? null : commandArgs; this.bClusterCriterias.addAll(clusterCriterias); commandCriteria.forEach( criteria -> { if (StringUtils.isNotBlank(criteria)) { this.bCommandCriteria.add(criteria); } } ); } /** * The command arguments to use in conjunction witOh the command executable selected for this job. * <p> * DEPRECATED: This API will be removed in 4.0.0 in favor of the List based method for improved control over * escaping of arguments. * * @param commandArgs The command args. Max length is 10,000 characters * @return The builder * @since 3.3.0 * @deprecated Use {@link #withCommandArgs(List)} */ @Deprecated public Builder withCommandArgs(@Nullable final String commandArgs) { this.bCommandArgs = StringUtils.isBlank(commandArgs) ? null : commandArgs; return this; } /** * The command arguments to use in conjunction with the command executable selected for this job. * * @param commandArgs The command args. The maximum combined length of the command args plus one space between * each argument must be less than or equal to 10,000 characters * @return The builder * @since 3.3.0 */ public Builder withCommandArgs(@Nullable final List<String> commandArgs) { if (commandArgs != null) { this.bCommandArgs = StringUtils.join(commandArgs, StringUtils.SPACE); if (StringUtils.isBlank(this.bCommandArgs)) { this.bCommandArgs = null; } } else { this.bCommandArgs = null; } return this; } /** * Set the group for the job. * * @param group The group * @return The builder */ public Builder withGroup(@Nullable final String group) { this.bGroup = group; return this; } /** * Set whether to disable log archive for the job. * * @param disableLogArchival true if you want to disable log archival * @return The builder */ public Builder withDisableLogArchival(final boolean disableLogArchival) { this.bDisableLogArchival = disableLogArchival; return this; } /** * Set the email to use for alerting of job completion. If no alert desired leave blank. * * @param email the email address to use * @return The builder */ public Builder withEmail(@Nullable final String email) { this.bEmail = email; return this; } /** * Set the number of cpu's being requested to run the job. Defaults to 1 if not set. * * @param cpu The number of cpu's. Must be greater than 0. * @return The builder * @deprecated Use {@link #withRuntime(Runtime)} instead */ @Deprecated public Builder withCpu(@Nullable final Integer cpu) { this.bRuntimeResources.withCpu(cpu); return this; } /** * Set the amount of memory being requested to run the job. * * @param memory The amount of memory in terms of MB's. Must be greater than 0. * @return The builder * @deprecated Use {@link #withRuntime(Runtime)} instead */ @Deprecated public Builder withMemory(@Nullable final Integer memory) { this.bRuntimeResources.withMemoryMb(memory == null ? null : memory.longValue()); return this; } /** * Set the ids of applications to override the default applications from the command with. * * @param applications The ids of applications to override * @return The builder */ public Builder withApplications(@Nullable final List<String> applications) { this.bApplications.clear(); if (applications != null) { this.bApplications.addAll(applications); } return this; } /** * Set the length of the job timeout in seconds after which Genie will kill the client process. * * @param timeout The timeout to use * @return The builder */ public Builder withTimeout(@Nullable final Integer timeout) { this.bTimeout = timeout; return this; } /** * Set the grouping to use for this job. * * @param grouping The grouping * @return The builder * @since 3.3.0 */ public Builder withGrouping(@Nullable final String grouping) { this.bGrouping = grouping; return this; } /** * Set the grouping instance to use for this job. * * @param groupingInstance The grouping instance * @return The builder * @since 3.3.0 */ public Builder withGroupingInstance(@Nullable final String groupingInstance) { this.bGroupingInstance = groupingInstance; return this; } /** * Set the requested job runtime environment details. * * @param runtime The {@link Runtime} information or {@literal null} * @return The {@link Builder} instance */ public Builder withRuntime(@Nullable final Runtime runtime) { this.bImages.clear(); if (runtime == null) { this.bRuntimeResources .withCpu(null) .withGpu(null) .withMemoryMb(null) .withDiskMb(null) .withNetworkMbps(null); } else { final RuntimeResources resources = runtime.getResources(); this.bRuntimeResources .withCpu(resources.getCpu().orElse(null)) .withGpu(resources.getGpu().orElse(null)) .withMemoryMb(resources.getMemoryMb().orElse(null)) .withDiskMb(resources.getDiskMb().orElse(null)) .withNetworkMbps(resources.getNetworkMbps().orElse(null)); this.bImages.putAll(runtime.getImages()); } return this; } /** * Build the job request. * * @return Create the final read-only JobRequest instance */ public JobRequest build() { return new JobRequest(this); } } }
2,268
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ClusterCriteria.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.validation.constraints.NotEmpty; import java.io.Serializable; import java.util.Set; /** * Cluster Criteria. * * @author amsharma * @author tgianos * @since 2.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) public class ClusterCriteria implements Serializable { private static final long serialVersionUID = 1782794735938665541L; @NotEmpty(message = "No valid (e.g. non-blank) tags present") private Set<String> tags; /** * Create a cluster criteria object with the included tags. * * @param tags The tags to add. Not null or empty and must have at least one non-empty tag. */ @JsonCreator public ClusterCriteria( @JsonProperty(value = "tags", required = true) final Set<String> tags ) { final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); tags.forEach( tag -> { if (StringUtils.isNotBlank(tag)) { builder.add(tag); } } ); this.tags = builder.build(); } }
2,269
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/JobExecution.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.netflix.genie.common.util.JsonUtils; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.constraints.Min; import javax.validation.constraints.Size; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * All information needed to show state of a running job. * * @author tgianos * @since 3.0.0 */ @Getter @JsonDeserialize(builder = JobExecution.Builder.class) public class JobExecution extends BaseDTO { /** * The exit code that will be set to indicate a job is killed. */ public static final int KILLED_EXIT_CODE = 999; /** * The exit code that will be set to indicate a job is has been lost by Genie. */ public static final int LOST_EXIT_CODE = 666; /** * The exit code that will be set to indicate a job has succeeded. */ public static final int SUCCESS_EXIT_CODE = 0; private static final long serialVersionUID = 5005391660522052211L; @Size(min = 1, max = 1024, message = "Host name is required but no longer than 1024 characters") private final String hostName; private final Integer processId; @Min( value = 1, message = "The delay between checks must be at least 1 millisecond. Probably should be much more than that" ) private final Long checkDelay; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant timeout; private final Integer exitCode; @Min( value = 1, message = "The amount of memory this job is set to use on the system" ) @Deprecated private final Integer memory; private final ArchiveStatus archiveStatus; private final JsonNode launcherExt; private final Runtime runtime; /** * Constructor used by the builder build() method. * * @param builder The builder to use */ protected JobExecution(final Builder builder) { super(builder); this.hostName = builder.bHostName; this.processId = builder.bProcessId; this.checkDelay = builder.bCheckDelay; this.exitCode = builder.bExitCode; this.timeout = builder.bTimeout; this.archiveStatus = builder.bArchiveStatus; this.launcherExt = builder.bLauncherExt; this.runtime = new Runtime.Builder() .withResources(builder.bRuntimeResources.build()) .withImages(builder.bImages) .build(); this.memory = this.runtime.getResources().getMemoryMb().map(Long::intValue).orElse(null); } /** * Get the process id for this job execution as Optional. * * @return The process id */ public Optional<Integer> getProcessId() { return Optional.ofNullable(this.processId); } /** * Get the amount of time (in milliseconds) to delay between checks of status of the job process. * * @return The time to delay as an Optional as it could be null */ public Optional<Long> getCheckDelay() { return Optional.ofNullable(this.checkDelay); } /** * Get the timeout date for this job after which if it is still running the system will attempt to kill it. * * @return The timeout date */ public Optional<Instant> getTimeout() { return Optional.ofNullable(this.timeout); } /** * Get the exit code of the process. * * @return The exit code as an Optional as it could be null */ public Optional<Integer> getExitCode() { return Optional.ofNullable(this.exitCode); } /** * Get the amount of memory (in MB) of the job. * * @return The amount of memory the job is set to use as an Optional as it could be null */ public Optional<Integer> getMemory() { return Optional.ofNullable(this.memory); } /** * Get the archival status of job files. * * @return the archival status as Optional as it could be null */ public Optional<ArchiveStatus> getArchiveStatus() { return Optional.ofNullable(this.archiveStatus); } /** * Get the launcher extension. * * @return the launcher extension as Optional as it could be null */ public Optional<JsonNode> getLauncherExt() { return Optional.ofNullable(this.launcherExt); } /** * A builder to create job requests. * * @author tgianos * @since 3.0.0 */ public static class Builder extends BaseDTO.Builder<Builder> { private final String bHostName; private Integer bProcessId; private Long bCheckDelay; private Instant bTimeout; private Integer bExitCode; private ArchiveStatus bArchiveStatus; private JsonNode bLauncherExt; private final RuntimeResources.Builder bRuntimeResources; private final Map<String, ContainerImage> bImages; /** * Constructor which has required fields. * * @param hostName The hostname where the job is running */ public Builder(@JsonProperty(value = "hostName", required = true) final String hostName) { super(); this.bHostName = hostName; this.bRuntimeResources = new RuntimeResources.Builder(); this.bImages = new HashMap<>(); } /** * Set the process id for the jobs' execution. * * @param processId The process id * @return The builder */ public Builder withProcessId(@Nullable final Integer processId) { this.bProcessId = processId; return this; } /** * Set the amount of time (in milliseconds) to delay between checks of the process. * * @param checkDelay The check delay to use * @return The builder */ public Builder withCheckDelay(@Nullable final Long checkDelay) { this.bCheckDelay = checkDelay; return this; } /** * Set the timeout date when the job will be failed if it hasn't completed by. * * @param timeout The timeout date * @return The builder */ public Builder withTimeout(@Nullable final Instant timeout) { this.bTimeout = timeout; return this; } /** * Set the exit code for the jobs' execution. If not set will default to -1. * * @param exitCode The exit code. * @return The builder */ public Builder withExitCode(@Nullable final Integer exitCode) { this.bExitCode = exitCode; return this; } /** * Set the amount of memory (in MB) to use for this job execution. * * @param memory The amount of memory in megabytes * @return The builder * @deprecated Use {@link #withRuntime(Runtime)} instead */ @Deprecated public Builder withMemory(@Nullable final Integer memory) { this.bRuntimeResources.withMemoryMb(memory == null ? null : memory.longValue()); return this; } /** * Set the archive status for this job. * * @param archiveStatus The archive status * @return The builder */ public Builder withArchiveStatus(@Nullable final ArchiveStatus archiveStatus) { this.bArchiveStatus = archiveStatus; return this; } /** * Set the launcher extension for this job. * * @param launcherExt The launcher extension * @return The builder */ public Builder withLauncherExt(@Nullable final JsonNode launcherExt) { this.bLauncherExt = launcherExt; return this; } /** * Set the runtime this job is executing with. * * @param runtime The runtime * @return This {@link Builder} instance */ public Builder withRuntime(@Nullable final Runtime runtime) { this.bImages.clear(); if (runtime == null) { this.bRuntimeResources .withCpu(null) .withGpu(null) .withMemoryMb(null) .withDiskMb(null) .withNetworkMbps(null); } else { final RuntimeResources resources = runtime.getResources(); this.bRuntimeResources .withCpu(resources.getCpu().orElse(null)) .withGpu(resources.getGpu().orElse(null)) .withMemoryMb(resources.getMemoryMb().orElse(null)) .withDiskMb(resources.getDiskMb().orElse(null)) .withNetworkMbps(resources.getNetworkMbps().orElse(null)); this.bImages.putAll(runtime.getImages()); } return this; } /** * Build the job request. * * @return Create the final read-only JobRequest instance */ public JobExecution build() { return new JobExecution(this); } } }
2,270
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/CommonDTO.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableSet; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.external.util.GenieObjectMapper; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.IOException; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * Common fields for multiple DTOs. * * @author tgianos * @since 3.0.0 */ @Getter public abstract class CommonDTO extends BaseDTO { private static final long serialVersionUID = -2082573569004634251L; @NotEmpty(message = "A version is required and must be at most 255 characters.") @Size(max = 255, message = "The version can be no longer than 255 characters") private final String version; @NotEmpty(message = "A user is required and must be at most 255 characters") @Size(max = 255, message = "The user can be no longer than 255 characters") private final String user; @NotEmpty(message = "A name is required and must be at most 255 characters") @Size(max = 255, message = "The name can be no longer than 255 characters") private final String name; @Size(max = 1000, message = "The description can be no longer than 1000 characters") private final String description; private final JsonNode metadata; private final Set<String> tags; /** * Constructor. * * @param builder The builder to use */ @SuppressWarnings("unchecked") CommonDTO(final Builder builder) { super(builder); this.name = builder.bName; this.user = builder.bUser; this.version = builder.bVersion; this.description = builder.bDescription; this.metadata = builder.bMetadata; this.tags = ImmutableSet.copyOf(builder.bTags); } /** * Get the description. * * @return The description as an optional */ public Optional<String> getDescription() { return Optional.ofNullable(this.description); } /** * Get the metadata of this resource as a JSON Node. * * @return Optional of the metadata if it exists */ public Optional<JsonNode> getMetadata() { return Optional.ofNullable(this.metadata); } /** * Builder pattern to save constructor arguments. * * @param <T> Type of builder that extends this * @author tgianos * @since 3.0.0 */ // NOTE: These abstract class builders are marked public not protected due to a JDK bug from 1999 which caused // issues with Clojure clients which use reflection to make the Java API calls. // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4283544 // Setting them to public seems to have solved the issue at the expense of "proper" code design @SuppressWarnings("unchecked") public abstract static class Builder<T extends Builder> extends BaseDTO.Builder<T> { private final String bName; private final String bUser; private final String bVersion; private String bDescription; private JsonNode bMetadata; private Set<String> bTags = new HashSet<>(); protected Builder(final String name, final String user, final String version) { this.bName = name; this.bUser = user; this.bVersion = version; } /** * Set the description for the resource. * * @param description The description to use * @return The builder */ public T withDescription(@Nullable final String description) { this.bDescription = description; return (T) this; } /** * Set the tags to use for the resource. * * @param tags The tags to use * @return The builder */ public T withTags(@Nullable final Set<String> tags) { this.bTags.clear(); if (tags != null) { this.bTags.addAll(tags); } return (T) this; } /** * With the metadata to set for the job as a JsonNode. * * @param metadata The metadata to set * @return The builder */ @JsonSetter public T withMetadata(@Nullable final JsonNode metadata) { this.bMetadata = metadata; return (T) this; } /** * With the metadata to set for the job as a string of valid JSON. * * @param metadata The metadata to set. Must be valid JSON * @return The builder * @throws GeniePreconditionException On invalid JSON */ public T withMetadata(@Nullable final String metadata) throws GeniePreconditionException { if (metadata == null) { this.bMetadata = null; } else { try { this.bMetadata = GenieObjectMapper.getMapper().readTree(metadata); } catch (final IOException ioe) { throw new GeniePreconditionException("Invalid JSON string passed in " + metadata, ioe); } } return (T) this; } } }
2,271
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/JobStatus.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; /** * Possible statuses for a Job. * * @author tgianos */ @Getter public enum JobStatus { /** * The id of the job has been reserved. */ RESERVED(true, true, false), /** * The job specification has been resolved. */ RESOLVED(true, false, true), /** * The job has been accepted by the system via the REST API. */ ACCEPTED(true, false, true), /** * The job has been claimed by a running agent. */ CLAIMED(true, false, false), /** * Job has been initialized, but not running yet. */ INIT(true, false, false), /** * Job is now running. */ RUNNING(true, false, false), /** * Job has finished executing, and is successful. */ SUCCEEDED(false, false, false), /** * Job has been killed. */ KILLED(false, false, false), /** * Job failed. */ FAILED(false, false, false), /** * Job cannot be run due to invalid criteria. */ INVALID(false, false, false); private static final Set<JobStatus> ACTIVE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isActive).collect(Collectors.toSet()) ); private static final Set<JobStatus> FINISHED_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isFinished).collect(Collectors.toSet()) ); private static final Set<JobStatus> RESOLVABLE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isResolvable).collect(Collectors.toSet()) ); private static final Set<JobStatus> CLAIMABLE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isClaimable).collect(Collectors.toSet()) ); private final boolean active; private final boolean resolvable; private final boolean claimable; /** * Constructor. * * @param active whether this status should be considered active or not * @param resolvable whether this status should be considered as a job that is valid to have a job specification * resolved or not * @param claimable Whether this status should be considered as a job that is valid to be claimed by an agent or * not */ JobStatus(final boolean active, final boolean resolvable, final boolean claimable) { this.active = active; this.resolvable = resolvable; this.claimable = claimable; } /** * Parse job status. * * @param value string to parse/convert * @return INIT, RUNNING, SUCCEEDED, KILLED, FAILED if match * @throws GeniePreconditionException if invalid value passed in */ public static JobStatus parse(final String value) throws GeniePreconditionException { if (StringUtils.isNotBlank(value)) { for (final JobStatus status : JobStatus.values()) { if (value.equalsIgnoreCase(status.toString())) { return status; } } } throw new GeniePreconditionException( "Unacceptable job status. Must be one of " + Arrays.toString(JobStatus.values()) ); } /** * Get an unmodifiable set of all the statuses that make up a job being considered active. * * @return Unmodifiable set of all active statuses */ public static Set<JobStatus> getActiveStatuses() { return ACTIVE_STATUSES; } /** * Get an unmodifiable set of all the statuses that make up a job being considered finished. * * @return Unmodifiable set of all finished statuses */ public static Set<JobStatus> getFinishedStatuses() { return FINISHED_STATUSES; } /** * Get an unmodifiable set of all the statuses from which a job can be marked resolved. * * @return Unmodifiable set of all resolvable statuses */ public static Set<JobStatus> getResolvableStatuses() { return RESOLVABLE_STATUSES; } /** * Get an unmodifiable set of all the statuses from which a job can be marked claimed. * * @return Unmodifiable set of all claimable statuses */ public static Set<JobStatus> getClaimableStatuses() { return CLAIMABLE_STATUSES; } /** * Check whether the job is no longer running. * * @return True if the job is no longer processing for one reason or another. */ public boolean isFinished() { return !this.active; } }
2,272
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/JobMetadata.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.Valid; import java.util.Optional; /** * Additional metadata associated with a Job Request such as client host, user agent, etc. * * @author tgianos * @since 3.0.0 */ @JsonDeserialize(builder = JobMetadata.Builder.class) @Getter public class JobMetadata extends BaseDTO { private final String clientHost; private final String userAgent; private final Integer numAttachments; private final Long totalSizeOfAttachments; private final Long stdOutSize; private final Long stdErrSize; /** * Constructor used only through the builder. * * @param builder The builder to construct from */ protected JobMetadata(@Valid final Builder builder) { super(builder); this.clientHost = builder.bClientHost; this.userAgent = builder.bUserAgent; this.numAttachments = builder.bNumAttachments; this.totalSizeOfAttachments = builder.bTotalSizeOfAttachments; this.stdOutSize = builder.bStdOutSize; this.stdErrSize = builder.bStdErrSize; } /** * Get the client host. * * @return Optional of the client host */ public Optional<String> getClientHost() { return Optional.ofNullable(this.clientHost); } /** * Get the user agent. * * @return Optional of the user agent */ public Optional<String> getUserAgent() { return Optional.ofNullable(this.userAgent); } /** * Get the number of attachments. * * @return The number of attachments as an optional */ public Optional<Integer> getNumAttachments() { return Optional.ofNullable(this.numAttachments); } /** * Get the total size of the attachments. * * @return The total size of attachments as an optional */ public Optional<Long> getTotalSizeOfAttachments() { return Optional.ofNullable(this.totalSizeOfAttachments); } /** * Get the size of standard out for this job. * * @return The size (in bytes) of this jobs standard out file as Optional */ public Optional<Long> getStdOutSize() { return Optional.ofNullable(this.stdOutSize); } /** * Get the size of standard error for this job. * * @return The size (in bytes) of this jobs standard error file as Optional */ public Optional<Long> getStdErrSize() { return Optional.ofNullable(this.stdErrSize); } /** * Builder for creating a JobMetadata instance. * * @author tgianos * @since 3.0.0 */ public static class Builder extends BaseDTO.Builder<Builder> { private String bClientHost; private String bUserAgent; private Integer bNumAttachments; private Long bTotalSizeOfAttachments; private Long bStdOutSize; private Long bStdErrSize; /** * Set the host name that sent the job request. * * @param clientHost The hostname to use. * @return The builder */ public Builder withClientHost(@Nullable final String clientHost) { this.bClientHost = clientHost; return this; } /** * Set the user agent string the request came in with. * * @param userAgent The user agent string * @return The builder */ public Builder withUserAgent(@Nullable final String userAgent) { this.bUserAgent = userAgent; return this; } /** * Set the number of attachments the job had. * * @param numAttachments The number of attachments sent in with the job request * @return The builder */ public Builder withNumAttachments(@Nullable final Integer numAttachments) { this.bNumAttachments = numAttachments; return this; } /** * Set the total size (in bytes) of the attachments sent with the job request. * * @param totalSizeOfAttachments The total size of the attachments sent in with the job request * @return The builder */ public Builder withTotalSizeOfAttachments(@Nullable final Long totalSizeOfAttachments) { this.bTotalSizeOfAttachments = totalSizeOfAttachments; return this; } /** * Set the total size (in bytes) of the jobs' standard out file. * * @param stdOutSize The total size of the jobs' standard out file * @return The builder */ public Builder withStdOutSize(@Nullable final Long stdOutSize) { this.bStdOutSize = stdOutSize; return this; } /** * Set the total size (in bytes) of the jobs' standard error file. * * @param stdErrSize The total size of the jobs' standard error file * @return The builder */ public Builder withStdErrSize(@Nullable final Long stdErrSize) { this.bStdErrSize = stdErrSize; return this; } /** * Create a new JobMetadata object from this builder. * * @return The JobMetadata read only instance */ public JobMetadata build() { return new JobMetadata(this); } } }
2,273
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ApplicationStatus.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.netflix.genie.common.exceptions.GeniePreconditionException; import org.apache.commons.lang3.StringUtils; /** * The available statuses for applications. * * @author tgianos */ public enum ApplicationStatus { /** * Application is active, and in-use. */ ACTIVE, /** * Application is deprecated, and will be made inactive in the future. */ DEPRECATED, /** * Application is inactive, and not in-use. */ INACTIVE; /** * Parse config status. * * @param value string to parse/convert into config status * @return ACTIVE, DEPRECATED, INACTIVE if match * @throws GeniePreconditionException on invalid value */ public static ApplicationStatus parse(final String value) throws GeniePreconditionException { if (StringUtils.isNotBlank(value)) { for (final ApplicationStatus status : ApplicationStatus.values()) { if (value.equalsIgnoreCase(status.toString())) { return status; } } } throw new GeniePreconditionException( "Unacceptable application status. Must be one of {ACTIVE, DEPRECATED, INACTIVE}" ); } }
2,274
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ArchiveStatus.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; /** * Possible archival statuses for a Job. * * @author mprimi * @since 4.3.0 */ public enum ArchiveStatus { /** * Files will be uploaded after the job finishes. */ PENDING, /** * Files were archived successfully. */ ARCHIVED, /** * Archival of files failed, files are not archived. */ FAILED, /** * Archiving was disabled, files are not archived. */ DISABLED, /** * No files were archived because no files were created. * i.e., job never reached the point where a directory is created. */ NO_FILES, /** * Archive status is unknown. */ UNKNOWN, }
2,275
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/RuntimeResources.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import javax.annotation.Nullable; import javax.validation.constraints.Min; import java.io.Serializable; import java.util.Objects; import java.util.Optional; /** * A representation of compute resources that a Genie entity (job/command/etc.) may request or use. * * @author tgianos * @since 4.3.0 */ @JsonDeserialize(builder = RuntimeResources.Builder.class) public class RuntimeResources implements Serializable { @Min(value = 1, message = "Must have at least one CPU") private final Integer cpu; @Min(value = 1, message = "Must have at least one GPU") private final Integer gpu; @Min(value = 1, message = "Must have at least 1 MB of memory") private final Long memoryMb; @Min(value = 1, message = "Must have at least 1 MB of disk space") private final Long diskMb; @Min(value = 1, message = "Must have at least 1 Mbps of network bandwidth") private final Long networkMbps; private RuntimeResources(final Builder builder) { this.cpu = builder.bCpu; this.gpu = builder.bGpu; this.memoryMb = builder.bMemoryMb; this.diskMb = builder.bDiskMb; this.networkMbps = builder.bNetworkMbps; } /** * Get the number of CPUs. * * @return The amount or {@link Optional#empty()} */ public Optional<Integer> getCpu() { return Optional.ofNullable(this.cpu); } /** * Get the number of GPUs. * * @return The amount or {@link Optional#empty()} */ public Optional<Integer> getGpu() { return Optional.ofNullable(this.gpu); } /** * Get the amount of memory. * * @return The amount or {@link Optional#empty()} */ public Optional<Long> getMemoryMb() { return Optional.ofNullable(this.memoryMb); } /** * Get the amount of disk space. * * @return The amount or {@link Optional#empty()} */ public Optional<Long> getDiskMb() { return Optional.ofNullable(this.diskMb); } /** * Get the network bandwidth size. * * @return The size or {@link Optional#empty()} */ public Optional<Long> getNetworkMbps() { return Optional.ofNullable(this.networkMbps); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.cpu, this.gpu, this.memoryMb, this.diskMb, this.networkMbps); } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof RuntimeResources)) { return false; } final RuntimeResources that = (RuntimeResources) o; return Objects.equals(this.cpu, that.cpu) && Objects.equals(this.gpu, that.gpu) && Objects.equals(this.memoryMb, that.memoryMb) && Objects.equals(this.diskMb, that.diskMb) && Objects.equals(this.networkMbps, that.networkMbps); } /** * {@inheritDoc} */ @Override public String toString() { return "RuntimeResources{" + "cpu=" + this.cpu + ", gpu=" + this.gpu + ", memoryMb=" + this.memoryMb + ", diskMb=" + this.diskMb + ", networkMbps=" + this.networkMbps + '}'; } /** * Builder for generating immutable {@link RuntimeResources} instances. * * @author tgianos * @since 4.3.0 */ public static class Builder { private Integer bCpu; private Integer bGpu; private Long bMemoryMb; private Long bDiskMb; private Long bNetworkMbps; /** * Set the number of CPUs. * * @param cpu The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withCpu(@Nullable final Integer cpu) { this.bCpu = cpu; return this; } /** * Set the number of GPUs. * * @param gpu The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withGpu(@Nullable final Integer gpu) { this.bGpu = gpu; return this; } /** * Set amount of memory in MB. * * @param memoryMb The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withMemoryMb(@Nullable final Long memoryMb) { this.bMemoryMb = memoryMb; return this; } /** * Set amount of disk space in MB. * * @param diskMb The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withDiskMb(@Nullable final Long diskMb) { this.bDiskMb = diskMb; return this; } /** * Set amount of network bandwidth in Mbps. * * @param networkMbps The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withNetworkMbps(@Nullable final Long networkMbps) { this.bNetworkMbps = networkMbps; return this; } /** * Create a new immutable {@link RuntimeResources} instance based on the current state of this builder instance. * * @return A {@link RuntimeResources} instance */ public RuntimeResources build() { return new RuntimeResources(this); } } }
2,276
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/BaseDTO.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.util.JsonUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.constraints.Size; import java.io.Serializable; import java.time.Instant; import java.util.Optional; /** * Base fields for multiple DTOs. * * @author tgianos * @since 3.0.0 */ @Getter @EqualsAndHashCode(of = "id", doNotUseGetters = true) public abstract class BaseDTO implements Serializable { private static final long serialVersionUID = 9093424855934127120L; @Size(max = 255, message = "Max length for the ID is 255 characters") private final String id; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant created; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant updated; /** * Constructor. * * @param builder The builder to use */ BaseDTO(final Builder builder) { this.id = builder.bId; this.created = builder.bCreated; this.updated = builder.bUpdated; } /** * Get the Id of this DTO. * * @return The id as an Optional */ public Optional<String> getId() { return Optional.ofNullable(this.id); } /** * Get the creation time. * * @return The creation time or null if not set. */ public Optional<Instant> getCreated() { return Optional.ofNullable(this.created); } /** * Get the update time. * * @return The update time or null if not set. */ public Optional<Instant> getUpdated() { return Optional.ofNullable(this.updated); } /** * Convert this object to a string representation. * * @return This application data represented as a JSON structure */ @Override public String toString() { try { return GenieObjectMapper.getMapper().writeValueAsString(this); } catch (final JsonProcessingException ioe) { return ioe.getLocalizedMessage(); } } /** * Builder pattern to save constructor arguments. * * @param <T> Type of builder that extends this * @author tgianos * @since 3.0.0 */ // NOTE: These abstract class builders are marked public not protected due to a JDK bug from 1999 which caused // issues with Clojure clients which use reflection to make the Java API calls. // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4283544 // Setting them to public seems to have solved the issue at the expense of "proper" code design @SuppressWarnings("unchecked") public abstract static class Builder<T extends Builder> { private String bId; private Instant bCreated; private Instant bUpdated; protected Builder() { } /** * Set the id for the resource. * * @param id The id * @return The builder */ public T withId(@Nullable final String id) { this.bId = id; return (T) this; } /** * Set the created time for the resource. * * @param created The created time * @return The builder */ public T withCreated(@Nullable final Instant created) { this.bCreated = created; return (T) this; } /** * Set the updated time for the resource. * * @param updated The updated time * @return The builder */ public T withUpdated(@Nullable final Instant updated) { this.bUpdated = updated; return (T) this; } } }
2,277
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ResolvedResources.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import java.util.Set; /** * Representing the result of resolving resources of type {@literal R} from a {@link Criterion}. * * @param <R> The type of the resource that was resolved * @author tgianos * @since 4.3.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ResolvedResources<R extends ExecutionEnvironmentDTO> { private final Criterion criterion; private final ImmutableSet<R> resources; /** * Constructor. * * @param criterion The {@link Criterion} that was used to resolve {@literal resources} * @param resources The resources that were resolved based on the {@literal criterion} */ @JsonCreator public ResolvedResources( @JsonProperty(value = "criterion", required = true) final Criterion criterion, @JsonProperty(value = "resources", required = true) final Set<R> resources ) { this.criterion = criterion; this.resources = ImmutableSet.copyOf(resources); } /** * Get the resources that were resolved. * * @return The resolved resources as an immutable {@link Set}. Any attempt to modify will cause error. */ public Set<R> getResources() { return this.resources; } }
2,278
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/Runtime.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import javax.annotation.Nullable; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * DTO for metadata related to the runtime environment of a given job. * * @author tgianos * @since 4.3.0 */ @JsonDeserialize(builder = Runtime.Builder.class) public class Runtime implements Serializable { private final RuntimeResources resources; private final Map<String, ContainerImage> images; private Runtime(final Builder builder) { this.resources = builder.bResources; this.images = Collections.unmodifiableMap(new HashMap<>(builder.bImages)); } /** * Get the compute resources for this runtime. * * @return The resources */ public RuntimeResources getResources() { return this.resources; } /** * The container images defined. * * @return The images that were defined as an immutable map. Any attempt to modify will throw exception. */ public Map<String, ContainerImage> getImages() { return this.images; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Runtime)) { return false; } final Runtime runtime = (Runtime) o; return this.resources.equals(runtime.resources) && this.images.equals(runtime.images); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.resources, this.images); } /** * {@inheritDoc} */ @Override public String toString() { return "Runtime{" + "resources=" + this.resources + ", images=" + this.images + '}'; } /** * Builder class for {@link Runtime} instances. */ public static class Builder { private RuntimeResources bResources; private final Map<String, ContainerImage> bImages; /** * Constructor. */ public Builder() { this.bResources = new RuntimeResources.Builder().build(); this.bImages = new HashMap<>(); } /** * Set the compute runtime resources to use. * * @param resources The {@link RuntimeResources} to use * @return This {@link Builder} instance */ public Builder withResources(@Nullable final RuntimeResources resources) { if (resources == null) { this.bResources = new RuntimeResources.Builder().build(); } else { this.bResources = resources; } return this; } /** * Set any container images needed with this resource (job, command, etc). * * @param images The map of system-wide image key to {@link ContainerImage} definition. * @return This {@link Builder} instance */ public Builder withImages(@Nullable final Map<String, ContainerImage> images) { this.bImages.clear(); if (images != null) { this.bImages.putAll(images); } return this; } /** * Create a new immutable {@link Runtime} instance based on the current contents of this builder instance. * * @return A new {@link Runtime} instance */ public Runtime build() { return new Runtime(this); } } }
2,279
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Data transfer objects for Genie for the APIs as well as the internal services. All DTOs should be read-only except * for their constructors. * * @author tgianos */ @ParametersAreNonnullByDefault package com.netflix.genie.common.dto; import javax.annotation.ParametersAreNonnullByDefault;
2,280
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/ContainerImage.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import javax.annotation.Nullable; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; /** * Representation of metadata corresponding to the container image (docker, etc.) that the job should be launched in. * * @author tgianos * @since 4.3.0 */ @JsonDeserialize(builder = ContainerImage.Builder.class) public class ContainerImage implements Serializable { private final String name; private final String tag; private final List<String> arguments; private ContainerImage(final Builder builder) { this.name = builder.bName; this.tag = builder.bTag; this.arguments = Collections.unmodifiableList(new ArrayList<>(builder.bArguments)); } /** * Get the name of the image to use for the job if one was specified. * * @return The name or {@link Optional#empty()} */ public Optional<String> getName() { return Optional.ofNullable(this.name); } /** * Get the tag of the image to use for the job if one was specified. * * @return The tag or {@link Optional#empty()} */ public Optional<String> getTag() { return Optional.ofNullable(this.tag); } /** * Get the image arguments if any. * * @return An unmodifiable list of arguments. Any attempt to modify will throw an exception */ public List<String> getArguments() { return this.arguments; } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.name, this.tag, this.arguments); } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ContainerImage)) { return false; } final ContainerImage containerImage = (ContainerImage) o; return Objects.equals(this.name, containerImage.name) && Objects.equals(this.tag, containerImage.tag) && Objects.equals(this.arguments, containerImage.arguments); } /** * {@inheritDoc} */ @Override public String toString() { return "ContainerImage{" + "name='" + this.name + '\'' + ", tag='" + this.tag + '\'' + ", arguments='" + this.arguments + '\'' + '}'; } /** * Builder for immutable instances of {@link ContainerImage}. * * @author tgianos * @since 4.3.0 */ public static class Builder { private String bName; private String bTag; private final List<String> bArguments; /** * Constructor. */ public Builder() { this.bArguments = new ArrayList<>(); } /** * Set the name of the image to use. * * @param name The name or {@literal null} * @return This {@link Builder} instance */ public Builder withName(@Nullable final String name) { this.bName = name; return this; } /** * Set the tag of the image to use. * * @param tag The tag or {@literal null} * @return This {@link Builder} instance */ public Builder withTag(@Nullable final String tag) { this.bTag = tag; return this; } /** * Set the arguments for the image. * * @param arguments The arguments. {@literal null} will clear any currently set arguments, as will empty list. * Any other value with replace. * @return This {@link Builder} instance */ public Builder withArguments(@Nullable final List<String> arguments) { this.bArguments.clear(); if (arguments != null) { this.bArguments.addAll(arguments); } return this; } /** * Create an immutable instance of {@link ContainerImage} based on the current contents of this builder * instance. * * @return A new {@link ContainerImage} instance */ public ContainerImage build() { return new ContainerImage(this); } } }
2,281
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/search/JobSearchResult.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto.search; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.datatype.jsr310.deser.DurationDeserializer; import com.netflix.genie.common.dto.JobStatus; import com.netflix.genie.common.util.JsonUtils; import com.netflix.genie.common.util.TimeUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.time.Duration; import java.time.Instant; import java.util.Optional; /** * This class represents the subset of data returned from a Job when a search for Jobs is conducted. * * @author tgianos * @since 3.0.0 */ @Getter @EqualsAndHashCode(callSuper = true) public class JobSearchResult extends BaseSearchResult { private static final long serialVersionUID = -3886685874572773514L; private final JobStatus status; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant started; @JsonSerialize(using = JsonUtils.OptionalInstantMillisecondSerializer.class) private final Instant finished; private final String clusterName; private final String commandName; @JsonSerialize(using = ToStringSerializer.class) @JsonDeserialize(using = DurationDeserializer.class) private final Duration runtime; /** * Constructor. * * @param id The id of the job * @param name The name of the job * @param user The user of the job * @param status The current status of the job * @param started The start time of the job * @param finished The finish time of the job * @param clusterName The name of the cluster this job is or was run on * @param commandName The name fo the command this job is or was run with */ @JsonCreator public JobSearchResult( @JsonProperty(value = "id", required = true) @NotBlank final String id, @JsonProperty(value = "name", required = true) @NotBlank final String name, @JsonProperty(value = "user", required = true) @NotBlank final String user, @JsonProperty(value = "status", required = true) @NotNull final JobStatus status, @JsonProperty("started") @Nullable final Instant started, @JsonProperty("finished") @Nullable final Instant finished, @JsonProperty("clusterName") @Nullable final String clusterName, @JsonProperty("commandName") @Nullable final String commandName ) { super(id, name, user); this.status = status; this.started = started; this.finished = finished; this.clusterName = clusterName; this.commandName = commandName; this.runtime = TimeUtils.getDuration(this.started, this.finished); } /** * Constructor. * * @param id The id of the job * @param name The name of the job * @param user The user of the job * @param status The current status of the job * @param started The start time of the job * @param finished The finish time of the job * @param clusterName The name of the cluster this job is or was run on * @param commandName The name fo the command this job is or was run with * @throws IllegalArgumentException If the status string can't be parsed into a {@link JobStatus} */ public JobSearchResult( @NotBlank final String id, @NotBlank final String name, @NotBlank final String user, @NotBlank final String status, @Nullable final Instant started, @Nullable final Instant finished, @Nullable final String clusterName, @Nullable final String commandName ) throws IllegalArgumentException { super(id, name, user); this.status = JobStatus.valueOf(status); this.started = started; this.finished = finished; this.clusterName = clusterName; this.commandName = commandName; this.runtime = TimeUtils.getDuration(this.started, this.finished); } /** * Get the time the job started. * * @return The started time or null if not set */ public Optional<Instant> getStarted() { return Optional.ofNullable(this.started); } /** * Get the time the job finished. * * @return The finished time or null if not set */ public Optional<Instant> getFinished() { return Optional.ofNullable(this.finished); } /** * Get the name of the cluster running the job if there currently is one. * * @return The name of the cluster where the job is running */ public Optional<String> getClusterName() { return Optional.ofNullable(this.clusterName); } /** * Get the name of the command running this job if there currently is one. * * @return The name of the command */ public Optional<String> getCommandName() { return Optional.ofNullable(this.commandName); } }
2,282
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/search/BaseSearchResult.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.dto.search; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.netflix.genie.common.external.util.GenieObjectMapper; import lombok.EqualsAndHashCode; import lombok.Getter; import javax.validation.constraints.NotBlank; import java.io.Serializable; /** * Base class for search results containing common fields. * * @author tgianos * @since 3.0.0 */ @Getter @EqualsAndHashCode(of = "id") public class BaseSearchResult implements Serializable { private static final long serialVersionUID = -273035797399359914L; private final String id; private final String name; private final String user; /** * Constructor. * * @param id The id of the object in the search result. * @param name The name of the object in the search result. * @param user The user who created the object. */ @JsonCreator BaseSearchResult( @NotBlank @JsonProperty(value = "id", required = true) final String id, @NotBlank @JsonProperty(value = "name", required = true) final String name, @NotBlank @JsonProperty(value = "user", required = true) final String user ) { this.id = id; this.name = name; this.user = user; } /** * Convert this object to a string representation. * * @return This application data represented as a JSON structure */ @Override public String toString() { try { return GenieObjectMapper.getMapper().writeValueAsString(this); } catch (final JsonProcessingException ioe) { return ioe.getLocalizedMessage(); } } }
2,283
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/dto/search/package-info.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * DTOs specifically related to search results. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.dto.search; import javax.annotation.ParametersAreNonnullByDefault;
2,284
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/util/TimeUtils.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.util; import javax.annotation.Nullable; import java.time.Duration; import java.time.Instant; /** * Utility methods for dealing with time. Particularly duration. * * @author tgianos * @since 3.0.0 */ public final class TimeUtils { /** * Protected constructor for utility class. */ private TimeUtils() { } /** * Get the duration between when something was started and finished. * * @param started The start time. Can be null will automatically set the duration to 0 * @param finished The finish time. If null will use (current time - started time) to get the duration * @return The duration or zero if no duration */ public static Duration getDuration(@Nullable final Instant started, @Nullable final Instant finished) { if (started == null || started.toEpochMilli() == 0L) { // Never started return Duration.ZERO; } else if (finished == null || finished.toEpochMilli() == 0L) { // Started but hasn't finished return Duration.ofMillis(Instant.now().toEpochMilli() - started.toEpochMilli()); } else { // Started and finished return Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli()); } } }
2,285
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/util/JsonUtils.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.util; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.external.util.GenieObjectMapper; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringTokenizer; import org.apache.commons.text.matcher.StringMatcherFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Utility methods for interacting with JSON. * * @author tgianos * @since 3.0.0 */ public final class JsonUtils { /** * Protected constructor for a utility class. */ protected JsonUtils() { } /** * Convert a Java object to a JSON string. * * @param value The Java object to marshall * @return The JSON string * @throws GenieException For any marshalling exception */ public static String marshall(final Object value) throws GenieException { try { return GenieObjectMapper.getMapper().writeValueAsString(value); } catch (final JsonProcessingException jpe) { throw new GenieServerException("Failed to marshall object", jpe); } } /** * Convert a JSON string of a collection back to a Java object. * * @param source The JSON string * @param typeReference The type reference of the collection to unmarshall to * @param <T> The type of the collection ie Set of String * @return The Java object * @throws GenieException For any exception during unmarshalling */ public static <T extends Collection> T unmarshall( final String source, final TypeReference<T> typeReference ) throws GenieException { try { if (StringUtils.isNotBlank(source)) { return GenieObjectMapper.getMapper().readValue(source, typeReference); } else { return GenieObjectMapper.getMapper().readValue("[]", typeReference); } } catch (final IOException ioe) { throw new GenieServerException("Failed to read JSON value", ioe); } } /** * Given a flat string of command line arguments this method will attempt to tokenize the string and split it for * use in DTOs. The split will occur on whitespace (tab, space, new line, carriage return) while respecting * single quotes to keep those elements together. * <p> * Example: * {@code "/bin/bash -xc 'echo "hello" world!'"} results in {@code ["/bin/bash", "-xc", "echo "hello" world!"]} * * @param commandArgs The original string representation of the command arguments * @return An ordered list of arguments */ @Nonnull public static List<String> splitArguments(final String commandArgs) { final StringTokenizer tokenizer = new StringTokenizer( commandArgs, StringMatcherFactory.INSTANCE.splitMatcher(), StringMatcherFactory.INSTANCE.quoteMatcher() ); return tokenizer.getTokenList(); } /** * Given an ordered list of command line arguments join them back together as a space delimited String where * each argument is wrapped in {@literal '}. * * @param commandArgs The command arguments to join back together * @return The command arguments joined together or {@literal null} if there weren't any arguments */ @Nullable public static String joinArguments(final List<String> commandArgs) { if (commandArgs.isEmpty()) { return null; } else { return commandArgs .stream() .map(argument -> '\'' + argument + '\'') .collect(Collectors.joining(StringUtils.SPACE)); } } /** * Truncate instants to millisecond precision during ISO 8601 serialization to string for backwards compatibility. * * @author tgianos * @since 4.1.2 */ public static class InstantMillisecondSerializer extends JsonSerializer<Instant> { /** * {@inheritDoc} */ @Override public void serialize( final Instant value, final JsonGenerator gen, final SerializerProvider serializers ) throws IOException { gen.writeString(value.truncatedTo(ChronoUnit.MILLIS).toString()); } } /** * Truncate instants to millisecond precision during ISO 8601 serialization to string for backwards compatibility. * * @author tgianos * @since 4.1.2 */ public static class OptionalInstantMillisecondSerializer extends JsonSerializer<Optional<Instant>> { /** * {@inheritDoc} */ @Override public void serialize( final Optional<Instant> value, final JsonGenerator gen, final SerializerProvider serializers ) throws IOException { if (value.isPresent()) { gen.writeString(value.get().truncatedTo(ChronoUnit.MILLIS).toString()); } else { gen.writeNull(); } } } }
2,286
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/util/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes that have common Genie utilities. * * @author tgianos */ package com.netflix.genie.common.util;
2,287
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieUserLimitExceededException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import lombok.Getter; /** * Extension of a GenieException for a user exceeding some limit (e.g., submitting too many jobs). * * @author mprimi * @since 3.1.0 */ @Getter public final class GenieUserLimitExceededException extends GenieException { private static final String ACTIVE_JOBS_LIMIT = "activeJobs"; private final String user; private final String exceededLimitName; /** * Constructor. * * @param user user name * @param limitName limit name * @param message message */ public GenieUserLimitExceededException( final String user, final String limitName, final String message ) { super(429, message); this.user = user; this.exceededLimitName = limitName; } /** * Static factory method to produce a GenieUserLimitExceededException suitable for when the user exceeded the * maximum number of active jobs and its trying to submit yet another. * * @param user the user name * @param activeJobsCount the count of active jobs for this user * @param activeJobsLimit the current limit on active jobs * @return a new GenieUserLimitExceededException */ public static GenieUserLimitExceededException createForActiveJobsLimit( final String user, final long activeJobsCount, final long activeJobsLimit ) { return new GenieUserLimitExceededException( user, ACTIVE_JOBS_LIMIT, "User exceeded active jobs limit (" + activeJobsCount + "/" + activeJobsLimit + ")" ); } }
2,288
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import com.fasterxml.jackson.annotation.JsonFilter; import com.netflix.genie.common.external.util.GenieObjectMapper; /** * The common exception class that represents a service failure. It includes an * HTTP error code and a human-readable error message. * * @author skrishnan * @author tgianos */ @JsonFilter(GenieObjectMapper.EXCEPTIONS_FILTER_NAME) public class GenieException extends Exception { private static final long serialVersionUID = 1L; /* the HTTP error code */ private final int errorCode; /** * Constructor. * * @param errorCode the HTTP status code for this exception * @param msg human readable message * @param cause reason for this exception */ public GenieException(final int errorCode, final String msg, final Throwable cause) { super(msg, cause); this.errorCode = errorCode; } /** * Constructor. * * @param errorCode the HTTP status code for this exception * @param msg human readable message */ public GenieException(final int errorCode, final String msg) { super(msg); this.errorCode = errorCode; } /** * Return the HTTP status code for this exception. * * @return the HTTP status code */ public int getErrorCode() { return errorCode; } }
2,289
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieBadRequestException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for all bad request failures. * * @author tgianos */ public class GenieBadRequestException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GenieBadRequestException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_BAD_REQUEST, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GenieBadRequestException(final String msg) { super(HttpURLConnection.HTTP_BAD_REQUEST, msg); } }
2,290
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GeniePreconditionException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for all precondition failures. * * @author tgianos */ public class GeniePreconditionException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GeniePreconditionException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_PRECON_FAILED, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GeniePreconditionException(final String msg) { super(HttpURLConnection.HTTP_PRECON_FAILED, msg); } }
2,291
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieServerUnavailableException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for all server unavailable failures. * * @author amsharma */ public class GenieServerUnavailableException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GenieServerUnavailableException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_UNAVAILABLE, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GenieServerUnavailableException(final String msg) { super(HttpURLConnection.HTTP_UNAVAILABLE, msg); } }
2,292
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieTimeoutException.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for timeouts. * * @author tgianos * @since 3.0.0 */ public class GenieTimeoutException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GenieTimeoutException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_CLIENT_TIMEOUT, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GenieTimeoutException(final String msg) { super(HttpURLConnection.HTTP_CLIENT_TIMEOUT, msg); } }
2,293
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieNotFoundException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for all not found exceptions. * * @author tgianos */ public class GenieNotFoundException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GenieNotFoundException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_NOT_FOUND, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GenieNotFoundException(final String msg) { super(HttpURLConnection.HTTP_NOT_FOUND, msg); } }
2,294
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes that represent Genie exceptions. * * @author tgianos */ @ParametersAreNonnullByDefault package com.netflix.genie.common.exceptions; import javax.annotation.ParametersAreNonnullByDefault;
2,295
0
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common
Create_ds/genie/genie-common/src/main/java/com/netflix/genie/common/exceptions/GenieServerException.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.common.exceptions; import java.net.HttpURLConnection; /** * Extension of a GenieException for all internal server failures. * * @author tgianos */ public class GenieServerException extends GenieException { /** * Constructor. * * @param msg human readable message * @param cause reason for this exception */ public GenieServerException(final String msg, final Throwable cause) { super(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, cause); } /** * Constructor. * * @param msg human readable message */ public GenieServerException(final String msg) { super(HttpURLConnection.HTTP_INTERNAL_ERROR, msg); } }
2,296
0
Create_ds/genie/genie-ui/src/integTest/java/com/netflix/genie/ui
Create_ds/genie/genie-ui/src/integTest/java/com/netflix/genie/ui/controllers/UIControllerIntegrationTest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.ui.controllers; import com.netflix.genie.web.apis.rest.v3.controllers.GenieExceptionMapper; import org.apache.commons.io.IOUtils; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * Integration tests for {@link UIController}. * * @author mprimi * @since 3.2.0 */ @ExtendWith(SpringExtension.class) @WebMvcTest(UIController.class) @ActiveProfiles("integration") class UIControllerIntegrationTest { @Autowired private MockMvc mvc; @MockBean private GenieExceptionMapper genieExceptionMapper; /** * Test forwarding of various UI pages to index.html. * * @throws Exception in case of error */ @Test void testForwardingToIndex() throws Exception { final List<String> validPaths = Arrays.asList( "/", "/applications", "/clusters", "/commands", "/jobs", "/output" ); for (String validPath : validPaths) { this.mvc .perform(MockMvcRequestBuilders.get(validPath)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("index")) .andReturn(); } } /** * Test serving of the index.html file. * * @throws Exception in case of error */ @Test void testGetIndex() throws Exception { final String indexContent; try (InputStream is = UIController.class.getResourceAsStream("/templates/index.html")) { Assertions.assertThat(is).isNotNull(); Assertions.assertThat(is.available() > 0).isTrue(); indexContent = IOUtils.toString(is, StandardCharsets.UTF_8); } final List<String> validPaths = Arrays.asList( "/", "/applications", "/clusters", "/commands", "/jobs", "/output/12345" ); for (String validPath : validPaths) { this.mvc .perform(MockMvcRequestBuilders.get(validPath)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) .andExpect(MockMvcResultMatchers.content().encoding(StandardCharsets.UTF_8.name())) .andExpect(MockMvcResultMatchers.content().string(indexContent)) .andReturn(); } } /** * Test forwarding of job files to the jobs API. * * @throws Exception in case of error */ @Test void getFile() throws Exception { final String jobId = UUID.randomUUID().toString(); final String file = "foo/bar.txt"; this.mvc .perform(MockMvcRequestBuilders.get("/file/{id}/{path}", jobId, file)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.forwardedUrl("/api/v3/jobs/" + jobId + "/" + file)) .andReturn(); } }
2,297
0
Create_ds/genie/genie-ui/src/integTest/java/com/netflix/genie/ui
Create_ds/genie/genie-ui/src/integTest/java/com/netflix/genie/ui/controllers/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Integration tests for Controllers in this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.ui.controllers; import javax.annotation.ParametersAreNonnullByDefault;
2,298
0
Create_ds/genie/genie-ui/src/test/java/com/netflix/genie/ui
Create_ds/genie/genie-ui/src/test/java/com/netflix/genie/ui/controllers/UIControllerTest.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.ui.controllers; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.web.servlet.HandlerMapping; import javax.servlet.http.HttpServletRequest; import java.net.URLEncoder; import java.util.UUID; /** * Unit tests for UIController class. * * @author tgianos * @since 3.0.0 */ class UIControllerTest { private UIController controller; /** * Setup for the tests. */ @BeforeEach void setup() { this.controller = new UIController(); } /** * Make sure the getIndex endpoint returns the right template name. */ @Test void canGetIndex() { Assertions.assertThat(this.controller.getIndex()).isEqualTo("index"); } /** * Make sure the getFile method returns the right forward command. * * @throws Exception if an error occurs */ @Test void canGetFile() throws Exception { final String id = UUID.randomUUID().toString(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/file/" + id + "/output/genie/log.out"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/file/{id}/**"); final String encodedId = URLEncoder.encode(id, "UTF-8"); final String expectedPath = "/api/v3/jobs/" + encodedId + "/output/genie/log.out"; Assertions.assertThat(this.controller.getFile(id, request)).isEqualTo("forward:" + expectedPath); } }
2,299