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-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/introspection/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.
*
*/
/**
* Auto configurations for the introspection module.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.introspection;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,800 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/introspection/IntrospectionAutoConfiguration.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.web.spring.autoconfigure.introspection;
import com.netflix.genie.common.internal.util.HostnameUtil;
import com.netflix.genie.web.agent.apis.rpc.servers.GRpcServerUtils;
import com.netflix.genie.web.introspection.GenieWebHostInfo;
import com.netflix.genie.web.introspection.GenieWebRpcInfo;
import com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.servers.AgentRpcServersAutoConfiguration;
import io.grpc.Server;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Auto configuration for shared DTO instances within the web server.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@AutoConfigureAfter(
{
AgentRpcServersAutoConfiguration.class
}
)
public class IntrospectionAutoConfiguration {
/**
* Get the {@link GenieWebHostInfo} for this application. This is the default fallback implementation if no other
* bean instance of this type has been created.
*
* @return A {@link GenieWebHostInfo} instance
* @throws UnknownHostException When the host can't be calculated
* @throws IllegalStateException When an instance can't be created
* @see InetAddress#getCanonicalHostName()
*/
@Bean
@ConditionalOnMissingBean(GenieWebHostInfo.class)
public GenieWebHostInfo genieHostInfo() throws UnknownHostException {
final String hostname = HostnameUtil.getHostname();
return new GenieWebHostInfo(hostname);
}
/**
* Provide a {@link GenieWebRpcInfo} bean if one hasn't already been defined.
*
* @param server The gRPC {@link Server} instance. Must not be {@link Server#isShutdown()} or
* {@link Server#isTerminated()}. Must be able to get the port the server is listening on.
* @return A {@link GenieWebRpcInfo} instance
* @throws IllegalStateException When an instance can't be created
*/
@Bean
@ConditionalOnMissingBean(
{
GenieWebRpcInfo.class
}
)
public GenieWebRpcInfo genieWebRpcInfo(final Server server) throws IllegalStateException {
if (server.isShutdown() || server.isTerminated()) {
throw new IllegalStateException("gRPC server is already shut down. Can't start.");
} else {
final int port = GRpcServerUtils.startServer(server);
if (port < 1) {
throw new IllegalStateException("gRPC server started on illegal port: " + port);
}
return new GenieWebRpcInfo(port);
}
}
}
| 2,801 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/properties/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 auto configurations related specifically to property binding.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.properties;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,802 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/properties | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/properties/converters/PropertyConvertersAutoConfiguration.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.web.spring.autoconfigure.properties.converters;
import com.netflix.genie.web.properties.converters.URIPropertyConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Auto configuration for registering {@link org.springframework.boot.context.properties.ConfigurationPropertiesBinding}
* beans.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class PropertyConvertersAutoConfiguration {
/**
* Provide a converter which will convert Strings to absolute {@link java.net.URI} instances.
*
* @return A {@link URIPropertyConverter} instance.
*/
@Bean
public URIPropertyConverter uriPropertyConverter() {
return new URIPropertyConverter();
}
}
| 2,803 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/properties | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/properties/converters/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.
*
*/
/**
* Auto configurations for property conversion.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.properties.converters;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,804 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/scripts/ScriptsAutoConfiguration.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.web.spring.autoconfigure.scripts;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.properties.AgentLauncherSelectorScriptProperties;
import com.netflix.genie.web.properties.ClusterSelectorScriptProperties;
import com.netflix.genie.web.properties.CommandSelectorManagedScriptProperties;
import com.netflix.genie.web.properties.ScriptManagerProperties;
import com.netflix.genie.web.scripts.AgentLauncherSelectorManagedScript;
import com.netflix.genie.web.scripts.ClusterSelectorManagedScript;
import com.netflix.genie.web.scripts.CommandSelectorManagedScript;
import com.netflix.genie.web.scripts.ManagedScript;
import com.netflix.genie.web.scripts.ScriptManager;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.TaskScheduler;
import javax.script.ScriptEngineManager;
import java.util.List;
import java.util.concurrent.Executors;
/**
* Configuration for script extensions.
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
AgentLauncherSelectorScriptProperties.class,
ClusterSelectorScriptProperties.class,
CommandSelectorManagedScriptProperties.class,
ScriptManagerProperties.class,
}
)
public class ScriptsAutoConfiguration {
/**
* Create a {@link ScriptManager} unless one exists.
*
* @param scriptManagerProperties properties
* @param taskScheduler task scheduler
* @param resourceLoader resource loader
* @param meterRegistry meter registry
* @return a {@link ScriptManager}
*/
@Bean
@ConditionalOnMissingBean(ScriptManager.class)
ScriptManager scriptManager(
final ScriptManagerProperties scriptManagerProperties,
@Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
final ResourceLoader resourceLoader,
final MeterRegistry meterRegistry
) {
return new ScriptManager(
scriptManagerProperties,
taskScheduler,
Executors.newCachedThreadPool(),
new ScriptEngineManager(),
resourceLoader,
meterRegistry
);
}
/**
* Create a {@link SmartInitializingSingleton} that "warms" known scripts so they're ready for execution on first
* invocation.
*
* @param managedScripts the managed scripts, if any exist in context
* @return A {@link ManagedScriptPreLoader} that runs after the application context is ready
*/
@Bean
public ManagedScriptPreLoader managedScriptPreLoader(final List<ManagedScript> managedScripts) {
return new ManagedScriptPreLoader(managedScripts);
}
/**
* Create a {@link ClusterSelectorManagedScript} unless one exists.
*
* @param scriptManager script manager
* @param scriptProperties script properties
* @param propertyMapCacheFactory the cache factory
* @param meterRegistry meter registry
* @return a {@link ClusterSelectorManagedScript}
*/
@Bean
@ConditionalOnMissingBean(ClusterSelectorManagedScript.class)
@ConditionalOnProperty(value = ClusterSelectorScriptProperties.SOURCE_PROPERTY)
ClusterSelectorManagedScript clusterSelectorScript(
final ScriptManager scriptManager,
final ClusterSelectorScriptProperties scriptProperties,
final PropertiesMapCache.Factory propertyMapCacheFactory,
final MeterRegistry meterRegistry
) {
return new ClusterSelectorManagedScript(
scriptManager,
scriptProperties,
meterRegistry,
propertyMapCacheFactory.get(
scriptProperties.getPropertiesRefreshInterval(),
ClusterSelectorScriptProperties.SCRIPT_PROPERTIES_PREFIX
)
);
}
/**
* Create a {@link CommandSelectorManagedScript} if necessary and one doesn't already exist.
*
* @param scriptManager script manager
* @param scriptProperties script properties
* @param propertyMapCacheFactory the cache factory
* @param meterRegistry meter registry
* @return a {@link CommandSelectorManagedScript}
*/
@Bean
@ConditionalOnMissingBean(CommandSelectorManagedScript.class)
@ConditionalOnProperty(value = CommandSelectorManagedScriptProperties.SOURCE_PROPERTY)
CommandSelectorManagedScript commandSelectormanagedScript(
final ScriptManager scriptManager,
final CommandSelectorManagedScriptProperties scriptProperties,
final PropertiesMapCache.Factory propertyMapCacheFactory,
final MeterRegistry meterRegistry
) {
return new CommandSelectorManagedScript(
scriptManager,
scriptProperties,
meterRegistry,
propertyMapCacheFactory.get(
scriptProperties.getPropertiesRefreshInterval(),
CommandSelectorManagedScriptProperties.SCRIPT_PROPERTIES_PREFIX
)
);
}
/**
* Create a {@link AgentLauncherSelectorManagedScript} if necessary and one doesn't already exist.
*
* @param scriptManager script manager
* @param scriptProperties script properties
* @param propertyMapCacheFactory the cache factory
* @param meterRegistry meter registry
* @return a {@link AgentLauncherSelectorManagedScript}
*/
@Bean
@ConditionalOnMissingBean(AgentLauncherSelectorManagedScript.class)
@ConditionalOnProperty(value = AgentLauncherSelectorScriptProperties.SOURCE_PROPERTY)
AgentLauncherSelectorManagedScript agentLauncherSelectorManagedScript(
final ScriptManager scriptManager,
final AgentLauncherSelectorScriptProperties scriptProperties,
final PropertiesMapCache.Factory propertyMapCacheFactory,
final MeterRegistry meterRegistry
) {
return new AgentLauncherSelectorManagedScript(
scriptManager,
scriptProperties,
meterRegistry,
propertyMapCacheFactory.get(
scriptProperties.getPropertiesRefreshInterval(),
AgentLauncherSelectorScriptProperties.SCRIPT_PROPERTIES_PREFIX
)
);
}
/**
* A {@link SmartInitializingSingleton} that warms up the existing script beans so they are ready for execution.
*/
static final class ManagedScriptPreLoader implements SmartInitializingSingleton {
private List<ManagedScript> managedScripts;
private ManagedScriptPreLoader(final List<ManagedScript> managedScripts) {
this.managedScripts = managedScripts;
}
/**
* {@inheritDoc}
*/
@Override
public void afterSingletonsInstantiated() {
this.managedScripts.forEach(ManagedScript::warmUp);
}
}
}
| 2,805 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/scripts/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.
*
*/
/**
* Script extensions configuration.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.scripts;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,806 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/aws/AWSAutoConfiguration.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.web.spring.autoconfigure.aws;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.ClientConfigurationFactory;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.regions.AwsRegionProvider;
import com.amazonaws.retry.PredefinedRetryPolicies;
import com.amazonaws.retry.RetryPolicy;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.netflix.genie.web.properties.RetryProperties;
import com.netflix.genie.web.properties.SNSNotificationsProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* AWS beans.
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
RetryProperties.class,
SNSNotificationsProperties.class,
}
)
public class AWSAutoConfiguration {
/**
* The name of the {@link AmazonSNS} client created specifically for job state notifications.
* <p>
* Note: this name must match the bean name defined in
* {@link io.awspring.cloud.messaging.config.annotation.SnsConfiguration} in order to override it.
*/
public static final String SNS_CLIENT_BEAN_NAME = "amazonSNS";
private static final String SNS_CLIENT_CONFIGURATION_BEAN_NAME = "SNSClientConfiguration";
private static final String SNS_CLIENT_RETRY_POLICY_BEAN_NAME = "SNSClientRetryPolicy";
/**
* Create a named {@link RetryPolicy} to be used by the {@link AmazonSNS} client, unless a bean by that name
* already exists in context.
*
* @param retryProperties The retry properties
* @return a named {@link RetryPolicy}
*/
@Bean(name = SNS_CLIENT_RETRY_POLICY_BEAN_NAME)
@ConditionalOnMissingBean(name = SNS_CLIENT_RETRY_POLICY_BEAN_NAME)
public RetryPolicy jobNotificationsSNSClientRetryPolicy(
final RetryProperties retryProperties
) {
return PredefinedRetryPolicies.getDefaultRetryPolicyWithCustomMaxRetries(
retryProperties.getSns().getNoOfRetries()
);
}
/**
* Create a named {@link ClientConfiguration} to be used by the {@link AmazonSNS} client, unless a bean by that
* name already exists in context.
*
* @param retryPolicy The retry policy
* @return a named {@link ClientConfiguration}
*/
@Bean(name = SNS_CLIENT_CONFIGURATION_BEAN_NAME)
@ConditionalOnMissingBean(name = SNS_CLIENT_CONFIGURATION_BEAN_NAME)
public ClientConfiguration jobNotificationsSNSClientConfiguration(
@Qualifier(SNS_CLIENT_RETRY_POLICY_BEAN_NAME) final RetryPolicy retryPolicy
) {
final ClientConfiguration configuration = new ClientConfigurationFactory().getConfig();
configuration.setRetryPolicy(retryPolicy);
return configuration;
}
/**
* Create a named {@link AmazonSNS} client to be used by JobNotification SNS publishers, unless a bean by that
* name already exists in context.
*
* @param credentialsProvider The credentials provider
* @param awsRegionProvider The region provider
* @param clientConfiguration The client configuration
* @return an {@link AmazonSNS} client
*/
@Bean(name = SNS_CLIENT_BEAN_NAME)
@ConditionalOnMissingBean(name = SNS_CLIENT_BEAN_NAME)
@ConditionalOnProperty(value = SNSNotificationsProperties.ENABLED_PROPERTY, havingValue = "true")
public AmazonSNS jobNotificationsSNSClient(
final AWSCredentialsProvider credentialsProvider,
final AwsRegionProvider awsRegionProvider,
@Qualifier(SNS_CLIENT_CONFIGURATION_BEAN_NAME) final ClientConfiguration clientConfiguration
) {
return AmazonSNSClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(awsRegionProvider.getRegion())
.withClientConfiguration(clientConfiguration)
.build();
}
}
| 2,807 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/aws/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.
*
*/
/**
* AWS beans Autoconfiguration.
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.aws;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,808 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/events/EventsAutoConfiguration.java | /*
*
* Copyright 2017 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.web.spring.autoconfigure.events;
import com.netflix.genie.web.events.GenieEventBus;
import com.netflix.genie.web.events.GenieEventBusImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SyncTaskExecutor;
/**
* Configuration related to Eventing within the Genie application.
*
* @author tgianos
* @since 3.1.2
*/
@Configuration
public class EventsAutoConfiguration {
/**
* A multicast event publisher to replace the default one used by Spring via the ApplicationContext.
*
* @param syncTaskExecutor The synchronous task executor to use
* @param asyncTaskExecutor The asynchronous task executor to use
* @return The application event multicaster to use
*/
@Bean
@ConditionalOnMissingBean(GenieEventBus.class)
public GenieEventBusImpl applicationEventMulticaster(
@Qualifier("genieSyncTaskExecutor") final SyncTaskExecutor syncTaskExecutor,
@Qualifier("genieAsyncTaskExecutor") final AsyncTaskExecutor asyncTaskExecutor
) {
final SimpleApplicationEventMulticaster syncMulticaster = new SimpleApplicationEventMulticaster();
syncMulticaster.setTaskExecutor(syncTaskExecutor);
final SimpleApplicationEventMulticaster asyncMulticaster = new SimpleApplicationEventMulticaster();
asyncMulticaster.setTaskExecutor(asyncTaskExecutor);
return new GenieEventBusImpl(syncMulticaster, asyncMulticaster);
}
}
| 2,809 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/events/NotificationsAutoConfiguration.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.web.spring.autoconfigure.events;
import com.amazonaws.services.sns.AmazonSNS;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.web.data.observers.PersistedJobStatusObserver;
import com.netflix.genie.web.data.observers.PersistedJobStatusObserverImpl;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.events.GenieEventBus;
import com.netflix.genie.web.events.JobFinishedSNSPublisher;
import com.netflix.genie.web.events.JobNotificationMetricPublisher;
import com.netflix.genie.web.events.JobStateChangeSNSPublisher;
import com.netflix.genie.web.properties.SNSNotificationsProperties;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Beans related to external notifications.
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
SNSNotificationsProperties.class
}
)
public class NotificationsAutoConfiguration {
/**
* Create {@link PersistedJobStatusObserver} if one does not exist.
*
* @param genieEventBus the genie event bus
* @return a {@link PersistedJobStatusObserver}
*/
@Bean
@ConditionalOnMissingBean(PersistedJobStatusObserver.class)
public PersistedJobStatusObserver persistedJobStatusObserver(
final GenieEventBus genieEventBus
) {
return new PersistedJobStatusObserverImpl(genieEventBus);
}
/**
* Create a {@link JobNotificationMetricPublisher} which publishes metrics related to to job state changes
* notifications.
*
* @param registry the metrics registry
* @return a {@link JobNotificationMetricPublisher}
*/
@Bean
@ConditionalOnMissingBean(JobNotificationMetricPublisher.class)
public JobNotificationMetricPublisher jobNotificationMetricPublisher(
final MeterRegistry registry
) {
return new JobNotificationMetricPublisher(registry);
}
/**
* Create a {@link JobStateChangeSNSPublisher} unless one exists in the context already.
*
* @param snsClient the Amazon SNS client
* @param properties configuration properties
* @param registry the metrics registry
* @return a {@link JobStateChangeSNSPublisher}
*/
@Bean
@ConditionalOnProperty(value = SNSNotificationsProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(JobStateChangeSNSPublisher.class)
public JobStateChangeSNSPublisher jobNotificationsSNSPublisher(
final SNSNotificationsProperties properties,
final MeterRegistry registry,
final AmazonSNS snsClient
) {
return new JobStateChangeSNSPublisher(
snsClient,
properties,
registry,
GenieObjectMapper.getMapper()
);
}
/**
* Create a {@link JobFinishedSNSPublisher} unless one exists in the context already.
*
* @param properties configuration properties
* @param registry the metrics registry
* @param snsClient the Amazon SNS client
* @param dataServices The {@link DataServices} instance to use
* @return a {@link JobFinishedSNSPublisher}
*/
@Bean
@ConditionalOnProperty(value = SNSNotificationsProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(JobFinishedSNSPublisher.class)
public JobFinishedSNSPublisher jobFinishedSNSPublisher(
final SNSNotificationsProperties properties,
final MeterRegistry registry,
final AmazonSNS snsClient,
final DataServices dataServices
) {
return new JobFinishedSNSPublisher(
snsClient,
properties,
dataServices,
registry,
GenieObjectMapper.getMapper()
);
}
}
| 2,810 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/events/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.
*
*/
/**
* Auto configuration for data module of to the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.events;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,811 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/data/DataAutoConfiguration.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.web.spring.autoconfigure.data;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.data.services.impl.jpa.JpaPersistenceServiceImpl;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories;
import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.persistence.EntityManager;
/**
* Default auto configuration of data related services and beans for Genie.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableJpaRepositories("com.netflix.genie.web.data.services.impl.jpa.repositories")
@EntityScan("com.netflix.genie.web.data.services.impl.jpa.entities")
public class DataAutoConfiguration {
/**
* Provide a {@link DataServices} instance if one isn't already in the context.
*
* @param persistenceService The {@link PersistenceService} implementation to use
* @return A {@link DataServices} instance
*/
@Bean
@ConditionalOnMissingBean(DataServices.class)
public DataServices genieDataServices(final PersistenceService persistenceService) {
return new DataServices(persistenceService);
}
/**
* Provide a {@link JpaRepositories} container instance if one wasn't already provided.
*
* @param applicationRepository The {@link JpaApplicationRepository} instance
* @param clusterRepository The {@link JpaClusterRepository} instance
* @param commandRepository The {@link JpaCommandRepository} instance
* @param criterionRepository The {@link JpaCriterionRepository} instance
* @param fileRepository The {@link JpaFileRepository} instance
* @param jobRepository The {@link JpaJobRepository} instance
* @param tagRepository The {@link JpaTagRepository} instance
* @return A new {@link JpaRepositories} instance to simplify passing around all repositories
*/
@Bean
@ConditionalOnMissingBean(JpaRepositories.class)
public JpaRepositories genieJpaRepositories(
final JpaApplicationRepository applicationRepository,
final JpaClusterRepository clusterRepository,
final JpaCommandRepository commandRepository,
final JpaCriterionRepository criterionRepository,
final JpaFileRepository fileRepository,
final JpaJobRepository jobRepository,
final JpaTagRepository tagRepository
) {
return new JpaRepositories(
applicationRepository,
clusterRepository,
commandRepository,
criterionRepository,
fileRepository,
jobRepository,
tagRepository
);
}
/**
* Provide a default implementation of {@link PersistenceService} if no other has been defined.
*
* @param entityManager The {@link EntityManager} for this application
* @param jpaRepositories The {@link JpaRepositories} for Genie
* @param tracingComponents The {@link BraveTracingComponents} instance to use
* @return A {@link JpaPersistenceServiceImpl} instance which implements {@link PersistenceService} backed by
* JPA and a relational database
*/
@Bean
@ConditionalOnMissingBean(PersistenceService.class)
public JpaPersistenceServiceImpl geniePersistenceService(
final EntityManager entityManager,
final JpaRepositories jpaRepositories,
final BraveTracingComponents tracingComponents
) {
return new JpaPersistenceServiceImpl(entityManager, jpaRepositories, tracingComponents);
}
}
| 2,812 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/data/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.
*
*/
/**
* Auto configuration for data module of to the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.data;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,813 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/aspects/AspectsAutoConfiguration.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.web.spring.autoconfigure.aspects;
import com.netflix.genie.web.aspects.DataServiceRetryAspect;
import com.netflix.genie.web.aspects.HealthCheckMetricsAspect;
import com.netflix.genie.web.aspects.SystemArchitecture;
import com.netflix.genie.web.properties.DataServiceRetryProperties;
import io.micrometer.core.instrument.MeterRegistry;
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.context.annotation.EnableAspectJAutoProxy;
/**
* Auto configuration for aspects that should be applied to a running Genie server instance.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
DataServiceRetryProperties.class
}
)
@EnableAspectJAutoProxy
public class AspectsAutoConfiguration {
/**
* An aspect for retrying data layer API calls.
*
* @param retryProperties The properties a user can configure for this aspect
* @return A {@link DataServiceRetryAspect} instance
*/
@Bean
@ConditionalOnMissingBean(DataServiceRetryAspect.class)
public DataServiceRetryAspect getDataServiceRetryAspect(final DataServiceRetryProperties retryProperties) {
return new DataServiceRetryAspect(retryProperties);
}
/**
* An aspect for collecting metrics for health checks.
*
* @param meterRegistry The metrics repository to use
* @return The instance of {@link HealthCheckMetricsAspect}
*/
@Bean
@ConditionalOnMissingBean(HealthCheckMetricsAspect.class)
public HealthCheckMetricsAspect healthCheckMetricsAspect(final MeterRegistry meterRegistry) {
return new HealthCheckMetricsAspect(meterRegistry);
}
/**
* A bean that defines pointcuts for various layers of the Genie system.
*
* @return A {@link SystemArchitecture} instance
*/
@Bean
@ConditionalOnMissingBean(SystemArchitecture.class)
public SystemArchitecture systemArchitecture() {
return new SystemArchitecture();
}
}
| 2,814 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/aspects/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.
*
*/
/**
* Auto configuration for aspects applied to the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.aspects;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,815 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/services/ServicesAutoConfiguration.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.web.spring.autoconfigure.services;
import com.netflix.genie.common.internal.aws.s3.S3ClientFactory;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.services.AgentFileStreamService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.properties.AttachmentServiceProperties;
import com.netflix.genie.web.properties.JobResolutionProperties;
import com.netflix.genie.web.properties.JobsActiveLimitProperties;
import com.netflix.genie.web.properties.JobsForwardingProperties;
import com.netflix.genie.web.properties.JobsLocationsProperties;
import com.netflix.genie.web.properties.JobsMemoryProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.properties.JobsUsersProperties;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.services.ArchivedJobService;
import com.netflix.genie.web.services.AttachmentService;
import com.netflix.genie.web.services.JobDirectoryServerService;
import com.netflix.genie.web.services.JobLaunchService;
import com.netflix.genie.web.services.JobResolverService;
import com.netflix.genie.web.services.RequestForwardingService;
import com.netflix.genie.web.services.impl.ArchivedJobServiceImpl;
import com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl;
import com.netflix.genie.web.services.impl.JobLaunchServiceImpl;
import com.netflix.genie.web.services.impl.JobResolverServiceImpl;
import com.netflix.genie.web.services.impl.LocalFileSystemAttachmentServiceImpl;
import com.netflix.genie.web.services.impl.RequestForwardingServiceImpl;
import com.netflix.genie.web.services.impl.S3AttachmentServiceImpl;
import io.micrometer.core.instrument.MeterRegistry;
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.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.client.RestTemplate;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URI;
import java.util.List;
/**
* Configuration for all the services.
*
* @author amsharma
* @since 3.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
JobsForwardingProperties.class,
JobsLocationsProperties.class,
JobsMemoryProperties.class,
JobsUsersProperties.class,
JobsActiveLimitProperties.class,
AttachmentServiceProperties.class
}
)
public class ServicesAutoConfiguration {
/**
* Provide a bean for {@link JobResolutionProperties} which encapsulates defaults and other values set by
* external configuration related to job resolution.
*
* @param environment The application {@link Environment}
* @return A {@link JobResolutionProperties} instance which will refresh itself in the background
*/
@Bean
public JobResolutionProperties jobResolutionProperties(final Environment environment) {
return new JobResolutionProperties(environment);
}
/**
* Collection of properties related to job execution.
*
* @param forwarding forwarding properties
* @param locations locations properties
* @param memory memory properties
* @param users users properties
* @param activeLimit active limit properties
* @return a {@code JobsProperties} instance
*/
@Bean
public JobsProperties jobsProperties(
final JobsForwardingProperties forwarding,
final JobsLocationsProperties locations,
final JobsMemoryProperties memory,
final JobsUsersProperties users,
final JobsActiveLimitProperties activeLimit
) {
return new JobsProperties(
forwarding,
locations,
memory,
users,
activeLimit
);
}
/**
* The attachment service to use.
*
* @param s3ClientFactory the S3 client factory
* @param attachmentServiceProperties the service properties
* @param meterRegistry the meter registry
* @return The attachment service to use
* @throws IOException if the local filesystem implmentation is used and it fails to initialize
*/
@Bean
@ConditionalOnMissingBean(AttachmentService.class)
public AttachmentService attachmentService(
final S3ClientFactory s3ClientFactory,
final AttachmentServiceProperties attachmentServiceProperties,
final MeterRegistry meterRegistry
) throws IOException {
final @NotNull URI location = attachmentServiceProperties.getLocationPrefix();
final String scheme = location.getScheme();
if ("s3".equals(scheme)) {
return new S3AttachmentServiceImpl(s3ClientFactory, attachmentServiceProperties, meterRegistry);
} else if ("file".equals(scheme)) {
return new LocalFileSystemAttachmentServiceImpl(attachmentServiceProperties);
} else {
throw new IllegalStateException(
"Unknown attachment service implementation to use for location: " + location
);
}
}
/**
* Get an implementation of {@link JobResolverService} if one hasn't already been defined.
*
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param clusterSelectors The {@link ClusterSelector} implementations to use
* @param commandSelector The {@link CommandSelector} implementation to use
* @param registry The metrics repository to use
* @param jobsProperties The properties for running a job set by the user
* @param jobResolutionProperties The {@link JobResolutionProperties} instance
* @param tracingComponents The {@link BraveTracingComponents} to use
* @return A {@link JobResolverServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(JobResolverService.class)
public JobResolverServiceImpl jobResolverService(
final DataServices dataServices,
@NotEmpty final List<ClusterSelector> clusterSelectors,
final CommandSelector commandSelector,
final MeterRegistry registry,
final JobsProperties jobsProperties,
final JobResolutionProperties jobResolutionProperties,
final BraveTracingComponents tracingComponents
) {
return new JobResolverServiceImpl(
dataServices,
clusterSelectors,
commandSelector,
registry,
jobsProperties,
jobResolutionProperties,
tracingComponents
);
}
/**
* Provide the default implementation of {@link JobDirectoryServerService} for serving job directory resources.
*
* @param resourceLoader The application resource loader used to get references to resources
* @param dataServices The {@link DataServices} instance to use
* @param agentFileStreamService The service to request a file from an agent running a job
* @param archivedJobService The {@link ArchivedJobService} implementation to use to get archived
* job data
* @param meterRegistry The meter registry used to keep track of metrics
* @param agentRoutingService The agent routing service
* @return An instance of {@link JobDirectoryServerServiceImpl}
*/
@Bean
@ConditionalOnMissingBean(JobDirectoryServerService.class)
public JobDirectoryServerServiceImpl jobDirectoryServerService(
final ResourceLoader resourceLoader,
final DataServices dataServices,
final AgentFileStreamService agentFileStreamService,
final ArchivedJobService archivedJobService,
final MeterRegistry meterRegistry,
final AgentRoutingService agentRoutingService
) {
return new JobDirectoryServerServiceImpl(
resourceLoader,
dataServices,
agentFileStreamService,
archivedJobService,
meterRegistry,
agentRoutingService
);
}
/**
* Provide a {@link JobLaunchService} implementation if one isn't available.
*
* @param dataServices The {@link DataServices} instance to use
* @param jobResolverService The {@link JobResolverService} implementation to use
* @param agentLauncherSelector The {@link AgentLauncherSelector} implementation to use
* @param tracingComponents The {@link BraveTracingComponents} instance to use
* @param registry The metrics registry to use
* @return A {@link JobLaunchServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(JobLaunchService.class)
public JobLaunchServiceImpl jobLaunchService(
final DataServices dataServices,
final JobResolverService jobResolverService,
final AgentLauncherSelector agentLauncherSelector,
final BraveTracingComponents tracingComponents,
final MeterRegistry registry
) {
return new JobLaunchServiceImpl(
dataServices,
jobResolverService,
agentLauncherSelector,
tracingComponents,
registry
);
}
/**
* Provide a {@link ArchivedJobService} implementation if one hasn't been provided already.
*
* @param dataServices The {@link DataServices} instance to use
* @param resourceLoader The {@link ResourceLoader} to use
* @param meterRegistry The {@link MeterRegistry} implementation to use
* @return A {@link ArchivedJobServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(ArchivedJobService.class)
public ArchivedJobServiceImpl archivedJobService(
final DataServices dataServices,
final ResourceLoader resourceLoader,
final MeterRegistry meterRegistry
) {
return new ArchivedJobServiceImpl(dataServices, resourceLoader, meterRegistry);
}
/**
* Provide a default implementation of {@link RequestForwardingService} for use by other services.
*
* @param genieRestTemplate The {@link RestTemplate} configured to be used to call other Genie nodes
* @param hostInfo The {@link GenieHostInfo} instance containing introspection information about
* the current node
* @param jobsForwardingProperties The properties for forwarding requests between Genie nodes
* @return A {@link RequestForwardingServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(RequestForwardingService.class)
public RequestForwardingServiceImpl requestForwardingService(
@Qualifier("genieRestTemplate") final RestTemplate genieRestTemplate,
final GenieHostInfo hostInfo,
final JobsForwardingProperties jobsForwardingProperties
) {
return new RequestForwardingServiceImpl(genieRestTemplate, hostInfo, jobsForwardingProperties);
}
}
| 2,816 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/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.
*
*/
/**
* Auto configuration for services module of the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,817 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/selectors/SelectorsAutoConfiguration.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.web.spring.autoconfigure.selectors;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.scripts.AgentLauncherSelectorManagedScript;
import com.netflix.genie.web.scripts.ClusterSelectorManagedScript;
import com.netflix.genie.web.scripts.CommandSelectorManagedScript;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.selectors.impl.RandomAgentLauncherSelectorImpl;
import com.netflix.genie.web.selectors.impl.RandomClusterSelectorImpl;
import com.netflix.genie.web.selectors.impl.RandomCommandSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptAgentLauncherSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptClusterSelectorImpl;
import com.netflix.genie.web.selectors.impl.ScriptCommandSelectorImpl;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import javax.validation.constraints.NotEmpty;
import java.util.Collection;
import java.util.Optional;
/**
* Spring Auto Configuration for the {@literal selectors} module.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class SelectorsAutoConfiguration {
/**
* The relative order of the {@link ScriptClusterSelectorImpl} if one is enabled relative to other
* {@link ClusterSelector} instances that may be in the context. This allows users to fit {@literal 50} more
* selectors between the script selector and the default {@link RandomClusterSelectorImpl}. If
* the user wants to place a selector implementation before the script one they only need to subtract from this
* value.
*/
public static final int SCRIPT_CLUSTER_SELECTOR_PRECEDENCE = Ordered.LOWEST_PRECEDENCE - 50;
/**
* Produce the {@link ScriptClusterSelectorImpl} instance to use for this Genie node if it was configured by the
* user. This bean is only created if the script is configured.
*
* @param clusterSelectorManagedScript the cluster selector script
* @param registry the metrics registry
* @return a {@link ScriptClusterSelectorImpl}
*/
@Bean
@Order(SCRIPT_CLUSTER_SELECTOR_PRECEDENCE)
@ConditionalOnBean(ClusterSelectorManagedScript.class)
public ScriptClusterSelectorImpl scriptClusterSelector(
final ClusterSelectorManagedScript clusterSelectorManagedScript,
final MeterRegistry registry
) {
return new ScriptClusterSelectorImpl(clusterSelectorManagedScript, registry);
}
/**
* The default cluster selector if all others fail.
* <p>
* Defaults to {@link Ordered#LOWEST_PRECEDENCE}.
*
* @return A {@link RandomClusterSelectorImpl} instance
*/
@Bean
@Order
public RandomClusterSelectorImpl randomizedClusterSelector() {
return new RandomClusterSelectorImpl();
}
/**
* Provide a default {@link CommandSelector} implementation if no other has been defined in the context already.
*
* @param commandSelectorManagedScriptOptional An {@link Optional} wrapping a {@link CommandSelectorManagedScript}
* instance if one is present in the context else
* {@link Optional#empty()}
* @param registry The {@link MeterRegistry} instance to use
* @return A {@link ScriptCommandSelectorImpl} if a {@link CommandSelectorManagedScript} instance as present else
* a {@link RandomCommandSelectorImpl} instance
*/
@Bean
@ConditionalOnMissingBean(CommandSelector.class)
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public CommandSelector commandSelector(
final Optional<CommandSelectorManagedScript> commandSelectorManagedScriptOptional,
final MeterRegistry registry
) {
if (commandSelectorManagedScriptOptional.isPresent()) {
return new ScriptCommandSelectorImpl(commandSelectorManagedScriptOptional.get(), registry);
} else {
return new RandomCommandSelectorImpl();
}
}
/**
* Provide a default {@link AgentLauncherSelector} implementation if no other has been defined in the context.
*
* @param agentLauncherSelectorManagedScript An {@link Optional} {@link AgentLauncherSelectorManagedScript}
* instance if one is present in the context
* @param agentLaunchers The available agent launchers
* @param registry The {@link MeterRegistry} instance to use
* @return A {@link ScriptAgentLauncherSelectorImpl} if a {@link AgentLauncherSelectorManagedScript} instance is
* present, else a {@link RandomAgentLauncherSelectorImpl} instance
*/
@Bean
@ConditionalOnMissingBean(AgentLauncherSelector.class)
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public AgentLauncherSelector agentLauncherSelector(
final Optional<AgentLauncherSelectorManagedScript> agentLauncherSelectorManagedScript,
@NotEmpty final Collection<AgentLauncher> agentLaunchers,
final MeterRegistry registry
) {
if (agentLauncherSelectorManagedScript.isPresent()) {
return new ScriptAgentLauncherSelectorImpl(
agentLauncherSelectorManagedScript.get(),
agentLaunchers,
registry
);
} else {
return new RandomAgentLauncherSelectorImpl(agentLaunchers);
}
}
}
| 2,818 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/selectors/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.
*
*/
/**
* Auto configuration for the {@literal selectors} module of Genie web.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.selectors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,819 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/CommandSelector.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.web.selectors;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.JobRequest;
import org.springframework.validation.annotation.Validated;
/**
* Interface for any classes which provide a way to select a {@link Command} from a set of commands
* which matched criterion provided by a user in a {@link JobRequest}.
*
* @author tgianos
* @since 4.0.0
*/
@Validated
public interface CommandSelector extends ResourceSelector<Command, CommandSelectionContext> {
}
| 2,820 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/ResourceSelector.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.web.selectors;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
/**
* Generic interface for a selector which selects a resource from a set of resources for a given job request.
*
* @param <R> The type of resource this selector is selecting
* @param <C> The type of context which this selector will accept. Must extend {@link ResourceSelectionContext}
* @author tgianos
* @since 4.0.0
*/
@Validated
public interface ResourceSelector<R, C extends ResourceSelectionContext<R>> {
/**
* Select a resource from the given set of resources if possible.
*
* @param context The context specific for this resource selection
* @return The a {@link ResourceSelectionResult} instance which contains information about the result of this
* invocation
* @throws ResourceSelectionException When the underlying implementation can't successfully come to a selection
* decision
*/
ResourceSelectionResult<R> select(@Valid C context) throws ResourceSelectionException;
}
| 2,821 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/ResourceSelectionContext.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.web.selectors;
import com.netflix.genie.common.internal.dtos.JobRequest;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Set;
/**
* Context object for encapsulating state into the selectors.
*
* @param <R> The type of resource this context is meant to help select
* @author tgianos
* @since 4.0.0
*/
@RequiredArgsConstructor
@Getter
@ToString(doNotUseGetters = true)
public abstract class ResourceSelectionContext<R> {
@NotBlank
private final String jobId;
@NotNull
private final JobRequest jobRequest;
private final boolean apiJob;
/**
* Return the {@link Set} of distinct resources that a selector is meant to chose from.
*
* @return The resources
*/
public abstract Set<R> getResources();
}
| 2,822 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/AgentLauncherSelectionContext.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.web.selectors;
import com.google.common.collect.ImmutableSet;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobRequestMetadata;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.dtos.ResolvedJob;
import lombok.Getter;
import lombok.ToString;
import javax.validation.constraints.NotBlank;
import java.util.Collection;
import java.util.Set;
/**
* Extension of {@link ResourceSelectionContext} to include specific data useful in AgentLauncher selection.
*
* @author mprimi
* @since 4.0.0
*/
@Getter
@ToString(callSuper = true, doNotUseGetters = true)
public class AgentLauncherSelectionContext extends ResourceSelectionContext<AgentLauncher> {
private final JobRequestMetadata jobRequestMetadata;
private final ResolvedJob resolvedJob;
private final Set<AgentLauncher> agentLaunchers;
/**
* Constructor.
*
* @param jobId the job id
* @param jobRequest the job request
* @param jobRequestMetadata the job request metadata
* @param resolvedJob the resolved job details
* @param agentLaunchers the list of available launchers
*/
public AgentLauncherSelectionContext(
@NotBlank final String jobId,
final JobRequest jobRequest,
final JobRequestMetadata jobRequestMetadata,
final ResolvedJob resolvedJob,
final Collection<AgentLauncher> agentLaunchers
) {
super(jobId, jobRequest, true);
this.jobRequestMetadata = jobRequestMetadata;
this.resolvedJob = resolvedJob;
this.agentLaunchers = ImmutableSet.copyOf(agentLaunchers);
}
/**
* {@inheritDoc}
*/
@Override
public Set<AgentLauncher> getResources() {
return agentLaunchers;
}
}
| 2,823 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/AgentLauncherSelector.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.web.selectors;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import org.springframework.validation.annotation.Validated;
import java.util.Collection;
/**
* Interface for any classes which provide a way to select a {@link AgentLauncher} from a set of available candidates.
*
* @author mprimi
* @since 4.0.0
*/
@Validated
public interface AgentLauncherSelector extends ResourceSelector<AgentLauncher, AgentLauncherSelectionContext> {
/**
* Get the list of all available {@link AgentLauncher}.
*
* @return a collection of {@link AgentLauncher}
*/
Collection<AgentLauncher> getAgentLaunchers();
}
| 2,824 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/ClusterSelectionContext.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.web.selectors;
import com.google.common.collect.ImmutableSet;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.JobRequest;
import lombok.Getter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Optional;
import java.util.Set;
/**
* Extension of {@link ResourceSelectionContext} to include specific data useful in cluster selection.
*
* @author tgianos
* @since 4.0.0
*/
@Getter
@ToString(callSuper = true, doNotUseGetters = true)
public class ClusterSelectionContext extends ResourceSelectionContext<Cluster> {
private final Command command;
private final Set<Cluster> clusters;
/**
* Constructor.
*
* @param jobId The id of the job which the command is being selected for
* @param jobRequest The job request the user originally made
* @param apiJob Whether the job was submitted via the API or from Agent CLI
* @param command The command which was already selected (if there was one)
* @param clusters The clusters to choose from
*/
public ClusterSelectionContext(
@NotEmpty final String jobId,
@NotNull final JobRequest jobRequest,
final boolean apiJob,
@Nullable @Valid final Command command,
@NotEmpty final Set<@Valid Cluster> clusters
) {
super(jobId, jobRequest, apiJob);
this.command = command;
this.clusters = ImmutableSet.copyOf(clusters);
}
/**
* Get the command which was already selected for the job if there was one.
* <p>
* This is currently returning an optional due to the support for v3 and v4 algorithms. Once v4 is the only
* resource selection algorithm command will no longer be optional.
*
* @return The {@link Command} wrapped in an {@link Optional}
*/
public Optional<Command> getCommand() {
return Optional.ofNullable(this.command);
}
/**
* {@inheritDoc}
*/
@Override
public Set<Cluster> getResources() {
return this.clusters;
}
}
| 2,825 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/ClusterSelector.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.web.selectors;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.JobRequest;
import org.springframework.validation.annotation.Validated;
/**
* Interface for any classes which provide a way to select a {@link Cluster} from a set of clusters
* which matched criterion provided by a user in a {@link JobRequest} and combined with the criteria for the command
* selected for a given job.
*
* @author tgianos
* @since 2.0.0
*/
@Validated
public interface ClusterSelector extends ResourceSelector<Cluster, ClusterSelectionContext> {
}
| 2,826 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/CommandSelectionContext.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.web.selectors;
import com.google.common.collect.ImmutableMap;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.JobRequest;
import lombok.Getter;
import lombok.ToString;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Map;
import java.util.Set;
/**
* Extension of {@link ResourceSelectionContext} to include specific data useful in command selection.
*
* @author tgianos
* @since 4.0.0
*/
@Getter
@ToString(callSuper = true, doNotUseGetters = true)
public class CommandSelectionContext extends ResourceSelectionContext<Command> {
private final Map<Command, Set<Cluster>> commandToClusters;
/**
* Constructor.
*
* @param jobId The id of the job which the command is being selected for
* @param jobRequest The job request the user originally made
* @param apiJob Whether the job was submitted via the API or from Agent CLI
* @param commandToClusters The map of command candidates to their respective clusters candidates
*/
public CommandSelectionContext(
@NotBlank final String jobId,
@NotNull final JobRequest jobRequest,
final boolean apiJob,
@NotEmpty final Map<@Valid Command, @NotEmpty Set<@Valid Cluster>> commandToClusters
) {
super(jobId, jobRequest, apiJob);
this.commandToClusters = ImmutableMap.copyOf(commandToClusters);
}
/**
* {@inheritDoc}
*/
@Override
public Set<Command> getResources() {
return this.commandToClusters.keySet();
}
}
| 2,827 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/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.
*
*/
/**
* Package to contain interfaces and classes which provide plugin functionality for selecting resources at runtime
* for jobs.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.selectors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,828 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/RandomClusterSelectorImpl.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.web.selectors.impl;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.web.selectors.ClusterSelectionContext;
import com.netflix.genie.web.selectors.ClusterSelector;
/**
* Basic implementation of a {@link ClusterSelector} where a random {@link Cluster} is selected from the options
* presented.
*
* @author tgianos
* @since 2.0.0
*/
public class RandomClusterSelectorImpl
extends RandomResourceSelector<Cluster, ClusterSelectionContext>
implements ClusterSelector {
}
| 2,829 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/RandomResourceSelector.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.web.selectors.impl;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.selectors.ResourceSelectionContext;
import com.netflix.genie.web.selectors.ResourceSelector;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
/**
* A base class for any selector which desires to select a random element from a collection of elements.
*
* @param <R> The type of resource the collection has
* @param <C> The type of context which this selector will accept. Must extend {@link ResourceSelectionContext}
* @author tgianos
* @since 4.0.0
*/
@Slf4j
class RandomResourceSelector<R, C extends ResourceSelectionContext<R>> implements ResourceSelector<R, C> {
static final String SELECTION_RATIONALE = "Selected randomly";
private final Random random = new Random();
/**
* {@inheritDoc}
*/
@Override
public ResourceSelectionResult<R> select(@Valid final C context) throws ResourceSelectionException {
log.debug("Called to select for job {}", context.getJobId());
final ResourceSelectionResult.Builder<R> builder = new ResourceSelectionResult.Builder<>(this.getClass());
try {
final R selectedResource = this.randomlySelect(context.getResources());
return builder.withSelectionRationale(SELECTION_RATIONALE).withSelectedResource(selectedResource).build();
} catch (final Exception e) {
throw new ResourceSelectionException(e);
}
}
@Nullable
private R randomlySelect(@NotEmpty final Collection<R> resources) {
// return a random one
final int index = this.random.nextInt(resources.size());
final Iterator<R> resourceIterator = resources.iterator();
R selectedResource = null;
int i = 0;
while (resourceIterator.hasNext() && i <= index) {
selectedResource = resourceIterator.next();
i++;
}
return selectedResource;
}
}
| 2,830 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/ScriptCommandSelectorImpl.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.web.selectors.impl;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.scripts.CommandSelectorManagedScript;
import com.netflix.genie.web.scripts.ResourceSelectorScriptResult;
import com.netflix.genie.web.selectors.CommandSelectionContext;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.util.MetricsConstants;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Implementation of {@link CommandSelector} which defers the decision to a script provided by the system
* administrators.
*
* @author tgianos
* @since 4.0.0
*/
@Slf4j
public class ScriptCommandSelectorImpl implements CommandSelector {
static final String SELECT_TIMER_NAME = "genie.selectors.command.script.select.timer";
private static final String NULL_TAG = "null";
private static final String NULL_RATIONALE = "Script returned no command, no preference";
private final CommandSelectorManagedScript commandSelectorManagedScript;
private final MeterRegistry registry;
/**
* Constructor.
*
* @param commandSelectorManagedScript The {@link CommandSelectorManagedScript} instance to use
* @param registry The {@link MeterRegistry} to use
*/
public ScriptCommandSelectorImpl(
final CommandSelectorManagedScript commandSelectorManagedScript,
final MeterRegistry registry
) {
this.commandSelectorManagedScript = commandSelectorManagedScript;
this.registry = registry;
}
/**
* {@inheritDoc}
*/
@Override
public ResourceSelectionResult<Command> select(
@Valid final CommandSelectionContext context
) throws ResourceSelectionException {
final long selectStart = System.nanoTime();
final String jobId = context.getJobId();
final Set<Command> resources = context.getResources();
log.debug("Called to select a command from {} for job {}", resources, jobId);
final Set<Tag> tags = Sets.newHashSet();
final ResourceSelectionResult.Builder<Command> builder = new ResourceSelectionResult.Builder<>(this.getClass());
try {
final ResourceSelectorScriptResult<Command> result
= this.commandSelectorManagedScript.selectResource(context);
MetricsUtils.addSuccessTags(tags);
final Optional<Command> commandOptional = result.getResource();
if (!commandOptional.isPresent()) {
final String rationale = result.getRationale().orElse(NULL_RATIONALE);
log.debug("No command selected due to: {}", rationale);
tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_ID, NULL_TAG));
builder.withSelectionRationale(rationale);
return builder.build();
}
final Command selectedCommand = commandOptional.get();
tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_ID, selectedCommand.getId()));
tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_NAME, selectedCommand.getMetadata().getName()));
return builder
.withSelectionRationale(result.getRationale().orElse(null))
.withSelectedResource(selectedCommand)
.build();
} catch (final Throwable e) {
final String errorMessage = "Command selection error: " + e.getMessage();
log.error(errorMessage, e);
MetricsUtils.addFailureTagsWithException(tags, e);
if (e instanceof ResourceSelectionException) {
throw e;
} else {
throw new ResourceSelectionException(e);
}
} finally {
this.registry
.timer(SELECT_TIMER_NAME, tags)
.record(System.nanoTime() - selectStart, TimeUnit.NANOSECONDS);
}
}
}
| 2,831 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/RandomAgentLauncherSelectorImpl.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.web.selectors.impl;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.selectors.AgentLauncherSelectionContext;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import lombok.Getter;
import java.util.Collection;
/**
* Basic implementation of a {@link AgentLauncherSelector} where a random {@link AgentLauncher} is selected from the
* options presented.
*
* @author mprimi
* @since 4.0.0
*/
public class RandomAgentLauncherSelectorImpl
extends RandomResourceSelector<AgentLauncher, AgentLauncherSelectionContext>
implements AgentLauncherSelector {
@Getter
private final Collection<AgentLauncher> agentLaunchers;
/**
* Constructor.
*
* @param agentLaunchers the list of available {@link AgentLauncher}.
*/
public RandomAgentLauncherSelectorImpl(final Collection<AgentLauncher> agentLaunchers) {
this.agentLaunchers = agentLaunchers;
}
}
| 2,832 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/ScriptAgentLauncherSelectorImpl.java | /*
*
* Copyright 2017 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.web.selectors.impl;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.scripts.AgentLauncherSelectorManagedScript;
import com.netflix.genie.web.scripts.ResourceSelectorScriptResult;
import com.netflix.genie.web.selectors.AgentLauncherSelectionContext;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.util.MetricsConstants;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* An implementation of the {@link AgentLauncherSelector} interface which uses user-provided script to make decisions
* based on the list of agent launchers and the job request supplied.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class ScriptAgentLauncherSelectorImpl implements AgentLauncherSelector {
static final String SELECT_TIMER_NAME = "genie.jobs.agentLauncher.selectors.script.select.timer";
private static final String NULL_TAG = "null";
private static final String NULL_RATIONALE = "Script returned null, no preference";
private final AgentLauncherSelectorManagedScript agentLauncherSelectorManagedScript;
private final Set<AgentLauncher> agentLaunchers;
private final MeterRegistry registry;
/**
* Constructor.
*
* @param agentLauncherSelectorManagedScript the agent launcher selector script
* @param agentLaunchers the available agent launchers
* @param registry the metrics registry
*/
public ScriptAgentLauncherSelectorImpl(
final AgentLauncherSelectorManagedScript agentLauncherSelectorManagedScript,
final Collection<AgentLauncher> agentLaunchers,
final MeterRegistry registry
) {
this.agentLauncherSelectorManagedScript = agentLauncherSelectorManagedScript;
this.agentLaunchers = ImmutableSet.copyOf(agentLaunchers);
this.registry = registry;
}
/**
* {@inheritDoc}
*/
@Override
public ResourceSelectionResult<AgentLauncher> select(
@Valid final AgentLauncherSelectionContext context
) throws ResourceSelectionException {
final long selectStart = System.nanoTime();
final String jobId = context.getJobId();
final Set<AgentLauncher> resources = context.getAgentLaunchers();
log.debug("Called to select agent launcher from {} for job {}", resources, jobId);
final Set<Tag> tags = Sets.newHashSet();
final ResourceSelectionResult.Builder<AgentLauncher> builder =
new ResourceSelectionResult.Builder<>(this.getClass());
try {
final ResourceSelectorScriptResult<AgentLauncher> result
= this.agentLauncherSelectorManagedScript.selectResource(context);
MetricsUtils.addSuccessTags(tags);
final Optional<AgentLauncher> agentLauncherOptional = result.getResource();
if (!agentLauncherOptional.isPresent()) {
final String rationale = result.getRationale().orElse(NULL_RATIONALE);
log.debug("No agent launcher selected due to: {}", rationale);
tags.add(Tag.of(MetricsConstants.TagKeys.AGENT_LAUNCHER_CLASS, NULL_TAG));
builder.withSelectionRationale(rationale);
return builder.build();
}
final AgentLauncher selectedAgentLauncher = agentLauncherOptional.get();
tags.add(
Tag.of(MetricsConstants.TagKeys.AGENT_LAUNCHER_CLASS, selectedAgentLauncher.getClass().getSimpleName())
);
return builder
.withSelectionRationale(result.getRationale().orElse(null))
.withSelectedResource(selectedAgentLauncher)
.build();
} catch (final Throwable e) {
final String errorMessage = "Agent launcher selection error: " + e.getMessage();
log.error(errorMessage, e);
MetricsUtils.addFailureTagsWithException(tags, e);
if (e instanceof ResourceSelectionException) {
throw e;
} else {
throw new ResourceSelectionException(e);
}
} finally {
this.registry
.timer(SELECT_TIMER_NAME, tags)
.record(System.nanoTime() - selectStart, TimeUnit.NANOSECONDS);
}
}
@Override
public Collection<AgentLauncher> getAgentLaunchers() {
return agentLaunchers;
}
}
| 2,833 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/ScriptClusterSelectorImpl.java | /*
*
* Copyright 2017 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.web.selectors.impl;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.scripts.ClusterSelectorManagedScript;
import com.netflix.genie.web.scripts.ResourceSelectorScriptResult;
import com.netflix.genie.web.selectors.ClusterSelectionContext;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.util.MetricsConstants;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* An implementation of the {@link ClusterSelector} interface which uses user-provided script to make decisions
* based on the list of clusters and the job request supplied.
*
* @author tgianos
* @since 3.1.0
*/
@Slf4j
public class ScriptClusterSelectorImpl implements ClusterSelector {
static final String SELECT_TIMER_NAME = "genie.jobs.clusters.selectors.script.select.timer";
private static final String NULL_TAG = "null";
private static final String NULL_RATIONALE = "Script returned null, no preference";
private final MeterRegistry registry;
private final ClusterSelectorManagedScript clusterSelectorManagedScript;
/**
* Constructor.
*
* @param clusterSelectorManagedScript the cluster selector script
* @param registry the metrics registry
*/
public ScriptClusterSelectorImpl(
final ClusterSelectorManagedScript clusterSelectorManagedScript,
final MeterRegistry registry
) {
this.clusterSelectorManagedScript = clusterSelectorManagedScript;
this.registry = registry;
}
/**
* {@inheritDoc}
*/
@Override
public ResourceSelectionResult<Cluster> select(
@Valid final ClusterSelectionContext context
) throws ResourceSelectionException {
final long selectStart = System.nanoTime();
final String jobId = context.getJobId();
final Set<Cluster> resources = context.getClusters();
log.debug("Called to select cluster from {} for job {}", resources, jobId);
final Set<Tag> tags = Sets.newHashSet();
final ResourceSelectionResult.Builder<Cluster> builder = new ResourceSelectionResult.Builder<>(this.getClass());
try {
final ResourceSelectorScriptResult<Cluster> result
= this.clusterSelectorManagedScript.selectResource(context);
MetricsUtils.addSuccessTags(tags);
final Optional<Cluster> clusterOptional = result.getResource();
if (!clusterOptional.isPresent()) {
final String rationale = result.getRationale().orElse(NULL_RATIONALE);
log.debug("No cluster selected due to: {}", rationale);
tags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_ID, NULL_TAG));
builder.withSelectionRationale(rationale);
return builder.build();
}
final Cluster selectedCluster = clusterOptional.get();
tags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_ID, selectedCluster.getId()));
tags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_NAME, selectedCluster.getMetadata().getName()));
return builder
.withSelectionRationale(result.getRationale().orElse(null))
.withSelectedResource(selectedCluster)
.build();
} catch (final Throwable e) {
final String errorMessage = "Cluster selection error: " + e.getMessage();
log.error(errorMessage, e);
MetricsUtils.addFailureTagsWithException(tags, e);
if (e instanceof ResourceSelectionException) {
throw e;
} else {
throw new ResourceSelectionException(e);
}
} finally {
this.registry
.timer(SELECT_TIMER_NAME, tags)
.record(System.nanoTime() - selectStart, TimeUnit.NANOSECONDS);
}
}
}
| 2,834 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/RandomCommandSelectorImpl.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.web.selectors.impl;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.web.selectors.CommandSelectionContext;
import com.netflix.genie.web.selectors.CommandSelector;
/**
* Basic implementation of a {@link CommandSelector} where a random {@link Command} is selected from the options
* presented.
*
* @author tgianos
* @since 4.0.0
*/
public class RandomCommandSelectorImpl
extends RandomResourceSelector<Command, CommandSelectionContext>
implements CommandSelector {
}
| 2,835 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/selectors/impl/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.
*
*/
/**
* Implementations of various selector interfaces.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.selectors.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,836 |
0 | Create_ds/genie/genie-common-external/src/main/java/com/netflix/genie/common/external | Create_ds/genie/genie-common-external/src/main/java/com/netflix/genie/common/external/util/GenieObjectMapper.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.external.util;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.time.ZoneId;
import java.util.Map;
import java.util.TimeZone;
/**
* A singleton for sharing a Jackson Object Mapper instance across Genie and not having to redefine the Object Mapper
* everywhere.
*
* @author tgianos
* @since 4.0.0
*/
public final class GenieObjectMapper {
/**
* The name of the {@link PropertyFilter} used to serialize Genie exceptions.
*/
public static final String EXCEPTIONS_FILTER_NAME = "GenieExceptionsJSONFilter";
/**
* The actual filter used for Genie exceptions. Ignores all fields except the ones listed below.
*/
private static final PropertyFilter EXCEPTIONS_FILTER = new SimpleBeanPropertyFilter.FilterExceptFilter(
ImmutableSet.of(
"errorCode",
"message"
)
);
/**
* Classes annotated with {@link JsonFilter} request to be processed with a certain filter by name.
* This map encodes the name to filter map in a form suitable for the {@link SimpleFilterProvider} below.
*/
private static final Map<String, PropertyFilter> FILTERS_MAP = ImmutableMap.of(
EXCEPTIONS_FILTER_NAME, EXCEPTIONS_FILTER
);
/**
* The {@link FilterProvider} to be installed in the {@link ObjectMapper}.
*/
public static final FilterProvider FILTER_PROVIDER = new SimpleFilterProvider(FILTERS_MAP);
private static final ObjectMapper MAPPER = JsonMapper.builder()
.addModule(new Jdk8Module())
.addModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
.defaultTimeZone(TimeZone.getTimeZone(ZoneId.of("UTC")))
.filterProvider(FILTER_PROVIDER)
.build();
private GenieObjectMapper() {
}
/**
* Get the preconfigured Object Mapper used across Genie for consistency.
*
* @return The object mapper to use
*/
public static ObjectMapper getMapper() {
return MAPPER;
}
}
| 2,837 |
0 | Create_ds/genie/genie-common-external/src/main/java/com/netflix/genie/common/external | Create_ds/genie/genie-common-external/src/main/java/com/netflix/genie/common/external/util/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 utility classes shared amongst various Genie modules.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.common.external.util;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,838 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/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.
*
*/
/**
* Classes shared by the entire Agent project.
*
* @author mprimi
* @since 4.0.0
*/
package com.netflix.genie.agent;
| 2,839 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/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.
*
*/
/**
* Utility classes tests.
*
* @author mprimi
* @since 4.0.0
*/
package com.netflix.genie.agent.utils;
| 2,840 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks/impl/FileLockTests.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.agent.utils.locks.impl;
import com.netflix.genie.agent.execution.exceptions.LockException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
/**
* Tests for {@link FileLock}.
*
* @author standon
* @since 4.0.0
*/
class FileLockTests {
/**
* Make sure close method for a FileLock gets called .
*
* @throws IOException when the file is bad
* @throws LockException when there is a problem getting lock on the file
*/
@Test
void fileLockClosed() throws IOException, LockException {
final FileLock mockLock = Mockito.mock(FileLock.class);
try (CloseableLock lock = mockLock) {
lock.lock();
}
Mockito.verify(mockLock, Mockito.times(1)).close();
}
/**
* Make sure close method for a FileLock gets called on exception.
*
* @throws IOException when the file is bad
*/
@Test
void fileLockClosedOnException() throws IOException {
final FileLock mockLock = Mockito.mock(FileLock.class);
try (CloseableLock lock = mockLock) {
lock.lock();
throw new LockException("dummy exception");
} catch (LockException ignored) {
}
Mockito.verify(mockLock, Mockito.times(1)).close();
}
}
| 2,841 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks/impl/FileLockFactoryTest.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.agent.utils.locks.impl;
import com.netflix.genie.agent.execution.exceptions.LockException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
/**
* Tests for {@link FileLockFactory}.
*
* @author standon
* @since 4.0.0
*/
class FileLockFactoryTest {
private FileLockFactory fileLockFactory;
@BeforeEach
void setup() {
this.fileLockFactory = new FileLockFactory();
}
@Test
void canGetTaskExecutor(@TempDir final Path tmpDir) throws IOException, LockException {
Assertions
.assertThat(
this.fileLockFactory.getLock(Files.createFile(tmpDir.resolve(UUID.randomUUID().toString())).toFile())
)
.isInstanceOf(FileLock.class);
}
}
| 2,842 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/utils/locks/impl/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.
*
*/
/**
* Lock implementation tests.
*
* @author standon
* @since 4.0.0
*/
package com.netflix.genie.agent.utils.locks.impl;
| 2,843 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/cli/CliAutoConfigurationTest.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.agent.cli;
import brave.Tracer;
import com.netflix.genie.agent.AgentMetadata;
import com.netflix.genie.agent.cli.logging.AgentLogManager;
import com.netflix.genie.agent.execution.services.AgentHeartBeatService;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.agent.execution.services.DownloadService;
import com.netflix.genie.agent.execution.services.KillService;
import com.netflix.genie.agent.execution.statemachine.JobExecutionStateMachineImpl;
import com.netflix.genie.agent.properties.AgentProperties;
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 org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import javax.xml.validation.Validator;
/**
* Tests for {@link CliAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class CliAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
CliAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(AgentProperties.class);
Assertions.assertThat(context).hasSingleBean(ArgumentDelegates.CacheArguments.class);
Assertions.assertThat(context).hasSingleBean(DownloadCommand.DownloadCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(ExecCommand.ExecCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(ExecCommand.class);
Assertions.assertThat(context).hasSingleBean(GenieAgentRunner.class);
Assertions.assertThat(context).hasSingleBean(HeartBeatCommand.HeartBeatCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(HeartBeatCommand.class);
Assertions.assertThat(context).hasSingleBean(HelpCommand.HelpCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(HelpCommand.class);
Assertions.assertThat(context).hasSingleBean(InfoCommand.InfoCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(InfoCommand.class);
Assertions.assertThat(context).hasSingleBean(MainCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(ArgumentDelegates.JobRequestArguments.class);
Assertions.assertThat(context).hasSingleBean(JobRequestConverter.class);
Assertions.assertThat(context).hasSingleBean(PingCommand.PingCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(PingCommand.class);
Assertions
.assertThat(context)
.hasSingleBean(ResolveJobSpecCommand.ResolveJobSpecCommandArguments.class);
Assertions.assertThat(context).hasSingleBean(ResolveJobSpecCommand.class);
Assertions.assertThat(context).hasSingleBean(ArgumentDelegates.ServerArguments.class);
Assertions.assertThat(context).hasSingleBean(ArgumentDelegates.CleanupArguments.class);
Assertions.assertThat(context).hasSingleBean(ArgumentDelegates.RuntimeConfigurationArguments.class);
Assertions.assertThat(context).hasSingleBean(AgentLogManager.class);
}
);
}
private static final class ExternalBeans {
@Bean
DownloadService downloadService() {
return Mockito.mock(DownloadService.class);
}
@Bean
KillService killService() {
return Mockito.mock(KillService.class);
}
@Bean
JobExecutionStateMachineImpl jobExecutionStateMachine() {
return Mockito.mock(JobExecutionStateMachineImpl.class);
}
@Bean
ArgumentParser argumentParser() {
return Mockito.mock(ArgumentParser.class);
}
@Bean
CommandFactory commandFactory() {
return Mockito.mock(CommandFactory.class);
}
@Bean
AgentHeartBeatService agentHeartBeatService() {
return Mockito.mock(AgentHeartBeatService.class);
}
@Bean
AgentMetadata agentMetadata() {
return Mockito.mock(AgentMetadata.class);
}
@Bean
Validator validator() {
return Mockito.mock(Validator.class);
}
@Bean
AgentJobService agentJobService() {
return Mockito.mock(AgentJobService.class);
}
@Bean
AgentLogManager agentLogManager() {
return Mockito.mock(AgentLogManager.class);
}
@Bean
BraveTracingComponents braveTracingComponents() {
return new BraveTracingComponents(
Mockito.mock(Tracer.class),
Mockito.mock(BraveTracePropagator.class),
Mockito.mock(BraveTracingCleanup.class),
Mockito.mock(BraveTagAdapter.class)
);
}
}
}
| 2,844 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/cli/TestCommands.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.agent.cli;
import com.beust.jcommander.Parameters;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Set;
/**
* Example AgentCommand and AgentCommandArguments used in tests.
*
* @author mprimi
* @since 4.0.0
*/
final class TestCommands {
private TestCommands() {
}
static List<AgentCommandArguments> allCommandArguments() {
return ImmutableList.of(
new ExampleCommandArgs1(),
new ExampleCommandArgs2()
);
}
static Set<String> allCommandNames() {
return ImmutableSet.of(
ExampleCommand1.NAME,
ExampleCommand1.SHORT_NAME,
ExampleCommand2.NAME,
ExampleCommand2.SHORT_NAME
);
}
static class ExampleCommand1 implements AgentCommand {
static final String NAME = "example1";
static final String SHORT_NAME = "ex1";
@Override
public ExitCode run() {
return ExitCode.SUCCESS;
}
}
@Parameters(commandNames = {ExampleCommand1.NAME, ExampleCommand1.SHORT_NAME})
static class ExampleCommandArgs1 implements AgentCommandArguments {
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return ExampleCommand1.class;
}
}
static class ExampleCommand2 implements AgentCommand {
static final String NAME = "example2";
static final String SHORT_NAME = "ex2";
@Override
public ExitCode run() {
return ExitCode.SUCCESS;
}
}
@Parameters(commandNames = {ExampleCommand2.NAME, ExampleCommand2.SHORT_NAME})
static class ExampleCommandArgs2 implements AgentCommandArguments {
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return ExampleCommand2.class;
}
}
}
| 2,845 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/cli/JCommanderAutoConfigurationTest.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.agent.cli;
import com.beust.jcommander.JCommander;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
/**
* Tests for {@link JCommanderAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class JCommanderAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
JCommanderAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GlobalAgentArguments.class);
Assertions.assertThat(context).hasSingleBean(JCommander.class);
Assertions.assertThat(context).hasSingleBean(CommandFactory.class);
Assertions.assertThat(context).hasSingleBean(ArgumentParser.class);
}
);
}
private static class ExternalBeans {
@Bean
MainCommandArguments mainCommandArguments() {
return Mockito.mock(MainCommandArguments.class);
}
}
}
| 2,846 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/cli/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.
*
*/
/**
* Commands for Agent and their command-line arguments descriptors.
*
* @author mprimi
* @since 4.0.0
*/
package com.netflix.genie.agent.cli;
| 2,847 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/ExecutionAutoConfigurationTest.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.agent.execution;
import brave.Tracer;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.netflix.genie.agent.AgentMetadata;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.cli.JobRequestConverter;
import com.netflix.genie.agent.cli.logging.AgentLogManager;
import com.netflix.genie.agent.execution.process.JobProcessManager;
import com.netflix.genie.agent.execution.services.AgentFileStreamService;
import com.netflix.genie.agent.execution.services.AgentHeartBeatService;
import com.netflix.genie.agent.execution.services.AgentJobKillService;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.agent.execution.services.JobMonitorService;
import com.netflix.genie.agent.execution.services.JobSetupService;
import com.netflix.genie.agent.execution.statemachine.ExecutionContext;
import com.netflix.genie.agent.execution.statemachine.ExecutionStage;
import com.netflix.genie.agent.execution.statemachine.JobExecutionStateMachine;
import com.netflix.genie.agent.execution.statemachine.listeners.ConsoleLogListener;
import com.netflix.genie.agent.execution.statemachine.listeners.LoggingListener;
import com.netflix.genie.agent.execution.statemachine.stages.ArchiveJobOutputsStage;
import com.netflix.genie.agent.execution.statemachine.stages.ClaimJobStage;
import com.netflix.genie.agent.execution.statemachine.stages.CleanupJobDirectoryStage;
import com.netflix.genie.agent.execution.statemachine.stages.ConfigureAgentStage;
import com.netflix.genie.agent.execution.statemachine.stages.ConfigureExecutionStage;
import com.netflix.genie.agent.execution.statemachine.stages.CreateJobDirectoryStage;
import com.netflix.genie.agent.execution.statemachine.stages.CreateJobScriptStage;
import com.netflix.genie.agent.execution.statemachine.stages.DetermineJobFinalStatusStage;
import com.netflix.genie.agent.execution.statemachine.stages.DownloadDependenciesStage;
import com.netflix.genie.agent.execution.statemachine.stages.HandshakeStage;
import com.netflix.genie.agent.execution.statemachine.stages.InitializeAgentStage;
import com.netflix.genie.agent.execution.statemachine.stages.LaunchJobStage;
import com.netflix.genie.agent.execution.statemachine.stages.LogExecutionErrorsStage;
import com.netflix.genie.agent.execution.statemachine.stages.ObtainJobSpecificationStage;
import com.netflix.genie.agent.execution.statemachine.stages.RefreshManifestStage;
import com.netflix.genie.agent.execution.statemachine.stages.RelocateLogFileStage;
import com.netflix.genie.agent.execution.statemachine.stages.ReserveJobIdStage;
import com.netflix.genie.agent.execution.statemachine.stages.SetJobStatusFinal;
import com.netflix.genie.agent.execution.statemachine.stages.SetJobStatusInit;
import com.netflix.genie.agent.execution.statemachine.stages.SetJobStatusRunning;
import com.netflix.genie.agent.execution.statemachine.stages.ShutdownStage;
import com.netflix.genie.agent.execution.statemachine.stages.StartFileServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.StartHeartbeatServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.StartKillServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.StopFileServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.StopHeartbeatServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.StopKillServiceStage;
import com.netflix.genie.agent.execution.statemachine.stages.WaitJobCompletionStage;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.common.internal.services.JobArchiveService;
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 org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
import java.util.Set;
/**
* Tests ExecutionAutoConfiguration.
*/
class ExecutionAutoConfigurationTest {
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
ExecutionAutoConfiguration.class
)
)
.withUserConfiguration(MocksConfiguration.class);
private final Set<Class<? extends ExecutionStage>> uniqueExecutionStages = ImmutableSet.of(
ArchiveJobOutputsStage.class,
ClaimJobStage.class,
CleanupJobDirectoryStage.class,
ConfigureAgentStage.class,
ConfigureExecutionStage.class,
CreateJobDirectoryStage.class,
CreateJobScriptStage.class,
DetermineJobFinalStatusStage.class,
DownloadDependenciesStage.class,
HandshakeStage.class,
InitializeAgentStage.class,
LaunchJobStage.class,
LogExecutionErrorsStage.class,
ObtainJobSpecificationStage.class,
RelocateLogFileStage.class,
ReserveJobIdStage.class,
SetJobStatusFinal.class,
SetJobStatusInit.class,
SetJobStatusRunning.class,
ShutdownStage.class,
StartFileServiceStage.class,
StartHeartbeatServiceStage.class,
StartKillServiceStage.class,
StopFileServiceStage.class,
StopHeartbeatServiceStage.class,
StopKillServiceStage.class,
WaitJobCompletionStage.class
);
private final Map<Class<? extends ExecutionStage>, Integer> repeatedExecutionStages = ImmutableMap.of(
RefreshManifestStage.class, 3
);
/**
* Test beans are created successfully.
*/
@Test
void executionContext() {
contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(LoggingListener.class);
Assertions.assertThat(context).hasSingleBean(ConsoleLogListener.class);
Assertions.assertThat(context).hasSingleBean(ExecutionContext.class);
Assertions.assertThat(context).hasSingleBean(JobExecutionStateMachine.class);
Assertions.assertThat(context).hasSingleBean(AgentProperties.class);
uniqueExecutionStages.forEach(
stageClass ->
Assertions.assertThat(context).hasSingleBean(stageClass)
);
repeatedExecutionStages.forEach(
(clazz, count) ->
Assertions.assertThat(context).getBeans(clazz).hasSize(count)
);
}
);
}
@Configuration
static class MocksConfiguration {
@Bean
AgentJobService agentJobService() {
return Mockito.mock(AgentJobService.class);
}
@Bean
AgentMetadata agentMetadata() {
return Mockito.mock(AgentMetadata.class);
}
@Bean
AgentHeartBeatService heartbeatService() {
return Mockito.mock(AgentHeartBeatService.class);
}
@Bean
AgentJobKillService killService() {
return Mockito.mock(AgentJobKillService.class);
}
@Bean
JobSetupService jobSetupService() {
return Mockito.mock(JobSetupService.class);
}
@Bean
JobRequestConverter jobRequestConverter() {
return Mockito.mock(JobRequestConverter.class);
}
@Bean
ArgumentDelegates.JobRequestArguments jobRequestArguments() {
return Mockito.mock(ArgumentDelegates.JobRequestArguments.class);
}
@Bean
AgentFileStreamService agentFileStreamService() {
return Mockito.mock(AgentFileStreamService.class);
}
@Bean
ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigArguments() {
return Mockito.mock(ArgumentDelegates.RuntimeConfigurationArguments.class);
}
@Bean
JobProcessManager jobProcessManager() {
return Mockito.mock(JobProcessManager.class);
}
@Bean
JobArchiveService jobArchiveService() {
return Mockito.mock(JobArchiveService.class);
}
@Bean
ArgumentDelegates.CleanupArguments cleanupArguments() {
return Mockito.mock(ArgumentDelegates.CleanupArguments.class);
}
@Bean
AgentLogManager agentLogManager() {
return Mockito.mock(AgentLogManager.class);
}
@Bean
JobMonitorService jobMonitorService() {
return Mockito.mock(JobMonitorService.class);
}
@Bean
BraveTracingComponents genieTracingComponents() {
return new BraveTracingComponents(
Mockito.mock(Tracer.class),
Mockito.mock(BraveTracePropagator.class),
Mockito.mock(BraveTracingCleanup.class),
Mockito.mock(BraveTagAdapter.class)
);
}
}
}
| 2,848 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/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.
*
*/
/**
* Job execution.
*
* @author mprimi
* @since 4.0.0
* <p>
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.execution;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,849 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/FetchingCacheServiceImplTest.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.agent.execution.services.impl;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.exceptions.DownloadException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import com.netflix.genie.agent.utils.locks.impl.FileLockFactory;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Tests for {@link FetchingCacheServiceImpl}.
*/
class FetchingCacheServiceImplTest {
private static final byte[] EMPTY_STRING_BYTES = "".getBytes(StandardCharsets.UTF_8);
private final ExecutorService executorService = Executors.newFixedThreadPool(2);
//Boolean flag representing that a downloadCompleted
private final AtomicBoolean downloadCompleted = new AtomicBoolean(false);
//CloseableLock used for the downloadComplete condition while simulating a download
private final ReentrantLock simulateDownloadLock = new ReentrantLock();
//Condition used during download simulation for waiting
private final Condition downloadComplete = simulateDownloadLock.newCondition();
private URI uri;
private ArgumentDelegates.CacheArguments cacheArguments;
private File targetFile;
private ThreadPoolTaskExecutor cleanUpTaskExecutor;
@BeforeEach
void setUp(@TempDir final Path temporaryFolder) throws Exception {
uri = new URI("https://my-server.com/path/to/config/config.xml");
cacheArguments = Mockito.mock(ArgumentDelegates.CacheArguments.class);
Mockito.when(
cacheArguments.getCacheDirectory()
).thenReturn(temporaryFolder.toFile());
targetFile = temporaryFolder.resolve("target").toFile();
cleanUpTaskExecutor = new ThreadPoolTaskExecutor();
cleanUpTaskExecutor.setCorePoolSize(1);
cleanUpTaskExecutor.initialize();
}
@AfterEach
void cleanUp() {
cleanUpTaskExecutor.shutdown();
}
/**
* Start two concurrent resource fetches.
* Make sure only one cache does the download/enters the critical section
*
* @throws Exception the exception
*/
@Test
void cacheConcurrentFetches() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final ReentrantLock lockBackingMock = new ReentrantLock();
//Latch to represent that lock acquisition was attempted
final CountDownLatch lockAcquisitionsAttempted = new CountDownLatch(2);
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAcquisitionsAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(
resourceLoader2.getResource(Mockito.anyString())
).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
numOfCacheMisses.incrementAndGet();
return simulateDownloadWithWait();
}
);
Mockito.when(resource2.exists()).thenReturn(true);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAcquisitionsAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have at least tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Only one thread reached the critical section
Assertions.assertThat(numOfCacheMisses.get()).isEqualTo(1);
}
/**
* Start two concurrent resource fetches.
* Make the first one to start download fail
* Make sure a cache files exist because the other fetch succeeds
*
* @throws Exception the exception
*/
@Test
void cacheConcurrentFetchFailOne() throws Exception {
final AtomicInteger numOfCacheMisses = new AtomicInteger(0);
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAcquisitionsAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAcquisitionsAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final Resource resource2 = Mockito.mock(Resource.class);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream(EMPTY_STRING_BYTES)
);
}
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Set up the second cache
Mockito.when(resourceLoader2.getResource(Mockito.anyString())).thenReturn(resource2);
Mockito.when(
resource2.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
//first thread trying to download
if (numOfCacheMisses.incrementAndGet() == 1) {
return simulateDownloadFailureWithWait();
} else { // second thread doing the download
return Mockito.spy(
new ByteArrayInputStream(EMPTY_STRING_BYTES)
);
}
}
);
Mockito.when(resource2.exists()).thenReturn(true);
Mockito.when(resource2.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
downloadCompleted.set(false);
numOfCacheMisses.set(0);
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
executorService.submit(() -> {
try {
cache2.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for both threads to try to lock
lockAcquisitionsAttempted.await();
//Either one thread would have tried a download or would try shortly.
//So, either one thread is waiting on a download or will try to download.
//Regardless since both threads have at least tried to lock once,
//signal download completed
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Both threads reached the critical section
Assertions.assertThat(numOfCacheMisses.get()).isEqualTo(2);
//Proper directory structure and files exist for the resource
Assertions
.assertThat(directoryStructureExists(cache1.getResourceCacheId(uri), lastModifiedTimeStamp, cache1))
.isTrue();
}
/**
* Make one cache download a resource version.
* While first one is downloading, make another thread
* delete the same version
* In the end, the previous resource should not exist
*
* @throws Exception the exception
*/
@Test
void fetchAndDeleteResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final CountDownLatch lockAcquisitionAttempted = new CountDownLatch(2);
final ReentrantLock lockBackingMock = new ReentrantLock();
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
lockAcquisitionAttempted.countDown();
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Latch to represent that download was started
final CountDownLatch downloadBegin = new CountDownLatch(1);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> {
downloadBegin.countDown();
simulateDownloadWithWait();
return Mockito.spy(
new ByteArrayInputStream(EMPTY_STRING_BYTES)
);
}
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Before submitting make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Get resource via first cache
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Download was started, first thread in critical section
downloadBegin.await();
//Start deletion.
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
lockAcquisitionAttempted.await();
downloadCompleted.set(true);
simulateDownloadLock.lock();
try {
downloadComplete.signal();
} finally {
simulateDownloadLock.unlock();
}
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource is deleted
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
}
/**
* Make one cache delete a resource version.
* While first one is deleting, make another thread
* download the same version
* In the end, the resource should exist
*
* @throws Exception the exception
*/
@Test
void deleteAndFetchResourceConcurrently() throws Exception {
final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
final Resource resource = Mockito.mock(Resource.class);
final AtomicInteger numJobsInLockMethod = new AtomicInteger(0);
final ReentrantLock lockBackingMock = new ReentrantLock();
final CountDownLatch downLoadJobEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionDone = new CountDownLatch(1);
final CountDownLatch deletionJObEnteredLockMethod = new CountDownLatch(1);
final CountDownLatch deletionSuccessVerified = new CountDownLatch(1);
//A mock lock backed by a reentrant lock guarding the resource
final CloseableLock resourceLock = Mockito.mock(CloseableLock.class);
Mockito.doAnswer(invocation -> {
//deletion thread since its submitted first as the only thread
if (numJobsInLockMethod.incrementAndGet() == 1) {
//make deletion wait until download thread enters the lock method
deletionJObEnteredLockMethod.countDown();
downLoadJobEnteredLockMethod.await();
} else { //download thread
downLoadJobEnteredLockMethod.countDown();
//wait until main thread verifies that deletion was successful
deletionSuccessVerified.await();
}
lockBackingMock.lock();
return null;
}).when(resourceLock).lock();
Mockito.doAnswer(invocation -> {
lockBackingMock.unlock();
return null;
}).when(resourceLock).close();
//Mock locking factory to use the reentrant lock backed lock
final FileLockFactory fileLockFactory = Mockito.mock(FileLockFactory.class);
Mockito.when(
fileLockFactory.getLock(Mockito.any())
).thenReturn(resourceLock);
//Set up first cache
Mockito.when(
resourceLoader.getResource(Mockito.anyString())
).thenReturn(resource);
Mockito.when(
resource.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> Mockito.spy(
new ByteArrayInputStream(EMPTY_STRING_BYTES)
)
);
final long lastModifiedTimeStamp = System.currentTimeMillis();
Mockito.when(resource.exists()).thenReturn(true);
Mockito.when(resource.lastModified()).thenReturn(lastModifiedTimeStamp);
final FetchingCacheServiceImpl cache1 = new FetchingCacheServiceImpl(
resourceLoader,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
final String resourceCacheId = cache1.getResourceCacheId(uri);
//Set the second cache
final ResourceLoader resourceLoader2 = Mockito.mock(ResourceLoader.class);
final FetchingCacheServiceImpl cache2 = new FetchingCacheServiceImpl(
resourceLoader2,
cacheArguments,
fileLockFactory,
cleanUpTaskExecutor
);
//Download the resource which needs to be deleted, else deletion will be a no op
//Set up a separate cache for it.
final ResourceLoader resourceLoader3 = Mockito.mock(ResourceLoader.class);
final Resource resource3 = Mockito.mock(Resource.class);
Mockito.when(resource3.exists()).thenReturn(true);
Mockito.when(resource3.lastModified()).thenReturn(lastModifiedTimeStamp);
Mockito.when(
resource3.getInputStream()
).thenAnswer(
(Answer<InputStream>) invocation -> Mockito.spy(
new ByteArrayInputStream(EMPTY_STRING_BYTES)
)
);
Mockito.when(
resourceLoader3.getResource(Mockito.anyString())
).thenReturn(resource3);
final FetchingCacheServiceImpl cache3 = new FetchingCacheServiceImpl(
resourceLoader3,
cacheArguments,
new FileLockFactory(),
cleanUpTaskExecutor
);
cache3.get(uri, targetFile);
//Assert that the cache download was successful
assertResourceDownloaded(cache3, resourceCacheId, lastModifiedTimeStamp);
//Before submitting the deletion and download jobs make sure conditions are set correctly
final CountDownLatch allFetchesDone = new CountDownLatch(2);
//Start deletion
executorService.submit(() -> {
try {
//Pass in lastDownloadedVersion = lastModifiedTimeStamp + 1 to trigger
//the deletion of the resource version = lastModifiedTimeStamp
cache2.cleanUpOlderResourceVersions(
resourceCacheId,
lastModifiedTimeStamp + 1
);
} catch (Exception e) {
e.printStackTrace();
} finally {
deletionDone.countDown();
allFetchesDone.countDown();
}
});
//Deletion thread in lock method
deletionJObEnteredLockMethod.await();
//Start download of the version being deleted.
//This one will make the deletion thread move ahead in lock method
//once it reaches lock method
executorService.submit(() -> {
try {
cache1.get(uri, targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
allFetchesDone.countDown();
}
});
//Wait for deletion job to be done
deletionDone.await();
//Assert that deletion was successful
assertResourceDeleted(cache1, resourceCacheId, lastModifiedTimeStamp);
//Make the download thread stop waiting in lock method
deletionSuccessVerified.countDown();
//Wait for all threads to be done before asserting
allFetchesDone.await();
//Make sure the resource downloaded is present
assertResourceDownloaded(cache2, resourceCacheId, lastModifiedTimeStamp);
}
private void assertResourceDeleted(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assertions
.assertThat(cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp))
.doesNotExist();
Assertions
.assertThat(cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp))
.doesNotExist();
Assertions
.assertThat(cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp))
.exists();
}
private void assertResourceDownloaded(
final FetchingCacheServiceImpl cacheService,
final String resourceCacheId,
final long lastModifiedTimeStamp
) {
Assertions
.assertThat(cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp))
.exists();
Assertions
.assertThat(cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp))
.doesNotExist();
Assertions
.assertThat(cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp))
.exists();
}
/**
* Simulate a download while waiting until notified.
*
* @return input stream from download
*/
private InputStream simulateDownloadWithWait() {
simulateDownloadLock.lock();
try {
while (!downloadCompleted.get()) {
downloadComplete.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
simulateDownloadLock.unlock();
}
return Mockito.spy(new ByteArrayInputStream(EMPTY_STRING_BYTES));
}
/**
* Simulate a download failure while waiting until notified.
*
* @return input stream from download
* @throws DownloadException simulated error
*/
private InputStream simulateDownloadFailureWithWait() throws DownloadException {
simulateDownloadWithWait();
throw new DownloadException("Simulated error downloading resource");
}
/**
* Verify that all the files exist after a successful download.
*
* @param resourceCacheId resource id for the cache
* @param lastModifiedTimeStamp resource version
* @param cacheService cache service instance
* @return true or false
*/
private boolean directoryStructureExists(
final String resourceCacheId,
final long lastModifiedTimeStamp,
final FetchingCacheServiceImpl cacheService
) {
return cacheService.getCacheResourceVersionDataFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& cacheService.getCacheResourceVersionLockFile(resourceCacheId, lastModifiedTimeStamp).exists()
&& !cacheService.getCacheResourceVersionDownloadFile(resourceCacheId, lastModifiedTimeStamp).exists();
}
}
| 2,850 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/ServicesAutoConfigurationTest.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.agent.execution.services.impl;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.agent.execution.services.DownloadService;
import com.netflix.genie.agent.execution.services.FetchingCacheService;
import com.netflix.genie.agent.execution.services.JobMonitorService;
import com.netflix.genie.agent.execution.services.JobSetupService;
import com.netflix.genie.agent.execution.services.KillService;
import com.netflix.genie.agent.execution.statemachine.ExecutionContext;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.agent.utils.locks.impl.FileLockFactory;
import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService;
import org.assertj.core.api.Assertions;
import org.assertj.core.util.Files;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.TaskScheduler;
import java.io.File;
class ServicesAutoConfigurationTest {
private ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
ServicesAutoConfiguration.class
)
)
.withUserConfiguration(ServicesAutoConfigurationTest.MocksConfiguration.class);
@Test
void executionContext() {
contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(AgentProperties.class);
Assertions.assertThat(context).hasSingleBean(DownloadService.class);
Assertions.assertThat(context).hasSingleBean(FetchingCacheService.class);
Assertions.assertThat(context).hasSingleBean(KillService.class);
Assertions.assertThat(context).hasSingleBean(JobSetupService.class);
Assertions.assertThat(context).hasSingleBean(JobMonitorService.class);
// All beans are lazy, so above assertions will trivially pass.
// Validate by forcing instantiation
Assertions.assertThat(context).getBean(DownloadService.class).isNotNull();
Assertions.assertThat(context).getBean(FetchingCacheService.class).isNotNull();
Assertions.assertThat(context).getBean(KillService.class).isNotNull();
Assertions.assertThat(context).getBean(JobSetupService.class).isNotNull();
Assertions.assertThat(context).getBean(JobMonitorService.class).isNotNull();
}
);
}
@Configuration
static class MocksConfiguration {
@Bean
ResourceLoader resourceLoader() {
return Mockito.mock(ResourceLoader.class);
}
@Bean
ArgumentDelegates.CacheArguments cacheArguments() {
// Cannot use @TempDir here because static class initialization via annotation
final File temp = Files.newTemporaryFolder();
final ArgumentDelegates.CacheArguments mock = Mockito.mock(ArgumentDelegates.CacheArguments.class);
Mockito.when(mock.getCacheDirectory()).thenReturn(temp);
return mock;
}
@Bean
FileLockFactory fileLockFactory() {
return Mockito.mock(FileLockFactory.class);
}
@Bean
JobDirectoryManifestCreatorService manifestCreatorService() {
return Mockito.mock(JobDirectoryManifestCreatorService.class);
}
@Bean
AgentJobService agentJobService() {
return Mockito.mock(AgentJobService.class);
}
@Bean(name = "sharedAgentTaskExecutor")
TaskExecutor taskExecutor() {
return Mockito.mock(TaskExecutor.class);
}
@Bean(name = "sharedAgentTaskScheduler")
TaskScheduler taskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
ExecutionContext executionContext() {
return Mockito.mock(ExecutionContext.class);
}
}
}
| 2,851 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/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.
*
*/
/**
* FileSystem fetching caching service tests.
*
* @author standon
* @since 4.0.0
*/
package com.netflix.genie.agent.execution.services.impl;
| 2,852 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/grpc/GRpcServicesAutoConfigurationTest.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.agent.execution.services.impl.grpc;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.services.AgentFileStreamService;
import com.netflix.genie.agent.execution.services.AgentHeartBeatService;
import com.netflix.genie.agent.execution.services.AgentJobKillService;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.agent.execution.services.KillService;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.agent.rpc.GRpcAutoConfiguration;
import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter;
import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.TaskScheduler;
/**
* Tests for {@link GRpcAutoConfiguration}.
*/
class GRpcServicesAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
GRpcServicesAutoConfiguration.class,
GRpcAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> Assertions
.assertThat(context)
.hasSingleBean(AgentProperties.class)
.hasSingleBean(AgentHeartBeatService.class)
.hasSingleBean(AgentJobKillService.class)
.hasSingleBean(AgentJobService.class)
.hasSingleBean(AgentFileStreamService.class)
);
}
private static class ExternalBeans {
@Bean
ArgumentDelegates.ServerArguments serverArguments() {
final ArgumentDelegates.ServerArguments mock = Mockito.mock(ArgumentDelegates.ServerArguments.class);
Mockito.when(mock.getServerHost()).thenReturn("server.com");
Mockito.when(mock.getServerPort()).thenReturn(1234);
Mockito.when(mock.getRpcTimeout()).thenReturn(3L);
return mock;
}
@Bean
JobServiceProtoConverter jobServiceProtoConverter() {
return Mockito.mock(JobServiceProtoConverter.class);
}
@Bean
KillService killService() {
return Mockito.mock(KillService.class);
}
@Bean(name = "sharedAgentTaskExecutor")
TaskExecutor taskExecutor() {
return Mockito.mock(TaskExecutor.class);
}
@Bean(name = "sharedAgentTaskScheduler")
TaskScheduler sharedAgentTaskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean(name = "heartBeatServiceTaskScheduler")
TaskScheduler heartBeatServiceTaskScheduler() {
return Mockito.mock(TaskScheduler.class);
}
@Bean
JobDirectoryManifestProtoConverter jobDirectoryManifestProtoConverter() {
return Mockito.mock(JobDirectoryManifestProtoConverter.class);
}
}
}
| 2,853 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/execution/services/impl/grpc/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 this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.execution.services.impl.grpc;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,854 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/rpc/GRpcAutoConfigurationTest.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.agent.rpc;
import brave.Tracing;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.proto.FileStreamServiceGrpc;
import com.netflix.genie.proto.HeartBeatServiceGrpc;
import com.netflix.genie.proto.JobKillServiceGrpc;
import com.netflix.genie.proto.JobServiceGrpc;
import com.netflix.genie.proto.PingServiceGrpc;
import io.grpc.ManagedChannel;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
/**
* Test for {@link GRpcAutoConfiguration}.
*/
class GRpcAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
GRpcAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> Assertions
.assertThat(context)
.hasSingleBean(ManagedChannel.class)
.hasSingleBean(PingServiceGrpc.PingServiceFutureStub.class)
.hasSingleBean(JobServiceGrpc.JobServiceFutureStub.class)
.hasSingleBean(HeartBeatServiceGrpc.HeartBeatServiceStub.class)
.hasSingleBean(JobKillServiceGrpc.JobKillServiceFutureStub.class)
.hasSingleBean(FileStreamServiceGrpc.FileStreamServiceStub.class)
.hasBean("genieGrpcTracingClientInterceptor")
);
}
private static class ExternalBeans {
@Bean
ArgumentDelegates.ServerArguments serverArguments() {
final ArgumentDelegates.ServerArguments mock = Mockito.mock(ArgumentDelegates.ServerArguments.class);
Mockito.when(mock.getServerHost()).thenReturn("server.com");
Mockito.when(mock.getServerPort()).thenReturn(1234);
Mockito.when(mock.getRpcTimeout()).thenReturn(3L);
return mock;
}
@Bean
Tracing tracing() {
return Tracing.newBuilder().build();
}
}
}
| 2,855 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/rpc/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 this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.rpc;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,856 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/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.
*
*/
/**
* Tests for configuration classes in package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.spring;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,857 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/processors/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.
*
*/
/**
* Tests for post processors.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.spring.processors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,858 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/processors/GenieDefaultPropertiesPostProcessorTest.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.agent.spring.processors;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* Tests to make sure default agent properties are loaded.
*
* @author tgianos
* @since 4.0.0
*/
class GenieDefaultPropertiesPostProcessorTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
private final GenieDefaultPropertiesPostProcessor processor = new GenieDefaultPropertiesPostProcessor();
@Test
void testSmokeProperty() {
this.contextRunner
.run(
context -> {
final SpringApplication application = Mockito.mock(SpringApplication.class);
final ConfigurableEnvironment environment = context.getEnvironment();
Assertions.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
).isFalse();
Assertions.assertThat(environment.getProperty("genie.smoke")).isBlank();
this.processor.postProcessEnvironment(environment, application);
Assertions
.assertThat(
environment
.getPropertySources()
.contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME)
)
.isTrue();
Assertions
.assertThat(environment.getProperty("genie.smoke", Boolean.class, false))
.isTrue();
}
);
}
}
| 2,859 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/autoconfigure/AgentAutoConfigurationTest.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.agent.spring.autoconfigure;
import com.netflix.genie.agent.AgentMetadataImpl;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.agent.utils.locks.impl.FileLockFactory;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.boot.task.TaskSchedulerCustomizer;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* Tests for {@link AgentAutoConfiguration}.
*
* @author standon
* @since 4.0.0
*/
class AgentAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentAutoConfiguration.class
)
);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(GenieHostInfo.class);
Assertions.assertThat(context).hasSingleBean(AgentMetadataImpl.class);
Assertions.assertThat(context).hasSingleBean(FileLockFactory.class);
Assertions
.assertThat(context)
.getBean("sharedAgentTaskExecutor")
.isOfAnyClassIn(ThreadPoolTaskExecutor.class);
Assertions.assertThat(context).hasBean("sharedAgentTaskScheduler");
Assertions
.assertThat(context)
.getBean("sharedAgentTaskScheduler")
.isOfAnyClassIn(ThreadPoolTaskScheduler.class);
Assertions.assertThat(context).hasBean("heartBeatServiceTaskScheduler");
Assertions
.assertThat(context)
.getBean("heartBeatServiceTaskScheduler")
.isOfAnyClassIn(ThreadPoolTaskScheduler.class);
Assertions.assertThat(context).hasSingleBean(AgentProperties.class);
Assertions.assertThat(context).hasSingleBean(TaskExecutorCustomizer.class);
Assertions.assertThat(context).hasSingleBean(TaskSchedulerCustomizer.class);
}
);
}
@Test
void testTaskExecutorCustomizer() {
final AgentProperties properties = new AgentProperties();
final TaskExecutorCustomizer customizer = new AgentAutoConfiguration().taskExecutorCustomizer(properties);
final ThreadPoolTaskExecutor taskExecutor = Mockito.mock(ThreadPoolTaskExecutor.class);
customizer.customize(taskExecutor);
Mockito.verify(taskExecutor).setWaitForTasksToCompleteOnShutdown(true);
Mockito.verify(taskExecutor).setAwaitTerminationSeconds(60);
}
@Test
void testTaskSchedulerCustomizer() {
final AgentProperties properties = new AgentProperties();
final TaskSchedulerCustomizer customizer = new AgentAutoConfiguration().taskSchedulerCustomizer(properties);
final ThreadPoolTaskScheduler taskScheduler = Mockito.mock(ThreadPoolTaskScheduler.class);
customizer.customize(taskScheduler);
Mockito.verify(taskScheduler).setWaitForTasksToCompleteOnShutdown(true);
Mockito.verify(taskScheduler).setAwaitTerminationSeconds(60);
}
}
| 2,860 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/autoconfigure/ProcessAutoConfigurationTest.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.agent.spring.autoconfigure;
import brave.Tracer;
import com.netflix.genie.agent.execution.process.JobProcessManager;
import com.netflix.genie.agent.execution.process.impl.JobProcessManagerImpl;
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 org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
/**
* Tests for {@link ProcessAutoConfiguration}.
*
* @author tgianos
* @since 4.0.0
*/
class ProcessAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
AgentAutoConfiguration.class,
ProcessAutoConfiguration.class
)
)
.withUserConfiguration(ExternalBeans.class);
@Test
void expectedBeansExist() {
this.contextRunner.run(
context -> {
Assertions.assertThat(context).hasSingleBean(JobProcessManagerImpl.class);
Assertions.assertThat(context).hasSingleBean(JobProcessManager.class);
}
);
}
private static class ExternalBeans {
@Bean
BraveTracingComponents tracingComponents() {
return new BraveTracingComponents(
Mockito.mock(Tracer.class),
Mockito.mock(BraveTracePropagator.class),
Mockito.mock(BraveTracingCleanup.class),
Mockito.mock(BraveTagAdapter.class)
);
}
}
}
| 2,861 |
0 | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring | Create_ds/genie/genie-agent/src/test/java/com/netflix/genie/agent/spring/autoconfigure/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.
*
*/
/**
* Tests for this package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.spring.autoconfigure;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,862 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/AgentMetadata.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.agent;
import javax.validation.constraints.NotBlank;
/**
* Container for Genie agent metadata and runtime information.
*
* @author mprimi
* @since 4.0.0
*/
public interface AgentMetadata {
/**
* Get the agent version string, as it appears in the agent jar metadata.
*
* @return a version string or a fallback
*/
@NotBlank String getAgentVersion();
/**
* Get the name of the host the agent is running on.
*
* @return a hostname or a fallback string
*/
@NotBlank String getAgentHostName();
/**
* Get the agent process ID.
*
* @return the agent process ID or a fallback string
*/
@NotBlank String getAgentPid();
}
| 2,863 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/AgentMetadataImpl.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.agent;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Implementation of AgentMetadata.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
@Getter
public class AgentMetadataImpl implements AgentMetadata {
private static final String FALLBACK_STRING = "unknown";
private final String agentVersion;
private final String agentHostName;
private final String agentPid;
/**
* Constructor.
*/
public AgentMetadataImpl() {
this(
getAgentVersionOrFallback(),
getAgentHostNameOrFallback(),
getAgentPidOrFallback()
);
}
/**
* Constructor with pre-resolved hostname.
*
* @param hostname The hostname
*/
public AgentMetadataImpl(final String hostname) {
this(
getAgentVersionOrFallback(),
hostname,
getAgentPidOrFallback()
);
}
private AgentMetadataImpl(
final String agentVersion,
final String agentHostName,
final String agentPid
) {
this.agentVersion = agentVersion;
this.agentHostName = agentHostName;
this.agentPid = agentPid;
}
private static String getAgentVersionOrFallback() {
final String agentVersion = AgentMetadataImpl.class.getPackage().getImplementationVersion();
if (!StringUtils.isBlank(agentVersion)) {
return agentVersion;
}
log.warn("Failed to retrieve agent version");
return FALLBACK_STRING;
}
private static String getAgentHostNameOrFallback() {
try {
final String hostName = InetAddress.getLocalHost().getCanonicalHostName();
if (!StringUtils.isBlank(hostName)) {
return hostName;
}
} catch (final UnknownHostException e) {
log.warn("Failed to retrieve local host name", e);
}
return FALLBACK_STRING;
}
private static String getAgentPidOrFallback() {
final String jvmId = ManagementFactory.getRuntimeMXBean().getName();
final Matcher pidPatternMatcher = Pattern.compile("(\\d+)@.*").matcher(jvmId);
if (pidPatternMatcher.matches() && !StringUtils.isBlank(pidPatternMatcher.group(1))) {
return pidPatternMatcher.group(1);
}
log.warn("Failed to retrieve agent PID (JVM id: {})", jvmId);
return FALLBACK_STRING;
}
}
| 2,864 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/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.
*
*/
/**
* Classes shared by the entire Agent project.
*
* @author mprimi
* @since 4.0.0
*/
package com.netflix.genie.agent;
| 2,865 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/PathUtils.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.agent.utils;
import com.netflix.genie.common.internal.jobs.JobConstants;
import java.io.File;
import java.nio.file.Path;
/**
* Utilities to compose filesystem paths.
*
* @author mprimi
* @since 4.0.0
*/
public final class PathUtils {
private PathUtils() {
}
/**
* Append an arbitrary set of components to a base path.
*
* @param baseDirectory the base directory
* @param children path components
* @return a Path
*/
public static Path composePath(
final File baseDirectory,
final String... children
) {
File pathAccumulator = baseDirectory;
for (String child : children) {
pathAccumulator = new File(pathAccumulator, child);
}
return pathAccumulator.toPath();
}
/**
* Append an arbitrary set of components to a base path.
*
* @param baseDirectory the base directory
* @param children path components
* @return a Path
*/
public static Path composePath(
final Path baseDirectory,
final String... children
) {
return composePath(baseDirectory.toFile(), children);
}
/**
* Compose the path to the applications directory inside a job directory.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobApplicationsDirectoryPath(
final File jobDirectory
) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR,
JobConstants.APPLICATION_PATH_VAR
);
}
/**
* Compose the path to an application directory inside a job directory.
*
* @param jobDirectory the job directory
* @param appId the application id
* @return a Path
*/
public static Path jobApplicationDirectoryPath(
final File jobDirectory,
final String appId
) {
return composePath(
jobApplicationsDirectoryPath(jobDirectory),
appId
);
}
/**
* Compose the path to the cluster directory inside a job directory.
*
* @param jobDirectory the job directory
* @param clusterId the cluster id
* @return a Path
*/
public static Path jobClusterDirectoryPath(final File jobDirectory, final String clusterId) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR,
JobConstants.CLUSTER_PATH_VAR,
clusterId
);
}
/**
* Compose the path to the command directory inside a job directory.
*
* @param jobDirectory the job directory
* @param commandId the command id
* @return a Path
*/
public static Path jobCommandDirectoryPath(final File jobDirectory, final String commandId) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR,
JobConstants.COMMAND_PATH_VAR,
commandId
);
}
/**
* Compose the path to the genie directory inside a job directory.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobGenieDirectoryPath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR
);
}
/**
* Compose the path to the genie logs directory inside a job directory.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobGenieLogsDirectoryPath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR,
JobConstants.LOGS_PATH_VAR
);
}
/**
* Compose the path to the dependencies directory for a given entity.
*
* @param entityDirectory the entity base directory
* @return a Path
*/
public static Path jobEntityDependenciesPath(final Path entityDirectory) {
return composePath(
new File(entityDirectory.toUri()),
JobConstants.DEPENDENCY_FILE_PATH_PREFIX
);
}
/**
* Compose the path to the configurations directory for a given entity.
*
* @param entityDirectory the entity base directory
* @return a Path
*/
public static Path jobEntityConfigPath(final Path entityDirectory) {
return composePath(
new File(entityDirectory.toUri()),
JobConstants.CONFIG_FILE_PATH_PREFIX
);
}
/**
* Compose the path to the setup file for a given entity.
*
* @param entityDirectory the entity base directory
* @return a Path
*/
public static Path jobEntitySetupFilePath(final Path entityDirectory) {
return composePath(
entityDirectory,
JobConstants.GENIE_ENTITY_SETUP_SCRIPT_FILE_NAME
);
}
/**
* Compose the path to the standard output log file for a job.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobStdOutPath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.STDOUT_LOG_FILE_NAME
);
}
/**
* Compose the path to the standard error log file for a job.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobStdErrPath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.STDERR_LOG_FILE_NAME
);
}
/**
* Compose the path to the agent log file for a job (after it has been relocated inside the job directory).
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobAgentLogFilePath(final File jobDirectory) {
return composePath(
jobGenieLogsDirectoryPath(jobDirectory),
JobConstants.GENIE_AGENT_LOG_FILE_NAME
);
}
/**
* Compose the path to the setup log file for a job (sourcing of entities setup files).
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobSetupLogFilePath(final File jobDirectory) {
return composePath(
jobGenieLogsDirectoryPath(jobDirectory),
JobConstants.GENIE_SETUP_LOG_FILE_NAME
);
}
/**
* Compose the path to the file where environment variables are dumped after running setup.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobEnvironmentLogFilePath(final File jobDirectory) {
return composePath(
jobGenieLogsDirectoryPath(jobDirectory),
JobConstants.GENIE_AGENT_ENV_FILE_NAME
);
}
/**
* Compose the path to the job script (a.k.a. run file).
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobScriptPath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.GENIE_JOB_LAUNCHER_SCRIPT
);
}
/**
* Compose the path to the marker file left behind if the script fails during setup.
*
* @param jobDirectory the job directory
* @return a Path
*/
public static Path jobSetupErrorMarkerFilePath(final File jobDirectory) {
return composePath(
jobDirectory,
JobConstants.GENIE_PATH_VAR,
JobConstants.GENIE_SETUP_ERROR_FILE_NAME
);
}
}
| 2,866 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/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.
*
*/
/**
* Utility classes.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.utils;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,867 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks/CloseableLock.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.agent.utils.locks;
import com.netflix.genie.agent.execution.exceptions.LockException;
import java.io.Closeable;
/**
* A simple interface representing a closeable lock.
*
* @author standon
* @since 4.0.0
*/
public interface CloseableLock extends Closeable {
/**
* Acquire a lock.
*
* @throws LockException in case of problem acquiring the lock
*/
void lock() throws LockException;
}
| 2,868 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks/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.
*
*/
/**
* Locks used for caching resources.
*
* @author standon
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.utils.locks;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,869 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks/impl/FileLockFactory.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.agent.utils.locks.impl;
import com.netflix.genie.agent.execution.exceptions.LockException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
/**
* Factory for creating locks implementing {@link CloseableLock}.
*
* @author standon
* @since 4.0.0
*/
@Slf4j
public class FileLockFactory {
/**
* Get a lock locking the provided File object.
*
* @param file file to be locked
* @return a lock locking the file
* @throws LockException in case of a problem getting a lock for the file
*/
public CloseableLock getLock(final File file) throws LockException {
return new FileLock(file);
}
}
| 2,870 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks/impl/FileLock.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.agent.utils.locks.impl;
import com.netflix.genie.agent.execution.exceptions.LockException;
import com.netflix.genie.agent.utils.locks.CloseableLock;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
/**
* CloseableLock for a file.
*
* @author standon
* @since 4.0.0
*/
public class FileLock implements CloseableLock {
//Refer to https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
private static final String FILE_ACCESS_MODE = "rws";
private FileChannel fileChannel;
//Maintain a link to the underlying nio file lock because of
//https://bugs.openjdk.java.net/browse/JDK-8166253
private java.nio.channels.FileLock nioFileLock;
/**
* Create a lock for the provided file.
*
* @param file file to be locked
* @throws LockException in case there is a problem creating a File CloseableLock
*/
public FileLock(final File file) throws LockException {
if (!file.exists()) {
throw new LockException("File " + file.toURI() + " does not exist");
}
try {
fileChannel = new RandomAccessFile(
file,
FILE_ACCESS_MODE
).getChannel();
} catch (Exception e) {
throw new LockException("Error creating a FileLock ", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
//FileChannel.close closes the nioFileLock. Closing
//it explicitly, else findbugs rule URF_UNREAD_FIELD is violated
nioFileLock.close();
fileChannel.close();
}
/**
* {@inheritDoc}
*/
@Override
public void lock() throws LockException {
try {
nioFileLock = fileChannel.lock();
} catch (Exception e) {
throw new LockException("Error locking file ", e);
}
}
}
| 2,871 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/utils/locks/impl/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.
*
*/
/**
* CloseableLock implementations used for caching resources.
*
* @author standon
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.utils.locks.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,872 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/AgentCommand.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.agent.cli;
/**
* Interface for commands that the agent executes.
*
* @author mprimi
* @since 4.0.0
*/
public interface AgentCommand {
/**
* Entry point for command execution.
*
* @return an {@link ExitCode}
*/
ExitCode run();
}
| 2,873 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ArgumentParser.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.agent.cli;
import com.beust.jcommander.JCommander;
import com.netflix.genie.agent.execution.CleanupStrategy;
import lombok.extern.slf4j.Slf4j;
import java.util.Set;
/**
* Command-line parser for the Genie Agent executable.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class ArgumentParser {
private final JCommander jCommander;
private final CommandFactory commandFactory;
private final MainCommandArguments mainCommandArguments;
ArgumentParser(
final JCommander jCommander,
final CommandFactory commandFactory,
final MainCommandArguments mainCommandArguments
) {
this.jCommander = jCommander;
this.commandFactory = commandFactory;
this.mainCommandArguments = mainCommandArguments;
}
/**
* Parse command-line arguments.
*
* @param args command-line arguments
*/
void parse(final String[] args) {
final String[] optionArguments = Util.getOptionArguments(args);
final String[] operandArguments = Util.getOperandArguments(args);
jCommander.parse(optionArguments);
mainCommandArguments.set(operandArguments);
}
/**
* Get a formatted string with all known options and sub-commands.
*
* @return the usage message string
*/
String getUsageMessage() {
final StringBuilder stringBuilder = new StringBuilder();
jCommander.getUsageFormatter().usage(stringBuilder);
stringBuilder
.append("\n\n")
.append(CleanupStrategy.CLEANUP_HELP_MESSAGE)
.append("\n")
.append(ArgumentConverters.CriterionConverter.CRITERION_SYNTAX_MESSAGE)
.append("\n")
.append(ArgumentConverters.UriOrLocalPathConverter.ATTACHMENT_HELP_MESSAGE)
.append("\n")
.append(ExitCode.EXIT_CODE_HELP_MESSAGE)
.append("\n");
return stringBuilder.toString();
}
/**
* Get the name of the command selected via arguments.
*
* @return the name of a command selected or null
*/
String getSelectedCommand() {
return jCommander.getParsedCommand();
}
Set<String> getCommandNames() {
return commandFactory.getCommandNames();
}
}
| 2,874 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/JobRequestArgumentsImpl.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.Criterion;
import lombok.Getter;
import java.io.File;
import java.util.List;
import java.util.Set;
/**
* Implementation of JobRequestArguments arguments delegate.
*
* @author mprimi
* @since 4.0.0
*/
@Getter
class JobRequestArgumentsImpl implements ArgumentDelegates.JobRequestArguments {
@VisibleForTesting
static final String DEFAULT_JOBS_DIRECTORY = "/tmp/genie/jobs/";
private final MainCommandArguments mainCommandArguments;
@Parameter(
names = {"--jobDirectoryLocation", "--job-directory-location"},
description = "The local directory in which the job directory is created and executed from",
converter = ArgumentConverters.FileConverter.class
)
private File jobDirectoryLocation = new File(DEFAULT_JOBS_DIRECTORY);
@Parameter(
names = {"--interactive"},
description = "Proxy standard {input,output,error} to the parent terminal, also disable console logging"
)
private boolean interactive;
@Parameter(
names = {"--archiveLocationPrefix", "--archive-location-prefix"},
description = "Deprecated. No-Op.",
validateWith = ArgumentValidators.S3URIValidator.class
)
private String archiveLocationPrefix;
@Parameter(
names = {"--timeout"},
description = "Time (in seconds) after which a running job is forcefully terminated"
)
private Integer timeout;
@Parameter(
names = {"--jobId", "--job-id"},
description = "Unique job identifier"
)
private String jobId;
@Parameter(
names = {"--clusterCriterion", "--cluster-criterion"},
description = "Criterion for cluster selection, can be repeated (see CRITERION SYNTAX)",
converter = ArgumentConverters.CriterionConverter.class,
splitter = NoopParameterSplitter.class
)
private List<Criterion> clusterCriteria = Lists.newArrayList();
@Parameter(
names = {"--commandCriterion", "--command-criterion"},
description = "Criterion for command selection (see CRITERION SYNTAX)",
converter = ArgumentConverters.CriterionConverter.class
)
private Criterion commandCriterion;
@Parameter(
names = {"--applicationIds", "--application-ids"},
description = "Override the applications a command normally depends on, can be repeated"
)
private List<String> applicationIds = Lists.newArrayList();
@Parameter(
names = {"--jobName", "--job-name"},
description = "Name of the job"
)
private String jobName;
@Parameter(
names = {"--user"},
description = "Username launching this job",
hidden = true // Not advertised to avoid abuse, but available for legitimate use cases
)
private String user = System.getProperty("user.name", "unknown-user");
@Parameter(
names = {"--email"},
description = "Email address where to send a job completion notification"
)
private String email;
@Parameter(
names = {"--grouping"},
description = "Group of jobs this job belongs to"
)
private String grouping;
@Parameter(
names = {"--groupingInstance", "--grouping-instance"},
description = "Group instance this job belongs to"
)
private String groupingInstance;
@Parameter(
names = {"--jobDescription", "--job-description"},
description = "Job description"
)
private String jobDescription;
@Parameter(
names = {"--jobTag", "--job-tag"},
description = "Job tag, can be repeated",
splitter = NoopParameterSplitter.class
)
private Set<String> jobTags = Sets.newHashSet();
@Parameter(
names = {"--jobVersion", "--job-version"},
description = "Job version"
)
private String jobVersion;
@Parameter(
names = {"--jobMetadata", "--job-metadata"},
description = "JSON job metadata",
converter = ArgumentConverters.JSONConverter.class
)
private JsonNode jobMetadata = GenieObjectMapper.getMapper().createObjectNode();
@Parameter(
names = {"--apiJob", "--api-job"},
description = "Whether the agent was launched by a Genie server in response to an API job submission",
hidden = true // Do not expose this option via CLI to users
)
private boolean jobRequestedViaAPI;
@Parameter(
names = {"--jobConfiguration", "--job-configuration"},
description = "URI or path of a job-level configuration file to attach, can be repeated",
converter = ArgumentConverters.UriOrLocalPathConverter.class,
validateValueWith = ArgumentValidators.URIListValidator.class,
splitter = NoopParameterSplitter.class
)
private List<String> jobConfigurations = Lists.newArrayList();
@Parameter(
names = {"--jobDependency", "--job-dependency"},
description = "URI or path of a job-level dependency file to attach, can be repeated",
converter = ArgumentConverters.UriOrLocalPathConverter.class,
validateValueWith = ArgumentValidators.URIListValidator.class,
splitter = NoopParameterSplitter.class
)
private List<String> jobDependencies = Lists.newArrayList();
@Parameter(
names = {"--jobSetup", "--job-setup"},
description = "URI or path of a job-level setup file to attach. The file is sourced during job setup",
converter = ArgumentConverters.UriOrLocalPathConverter.class,
validateValueWith = ArgumentValidators.URIValidator.class
)
private String jobSetup;
@Parameter(
names = {"--disableArchiving", "--disable-archiving"},
description = "Whether the default archiving of a job directory at the end of a job should be disabled"
)
private boolean archivingDisabled;
JobRequestArgumentsImpl(final MainCommandArguments mainCommandArguments) {
this.mainCommandArguments = mainCommandArguments;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getCommandArguments() {
return mainCommandArguments.get();
}
}
| 2,875 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/GlobalAgentArguments.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.agent.cli;
import lombok.Getter;
/**
* Global command-line options for the agent.
*
* @author mprimi
* @since 4.0.0
*/
@Getter
class GlobalAgentArguments {
}
| 2,876 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/Util.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.agent.cli;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* CLI utility methods.
*
* @author mprimi
* @since 4.0.0
*/
public final class Util {
/**
* Bare double dash is a command-line option conventionally used to delimit options from arguments.
* See POSIX POSIX.1-2017 - Utility Conventions - Gudeline #10
* http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
*/
private static final String BARE_DOUBLE_DASH = "--";
private static final String BARE_DOUBLE_DASH_REPLACEMENT = "-//-";
/**
* Hidden constructor.
*/
private Util() {
}
/**
* Replace all "bare double dash" arguments in the input array.
*
* @param args the arguments array
* @return a new array with bare double dashes replaced by a special marker
*/
public static String[] mangleBareDoubleDash(final String[] args) {
return replaceAll(args, BARE_DOUBLE_DASH, BARE_DOUBLE_DASH_REPLACEMENT);
}
/**
* Restore "bare double dash" arguments in the input array.
*
* @param args the arguments array with where double dashes were replaced
* @return a new array with bare double dashes restored in place of the special marker
*/
public static String[] unmangleBareDoubleDash(final String[] args) {
return replaceAll(args, BARE_DOUBLE_DASH_REPLACEMENT, BARE_DOUBLE_DASH);
}
private static String[] replaceAll(final String[] args, final String from, final String to) {
return Arrays.stream(args).map(arg -> from.equals(arg) ? to : arg).toArray(String[]::new);
}
/**
* Get a subset of arguments before the double dash (a.k.a. options).
*
* @param args the raw array of arguments
* @return an array of arguments. Possibly empty, possibly the same as the input array.
*/
public static String[] getOptionArguments(final String[] args) {
final List<String> temporary = new ArrayList<>(args.length);
for (int i = 0; i < args.length; i++) {
if (BARE_DOUBLE_DASH.equals(args[i])) {
break;
}
temporary.add(args[i]);
}
return temporary.toArray(new String[temporary.size()]);
}
/**
* Get a subset of argument after the double dash (a.k.a. operands)
*
* @param args the raw array of arguments
* @return an array of arguments. Possibly empty
*/
public static String[] getOperandArguments(final String[] args) {
final List<String> temporary = new ArrayList<>(args.length);
int i;
for (i = 0; i < args.length; i++) {
if (BARE_DOUBLE_DASH.equals(args[i])) {
break;
}
}
for (i += 1; i < args.length; i++) {
temporary.add(args[i]);
}
return temporary.toArray(new String[temporary.size()]);
}
}
| 2,877 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/NoopParameterSplitter.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.agent.cli;
import com.beust.jcommander.converters.IParameterSplitter;
import com.google.common.collect.Lists;
import java.util.List;
/**
* Argument splitter that does not split arguments.
*
* @author mprimi
* @since 4.0.0
*/
class NoopParameterSplitter implements IParameterSplitter {
/**
* {@inheritDoc}
*/
@Override
public List<String> split(final String value) {
return Lists.newArrayList(value);
}
}
| 2,878 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ExecCommand.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.agent.cli;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
import com.google.common.annotations.VisibleForTesting;
import com.netflix.genie.agent.cli.logging.ConsoleLog;
import com.netflix.genie.agent.execution.services.KillService;
import com.netflix.genie.agent.execution.statemachine.ExecutionContext;
import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException;
import com.netflix.genie.agent.execution.statemachine.JobExecutionStateMachine;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.agent.properties.ShutdownProperties;
import com.netflix.genie.common.internal.dtos.JobStatus;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Command to execute a Genie job.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class ExecCommand implements AgentCommand {
private final ExecCommandArguments execCommandArguments;
private final JobExecutionStateMachine stateMachine;
private final KillService killService;
private final ThreadFactory threadFactory;
private final ShutdownProperties shutdownProperties;
private final ReentrantLock isRunningLock = new ReentrantLock();
private final Condition isRunningCondition = this.isRunningLock.newCondition();
private boolean isRunning;
ExecCommand(
final ExecCommandArguments execCommandArguments,
final JobExecutionStateMachine stateMachine,
final KillService killService,
final AgentProperties agentProperties
) {
this(
execCommandArguments,
stateMachine,
killService,
agentProperties,
Thread::new
);
}
@VisibleForTesting
ExecCommand(
final ExecCommandArguments execCommandArguments,
final JobExecutionStateMachine stateMachine,
final KillService killService,
final AgentProperties agentProperties,
final ThreadFactory threadFactory // For testing shutdown hooks
) {
this.execCommandArguments = execCommandArguments;
this.stateMachine = stateMachine;
this.killService = killService;
this.shutdownProperties = agentProperties.getShutdown();
this.threadFactory = threadFactory;
}
@Override
public ExitCode run() {
// Lock-free since the only other thread accessing this has not been registered yet
this.isRunning = true;
// Before execution starts, add shutdown hooks
Runtime.getRuntime().addShutdownHook(this.threadFactory.newThread(this::waitForCleanShutdown));
Runtime.getRuntime().addShutdownHook(this.threadFactory.newThread(this::handleSystemSignal));
log.info("Starting job execution");
try {
this.stateMachine.run();
} catch (final Exception e) {
log.error("Job state machine execution failed: {}", e.getMessage());
throw e;
}
final ExecutionContext executionContext = this.stateMachine.getExecutionContext();
final JobStatus finalJobStatus = executionContext.getCurrentJobStatus();
final boolean jobLaunched = executionContext.isJobLaunched();
final FatalJobExecutionException fatalException = executionContext.getExecutionAbortedFatalException();
if (fatalException != null) {
ConsoleLog.getLogger().error(
"Job execution fatal error in state {}: {}",
fatalException.getSourceState(),
fatalException.getCause().getMessage()
);
}
final ExitCode exitCode;
switch (finalJobStatus) {
case SUCCEEDED:
log.info("Job executed successfully");
exitCode = ExitCode.SUCCESS;
break;
case KILLED:
log.info("Job killed during execution");
exitCode = ExitCode.EXEC_ABORTED;
break;
case FAILED:
if (jobLaunched) {
log.info("Job execution failed");
exitCode = ExitCode.EXEC_FAIL;
} else {
log.info("Job setup failed");
exitCode = ExitCode.COMMAND_INIT_FAIL;
}
break;
case INVALID:
log.info("Job execution initialization failed");
exitCode = ExitCode.INIT_FAIL;
break;
default:
throw new RuntimeException("Unexpected final job status: " + finalJobStatus.name());
}
this.isRunningLock.lock();
try {
this.isRunning = false;
this.isRunningCondition.signalAll();
} finally {
this.isRunningLock.unlock();
}
return exitCode;
}
/**
* This code runs when the JVM is about to shut down.
* There are 2 different scenarios:
* 1) Execution is completed -- Nothing to do in this case.
* 2) A signal (TERM/HUP/INT) was received -- Job execution should be stopped in this case.
*/
private void handleSystemSignal() {
final boolean shouldAbortExecution;
this.isRunningLock.lock();
try {
shouldAbortExecution = this.isRunning;
} finally {
this.isRunningLock.unlock();
}
if (shouldAbortExecution) {
ConsoleLog.getLogger().info("Aborting job execution");
killService.kill(KillService.KillSource.SYSTEM_SIGNAL);
}
}
/**
* This code runs when the JVM is about to shut down.
* It keeps the process alive until the agent has had a chance to shut down cleanly (whatever that means, i.e.
* success, failure, kill, ...) in order to for example archive logs, update job status, etc.
*/
private void waitForCleanShutdown() {
// Don't hold off shutdown indefinitely
final long maxWaitSeconds = shutdownProperties.getExecutionCompletionLeeway().getSeconds();
final Instant waitDeadline = Instant.now().plusSeconds(maxWaitSeconds);
this.isRunningLock.lock();
try {
while (this.isRunning) {
ConsoleLog.getLogger().info("Waiting for shutdown...");
if (Instant.now().isAfter(waitDeadline)) {
log.error("Execution did not complete in the allocated time");
return;
}
try {
this.isRunningCondition.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Interrupted while waiting execution completion");
}
}
} finally {
this.isRunningLock.unlock();
log.info("Unblocking shutdown ({})", this.isRunning ? "still running" : "completed");
}
}
@Parameters(commandNames = CommandNames.EXEC, commandDescription = "Execute a Genie job")
@Getter
static class ExecCommandArguments implements AgentCommandArguments {
@ParametersDelegate
private final ArgumentDelegates.ServerArguments serverArguments;
@ParametersDelegate
private final ArgumentDelegates.CacheArguments cacheArguments;
@ParametersDelegate
private final ArgumentDelegates.JobRequestArguments jobRequestArguments;
@ParametersDelegate
private final ArgumentDelegates.CleanupArguments cleanupArguments;
@ParametersDelegate
private final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments;
ExecCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments,
final ArgumentDelegates.CacheArguments cacheArguments,
final ArgumentDelegates.JobRequestArguments jobRequestArguments,
final ArgumentDelegates.CleanupArguments cleanupArguments,
final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments
) {
this.serverArguments = serverArguments;
this.cacheArguments = cacheArguments;
this.jobRequestArguments = jobRequestArguments;
this.cleanupArguments = cleanupArguments;
this.runtimeConfigurationArguments = runtimeConfigurationArguments;
}
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return ExecCommand.class;
}
}
}
| 2,879 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/PingCommand.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
import com.google.protobuf.util.Timestamps;
import com.netflix.genie.agent.AgentMetadata;
import com.netflix.genie.proto.PingRequest;
import com.netflix.genie.proto.PingServiceGrpc;
import com.netflix.genie.proto.PongResponse;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Command to ping the server and test for connectivity and latency.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class PingCommand implements AgentCommand {
static final String CLIENT_HOST_NAME_METADATA_KEY = "clientHostName";
private final PingCommandArguments pingCommandArguments;
private final PingServiceGrpc.PingServiceFutureStub pingServiceClient;
private final AgentMetadata agentMetadata;
PingCommand(
final PingCommandArguments pingCommandArguments,
final PingServiceGrpc.PingServiceFutureStub pingServiceClient,
final AgentMetadata agentMetadata
) {
this.pingCommandArguments = pingCommandArguments;
this.pingServiceClient = pingServiceClient;
this.agentMetadata = agentMetadata;
}
@Override
public ExitCode run() {
final String requestID =
pingCommandArguments.getRequestId() == null
? UUID.randomUUID().toString() : pingCommandArguments.getRequestId();
final String source = agentMetadata.getAgentPid() + "@" + agentMetadata.getAgentHostName();
final PingRequest request = PingRequest.newBuilder()
.setRequestId(requestID)
.setSourceName(source)
.setTimestamp(Timestamps.fromMillis(System.currentTimeMillis()))
.putClientMetadata(CLIENT_HOST_NAME_METADATA_KEY, agentMetadata.getAgentHostName())
.build();
log.info(
"Sending Ping with id: {}, timestamp: {}",
requestID,
Timestamps.toString(request.getTimestamp())
);
final long start = System.nanoTime();
final PongResponse response;
try {
response = pingServiceClient.ping(request).get(
pingCommandArguments.getRpcTimeout(),
TimeUnit.SECONDS
);
} catch (final InterruptedException | ExecutionException | TimeoutException e) {
throw new RuntimeException("Failed to ping server", e);
}
final long end = System.nanoTime();
final long elapsedMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
log.info("Server responded to ping in {} ms. Server metadata:", elapsedMillis);
for (Map.Entry<String, String> serverMetadataEntry : response.getServerMetadataMap().entrySet()) {
log.info(
" - {} = {}",
serverMetadataEntry.getKey(),
serverMetadataEntry.getValue());
}
return ExitCode.SUCCESS;
}
@Parameters(commandNames = CommandNames.PING, commandDescription = "Test connectivity with the server")
static class PingCommandArguments implements AgentCommandArguments {
@ParametersDelegate
private final ArgumentDelegates.ServerArguments serverArguments;
@Parameter(
names = {"--requestId"},
description = "Request id (defaults to UUID)",
validateWith = ArgumentValidators.StringValidator.class
)
@Getter
private String requestId;
PingCommandArguments(final ArgumentDelegates.ServerArguments serverArguments) {
this.serverArguments = serverArguments;
}
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return PingCommand.class;
}
String getServerHost() {
return serverArguments.getServerHost();
}
int getServerPort() {
return serverArguments.getServerPort();
}
long getRpcTimeout() {
return serverArguments.getRpcTimeout();
}
}
}
| 2,880 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/HeartBeatCommand.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
import com.netflix.genie.agent.execution.services.AgentHeartBeatService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Command to establish a persistent connection with Genie server and exchange heartbeats.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class HeartBeatCommand implements AgentCommand {
private final HeartBeatCommandArguments heartBeatCommandArguments;
private final AgentHeartBeatService agentHeartBeatService;
private AtomicBoolean isConnected = new AtomicBoolean(false);
HeartBeatCommand(
final HeartBeatCommandArguments heartBeatCommandArguments,
final AgentHeartBeatService agentHeartBeatService
) {
this.heartBeatCommandArguments = heartBeatCommandArguments;
this.agentHeartBeatService = agentHeartBeatService;
}
@Override
public ExitCode run() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(1);
scheduler.initialize();
scheduler.scheduleAtFixedRate(this::checkConnectionStatus, 1000);
final String pseudoJobId = this.getClass().getSimpleName() + UUID.randomUUID().toString();
System.out.println("Initiating protocol with pseudo jobId: " + pseudoJobId);
agentHeartBeatService.start(pseudoJobId);
synchronized (this) {
try {
wait(TimeUnit.MILLISECONDS.convert(heartBeatCommandArguments.getRunDuration(), TimeUnit.SECONDS));
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted");
}
}
agentHeartBeatService.stop();
return ExitCode.SUCCESS;
}
private void checkConnectionStatus() {
final boolean isCurrentlyConnected = agentHeartBeatService.isConnected();
final boolean wasPreviouslyConnected = isConnected.getAndSet(isCurrentlyConnected);
if (wasPreviouslyConnected != isCurrentlyConnected) {
System.out.println("Connection status: " + (isCurrentlyConnected ? "CONNECTED" : "DISCONNECTED"));
}
}
@Parameters(commandNames = CommandNames.HEARTBEAT, commandDescription = "Send heartbeats to a server")
@Getter
static class HeartBeatCommandArguments implements AgentCommandArguments {
@ParametersDelegate
private final ArgumentDelegates.ServerArguments serverArguments;
@Parameter(
names = {"--duration"},
description = "How long to run before terminating (in seconds, 0 for unlimited)"
)
private int runDuration;
HeartBeatCommandArguments(final ArgumentDelegates.ServerArguments serverArguments) {
this.serverArguments = serverArguments;
}
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return HeartBeatCommand.class;
}
}
}
| 2,881 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/AgentCommandArguments.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.agent.cli;
/**
* Interface for argument classes used by {@link ArgumentParser}.
*
* @author mprimi
* @since 4.0.0
*/
interface AgentCommandArguments {
/**
* The command class that consumes this type of arguments.
*
* @return a concrete AgentCommand class
*/
Class<? extends AgentCommand> getConsumerClass();
}
| 2,882 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ArgumentValidators.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.agent.cli;
import com.amazonaws.services.s3.AmazonS3URI;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.IValueValidator;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.validators.PositiveInteger;
import org.apache.commons.lang3.StringUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* Parameter validators for command-line arguments.
*
* @author mprimi
* @since 4.0.0
*/
final class ArgumentValidators {
/**
* Hide constructor.
*/
private ArgumentValidators() {
}
/**
* Validates a string parameter is not null or empty.
*/
public static class StringValidator implements IParameterValidator {
/**
* {@inheritDoc}
*/
@Override
public void validate(final String name, final String value) throws ParameterException {
if (StringUtils.isBlank(value)) {
throw new ParameterException(name + " is null or empty");
}
}
}
/**
* Validates a string parameter is a valid S3 uri.
*/
public static class S3URIValidator implements IParameterValidator {
/**
* {@inheritDoc}
*/
@Override
public void validate(final String name, final String value) throws ParameterException {
try {
//Check if a valid S3 uri can be created
new AmazonS3URI(value);
} catch (Exception e) {
throw new ParameterException(name + " is not a valid S3 uri");
}
}
}
/**
* Validates a integer parameter is a positive integer.
*/
public static class PortValidator extends PositiveInteger {
}
/**
* Validates an URI parameter can be parsed as URI.
* If the resource type is local file, validate it exists, it is readable, etc.
*/
public static class URIValidator implements IValueValidator<String> {
/**
* {@inheritDoc}
*/
@Override
public void validate(final String name, final String value) throws ParameterException {
// Make sure the value is a valid URI
final URI uri;
try {
uri = new URI(value);
} catch (URISyntaxException e) {
throw new ParameterException("Invalid URI " + value + " (for option: " + name + ")", e);
}
// If it's a file, make sure it exists, it's a file, it's readable, etc.
if (uri.getScheme().equals("file")) {
final Path path = Paths.get(uri.getPath());
if (!Files.exists(path)) {
throw new ParameterException("File " + value + " does not exist (for option: " + name + ")");
} else if (!Files.isRegularFile(path)) {
throw new ParameterException("File " + value + " is not a file (for option: " + name + ")");
} else if (!Files.isReadable(path)) {
throw new ParameterException("File " + value + " is not readable (for option: " + name + ")");
}
}
}
}
/**
* Validates a URI collection parameter by delegating validation to {@link URIValidator}.
*/
public static class URIListValidator implements IValueValidator<List<String>> {
/**
* {@inheritDoc}
*/
@Override
public void validate(final String name, final List<String> values) throws ParameterException {
final URIValidator validator = new URIValidator();
for (final String value : values) {
validator.validate(name, value);
}
}
}
}
| 2,883 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/HelpCommand.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.agent.cli;
import com.beust.jcommander.Parameters;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Command to print agent usage/help message.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class HelpCommand implements AgentCommand {
private final ArgumentParser argumentParser;
HelpCommand(final ArgumentParser argumentParser) {
this.argumentParser = argumentParser;
}
@Override
public ExitCode run() {
System.out.println(argumentParser.getUsageMessage());
return ExitCode.SUCCESS;
}
@Parameters(commandNames = CommandNames.HELP, commandDescription = "Print agent usage and help message")
@Getter
static class HelpCommandArguments implements AgentCommandArguments {
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return HelpCommand.class;
}
}
}
| 2,884 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ResolveJobSpecCommand.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.netflix.genie.agent.execution.exceptions.JobSpecificationResolutionException;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.AgentJobRequest;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
/**
* Command to request the server to resolve a job request into a job specification.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class ResolveJobSpecCommand implements AgentCommand {
private final ResolveJobSpecCommandArguments resolveJobSpecCommandArguments;
private final AgentJobService agentJobService;
private final JobRequestConverter jobRequestConverter;
ResolveJobSpecCommand(
final ResolveJobSpecCommandArguments resolveJobSpecCommandArguments,
final AgentJobService agentJobService,
final JobRequestConverter jobRequestConverter
) {
this.resolveJobSpecCommandArguments = resolveJobSpecCommandArguments;
this.agentJobService = agentJobService;
this.jobRequestConverter = jobRequestConverter;
}
@Override
public ExitCode run() {
log.info("Resolving job specification");
final ObjectMapper prettyJsonMapper = GenieObjectMapper.getMapper()
.copy() // Don't reconfigure the shared mapper
.enable(SerializationFeature.INDENT_OUTPUT);
final JobSpecification spec;
final String jobId = resolveJobSpecCommandArguments.getSpecificationId();
if (!StringUtils.isBlank(jobId)) {
// Do a specification lookup if an id is given
log.info("Looking up specification of job {}", jobId);
try {
spec = agentJobService.getJobSpecification(jobId);
} catch (final JobSpecificationResolutionException e) {
throw new RuntimeException("Failed to get spec: " + jobId, e);
}
} else {
// Compose a job request from argument
final AgentJobRequest agentJobRequest;
try {
final ArgumentDelegates.JobRequestArguments jobArgs
= resolveJobSpecCommandArguments.getJobRequestArguments();
agentJobRequest = jobRequestConverter.agentJobRequestArgsToDTO(jobArgs);
} catch (final JobRequestConverter.ConversionException e) {
throw new RuntimeException("Failed to construct job request from arguments", e);
}
// Print request
if (!resolveJobSpecCommandArguments.isPrintRequestDisabled()) {
try {
System.out.println(prettyJsonMapper.writeValueAsString(agentJobRequest));
} catch (final JsonProcessingException e) {
throw new RuntimeException("Failed to map request to JSON", e);
}
}
// Resolve via service
try {
spec = agentJobService.resolveJobSpecificationDryRun(agentJobRequest);
} catch (final JobSpecificationResolutionException e) {
throw new RuntimeException("Failed to resolve job specification", e);
}
}
// Translate response to JSON
final String specJsonString;
try {
specJsonString = prettyJsonMapper.writeValueAsString(spec);
} catch (final JsonProcessingException e) {
throw new RuntimeException("Failed to map specification to JSON", e);
}
// Print specification
System.out.println(specJsonString);
// Write specification to file
final File outputFile = resolveJobSpecCommandArguments.getOutputFile();
if (outputFile != null) {
try {
Files.write(
outputFile.toPath(),
specJsonString.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE_NEW
);
} catch (final IOException e) {
throw new RuntimeException("Failed to write request to: " + outputFile.getAbsolutePath(), e);
}
}
return ExitCode.SUCCESS;
}
@Parameters(
commandNames = CommandNames.RESOLVE,
commandDescription = "Resolve job parameters into a job specification via server")
@Getter
static class ResolveJobSpecCommandArguments implements AgentCommandArguments {
@ParametersDelegate
private final ArgumentDelegates.ServerArguments serverArguments;
@ParametersDelegate
private final ArgumentDelegates.JobRequestArguments jobRequestArguments;
@Parameter(
names = {"--spec-id"},
description = "Lookup an existing specification rather than resolving (ignores other job arguments)"
)
private String specificationId;
@Parameter(
names = {"--output-file"},
description = "Output file for specification (in JSON form)",
converter = ArgumentConverters.FileConverter.class
)
private File outputFile;
@Parameter(
names = {"--no-request"},
description = "Do not print the request to console"
)
private boolean printRequestDisabled;
ResolveJobSpecCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments,
final ArgumentDelegates.JobRequestArguments jobRequestArguments
) {
this.serverArguments = serverArguments;
this.jobRequestArguments = jobRequestArguments;
}
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return ResolveJobSpecCommand.class;
}
}
}
| 2,885 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/GenieAgentRunner.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.agent.cli;
import brave.ScopedSpan;
import brave.SpanCustomizer;
import brave.Tracer;
import brave.propagation.TraceContext;
import com.beust.jcommander.ParameterException;
import com.netflix.genie.agent.cli.logging.ConsoleLog;
import com.netflix.genie.common.internal.tracing.TracingConstants;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.core.env.Environment;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
/**
* Main entry point for execution after the application is initialized.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class GenieAgentRunner implements CommandLineRunner, ExitCodeGenerator {
static final String RUN_SPAN_NAME = "genie-agent-run";
private final ArgumentParser argumentParser;
private final CommandFactory commandFactory;
private final Environment environment;
private final BraveTracePropagator tracePropagator;
private final BraveTracingCleanup tracingCleanup;
private final Tracer tracer;
private final BraveTagAdapter tagAdapter;
private ExitCode exitCode = ExitCode.INIT_FAIL;
GenieAgentRunner(
final ArgumentParser argumentParser,
final CommandFactory commandFactory,
final BraveTracingComponents tracingComponents,
final Environment environment
) {
this.argumentParser = argumentParser;
this.commandFactory = commandFactory;
this.tracePropagator = tracingComponents.getTracePropagator();
this.tracingCleanup = tracingComponents.getTracingCleaner();
this.tracer = tracingComponents.getTracer();
this.tagAdapter = tracingComponents.getTagAdapter();
this.environment = environment;
}
@Override
public void run(final String... args) throws Exception {
final ScopedSpan runSpan = this.initializeTracing();
try {
ConsoleLog.printBanner(this.environment);
try {
internalRun(args);
} catch (final Throwable t) {
final Throwable userConsoleException = t.getCause() != null ? t.getCause() : t;
ConsoleLog.getLogger().error(
"Command execution failed: {}",
userConsoleException.getMessage()
);
log.error("Command execution failed", t);
runSpan.error(t);
}
} finally {
runSpan.finish();
this.tracingCleanup.cleanup();
}
}
private void internalRun(final String[] args) {
final SpanCustomizer span = this.tracer.currentSpanCustomizer();
log.info("Parsing arguments: {}", Arrays.toString(args));
this.exitCode = ExitCode.INVALID_ARGS;
//TODO: workaround for https://jira.spring.io/browse/SPR-17416
final String[] originalArgs = Util.unmangleBareDoubleDash(args);
log.debug("Arguments: {}", Arrays.toString(originalArgs));
try {
this.argumentParser.parse(originalArgs);
} catch (ParameterException e) {
throw new IllegalArgumentException("Failed to parse arguments: " + e.getMessage(), e);
}
final String commandName = this.argumentParser.getSelectedCommand();
final Set<String> availableCommands = this.argumentParser.getCommandNames();
final String availableCommandsString = Arrays.toString(availableCommands.toArray());
if (commandName == null) {
throw new IllegalArgumentException("No command selected -- commands available: " + availableCommandsString);
} else if (!availableCommands.contains(commandName)) {
throw new IllegalArgumentException("Invalid command -- commands available: " + availableCommandsString);
}
this.tagAdapter.tag(span, TracingConstants.AGENT_CLI_COMMAND_NAME_TAG, commandName);
ConsoleLog.getLogger().info("Preparing agent to execute command: '{}'", commandName);
log.info("Initializing command: {}", commandName);
this.exitCode = ExitCode.COMMAND_INIT_FAIL;
final AgentCommand command = this.commandFactory.get(commandName);
this.exitCode = ExitCode.EXEC_FAIL;
this.exitCode = command.run();
}
@Override
public int getExitCode() {
ConsoleLog.getLogger().info(
"Terminating with code: {} ({})",
this.exitCode.getCode(),
this.exitCode.getMessage()
);
return this.exitCode.getCode();
}
private ScopedSpan initializeTracing() {
// Attempt to extract any existing trace information from the environment
final Optional<TraceContext> existingTraceContext = this.tracePropagator.extract(System.getenv());
final ScopedSpan runSpan = existingTraceContext.isPresent()
? this.tracer.startScopedSpanWithParent(RUN_SPAN_NAME, existingTraceContext.get())
: this.tracer.startScopedSpan(RUN_SPAN_NAME);
// Quickly create and report an initial span
final TraceContext initContext = runSpan.context();
final String traceId = initContext.traceIdString();
log.info("Trace ID: {}", traceId);
ConsoleLog.getLogger().info("Trace ID: {}", traceId);
return runSpan;
}
}
| 2,886 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/CleanupArgumentsImpl.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.netflix.genie.agent.execution.CleanupStrategy;
/**
* Implementation of {@link ArgumentDelegates.CleanupArguments} delegate.
*
* @author mprimi
* @since 4.0.0
*/
class CleanupArgumentsImpl implements ArgumentDelegates.CleanupArguments {
@Parameter(
names = {"--noCleanup", "--no-cleanup"},
description = "Skip the post-execution cleanup and leave all files in place"
)
private boolean skipCleanup;
@Parameter(
names = {"--fullCleanup", "--full-cleanup"},
description = "Remove the entire job folder post-execution"
)
private boolean fullCleanup;
/**
* {@inheritDoc}
*/
@Override
public CleanupStrategy getCleanupStrategy() {
if (skipCleanup) {
return CleanupStrategy.NO_CLEANUP;
} else if (fullCleanup) {
return CleanupStrategy.FULL_CLEANUP;
}
return CleanupStrategy.DEPENDENCIES_CLEANUP;
}
}
| 2,887 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/InfoCommand.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.collect.Lists;
import com.netflix.genie.agent.AgentMetadata;
import com.netflix.genie.agent.execution.statemachine.ExecutionStage;
import com.netflix.genie.agent.execution.statemachine.JobExecutionStateMachine;
import com.netflix.genie.agent.execution.statemachine.States;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Command to print diagnostic information such as environment variables, beans, etc.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class InfoCommand implements AgentCommand {
private static final String NEWLINE = System.lineSeparator();
private final InfoCommandArguments infoCommandArguments;
private final ConfigurableApplicationContext applicationContext;
private final AgentMetadata agentMetadata;
InfoCommand(
final InfoCommandArguments infoCommandArguments,
final ConfigurableApplicationContext applicationContext,
final AgentMetadata agentMetadata
) {
this.infoCommandArguments = infoCommandArguments;
this.applicationContext = applicationContext;
this.agentMetadata = agentMetadata;
}
@Override
public ExitCode run() {
final StringBuilder messageBuilder = new StringBuilder();
messageBuilder
.append("Agent info:")
.append(NEWLINE)
.append(" version: ")
.append(agentMetadata.getAgentVersion())
.append(NEWLINE)
.append(" host: ")
.append(agentMetadata.getAgentHostName())
.append(NEWLINE)
.append(" pid: ")
.append(agentMetadata.getAgentPid())
.append(NEWLINE);
messageBuilder
.append("Active profiles:")
.append(NEWLINE);
for (String profileName : applicationContext.getEnvironment().getActiveProfiles()) {
messageBuilder
.append(" - ")
.append(profileName)
.append(NEWLINE);
}
messageBuilder
.append("Default profiles:")
.append(NEWLINE);
for (String profileName : applicationContext.getEnvironment().getDefaultProfiles()) {
messageBuilder
.append(" - ")
.append(profileName)
.append(NEWLINE);
}
if (infoCommandArguments.getIncludeBeans()) {
messageBuilder
.append("Beans in context: ")
.append(applicationContext.getBeanDefinitionCount())
.append(NEWLINE);
final String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
final BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName);
final String beanClass = beanDefinition.getBeanClassName();
final String description = new StringBuilder()
.append(beanDefinition.isLazyInit() ? "lazy" : "eager")
.append(beanDefinition.isPrototype() ? ", prototype" : "")
.append(beanDefinition.isSingleton() ? ", singleton" : "")
.toString();
messageBuilder
.append(
String.format(
" - %s (%s) [%s]",
beanName,
beanClass == null ? "?" : beanClass,
description
)
)
.append(NEWLINE);
}
}
if (infoCommandArguments.getIncludeEnvironment()) {
final Set<Map.Entry<String, Object>> envEntries =
applicationContext.getEnvironment().getSystemEnvironment().entrySet();
messageBuilder
.append("Environment variables: ")
.append(envEntries.size())
.append(NEWLINE);
for (Map.Entry<String, Object> envEntry : envEntries) {
messageBuilder
.append(
String.format(
" - %s=%s",
envEntry.getKey(),
envEntry.getValue()
)
)
.append(NEWLINE);
}
}
if (infoCommandArguments.getIncludeProperties()) {
final Set<Map.Entry<String, Object>> properties =
applicationContext.getEnvironment().getSystemProperties().entrySet();
messageBuilder
.append("Properties: ")
.append(properties.size())
.append(NEWLINE);
for (Map.Entry<String, Object> property : properties) {
messageBuilder
.append(
String.format(
" - %s=%s",
property.getKey(),
property.getValue()
)
)
.append(NEWLINE);
}
final PropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
messageBuilder
.append("Property sources: ")
.append(NEWLINE);
for (PropertySource<?> propertySource : propertySources) {
messageBuilder
.append(
String.format(
" - %s (%s)",
propertySource.getName(),
propertySource.getClass().getSimpleName()
)
)
.append(NEWLINE);
}
}
if (infoCommandArguments.getIncludeStateMachine()) {
messageBuilder
.append("Job execution state machine: ")
.append(NEWLINE)
.append("// ------------------------------------------------------------------------")
.append(NEWLINE);
final JobExecutionStateMachine jobExecutionStateMachine
= applicationContext.getBean(JobExecutionStateMachine.class);
final List<ExecutionStage> stages = jobExecutionStateMachine.getExecutionStages();
createStateMachineDotGraph(stages, messageBuilder);
}
System.out.println(messageBuilder);
return ExitCode.SUCCESS;
}
private void createStateMachineDotGraph(
final List<ExecutionStage> stages,
final StringBuilder messageBuilder
) {
final List<States> states = Lists.newArrayList();
states.add(States.INITIAL_STATE);
stages.forEach(stage -> states.add(stage.getState()));
states.add(States.FINAL_STATE);
final List<Pair<States, States>> transitions = Lists.newArrayList();
for (int i = 0; i < states.size() - 1; i++) {
transitions.add(Pair.of(states.get(i), states.get(i + 1)));
}
messageBuilder
.append("digraph state_machine {")
.append(NEWLINE);
messageBuilder
.append(" // States")
.append(NEWLINE);
states.forEach(
state -> {
final String shape;
if (state == States.INITIAL_STATE) {
shape = "shape=diamond";
} else if (state == States.FINAL_STATE) {
shape = "shape=rectangle";
} else {
shape = "";
}
final String edgeTickness;
if (state.isCriticalState()) {
edgeTickness = "penwidth=3.0";
} else {
edgeTickness = "";
}
messageBuilder
.append(" ")
.append(state.name())
.append(" [label=")
.append(state.name())
.append(" ")
.append(shape)
.append(" ")
.append(edgeTickness)
.append("]")
.append(NEWLINE);
}
);
messageBuilder
.append(" // Transitions")
.append(NEWLINE);
transitions.forEach(
transition ->
messageBuilder
.append(" ")
.append(transition.getLeft())
.append(" -> ")
.append(transition.getRight())
.append(NEWLINE)
);
messageBuilder
.append(" // Skip transitions")
.append(NEWLINE);
// Draw an edge from a state whose next state is skippable to the next non-skippable state.
for (int i = 0; i < states.size() - 2; i++) {
final States state = states.get(i);
final boolean skipNext = states.get(i + 1).isSkippedDuringAbortedExecution();
if (skipNext) {
// Find the next non-skipped stage
for (int j = i + 1; j < states.size() - 1; j++) {
final States nextState = states.get(j);
if (!nextState.isSkippedDuringAbortedExecution()) {
messageBuilder
.append(" ")
.append(state)
.append(" -> ")
.append(nextState)
.append(" [style=dotted]")
.append(NEWLINE);
break;
}
}
}
}
messageBuilder
.append(" // Retry transitions")
.append(NEWLINE);
states.forEach(
state -> {
final @Min(0) int retries = state.getTransitionRetries();
if (retries > 0) {
messageBuilder
.append(" ")
.append(state)
.append(" -> ")
.append(state)
.append(" [style=dashed label=\"")
.append(retries)
.append(" retries\"]")
.append(NEWLINE);
}
}
);
messageBuilder
.append("}")
.append(NEWLINE)
.append("// ------------------------------------------------------------------------")
.append(NEWLINE);
}
@Parameters(commandNames = CommandNames.INFO, commandDescription = "Print agent and environment information")
@Getter
static class InfoCommandArguments implements AgentCommandArguments {
@Parameter(names = {"--beans"}, description = "Print beans")
private Boolean includeBeans = true;
@Parameter(names = {"--env"}, description = "Print environment variables")
private Boolean includeEnvironment = true;
@Parameter(names = {"--properties"}, description = "Print properties")
private Boolean includeProperties = true;
@Parameter(names = {"--state-machine"}, description = "Print job execution state machine in (.dot notation)")
private Boolean includeStateMachine = false;
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return InfoCommand.class;
}
}
}
| 2,888 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ExitCode.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.agent.cli;
import lombok.Getter;
/**
* Exit codes for Genie agent.
*
* @author mprimi
* @since 4.0.0
*/
public enum ExitCode {
/**
* Agent command execution completed successfully.
*/
SUCCESS(0, "Success"),
/**
* Agent failed to bootstrap and/or initialize.
*/
INIT_FAIL(101, "Agent initialization error"),
/**
* Command-line options provided are invalid.
*/
INVALID_ARGS(102, "Invalid arguments"),
/**
* The selected agent command failed to initialize.
*/
COMMAND_INIT_FAIL(103, "Command initialization error"),
/**
* The selected agent command failed to execute.
*/
EXEC_FAIL(104, "Command execution error"),
/**
* The selected agent command was forcefully terminated before completion.
*/
EXEC_ABORTED(105, "Command execution aborted");
static final String EXIT_CODE_HELP_MESSAGE;
static {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append("EXIT CODES:").append("\n");
for (final ExitCode exitCode : ExitCode.values()) {
stringBuilder
.append(exitCode.getCode())
.append(": ")
.append(exitCode.name())
.append(" - ")
.append(exitCode.getMessage())
.append("\n");
}
EXIT_CODE_HELP_MESSAGE = stringBuilder.toString();
}
@Getter
private final int code;
@Getter
private final String message;
ExitCode(final int code, final String message) {
this.code = code;
this.message = message;
}
}
| 2,889 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/DownloadCommand.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
import com.google.common.collect.Lists;
import com.netflix.genie.agent.execution.exceptions.DownloadException;
import com.netflix.genie.agent.execution.services.DownloadService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.net.URI;
import java.nio.file.Paths;
import java.util.List;
/**
* Command to download dependencies as a job would.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
class DownloadCommand implements AgentCommand {
private final DownloadCommandArguments downloadCommandArguments;
private final DownloadService downloadService;
DownloadCommand(
final DownloadCommandArguments downloadCommandArguments,
final DownloadService downloadService
) {
this.downloadCommandArguments = downloadCommandArguments;
this.downloadService = downloadService;
}
@Override
public ExitCode run() {
final List<URI> uris = downloadCommandArguments.getFileUris();
final File destinationDirectory = downloadCommandArguments.getDestinationDirectory();
if (!destinationDirectory.exists() || !destinationDirectory.isDirectory()) {
throw new ParameterException(
"Not a valid destination directory: "
+ destinationDirectory.getAbsolutePath()
);
}
log.info(
"Downloading {} files into: {}",
uris.size(),
downloadCommandArguments.getDestinationDirectory()
);
final DownloadService.Manifest.Builder manifestBuilder = downloadService.newManifestBuilder();
for (final URI uri : uris) {
log.info(" * {}", uri);
manifestBuilder.addFileWithTargetDirectory(uri, destinationDirectory);
}
final DownloadService.Manifest manifest = manifestBuilder.build();
try {
downloadService.download(manifest);
} catch (final DownloadException e) {
throw new RuntimeException("Download failed", e);
}
return ExitCode.SUCCESS;
}
@Parameters(commandNames = CommandNames.DOWNLOAD, commandDescription = "Download a set of files")
static class DownloadCommandArguments implements AgentCommandArguments {
@ParametersDelegate
@Getter
private final ArgumentDelegates.CacheArguments cacheArguments;
@Parameter(
names = {"--sources"},
description = "URLs of files to download",
validateWith = ArgumentValidators.StringValidator.class,
converter = ArgumentConverters.URIConverter.class,
variableArity = true
)
@Getter
private List<URI> fileUris;
@Parameter(
names = {"--destinationDirectory"},
validateWith = ArgumentValidators.StringValidator.class,
converter = ArgumentConverters.FileConverter.class
)
@Getter
private File destinationDirectory;
DownloadCommandArguments(
final ArgumentDelegates.CacheArguments cacheArguments
) {
this.cacheArguments = cacheArguments;
this.fileUris = Lists.newArrayList();
this.destinationDirectory = Paths.get("").toAbsolutePath().toFile();
}
@Override
public Class<? extends AgentCommand> getConsumerClass() {
return DownloadCommand.class;
}
}
}
| 2,890 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ServerArgumentsImpl.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.validators.PositiveInteger;
import lombok.Getter;
/**
* Implementation of ServerArguments delegate.
*/
@Getter
class ServerArgumentsImpl implements ArgumentDelegates.ServerArguments {
@Parameter(
names = {"--serverHost", "--server-host"},
description = "Server hostname or address",
validateWith = ArgumentValidators.StringValidator.class
)
private String serverHost = "localhost";
@Parameter(
names = {"--serverPort", "--server-port"},
description = "Server port",
validateWith = ArgumentValidators.PortValidator.class
)
private int serverPort = 7979;
@Parameter(
names = {"--rpcTimeout", "--rpc-timeout"},
description = "Timeout for blocking RPC calls in seconds",
validateWith = PositiveInteger.class
)
private long rpcTimeout = 30;
}
| 2,891 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/CliAutoConfiguration.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.agent.cli;
import com.netflix.genie.agent.AgentMetadata;
import com.netflix.genie.agent.cli.logging.AgentLogManager;
import com.netflix.genie.agent.cli.logging.AgentLogManagerLog4j2Impl;
import com.netflix.genie.agent.execution.services.AgentHeartBeatService;
import com.netflix.genie.agent.execution.services.AgentJobService;
import com.netflix.genie.agent.execution.services.DownloadService;
import com.netflix.genie.agent.execution.services.KillService;
import com.netflix.genie.agent.execution.statemachine.JobExecutionStateMachine;
import com.netflix.genie.agent.properties.AgentProperties;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.proto.PingServiceGrpc;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import javax.validation.Validator;
/**
* Spring auto configuration class to contain all beans involved in the CLI for the Agent.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
AgentProperties.class
}
)
public class CliAutoConfiguration {
/**
* Provide a bean for cache command line arguments.
*
* @return a {@link CacheArgumentsImpl} instance
*/
@Bean
public CacheArgumentsImpl cacheArgumentsDelegate() {
return new CacheArgumentsImpl();
}
/**
* Provide a bean for arguments for a download command.
*
* @param cacheArguments Any arguments that were provided for the cache of this agent instance
* @return An instance of {@link com.netflix.genie.agent.cli.DownloadCommand.DownloadCommandArguments}
*/
@Bean
public DownloadCommand.DownloadCommandArguments downloadCommandArguments(
final ArgumentDelegates.CacheArguments cacheArguments
) {
return new DownloadCommand.DownloadCommandArguments(cacheArguments);
}
/**
* Provide a lazy bean definition for a {@link DownloadCommand}.
*
* @param downloadCommandArguments The download command arguments to use
* @param downloadService The download service to use
* @return An instance of {@link DownloadCommand}
*/
@Bean
@Lazy
public DownloadCommand downloadCommand(
final DownloadCommand.DownloadCommandArguments downloadCommandArguments,
final DownloadService downloadService
) {
return new DownloadCommand(downloadCommandArguments, downloadService);
}
/**
* Provide a bean for execution command arguments.
*
* @param serverArguments The server arguments to use
* @param cacheArguments The cache arguments to use
* @param jobRequestArguments The job request arguments to use
* @param cleanupArguments The cleanup arguments to use
* @param runtimeConfigurationArguments the runtime configuration arguments group
* @return An instance of {@link com.netflix.genie.agent.cli.ExecCommand.ExecCommandArguments}
*/
@Bean
public ExecCommand.ExecCommandArguments execCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments,
final ArgumentDelegates.CacheArguments cacheArguments,
final ArgumentDelegates.JobRequestArguments jobRequestArguments,
final ArgumentDelegates.CleanupArguments cleanupArguments,
final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments
) {
return new ExecCommand.ExecCommandArguments(
serverArguments,
cacheArguments,
jobRequestArguments,
cleanupArguments,
runtimeConfigurationArguments
);
}
/**
* Provide a lazy bean definition for an {@link ExecCommand}.
*
* @param execCommandArguments The exec command arguments to use
* @param jobExecutionStateMachine The job execution state machine instance to use
* @param killService The kill service to use
* @param agentProperties The agent properties
* @return A bean definition for an {@link ExecCommand} if one hasn't already been defined
*/
@Bean
@Lazy
public ExecCommand execCommand(
final ExecCommand.ExecCommandArguments execCommandArguments,
final JobExecutionStateMachine jobExecutionStateMachine,
final KillService killService,
final AgentProperties agentProperties
) {
return new ExecCommand(execCommandArguments, jobExecutionStateMachine, killService, agentProperties);
}
/**
* The main {@link GenieAgentRunner} entry point bean which implements
* {@link org.springframework.boot.CommandLineRunner}.
*
* @param argumentParser The argument parser to use
* @param commandFactory The command factory to use
* @param tracingComponents The {@link BraveTracingComponents} to use
* @param environment The spring environment
* @return An instance of {@link GenieAgentRunner} if one hasn't already been provided
*/
@Bean
public GenieAgentRunner genieAgentRunner(
final ArgumentParser argumentParser,
final CommandFactory commandFactory,
final BraveTracingComponents tracingComponents,
final Environment environment
) {
return new GenieAgentRunner(argumentParser, commandFactory, tracingComponents, environment);
}
/**
* Provide a bean for {@link com.netflix.genie.agent.cli.HeartBeatCommand.HeartBeatCommandArguments}.
*
* @param serverArguments The server arguments to use
* @return An instance of {@link com.netflix.genie.agent.cli.HeartBeatCommand.HeartBeatCommandArguments}
*/
@Bean
public HeartBeatCommand.HeartBeatCommandArguments heartBeatCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments
) {
return new HeartBeatCommand.HeartBeatCommandArguments(serverArguments);
}
/**
* Provide a lazy bean definition for a {@link HeartBeatCommand}.
*
* @param heartBeatCommandArguments The heart beat command arguments to use
* @param agentHeartBeatService The heart beat service to use
* @return An instance of {@link HeartBeatCommand}
*/
@Bean
@Lazy
public HeartBeatCommand heartBeatCommand(
final HeartBeatCommand.HeartBeatCommandArguments heartBeatCommandArguments,
final AgentHeartBeatService agentHeartBeatService
) {
return new HeartBeatCommand(heartBeatCommandArguments, agentHeartBeatService);
}
/**
* Provide an bean of {@link com.netflix.genie.agent.cli.HelpCommand.HelpCommandArguments}.
*
* @return An instance of {@link com.netflix.genie.agent.cli.HelpCommand.HelpCommandArguments}
*/
@Bean
public HelpCommand.HelpCommandArguments helpCommandArguments() {
return new HelpCommand.HelpCommandArguments();
}
/**
* Provide a lazy bean instance of {@link HelpCommand}.
*
* @param argumentParser The argument parser to use
* @return The {@link HelpCommand} instance
*/
@Bean
@Lazy
public HelpCommand helpCommand(final ArgumentParser argumentParser) {
return new HelpCommand(argumentParser);
}
/**
* Provide an instance of {@link com.netflix.genie.agent.cli.InfoCommand.InfoCommandArguments}.
*
* @return An {@link com.netflix.genie.agent.cli.InfoCommand.InfoCommandArguments} instance
*/
@Bean
public InfoCommand.InfoCommandArguments infoCommandArguments() {
return new InfoCommand.InfoCommandArguments();
}
/**
* Provide a lazy bean definition for an {@link InfoCommand}.
*
* @param infoCommandArguments The info command arguments to use
* @param configurableApplicationContext The Spring context to use
* @param agentMetadata The agent metadata to use
* @return A lazy bean definition for an {@link InfoCommand} instance
*/
@Bean
@Lazy
public InfoCommand infoCommand(
final InfoCommand.InfoCommandArguments infoCommandArguments,
final ConfigurableApplicationContext configurableApplicationContext,
final AgentMetadata agentMetadata
) {
return new InfoCommand(infoCommandArguments, configurableApplicationContext, agentMetadata);
}
/**
* Provide a {@link com.netflix.genie.agent.cli.MainCommandArguments}.
*
* @return An instance of {@link com.netflix.genie.agent.cli.MainCommandArguments}.
*/
@Bean
public MainCommandArguments mainCommandArguments() {
return new MainCommandArguments();
}
/**
* Provide a {@link com.netflix.genie.agent.cli.ArgumentDelegates.JobRequestArguments}.
*
* @param mainCommandArguments container for the main arguments
* @return An instance of {@link com.netflix.genie.agent.cli.ArgumentDelegates.JobRequestArguments}
*/
@Bean
public JobRequestArgumentsImpl jobRequestArguments(final MainCommandArguments mainCommandArguments) {
return new JobRequestArgumentsImpl(mainCommandArguments);
}
/**
* Provide an instance of {@link JobRequestConverter}.
*
* @param validator The validator to use
* @return A {@link JobRequestConverter} instance
*/
@Bean
@Lazy
public JobRequestConverter jobRequestConverter(final Validator validator) {
return new JobRequestConverter(validator);
}
/**
* Provides a {@link com.netflix.genie.agent.cli.PingCommand.PingCommandArguments} bean.
*
* @param serverArguments The server arguments to use
* @return A {@link com.netflix.genie.agent.cli.PingCommand.PingCommandArguments} instance
*/
@Bean
public PingCommand.PingCommandArguments pingCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments
) {
return new PingCommand.PingCommandArguments(serverArguments);
}
/**
* Provide a lazy bean for a {@link PingCommand}.
*
* @param pingCommandArguments The ping command arguments to use
* @param pingServiceFutureStub The gRPC future stub to use
* @param agentMetadata The agent metadata to use
* @return A {@link PingCommand} instance
*/
@Bean
@Lazy
public PingCommand pingCommand(
final PingCommand.PingCommandArguments pingCommandArguments,
final PingServiceGrpc.PingServiceFutureStub pingServiceFutureStub,
final AgentMetadata agentMetadata
) {
return new PingCommand(pingCommandArguments, pingServiceFutureStub, agentMetadata);
}
/**
* Provide a bean of type {@link com.netflix.genie.agent.cli.ResolveJobSpecCommand.ResolveJobSpecCommandArguments}.
*
* @param serverArguments The server arguments to use
* @param jobRequestArguments The job request arguments to use
* @return An instance of {@link com.netflix.genie.agent.cli.ResolveJobSpecCommand.ResolveJobSpecCommandArguments}
*/
@Bean
public ResolveJobSpecCommand.ResolveJobSpecCommandArguments resolveJobSpecCommandArguments(
final ArgumentDelegates.ServerArguments serverArguments,
final ArgumentDelegates.JobRequestArguments jobRequestArguments
) {
return new ResolveJobSpecCommand.ResolveJobSpecCommandArguments(serverArguments, jobRequestArguments);
}
/**
* Provide a lazy bean definition for a {@link ResolveJobSpecCommand}.
*
* @param resolveJobSpecCommandArguments The resolve job spec arguments to use
* @param agentJobService The agent job service to use
* @param jobRequestConverter The job request converter to use
* @return A {@link ResolveJobSpecCommand} instance
*/
@Bean
@Lazy
public ResolveJobSpecCommand resolveJobSpecCommand(
final ResolveJobSpecCommand.ResolveJobSpecCommandArguments resolveJobSpecCommandArguments,
final AgentJobService agentJobService,
final JobRequestConverter jobRequestConverter
) {
return new ResolveJobSpecCommand(resolveJobSpecCommandArguments, agentJobService, jobRequestConverter);
}
/**
* Provide a {@link com.netflix.genie.agent.cli.ArgumentDelegates.ServerArguments}.
*
* @return A {@link ServerArgumentsImpl} instance
*/
@Bean
public ServerArgumentsImpl serverArguments() {
return new ServerArgumentsImpl();
}
/**
* Provide a {@link com.netflix.genie.agent.cli.ArgumentDelegates.CleanupArguments}.
*
* @return A {@link CleanupArgumentsImpl} instance
*/
@Bean
public CleanupArgumentsImpl cleanupArguments() {
return new CleanupArgumentsImpl();
}
/**
* Provide a {@link com.netflix.genie.agent.cli.ArgumentDelegates.RuntimeConfigurationArguments}.
*
* @return A {@link RuntimeConfigurationArgumentsImpl} instance
*/
@Bean
public RuntimeConfigurationArgumentsImpl runtimeConfigurationArguments() {
return new RuntimeConfigurationArgumentsImpl();
}
/**
* Provide an {@link AgentLogManager} implementation that can relocate the agent log file created by log4j2.
*
* @return the log4j2 implementation of {@link AgentLogManager}
*/
@Bean
@ConditionalOnClass(name = {"org.apache.logging.log4j.core.LoggerContext"})
@ConditionalOnMissingBean(AgentLogManager.class)
public AgentLogManagerLog4j2Impl agentLogManagerLog4j2() {
return new AgentLogManagerLog4j2Impl(
(org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)
);
}
}
| 2,892 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ArgumentDelegates.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.agent.cli;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.agent.execution.CleanupStrategy;
import com.netflix.genie.common.internal.dtos.Criterion;
import java.io.File;
import java.util.List;
import java.util.Set;
/**
* Interfaces for command-line delegates (groups of options shared by multiple commands).
*
* @author mprimi
* @since 4.0.0
*/
public interface ArgumentDelegates {
/**
* Delegate for server connection options.
*/
interface ServerArguments {
String getServerHost();
int getServerPort();
long getRpcTimeout();
}
/**
* Delegate for agent dependencies cache.
*/
interface CacheArguments {
File getCacheDirectory();
}
/**
* Delegate for agent job request parameters.
*/
interface JobRequestArguments {
List<String> getCommandArguments();
File getJobDirectoryLocation();
boolean isInteractive();
String getArchiveLocationPrefix();
Integer getTimeout();
String getJobId();
List<Criterion> getClusterCriteria();
Criterion getCommandCriterion();
List<String> getApplicationIds();
String getJobName();
String getUser();
String getEmail();
String getGrouping();
String getGroupingInstance();
String getJobDescription();
Set<String> getJobTags();
String getJobVersion();
JsonNode getJobMetadata();
boolean isJobRequestedViaAPI();
List<String> getJobConfigurations();
List<String> getJobDependencies();
String getJobSetup();
boolean isArchivingDisabled();
}
/**
* Delegate for job folder cleanup options.
*/
interface CleanupArguments {
CleanupStrategy getCleanupStrategy();
}
/**
* Delegate for agent runtime options.
*/
interface RuntimeConfigurationArguments {
boolean isLaunchInJobDirectory();
}
}
| 2,893 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/RuntimeConfigurationArgumentsImpl.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.agent.cli;
import com.beust.jcommander.Parameter;
import lombok.Getter;
/**
* Implementation of RuntimeConfigurationArguments delegate.
*
* @author mprimi
* @since 4.0.0
*/
@Getter
class RuntimeConfigurationArgumentsImpl implements ArgumentDelegates.RuntimeConfigurationArguments {
@Parameter(
names = {"--launchInJobDirectory", "--launch-in-job-directory"},
description = "Whether the job process should be forked within the job directory"
)
private boolean launchInJobDirectory;
}
| 2,894 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/CacheArgumentsImpl.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.agent.cli;
import com.beust.jcommander.Parameter;
import com.google.common.annotations.VisibleForTesting;
import lombok.Getter;
import java.io.File;
/**
* Implementation of CacheArguments delegate.
*
* @author mprimi
* @since 4.0.0
*/
@Getter
class CacheArgumentsImpl implements ArgumentDelegates.CacheArguments {
@VisibleForTesting
static final String DEFAULT_CACHE_PATH = "/tmp/genie/cache";
@Parameter(
names = {"--cacheDirectory", "--cache-directory"},
description = "Location of the Genie Agent dependencies cache",
converter = ArgumentConverters.FileConverter.class,
validateWith = ArgumentValidators.StringValidator.class
)
private File cacheDirectory = new File(DEFAULT_CACHE_PATH);
}
| 2,895 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/JCommanderAutoConfiguration.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.agent.cli;
import com.beust.jcommander.JCommander;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* Auto configuration for configuring {@link JCommander} to parse CLI arguments of the Agent.
*
* @author mprimi
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class JCommanderAutoConfiguration {
/**
* Provide a {@link GlobalAgentArguments} bean.
*
* @return A {@link GlobalAgentArguments} instance
*/
@Bean
public GlobalAgentArguments globalAgentArguments() {
return new GlobalAgentArguments();
}
/**
* Provide a {@link JCommander} bean.
*
* @param globalAgentArguments The global command arguments to use
* @param agentCommandArguments An command argument beans in the environment that should also be used in addition
* to the global command arguments
* @return A {@link JCommander} instance
*/
@Bean
public JCommander jCommander(
final GlobalAgentArguments globalAgentArguments,
final List<AgentCommandArguments> agentCommandArguments
) {
final JCommander.Builder jCommanderBuilder = JCommander.newBuilder()
.addObject(globalAgentArguments)
.acceptUnknownOptions(false);
agentCommandArguments.forEach(jCommanderBuilder::addCommand);
return jCommanderBuilder.build();
}
/**
* Provide a command factory bean.
*
* @param agentCommandArguments Any agent command argument implementations that are in the application context
* @param applicationContext The Spring application context
* @return A {@link CommandFactory} instance
*/
@Bean
public CommandFactory commandFactory(
final List<AgentCommandArguments> agentCommandArguments,
final ApplicationContext applicationContext
) {
return new CommandFactory(agentCommandArguments, applicationContext);
}
/**
* Provide an argument parser bean.
*
* @param jCommander The JCommander instance to use
* @param commandFactory The command factory instance to use
* @param mainCommandArguments The container of main arguments for the command
* @return An {@link ArgumentParser} instance
*/
@Bean
public ArgumentParser argumentParser(
final JCommander jCommander,
final CommandFactory commandFactory,
final MainCommandArguments mainCommandArguments
) {
return new ArgumentParser(jCommander, commandFactory, mainCommandArguments);
}
}
| 2,896 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/ArgumentConverters.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.agent.cli;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.Criterion;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utilities to convert arguments during parsing.
*
* @author mprimi
* @since 4.0.0
*/
final class ArgumentConverters {
/**
* Hide constructor.
*/
private ArgumentConverters() {
}
static final class FileConverter implements IStringConverter<File> {
@Override
public File convert(final String value) {
if (StringUtils.isBlank(value)) {
throw new ParameterException("Invalid file: '" + value + "'");
}
return new File(value);
}
}
static final class URIConverter implements IStringConverter<URI> {
@Override
public URI convert(final String value) {
try {
return new URI(value);
} catch (final URISyntaxException e) {
throw new ParameterException("Invalid URI: " + value, e);
}
}
}
static final class CriterionConverter implements IStringConverter<Criterion> {
// Used to guarantee consistency in all places used (documentation, multiple regex)
private static final String ID_KEY = "ID";
private static final String NAME_KEY = "NAME";
private static final String VERSION_KEY = "VERSION";
private static final String STATUS_KEY = "STATUS";
private static final String TAGS_KEY = "TAGS";
// Used to guarantee consistency between regex compilation and matcher access
private static final String ID_CAPTURE_GROUP = "id";
private static final String NAME_CAPTURE_GROUP = "name";
private static final String VERSION_CAPTURE_GROUP = "version";
private static final String STATUS_CAPTURE_GROUP = "status";
private static final String TAGS_CAPTURE_GROUP = "tags";
private static final String EXAMPLE_CRITERION
= ID_KEY + "=i/" + NAME_KEY + "=n/" + VERSION_KEY + "=v/" + STATUS_KEY + "=s/" + TAGS_KEY + "=t1,t2,t3\n";
private static final String COMPONENT_STRING = StringUtils.join(
Lists.newArrayList(
ID_KEY,
NAME_KEY,
VERSION_KEY,
STATUS_KEY,
TAGS_KEY
),
','
);
static final String CRITERION_SYNTAX_MESSAGE = "CRITERION SYNTAX:\n"
+ "Criterion is parsed as a string in the format:\n"
+ " " + EXAMPLE_CRITERION
+ "Note:\n"
+ " - All components (" + COMPONENT_STRING + ") are optional, but at least one is required\n"
+ " - Order of components is enforced (i.e. NAME cannot appear before ID)\n"
+ " - Values cannot be empty (skip the components altogether if no value is present)\n";
private static final Pattern SINGLE_CRITERION_PATTERN = Pattern.compile(
"^" + ID_KEY + "=(?<" + ID_CAPTURE_GROUP + ">[^/]+)|"
+ NAME_KEY + "=(?<" + NAME_CAPTURE_GROUP + ">[^/]+)|"
+ VERSION_KEY + "=(?<" + VERSION_CAPTURE_GROUP + ">[^/]+)|"
+ STATUS_KEY + "=(?<" + STATUS_CAPTURE_GROUP + ">[^/]+)|"
+ TAGS_KEY + "=(?<" + TAGS_CAPTURE_GROUP + ">[^/]+)$"
);
private static final Pattern MULTI_CRITERION_PATTERN = Pattern.compile(
"^(" + ID_KEY + "=(?<" + ID_CAPTURE_GROUP + ">[^/]+)/)?"
+ "(" + NAME_KEY + "=(?<" + NAME_CAPTURE_GROUP + ">[^/]+))?/?"
+ "(" + VERSION_KEY + "=(?<" + VERSION_CAPTURE_GROUP + ">[^/]+))?/?"
+ "(" + STATUS_KEY + "=(?<" + STATUS_CAPTURE_GROUP + ">[^/]+))?/?"
+ "(" + TAGS_KEY + "=(?<" + TAGS_CAPTURE_GROUP + ">[^/]+))?$"
);
@Override
public Criterion convert(final String value) {
final Criterion.Builder criterionBuilder = new Criterion.Builder();
final Matcher multiComponentMatcher = MULTI_CRITERION_PATTERN.matcher(value);
final Matcher singleComponentMatcher = SINGLE_CRITERION_PATTERN.matcher(value);
final Matcher matchingMatcher;
if (multiComponentMatcher.matches()) {
matchingMatcher = multiComponentMatcher;
} else if (singleComponentMatcher.matches()) {
matchingMatcher = singleComponentMatcher;
} else {
throw new ParameterException("Invalid criterion: " + value);
}
final String id = matchingMatcher.group(ID_CAPTURE_GROUP);
final String name = matchingMatcher.group(NAME_CAPTURE_GROUP);
final String version = matchingMatcher.group(VERSION_CAPTURE_GROUP);
final String status = matchingMatcher.group(STATUS_CAPTURE_GROUP);
final String tags = matchingMatcher.group(TAGS_CAPTURE_GROUP);
final Set<String> splitTags = tags == null ? null : Sets.newHashSet(tags.split(","));
criterionBuilder
.withId(id)
.withName(name)
.withVersion(version)
.withStatus(status)
.withTags(splitTags);
try {
return criterionBuilder.build();
} catch (final IllegalArgumentException e) {
throw new ParameterException("Invalid criterion: " + value, e);
}
}
}
static final class JSONConverter implements IStringConverter<JsonNode> {
@Override
public JsonNode convert(final String value) {
try {
return GenieObjectMapper.getMapper().readTree(value);
} catch (final IOException e) {
throw new ParameterException("Failed to parse JSON argument", e);
}
}
}
static final class UriOrLocalPathConverter implements IStringConverter<String> {
static final String ATTACHMENT_HELP_MESSAGE = "ATTACHMENTS:\n"
+ "Different kinds of job-specific files can be attached to a job.\n"
+ "These are broken down by Genie in 3 categories:\n"
+ " - Configurations: to configure components or tools (e.g. properties files, XML, YAML. ...)\n"
+ " - Dependencies: binaries or archives (e.g., jar, tar.gz, ...)\n"
+ " - Setup: a shell script sourced before executing the job (to set environment, expand archives, ...)\n"
+ "\n"
+ "These job attachments are downloaded to the job folder during setup and they are archived after \n"
+ "execution (conditional on cleanup and archival options).\n"
+ "\n"
+ "Attachments can either be valid URIs or paths to local files, example:\n"
+ " s3://configurations/hadoop/spark/1.6.1/hive-site.xml\n"
+ " http://some-domain.org/some-project/my-config.properties\n"
+ " file:///tmp/myscript.presto\n"
+ " file:/tmp/query.sql\n"
+ " ./myscript.sql (shortcut for file:/${PWD}/myscript.sql)\n";
/**
* {@inheritDoc}
*/
@Override
public String convert(final String value) {
final URI uri;
try {
uri = new URI(value);
} catch (URISyntaxException e) {
throw new ParameterException("Resource URI or path: '" + value + "'", e);
}
// If URI has a scheme, leave it alone and pass it along.
if (uri.getScheme() != null) {
return uri.toASCIIString();
}
// Otherwise try to resolve it as an local file path.
final URI newUri;
try {
newUri = new URI(
"file",
uri.getHost(),
Paths.get(value).toAbsolutePath().normalize().toString(),
uri.getQuery(),
uri.getFragment()
);
} catch (URISyntaxException e) {
throw new ParameterException("Failed to construct uri for local resource: '" + value + "'", e);
}
return newUri.toASCIIString();
}
}
}
| 2,897 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/CommandNames.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.agent.cli;
import com.google.common.annotations.VisibleForTesting;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Constants for command names.
*
* @author mprimi
* @since 4.0.0
*/
final class CommandNames {
static final String HELP = "help";
static final String EXEC = "exec";
static final String INFO = "info";
static final String PING = "ping";
static final String DOWNLOAD = "download";
static final String RESOLVE = "resolve";
static final String HEARTBEAT = "heartbeat";
private static final Set<Field> COMMAND_NAMES_FIELDS;
static {
final Field[] fields = CommandNames.class.getDeclaredFields();
final List<Field> superFields = Arrays.asList(CommandNames.class.getSuperclass().getDeclaredFields());
COMMAND_NAMES_FIELDS = Collections.unmodifiableSet(
Arrays.stream(fields)
.filter(f -> Modifier.isStatic(f.getModifiers()))
.filter(f -> Modifier.isFinal(f.getModifiers()))
.filter(f -> f.getType() == String.class)
.filter(f -> !superFields.contains(f))
.peek(f -> f.setAccessible(true))
.collect(Collectors.toSet())
);
}
private CommandNames() {
}
@VisibleForTesting
static Set<Field> getCommandNamesFields() {
return COMMAND_NAMES_FIELDS;
}
}
| 2,898 |
0 | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent | Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/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.
*
*/
/**
* Commands for Agent and their command-line arguments descriptors.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.cli;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.