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-agent/src/main/java/com/netflix/genie/agent
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/MainCommandArguments.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.collect.Lists; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Container for operand arguments (arguments meant for the underlying command, that the agent should not try to * interpret. * * @author mprimi * @since 4.0.0 */ class MainCommandArguments { private final List<String> arguments = Lists.newArrayList(); private final List<String> argumentsReadonlyView = Collections.unmodifiableList(arguments); List<String> get() { return argumentsReadonlyView; } void set(final String[] operandArguments) { arguments.addAll(Arrays.asList(operandArguments)); } }
2,900
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/JobRequestConverter.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.collect.Lists; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.dtos.AgentConfigRequest; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.ExecutionEnvironment; import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria; import com.netflix.genie.common.internal.dtos.JobMetadata; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.validation.ConstraintViolation; import javax.validation.Validator; import javax.validation.constraints.NotEmpty; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.stream.Collectors; /** * Convert job request arguments delegate into an {@link AgentJobRequest}. * * @author mprimi * @since 4.0.0 */ public class JobRequestConverter { private static final String SINGLE_QUOTE = "'"; private static final String ESCAPED_SINGLE_QUOTE = "'\\''"; private static final String SPACE = " "; private final Validator validator; JobRequestConverter(final Validator validator) { this.validator = validator; } /** * Convert Job request arguments into an AgentJobRequest object. * * @param jobRequestArguments a job request arguments delegate * @return an AgentJobRequest DTO * @throws ConversionException if the resulting AgentJobRequest fails validation */ public AgentJobRequest agentJobRequestArgsToDTO( final ArgumentDelegates.JobRequestArguments jobRequestArguments ) throws ConversionException { final ExecutionResourceCriteria criteria = new ExecutionResourceCriteria( jobRequestArguments.getClusterCriteria(), jobRequestArguments.getCommandCriterion(), jobRequestArguments.getApplicationIds() ); final String jobVersion = jobRequestArguments.getJobVersion(); final JobMetadata.Builder jobMetadataBuilder; if (StringUtils.isBlank(jobVersion)) { jobMetadataBuilder = new JobMetadata.Builder( jobRequestArguments.getJobName(), jobRequestArguments.getUser() ); } else { jobMetadataBuilder = new JobMetadata.Builder( jobRequestArguments.getJobName(), jobRequestArguments.getUser(), jobVersion ); } jobMetadataBuilder .withEmail(jobRequestArguments.getEmail()) .withGrouping(jobRequestArguments.getGrouping()) .withGroupingInstance(jobRequestArguments.getGroupingInstance()) .withMetadata(jobRequestArguments.getJobMetadata()) .withDescription(jobRequestArguments.getJobDescription()) .withTags(jobRequestArguments.getJobTags()) .build(); final AgentConfigRequest requestedAgentConfig = new AgentConfigRequest .Builder() .withRequestedJobDirectoryLocation(jobRequestArguments.getJobDirectoryLocation()) .withTimeoutRequested(jobRequestArguments.getTimeout()) .withInteractive(jobRequestArguments.isInteractive()) .withArchivingDisabled(jobRequestArguments.isArchivingDisabled()) .build(); final List<String> configs = jobRequestArguments.getJobConfigurations(); final List<String> deps = jobRequestArguments.getJobDependencies(); final ExecutionEnvironment jobExecutionResources = new ExecutionEnvironment( configs.isEmpty() ? null : Sets.newHashSet(configs), deps.isEmpty() ? null : Sets.newHashSet(deps), jobRequestArguments.getJobSetup() ); // Convert split, parsed arguments received via command-line back to the same single-string, unparsed // format that comes through the V3 API. final List<String> commandArguments = getV3ArgumentsString(jobRequestArguments.getCommandArguments()); final AgentJobRequest agentJobRequest = new AgentJobRequest.Builder( jobMetadataBuilder.build(), criteria, requestedAgentConfig ) .withCommandArgs(commandArguments) .withRequestedId(jobRequestArguments.getJobId()) .withResources(jobExecutionResources) .build(); final Set<ConstraintViolation<AgentJobRequest>> violations = this.validator.validate(agentJobRequest); if (!violations.isEmpty()) { throw new ConversionException(violations); } return agentJobRequest; } // In order to make all command arguments look the same in a job specification object, transform the // split and unwrapped arguments back into a quoted string. // This allows the downstream agent code to make no special case. // All arguments are coming in as they would from the V3 API. // This means: // - Escape single-quotes // - Wrap each token in single quotes // - Join everything into a single string and send it as a list with just one element private List<String> getV3ArgumentsString(final List<String> commandArguments) { return Lists.newArrayList( commandArguments.stream() .map(s -> s.replaceAll(SINGLE_QUOTE, Matcher.quoteReplacement(ESCAPED_SINGLE_QUOTE))) .map(s -> SINGLE_QUOTE + s + SINGLE_QUOTE) .collect(Collectors.joining(SPACE)) ); } /** * Exception thrown in case of conversion error due to resulting object failing validation. */ public static class ConversionException extends Exception { @Getter private final Set<ConstraintViolation<AgentJobRequest>> violations; ConversionException(@NotEmpty final Set<ConstraintViolation<AgentJobRequest>> violations) { super( String.format( "Job request failed validation: %s (%d total violations)", violations.iterator().next().getMessage(), violations.size() ) ); this.violations = violations; } } }
2,901
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/CommandFactory.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.Maps; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import java.util.List; import java.util.Map; import java.util.Set; /** * Factory to create a (lazy) instance of the requested AgentCommand. * * @author mprimi * @since 4.0.0 */ @Slf4j class CommandFactory { private final List<AgentCommandArguments> agentCommandArgumentsBeans; private final ApplicationContext applicationContext; private final Map<String, Class<? extends AgentCommand>> commandMap = Maps.newHashMap(); CommandFactory( final List<AgentCommandArguments> agentCommandArguments, final ApplicationContext applicationContext ) { this.agentCommandArgumentsBeans = agentCommandArguments; this.applicationContext = applicationContext; agentCommandArguments.forEach( commandArgs -> { Sets.newHashSet(commandArgs.getClass().getAnnotation(Parameters.class).commandNames()).forEach( commandName -> { commandMap.put(commandName, commandArgs.getConsumerClass()); } ); } ); } AgentCommand get(final String requestedCommandName) { final Class<? extends AgentCommand> commandClass = commandMap.get(requestedCommandName); final AgentCommand commandInstance; if (commandClass == null) { log.error("Command not found: {}", requestedCommandName); commandInstance = null; } else { commandInstance = applicationContext.getAutowireCapableBeanFactory().getBean(commandClass); } return commandInstance; } Set<String> getCommandNames() { return commandMap.keySet(); } }
2,902
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/logging/AgentLogManagerLog4j2Impl.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.cli.logging; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.FileAppender; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.atomic.AtomicReference; /** * Utility class that locates and relocates the agent log file. * This implementation is based on log4j2. * * @author mprimi * @since 4.0.0 */ @Slf4j public final class AgentLogManagerLog4j2Impl implements AgentLogManager { /** * This name must match with the appender declaration in log4j2 configuration file. */ private static final String AGENT_LOG_FILE_APPENDER_NAME = "AgentLogFile"; private final AtomicReference<Path> logFilePath = new AtomicReference<>(); /** * Constructor. * * @param context the log4j2 logger context */ public AgentLogManagerLog4j2Impl(final LoggerContext context) { final FileAppender logFileAppender = context.getConfiguration().getAppender(AGENT_LOG_FILE_APPENDER_NAME); final String filename = logFileAppender.getFileName(); if (StringUtils.isBlank(filename)) { throw new IllegalStateException("Could not determine location of agent log file"); } this.logFilePath.set(Paths.get(filename)); ConsoleLog.getLogger().info("Agent (temporarily) logging to: {}", filename); } /** * {@inheritDoc} */ @Override public Path getLogFilePath() { return logFilePath.get(); } /** * {@inheritDoc} */ @Override public void relocateLogFile(final Path destinationPath) throws IOException { final Path sourcePath = this.logFilePath.get(); final Path destinationAbsolutePath = destinationPath.toAbsolutePath(); log.info("Relocating agent log file from: {} to: {}", sourcePath, destinationAbsolutePath); if (!Files.exists(sourcePath)) { throw new IOException("Log file does not exists: " + sourcePath.toString()); } else if (Files.exists(destinationAbsolutePath)) { throw new IOException("Destination already exists: " + destinationAbsolutePath.toString()); } else if (!sourcePath.getFileSystem().provider().equals(destinationAbsolutePath.getFileSystem().provider())) { throw new IOException("Source and destination are not in the same filesystem"); } Files.move(sourcePath, destinationAbsolutePath); this.logFilePath.set(destinationAbsolutePath); ConsoleLog.getLogger().info("Agent log file relocated to: " + destinationAbsolutePath); } }
2,903
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/logging/ConsoleLog.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.logging; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.StreamUtils; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Utilities for interacting with the user terminal/console. * * @author mprimi * @since 4.0.0 */ @Slf4j public final class ConsoleLog { /** * The name of this logger must match the one explicitly whitelisted in the underlying logger configuration * consumed by Spring. It is treated differently than other logs. */ private static final String CONSOLE_LOGGER_NAME = "genie-agent"; private static final Logger CONSOLE_LOGGER = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME); /** * Because the banner is printed in the log file and not visible to the user, manually re-print it * in {@code UserConsole}. Use the existing Spring configuration to control this behavior. */ private static final String BANNER_LOCATION_SPRING_PROPERTY_KEY = SpringApplication.BANNER_LOCATION_PROPERTY; private static final String BANNER_CHARSET_SPRING_PROPERTY_KEY = "spring.banner.charset"; private ConsoleLog() { } /** * Get the LOGGER visible to user on the console. * All other LOGGER messages are logged on file only to avoid interfering with the job console output. * * @return a special Logger whose messages are visible on the user terminal. */ public static Logger getLogger() { return CONSOLE_LOGGER; } /** * Load and print the Spring banner (if one is configured) to UserConsole. * * @param environment the Spring environment */ public static void printBanner(final Environment environment) { try { final String bannerLocation = environment.getProperty(BANNER_LOCATION_SPRING_PROPERTY_KEY); if (StringUtils.isNotBlank(bannerLocation)) { final ResourceLoader resourceLoader = new DefaultResourceLoader(); final Resource resource = resourceLoader.getResource(bannerLocation); if (resource.exists()) { final String banner = StreamUtils.copyToString( resource.getInputStream(), environment.getProperty( BANNER_CHARSET_SPRING_PROPERTY_KEY, Charset.class, StandardCharsets.UTF_8 ) ); ConsoleLog.getLogger().info(banner); } } } catch (final Throwable t) { log.error("Failed to print banner", t); } } }
2,904
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/logging/AgentLogManager.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.cli.logging; import java.io.IOException; import java.nio.file.Path; /** * Utility to locate and relocate agent log file. * * @author mprimi * @since 4.0.0 */ public interface AgentLogManager { /** * Get the current location of the agent log file. * * @return a path string */ Path getLogFilePath(); /** * Attempt to relocate the agent log file inside the job directory. * * @param destinationPath the destination path * @throws IOException if relocation fails */ void relocateLogFile(Path destinationPath) throws IOException; }
2,905
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/cli/logging/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. * */ /** * Logging components. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.cli.logging; import javax.annotation.ParametersAreNonnullByDefault;
2,906
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/properties/HeartBeatServiceProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties for {@link com.netflix.genie.agent.execution.services.AgentHeartBeatService}. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class HeartBeatServiceProperties { /** * Period between heartbeats. */ @DurationMin(seconds = 1) private Duration interval = Duration.ofSeconds(2); /** * Delay before retrying after an error. */ @DurationMin(millis = 50) private Duration errorRetryDelay = Duration.ofSeconds(1); }
2,907
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/properties/JobKillServiceProperties.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.properties; import com.netflix.genie.common.internal.properties.ExponentialBackOffTriggerProperties; import com.netflix.genie.common.internal.util.ExponentialBackOffTrigger; import lombok.Getter; import lombok.Setter; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import java.time.Duration; /** * Properties for {@link com.netflix.genie.agent.execution.services.AgentJobKillService}. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class JobKillServiceProperties { /** * Backoff for checking for a server response. */ @NotNull private ExponentialBackOffTriggerProperties responseCheckBackOff = new ExponentialBackOffTriggerProperties( ExponentialBackOffTrigger.DelayType.FROM_PREVIOUS_EXECUTION_COMPLETION, Duration.ofMillis(500), Duration.ofSeconds(5), 1.2f ); }
2,908
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/properties/AgentProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.time.Duration; /** * Root properties class for agent. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentProperties.PREFIX) @Getter @Setter @Validated public class AgentProperties { /** * Properties prefix. */ public static final String PREFIX = "genie.agent.runtime"; /** * Time allowed for clean shutdown before the agent is considered stuck and shut down abruptly. */ @DurationMin(minutes = 1) private Duration emergencyShutdownDelay = Duration.ofMinutes(5); /** * Maximum time to synchronously wait when trying to force push a new manifest. */ @DurationMin(seconds = 1) private Duration forceManifestRefreshTimeout = Duration.ofSeconds(5); /** * FileStreamService properties. */ @Valid private FileStreamServiceProperties fileStreamService = new FileStreamServiceProperties(); /** * HeartBeatService properties. */ @Valid private HeartBeatServiceProperties heartBeatService = new HeartBeatServiceProperties(); /** * JobKillService properties. */ @Valid private JobKillServiceProperties jobKillService = new JobKillServiceProperties(); /** * JobMonitorService properties. */ @Valid private JobMonitorServiceProperties jobMonitorService = new JobMonitorServiceProperties(); /** * Shutdown properties. */ @Valid private ShutdownProperties shutdown = new ShutdownProperties(); /** * JobSetupService properties. */ @Valid private JobSetupServiceProperties jobSetupService = new JobSetupServiceProperties(); }
2,909
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/properties/JobMonitorServiceProperties.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.properties; import com.netflix.genie.agent.execution.services.JobMonitorService; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.time.Duration; /** * Properties of {@link JobMonitorService}. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class JobMonitorServiceProperties { /** * Interval for checking the job status seen by the server. */ @DurationMin(seconds = 10) private Duration checkInterval = Duration.ofMinutes(1); /** * Maximum number of files in the job directory (files not included in the manifest are exempt). */ @Min(100) private int maxFiles = 64_000; /** * Maximum size of the job directory (files not included in the manifest are exempt). */ @NotNull private DataSize maxTotalSize = DataSize.ofGigabytes(16); /** * Maximum size of any one file in the job directory (files not included in the manifest are exempt). */ @NotNull private DataSize maxFileSize = DataSize.ofGigabytes(8); /** * Whether to monitor the job status seen by the server. */ @NotNull private Boolean checkRemoteJobStatus = true; }
2,910
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/properties/FileStreamServiceProperties.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.properties; import com.netflix.genie.agent.execution.services.AgentFileStreamService; import com.netflix.genie.common.internal.properties.ExponentialBackOffTriggerProperties; import com.netflix.genie.common.internal.util.ExponentialBackOffTrigger; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.time.Duration; /** * Properties for {@link AgentFileStreamService}. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class FileStreamServiceProperties { /** * Exponential backoff for errors in control stream. */ @NotNull private ExponentialBackOffTriggerProperties errorBackOff = new ExponentialBackOffTriggerProperties( ExponentialBackOffTrigger.DelayType.FROM_PREVIOUS_EXECUTION_BEGIN, Duration.ofSeconds(1), Duration.ofSeconds(10), 1.1f ); /** * Enable compression of data. */ private boolean enableCompression = true; /** * Maximum size of file chunk transmitted. */ private DataSize dataChunkMaxSize = DataSize.ofMegabytes(1); /** * Maximum number of files transmitted concurrently. */ @Min(1) private int maxConcurrentStreams = 5; /** * Time allowed to the service to complete ongoing transfers before shutting down. */ @DurationMin(seconds = 1) private Duration drainTimeout = Duration.ofSeconds(15); }
2,911
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/properties/JobSetupServiceProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotEmpty; /** * Properties for {@link com.netflix.genie.agent.execution.services.JobSetupService}. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class JobSetupServiceProperties { /** * The regular expression to filter which environment variable are dumped into {@code env.log} before a job is * launched. This is provided so that sensitive environment variables can be filtered out. * Environment dumping can also be completely disabled by providing an expression that matches nothing (such as * {@code '^$'}. The value of this property is injected into a bash script between single quotes. */ @NotEmpty private String environmentDumpFilterExpression = ".*"; /** * Switch to invert the matching of {@code environmentDumpFilterExpression}. * If {@code false} (default) environment entries matching the expression are dumped, and the rest are filtered out. * If {@code true} environment entries NOT matching the expression are dumped, the rest are filtered out. */ private boolean environmentDumpFilterInverted; }
2,912
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/properties/ShutdownProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties to configure the Agent shutdown process. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public class ShutdownProperties { /** * Time allowed to the job state machine to complete after the job has been killed. */ @DurationMin(seconds = 1) private Duration executionCompletionLeeway = Duration.ofSeconds(60); /** * Time allowed to internal task executors to complete running tasks before shutting them down. */ @DurationMin(seconds = 1) private Duration internalExecutorsLeeway = Duration.ofSeconds(30); /** * Time allowed to internal task schedulers to complete running tasks before shutting them down. */ @DurationMin(seconds = 1) private Duration internalSchedulersLeeway = Duration.ofSeconds(30); /** * Time allowed to Spring task executor to complete running tasks before shutting them down. */ @DurationMin(seconds = 1) private Duration systemExecutorLeeway = Duration.ofSeconds(60); /** * Time allowed to Spring task scheduler to complete running tasks before shutting them down. */ @DurationMin(seconds = 1) private Duration systemSchedulerLeeway = Duration.ofSeconds(60); }
2,913
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/properties/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. * */ /** * Agent properties. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.properties; import javax.annotation.ParametersAreNonnullByDefault;
2,914
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/execution/ExecutionAutoConfiguration.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; import brave.Tracer; 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.JobExecutionStateMachineImpl; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.agent.execution.statemachine.listeners.ConsoleLogListener; import com.netflix.genie.agent.execution.statemachine.listeners.JobExecutionListener; import com.netflix.genie.agent.execution.statemachine.listeners.LoggingListener; import com.netflix.genie.agent.execution.statemachine.listeners.TracingListener; 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.BraveTracingComponents; 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.Lazy; import org.springframework.core.annotation.Order; import javax.validation.constraints.NotEmpty; import java.util.Collection; import java.util.List; /** * Spring auto configuration for beans required for job execution. * * @author tgianos * @since 4.0.0 */ @Configuration @EnableConfigurationProperties( { AgentProperties.class } ) public class ExecutionAutoConfiguration { /** * Provide a lazy {@link LoggingListener} bean. * * @return A {@link LoggingListener} instance */ @Bean @Lazy @ConditionalOnMissingBean(LoggingListener.class) public LoggingListener loggingListener() { return new LoggingListener(); } /** * Provide a lazy {@link ConsoleLogListener} bean. * * @return A {@link ConsoleLogListener} instance */ @Bean @Lazy @ConditionalOnMissingBean(ConsoleLogListener.class) public ConsoleLogListener consoleLogLoggingListener() { return new ConsoleLogListener(); } /** * Provide an instance of {@link TracingListener} which will add metadata to spans based on events through the * execution state machine. * * @param tracer The {@link Tracer} to use to get active spans * @return A {@link TracingListener} instance */ @Bean @Lazy @ConditionalOnMissingBean(TracingListener.class) public TracingListener jobExecutionTracingListener(final Tracer tracer) { return new TracingListener(tracer); } /** * Provide the {@link ExecutionContext} bean. * * @return A {@link ExecutionContext}. */ @Bean @Lazy @ConditionalOnMissingBean ExecutionContext executionContext(final AgentProperties agentProperties) { return new ExecutionContext(agentProperties); } /** * Provide the default job execution state machine instance which will handle the entire lifecycle of the job * this agent instance is responsible for. * * @param executionStages The available stages * @param executionContext The context object for sharing state * @param listeners Any listeners that may be in the system to react to events * @param jobProcessManager The process manager for the actual client job * @return a {@link JobExecutionStateMachineImpl} instance */ @Bean @Lazy JobExecutionStateMachineImpl jobExecutionStateMachine( @NotEmpty final List<ExecutionStage> executionStages, final ExecutionContext executionContext, final Collection<JobExecutionListener> listeners, final JobProcessManager jobProcessManager ) { return new JobExecutionStateMachineImpl(executionStages, executionContext, listeners, jobProcessManager); } /** * Create a {@link InitializeAgentStage} bean if one is not already defined. * * @param agentMetadata the agent metadata */ @Bean @Lazy @Order(10) @ConditionalOnMissingBean(InitializeAgentStage.class) InitializeAgentStage initializeAgentStage(final AgentMetadata agentMetadata) { return new InitializeAgentStage(agentMetadata); } /** * Create a {@link HandshakeStage} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(20) @ConditionalOnMissingBean(HandshakeStage.class) HandshakeStage handshakeStage(final AgentJobService agentJobService) { return new HandshakeStage(agentJobService); } /** * Create a {@link ConfigureAgentStage} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(25) @ConditionalOnMissingBean(ConfigureAgentStage.class) ConfigureAgentStage configureAgentStage( final AgentJobService agentJobService ) { return new ConfigureAgentStage( agentJobService ); } /** * Create a {@link ConfigureExecutionStage} bean if one is not already defined. * * @param jobRequestConverter the job request converter * @param jobRequestArguments the job request arguments group * @param runtimeConfigurationArguments the runtime configuration arguments group * @param cleanupArguments the cleanup arguments group */ @Bean @Lazy @Order(30) @ConditionalOnMissingBean(ConfigureExecutionStage.class) ConfigureExecutionStage configureExecutionStage( final JobRequestConverter jobRequestConverter, final ArgumentDelegates.JobRequestArguments jobRequestArguments, final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments, final ArgumentDelegates.CleanupArguments cleanupArguments ) { return new ConfigureExecutionStage( jobRequestConverter, jobRequestArguments, runtimeConfigurationArguments, cleanupArguments ); } /** * Create a {@link ReserveJobIdStage} bean if one is not already defined. * * @param agentJobService the agent job service * @param tracingComponents The {@link BraveTracingComponents} instance */ @Bean @Lazy @Order(40) @ConditionalOnMissingBean(ReserveJobIdStage.class) ReserveJobIdStage reserveJobIdStage( final AgentJobService agentJobService, final BraveTracingComponents tracingComponents ) { return new ReserveJobIdStage(agentJobService, tracingComponents); } /** * Create a {@link ObtainJobSpecificationStage} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(50) @ConditionalOnMissingBean(ObtainJobSpecificationStage.class) ObtainJobSpecificationStage obtainJobSpecificationStage(final AgentJobService agentJobService) { return new ObtainJobSpecificationStage(agentJobService); } /** * Create a {@link CreateJobDirectoryStage} bean if one is not already defined. * * @param jobSetupService the job setup service */ @Bean @Lazy @Order(60) @ConditionalOnMissingBean(CreateJobDirectoryStage.class) CreateJobDirectoryStage createJobDirectoryStage(final JobSetupService jobSetupService) { return new CreateJobDirectoryStage(jobSetupService); } /** * Create a {@link RelocateLogFileStage} bean if one is not already defined. * * @param agentLogManager the agent log manager */ @Bean @Lazy @Order(70) @ConditionalOnMissingBean(RelocateLogFileStage.class) RelocateLogFileStage relocateLogFileStage(final AgentLogManager agentLogManager) { return new RelocateLogFileStage(agentLogManager); } /** * Create a {@link ClaimJobStage} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(80) @ConditionalOnMissingBean(ClaimJobStage.class) ClaimJobStage claimJobStage(final AgentJobService agentJobService) { return new ClaimJobStage(agentJobService); } /** * Create a {@link StartHeartbeatServiceStage} bean if one is not already defined. * * @param heartbeatService the heartbeat service */ @Bean @Lazy @Order(90) @ConditionalOnMissingBean(StartHeartbeatServiceStage.class) StartHeartbeatServiceStage startHeartbeatServiceStage(final AgentHeartBeatService heartbeatService) { return new StartHeartbeatServiceStage(heartbeatService); } /** * Create a {@link StartKillServiceStage} bean if one is not already defined. * * @param killService the kill service */ @Bean @Lazy @Order(100) @ConditionalOnMissingBean(StartKillServiceStage.class) StartKillServiceStage startKillServiceStage(final AgentJobKillService killService) { return new StartKillServiceStage(killService); } /** * Create a {@link StartFileServiceStage} bean if one is not already defined. * * @param agentFileStreamService the agent file stream service */ @Bean @Lazy @Order(110) @ConditionalOnMissingBean(StartFileServiceStage.class) StartFileServiceStage startFileServiceStage(final AgentFileStreamService agentFileStreamService) { return new StartFileServiceStage(agentFileStreamService); } /** * Create a {@link SetJobStatusInit} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(120) @ConditionalOnMissingBean(SetJobStatusInit.class) SetJobStatusInit setJobStatusInit(final AgentJobService agentJobService) { return new SetJobStatusInit(agentJobService); } /** * Create a {@link CreateJobScriptStage} bean if one is not already defined. * * @param jobSetupService the job setup service */ @Bean @Lazy @Order(130) @ConditionalOnMissingBean(CreateJobScriptStage.class) CreateJobScriptStage createJobScriptStage(final JobSetupService jobSetupService) { return new CreateJobScriptStage(jobSetupService); } /** * Create a {@link DownloadDependenciesStage} bean if one is not already defined. * * @param jobSetupService the job setup service */ @Bean @Lazy @Order(140) @ConditionalOnMissingBean(DownloadDependenciesStage.class) DownloadDependenciesStage downloadDependenciesStage(final JobSetupService jobSetupService) { return new DownloadDependenciesStage(jobSetupService); } /** * Create a {@link RefreshManifestStage} bean if one is not already defined. * * @param agentFileStreamService the agent file stream service */ @Bean @Lazy @Order(145) @ConditionalOnMissingBean(name = "postSetupRefreshManifestStage") RefreshManifestStage postSetupRefreshManifestStage(final AgentFileStreamService agentFileStreamService) { return new RefreshManifestStage(agentFileStreamService, States.POST_SETUP_MANIFEST_REFRESH); } /** * Create a {@link LaunchJobStage} bean if one is not already defined. * * @param jobProcessManager the job process manager */ @Bean @Lazy @Order(150) @ConditionalOnMissingBean(LaunchJobStage.class) LaunchJobStage launchJobStage(final JobProcessManager jobProcessManager) { return new LaunchJobStage(jobProcessManager); } /** * Create a {@link RefreshManifestStage} bean if one is not already defined. * * @param agentFileStreamService the agent file stream service */ @Bean @Lazy @Order(155) @ConditionalOnMissingBean(name = "postLaunchRefreshManifestStage") RefreshManifestStage postLaunchRefreshManifestStage(final AgentFileStreamService agentFileStreamService) { return new RefreshManifestStage(agentFileStreamService, States.POST_LAUNCH_MANIFEST_REFRESH); } /** * Create a {@link SetJobStatusRunning} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(160) @ConditionalOnMissingBean(SetJobStatusRunning.class) SetJobStatusRunning setJobStatusRunning(final AgentJobService agentJobService) { return new SetJobStatusRunning(agentJobService); } /** * Create a {@link WaitJobCompletionStage} bean if one is not already defined. * * @param jobProcessManager the job process manager * @param jobMonitorService the job monitor service */ @Bean @Lazy @Order(170) @ConditionalOnMissingBean(WaitJobCompletionStage.class) WaitJobCompletionStage waitJobCompletionStage( final JobProcessManager jobProcessManager, final JobMonitorService jobMonitorService ) { return new WaitJobCompletionStage(jobProcessManager, jobMonitorService); } /** * Create a {@link RefreshManifestStage} bean if one is not already defined. * * @param agentFileStreamService the agent file stream service */ @Bean @Lazy @Order(175) @ConditionalOnMissingBean(name = "postExecutionRefreshManifestStage") RefreshManifestStage postExecutionRefreshManifestStage(final AgentFileStreamService agentFileStreamService) { return new RefreshManifestStage(agentFileStreamService, States.POST_EXECUTION_MANIFEST_REFRESH); } /** * Create a {@link DetermineJobFinalStatusStage} bean if one is not already defined. */ @Bean @Lazy @Order(180) @ConditionalOnMissingBean(DetermineJobFinalStatusStage.class) DetermineJobFinalStatusStage determineJobFinalStatusStage() { return new DetermineJobFinalStatusStage(); } /** * Create a {@link SetJobStatusFinal} bean if one is not already defined. * * @param agentJobService the agent job service */ @Bean @Lazy @Order(190) @ConditionalOnMissingBean(SetJobStatusFinal.class) SetJobStatusFinal setJobStatusFinal(final AgentJobService agentJobService) { return new SetJobStatusFinal(agentJobService); } /** * Create a {@link StopKillServiceStage} bean if one is not already defined. * * @param killService the kill service */ @Bean @Lazy @Order(200) @ConditionalOnMissingBean(StopKillServiceStage.class) StopKillServiceStage stopKillServiceStage(final AgentJobKillService killService) { return new StopKillServiceStage(killService); } /** * Create a {@link LogExecutionErrorsStage} bean if one is not already defined. */ @Bean @Lazy @Order(210) @ConditionalOnMissingBean(LogExecutionErrorsStage.class) LogExecutionErrorsStage logExecutionErrorsStage() { return new LogExecutionErrorsStage(); } /** * Create a {@link ArchiveJobOutputsStage} bean if one is not already defined. * * @param jobArchiveService the job archive service * @param agentJobService the agent job service */ @Bean @Lazy @Order(220) @ConditionalOnMissingBean(ArchiveJobOutputsStage.class) ArchiveJobOutputsStage archiveJobOutputsStage( final JobArchiveService jobArchiveService, final AgentJobService agentJobService ) { return new ArchiveJobOutputsStage(jobArchiveService, agentJobService); } /** * Create a {@link StopHeartbeatServiceStage} bean if one is not already defined. * * @param heartbeatService the heartbeat service */ @Bean @Lazy @Order(230) @ConditionalOnMissingBean(StopHeartbeatServiceStage.class) StopHeartbeatServiceStage stopHeartbeatServiceStage(final AgentHeartBeatService heartbeatService) { return new StopHeartbeatServiceStage(heartbeatService); } /** * Create a {@link StopFileServiceStage} bean if one is not already defined. * * @param agentFileStreamService the agent file stream service */ @Bean @Lazy @Order(240) @ConditionalOnMissingBean(StopFileServiceStage.class) StopFileServiceStage stopFileServiceStage(final AgentFileStreamService agentFileStreamService) { return new StopFileServiceStage(agentFileStreamService); } /** * Create a {@link CleanupJobDirectoryStage} bean if one is not already defined. * * @param jobSetupService the job setup service */ @Bean @Lazy @Order(250) @ConditionalOnMissingBean(CleanupJobDirectoryStage.class) CleanupJobDirectoryStage cleanupJobDirectoryStage(final JobSetupService jobSetupService) { return new CleanupJobDirectoryStage(jobSetupService); } /** * Create a {@link ShutdownStage} bean if one is not already defined. */ @Bean @Lazy @Order(260) @ConditionalOnMissingBean(ShutdownStage.class) ShutdownStage shutdownStage() { return new ShutdownStage(); } }
2,915
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/execution/CleanupStrategy.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; /** * Enum to describe the different kind of post-execution cleanup of the job directory. * * @author mprimi * @since 4.0.0 */ public enum CleanupStrategy { /** * Skip cleanup completely. */ NO_CLEANUP, /** * Wipe the entire job directory. */ FULL_CLEANUP, /** * Clean the contents of dependencies sub-directories, leave the rest. */ DEPENDENCIES_CLEANUP; /** * Section of the help message explaining the cleanup strategy. */ public static final String CLEANUP_HELP_MESSAGE = "JOB DIRECTORY CLEANUP:\n" + "The default cleanup behavior is to delete downloaded dependencies after job execution completed\n" + "(whether or not it was successful). A different strategy (no cleanup, full cleanup, ...) can be\n" + "selected via command-line flags"; /** * The default strategy. */ public static final CleanupStrategy DEFAULT_STRATEGY = DEPENDENCIES_CLEANUP; }
2,916
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/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 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution; import javax.annotation.ParametersAreNonnullByDefault;
2,917
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/JobExecutionStateMachineImpl.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.statemachine; import com.google.common.collect.ImmutableSet; import com.netflix.genie.agent.execution.process.JobProcessManager; import com.netflix.genie.agent.execution.services.KillService; import com.netflix.genie.agent.execution.statemachine.listeners.JobExecutionListener; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import java.util.Collection; import java.util.List; /** * Implementation of the job execution state machine. * * @author mprimi * @since 4.0.0 */ @Slf4j public class JobExecutionStateMachineImpl implements JobExecutionStateMachine { private static final long RETRY_DELAY = 250; @Getter private final List<ExecutionStage> executionStages; @Getter private final ExecutionContext executionContext; private final JobExecutionListener listener; private final JobProcessManager jobProcessManager; /** * Constructor. * * @param executionStages the (ordered) list of execution stages * @param executionContext the execution context passed across stages during execution * @param listeners the list of listeners * @param jobProcessManager the job process manager */ public JobExecutionStateMachineImpl( final List<ExecutionStage> executionStages, final ExecutionContext executionContext, final Collection<JobExecutionListener> listeners, final JobProcessManager jobProcessManager ) { this.executionStages = executionStages; this.executionContext = executionContext; this.listener = new CompositeListener(ImmutableSet.copyOf(listeners)); this.jobProcessManager = jobProcessManager; } /** * {@inheritDoc} */ @Override public void run() { if (!this.executionContext.getStarted().compareAndSet(false, true)) { throw new IllegalStateException("Called run on an already started state machine"); } this.executionContext.setStateMachine(this); this.listener.stateMachineStarted(); for (final ExecutionStage executionStage : this.executionStages) { final States state = executionStage.getState(); log.debug("Execution stage: {} for state {} ({}, {}, {} retries)", executionStage.getClass().getSimpleName(), state.name(), state.isCriticalState() ? "CRITICAL" : "NON-CRITICAL", state.isSkippedDuringAbortedExecution() ? "SKIP" : "NON-SKIP", state.getTransitionRetries() ); this.listener.stateEntered(state); this.executeStageAction(state, executionStage); this.listener.stateExited(state); } this.listener.stateEntered(States.DONE); this.listener.stateMachineStopped(); } @Override public void kill(final KillService.KillSource killSource) { log.info("Shutting down job execution (kill event source: {}", killSource); if (killSource == KillService.KillSource.REMOTE_STATUS_MONITOR) { this.executionContext.setSkipFinalStatusUpdate(true); } this.executionContext.setJobKilled(true); this.jobProcessManager.kill(killSource); } private void executeStageAction(final States state, final ExecutionStage executionStage) { // Reset retries backoff long currentRetryDelay = 0; int retriesLeft = state.getTransitionRetries(); while (true) { // If execution is a aborted and this is a skip state, stop. if (this.executionContext.isExecutionAborted() && state.isSkippedDuringAbortedExecution()) { this.listener.stateSkipped(state); log.debug("Skipping stage {} due to aborted execution", state); return; } // Attempt the stage action this.listener.beforeStateActionAttempt(state); Exception exception = null; try { executionStage.attemptStageAction(executionContext); } catch (Exception e) { log.debug("Exception in state: " + state, e); exception = e; } this.listener.afterStateActionAttempt(state, exception); // No exception, stop if (exception == null) { log.debug("Stage execution successful"); return; } // Record the raw exception this.executionContext.recordTransitionException(state, exception); FatalJobExecutionException fatalJobExecutionException = null; if (exception instanceof RetryableJobExecutionException && retriesLeft > 0) { // Try action again after a delay retriesLeft--; currentRetryDelay += RETRY_DELAY; } else if (exception instanceof RetryableJobExecutionException) { // No retries left, save as fatal exception fatalJobExecutionException = new FatalJobExecutionException( state, "No more attempts left for retryable error in state " + state, exception ); this.executionContext.recordTransitionException(state, fatalJobExecutionException); } else if (exception instanceof FatalJobExecutionException) { // Save fatal exception fatalJobExecutionException = (FatalJobExecutionException) exception; } else { // Create fatal exception out of unexpected exception fatalJobExecutionException = new FatalJobExecutionException( state, "Unhandled exception" + exception.getMessage(), exception ); this.executionContext.recordTransitionException(state, fatalJobExecutionException); } if (fatalJobExecutionException != null) { if (state.isCriticalState() && !executionContext.isExecutionAborted()) { // Fatal exception in critical stage aborts execution, unless it's already aborted this.executionContext.setExecutionAbortedFatalException(fatalJobExecutionException); this.listener.executionAborted(state, fatalJobExecutionException); } this.listener.fatalException(state, fatalJobExecutionException); // Fatal exception always stops further attempts return; } // Calculate delay before next retry // Delay the next attempt log.debug("Action will be attempted again in {}ms", currentRetryDelay); this.listener.delayedStateActionRetry(state, currentRetryDelay); try { Thread.sleep(currentRetryDelay); } catch (InterruptedException ex) { log.info("Interrupted during delayed retry"); } } } private static final class CompositeListener implements JobExecutionListener { private final Collection<JobExecutionListener> listeners; private CompositeListener(final Collection<JobExecutionListener> listeners) { this.listeners = listeners; } @Override public void stateEntered(final States state) { listeners.forEach(listener -> listener.stateEntered(state)); } @Override public void stateExited(final States state) { listeners.forEach(listener -> listener.stateExited(state)); } @Override public void beforeStateActionAttempt(final States state) { listeners.forEach(listener -> listener.beforeStateActionAttempt(state)); } @Override public void afterStateActionAttempt(final States state, @Nullable final Exception exception) { listeners.forEach(listener -> listener.afterStateActionAttempt(state, exception)); } @Override public void stateMachineStarted() { listeners.forEach(JobExecutionListener::stateMachineStarted); } @Override public void stateMachineStopped() { listeners.forEach(JobExecutionListener::stateMachineStopped); } @Override public void stateSkipped(final States state) { listeners.forEach(listener -> listener.stateSkipped(state)); } @Override public void fatalException(final States state, final FatalJobExecutionException exception) { listeners.forEach(listener -> listener.fatalException(state, exception)); } @Override public void executionAborted(final States state, final FatalJobExecutionException exception) { listeners.forEach(listener -> listener.executionAborted(state, exception)); } @Override public void delayedStateActionRetry(final States state, final long retryDelay) { listeners.forEach(listener -> listener.delayedStateActionRetry(state, retryDelay)); } } }
2,918
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/ExecutionStage.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.statemachine; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Abstract base class for Genie Agent stage of execution. * The execution state machine is constructed as a sequence of stages that each job goes through (e.g., claim job, * setup job directory, launch job, etc). * Each stage consists of a state machine state and an action that needs to be completed in order to successfully * transition to the next stage. This action is implemented in concrete subclasses. * <p> * Stages are categorized along these dimensions: * - Critical vs. optional: if a critical stage fails, execution is aborted and the job is considered failed. * Optional stages can produce fatal error without compromising the overall execution (example: job file archival). * - Skippable vs. non-skippable: skippable stages are skipped if a job was aborted due to fatal error or kill. * * @author mprimi * @since 4.0.0 */ @Slf4j @Getter public abstract class ExecutionStage { private final States state; /** * Constructor. * * @param state the state machine state associated with this stage */ protected ExecutionStage(final States state) { this.state = state; } protected FatalJobExecutionException createFatalException(final String message, final Throwable cause) { return new FatalJobExecutionException(this.getState(), message, cause); } protected FatalJobExecutionException createFatalException(final Throwable cause) { return this.createFatalException( "Fatal error in state " + this.getState().name() + ": " + cause.getMessage(), cause ); } protected RetryableJobExecutionException createRetryableException(final Throwable cause) { throw new RetryableJobExecutionException( "Retryable error in state " + this.getState().name() + ": " + cause.getMessage(), cause ); } /** * Action associated with this stage. May be skipped if execution is aborted and the stage is defined as skippable, * or if the action was attempted and threw a fatal exception, or if the retriable attempts were exhausted. * * @param executionContext the execution context, carrying execution state across actions * @throws RetryableJobExecutionException in case of error that deserves another attempt (for example, temporary * failure to connect to the server * @throws FatalJobExecutionException in case of error that should not be retried (for example, trying to use a * job id that was already in use) */ protected abstract void attemptStageAction( ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException; }
2,919
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/JobExecutionStateMachine.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.statemachine; import com.netflix.genie.agent.execution.services.KillService; import java.util.List; /** * Interface JobExecutionStateMachine hides the actual state machine details. * * @author mprimi * @since 4.0.0 */ public interface JobExecutionStateMachine { /** * Runs the state machine until completion. */ void run(); /** * Get the list of execution stages. * * @return an immutable ordered list of execution stages */ List<ExecutionStage> getExecutionStages(); /** * Get the execution context. * This is meant for post-execution read-only access. * * @return the execution context used by the state machine. */ ExecutionContext getExecutionContext(); /** * Abort execution, if necessary by stopping the running job process. * The state machine still runs to termination, but may skip steps as appropriate. * * @param killSource a representation of who/what requested the kill */ void kill(KillService.KillSource killSource); }
2,920
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/ExecutionContext.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.statemachine; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.netflix.genie.agent.execution.CleanupStrategy; import com.netflix.genie.agent.execution.process.JobProcessResult; import com.netflix.genie.agent.execution.statemachine.stages.ClaimJobStage; 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.InitializeAgentStage; import com.netflix.genie.agent.execution.statemachine.stages.LaunchJobStage; import com.netflix.genie.agent.execution.statemachine.stages.ObtainJobSpecificationStage; import com.netflix.genie.agent.execution.statemachine.stages.ReserveJobIdStage; import com.netflix.genie.agent.execution.statemachine.stages.WaitJobCompletionStage; import com.netflix.genie.agent.properties.AgentProperties; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import javax.validation.constraints.NotNull; import java.io.File; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Stores runtime information that is passed from one state to the next. * Example, exceptions encountered during execution, whether a job process was launched or not, the local job directory, * if one was created, etc. * * @author mprimi * @since 4.0.0 */ @Getter(onMethod_ = {@Synchronized}) @Setter(onMethod_ = {@Synchronized}) public class ExecutionContext { /** * Whether the state machine associated to this execution context has already been started. */ private final AtomicBoolean started = new AtomicBoolean(false); /** * List of all exception thrown by state transitions. */ private final List<TransitionExceptionRecord> transitionExceptionRecords = Lists.newArrayList(); /** * Agent properties. */ private final AgentProperties agentProperties; /** * Agent client metadata sent to the server in certain requests. * Present if {@link InitializeAgentStage} ran successfully. */ private AgentClientMetadata agentClientMetadata; /** * Job id requested by the user. * Present if the the jobId option is present on the command-line and the * {@link ConfigureExecutionStage} ran successfully. * May be blank/null if the the agent is not executing an "API" job. */ private String requestedJobId; /** * Job id reserved for this job. * Present and guaranteed not to be blank if the {@link ReserveJobIdStage} ran successfully. */ private String reservedJobId; /** * Job id claimed by this agent for execution. * Present and guaranteed not to be blank if the {@link ClaimJobStage} ran successfully. */ private String claimedJobId; /** * The job status as seen by the server. * Present if {@link ReserveJobIdStage} ran successfully, modified as execution progresses. */ private JobStatus currentJobStatus = JobStatus.INVALID; /** * The job request constructed from command-line arguments. * Present if {@link ConfigureExecutionStage} ran successfully and if the agent is excuting a new job specified via * command-line arguments (as opposed to claiming a pre-resolved job submitted via API). */ private AgentJobRequest agentJobRequest; /** * True if the agent is executing a job that was submitted via API and is pre-resolved on the server. * False if the agent is creating and executing a new job based on command-line arguments. */ private boolean isPreResolved; /** * The job specification obtained from the server. * Present if {@link ObtainJobSpecificationStage} ran successfully. */ private JobSpecification jobSpecification; /** * The local job directory created to execute a job. * Present if {@link CreateJobDirectoryStage} ran successfully. */ private File jobDirectory; /** * The local job script file. * Present if {@link CreateJobScriptStage} ran successfully. */ private File jobScript; /** * True if the job process should be launched from within the job directory. * False if the job should be launched from the current directory. */ private boolean isRunFromJobDirectory; /** * True if the job process was launched (in {@link LaunchJobStage}), false if execution was aborted before reaching * that stage. */ private boolean jobLaunched; /** * The result (based on exit code) of launching the job process. * Present if the job was launched and * {@link WaitJobCompletionStage} ran successfully. */ private JobProcessResult jobProcessResult; /** * True if at any point a request was received to kill the job. */ private boolean isJobKilled; /** * Current tally of attempts left for a given state transition. * Reset to 1 (or bigger) when each new state is reached. * Can be zeroed if an attempt results in a fatal error. */ private int attemptsLeft; /** * An exception that caused the execution to be aborted. * Present if a critical stage encountered a fatal exception (either thrown by the transition, or due to exhaustion * of attempts, or due to unhandled exception. */ private FatalJobExecutionException executionAbortedFatalException; /** * The kind of cleanup to perform post-execution. * Present if {@link ConfigureExecutionStage} ran successfully. */ @NotNull private CleanupStrategy cleanupStrategy = CleanupStrategy.DEFAULT_STRATEGY; /** * The next job status that should be send to the server. */ @NotNull private JobStatus nextJobStatus = JobStatus.INVALID; /** * The message to attach to when the job status is updated. */ private String nextJobStatusMessage; /** * The state machine that executes the job. */ private JobExecutionStateMachine stateMachine; /** * Whether to skip sending the final job status to the server. * Used when the job is shut down because the remote status was already set to FAILED by the leader. */ private boolean skipFinalStatusUpdate; /** * Constructor. * * @param agentProperties The agent properties */ public ExecutionContext(final AgentProperties agentProperties) { this.agentProperties = agentProperties; } /** * Record an execution exception, even if it is retryable. * * @param state the state in which the exception occurred * @param recordedException the exception */ public void recordTransitionException(final States state, final Exception recordedException) { this.transitionExceptionRecords.add( new TransitionExceptionRecord(state, recordedException) ); } /** * Get the list of execution exception encountered (fatal and non-fatal). * * @return a list of exception records */ public List<TransitionExceptionRecord> getTransitionExceptionRecords() { return ImmutableList.copyOf(this.transitionExceptionRecords); } /** * Convenience method to determine whether the execution is aborted (as a result of a fatal error in a critical * state or due to a kill request). * * @return whether the execution is aborted. */ public boolean isExecutionAborted() { return this.executionAbortedFatalException != null || this.isJobKilled; } /** * Data object that contains an exception and the state in which it was encountered. */ @AllArgsConstructor @Getter public static class TransitionExceptionRecord { private final States state; private final Exception recordedException; } }
2,921
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/States.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.statemachine; import com.netflix.genie.common.dto.JobStatusMessages; import lombok.Getter; import javax.validation.constraints.Min; /** * Execution state machine states. * * @author mprimi * @since 4.0.0 */ @Getter public enum States { /** * Initial state, NOOP, before execution to start. */ READY(0, false), /** * Initialize the agent. */ INITIALIZE_AGENT(0, true, JobStatusMessages.FAILED_AGENT_STARTUP), /** * Perform agent/server handshake. */ HANDSHAKE(3, true, JobStatusMessages.FAILED_AGENT_SERVER_HANDSHAKE), /** * Configure the agent based on server-provided values. */ CONFIGURE_AGENT(1, true), /** * Configure the execution based on command-line arguments. */ CONFIGURE_EXECUTION(0, true, JobStatusMessages.FAILED_AGENT_CONFIGURATION), /** * Reserve the job id. */ RESERVE_JOB_ID(3, true, JobStatusMessages.FAILED_TO_RESERVE_JOB_ID), /** * Obtain the job specification. */ OBTAIN_JOB_SPECIFICATION(3, true, JobStatusMessages.FAILED_TO_OBTAIN_JOB_SPECIFICATION), /** * Claim the job for execution. */ CLAIM_JOB(3, true, JobStatusMessages.FAILED_TO_CLAIM_JOB), /** * Start heartbeat service. */ START_HEARTBEAT_SERVICE(0, true, JobStatusMessages.FAILED_TO_START_SERVICE), /** * Start kill service. */ START_KILL_SERVICE(0, true, JobStatusMessages.FAILED_TO_START_SERVICE), /** * Create the job directory. */ CREATE_JOB_DIRECTORY(0, true, JobStatusMessages.FAILED_TO_CREATE_JOB_DIRECTORY), /** * Relocate the agent log inside the job directory. */ RELOCATE_LOG(0, true), /** * Start file stream service. */ START_FILE_STREAM_SERVICE(0, true, JobStatusMessages.FAILED_TO_START_SERVICE), /** * Update the job status to INIT. */ SET_STATUS_INIT(3, true, JobStatusMessages.FAILED_TO_UPDATE_STATUS), /** * Create the job script (a.k.a. 'run' file). */ CREATE_JOB_SCRIPT(0, true, JobStatusMessages.FAILED_TO_CREATE_JOB_SCRIPT), /** * Download dependencies. */ DOWNLOAD_DEPENDENCIES(0, true, JobStatusMessages.FAILED_TO_DOWNLOAD_DEPENDENCIES), /** * Launch the job process. */ LAUNCH_JOB(0, true, JobStatusMessages.FAILED_TO_LAUNCH_JOB), /** * Update the job status to RUNNING. */ SET_STATUS_RUNNING(3, true, JobStatusMessages.FAILED_TO_UPDATE_STATUS), /** * Wait for job completion. */ WAIT_JOB_COMPLETION(0, false, JobStatusMessages.FAILED_TO_WAIT_FOR_JOB_COMPLETION), /** * Final update to the job status. */ SET_STATUS_FINAL(3, false, JobStatusMessages.FAILED_TO_UPDATE_STATUS), /** * Stop the kill service. */ STOP_KILL_SERVICE(0, false), /** * Dump execution error summary in the log. */ LOG_EXECUTION_ERRORS(0, false), /** * Archive job outputs and logs. */ ARCHIVE(0, false), /** * Stop the heartbeat service. */ STOP_HEARTBEAT_SERVICE(0, false), /** * Stop the file stream service. */ STOP_FILES_STREAM_SERVICE(0, false), /** * Clean job directory post-execution. */ CLEAN(0, false), /** * Shutdown execution state machine. */ SHUTDOWN(0, false), /** * Final stage. */ DONE(0, false), /** * Determine the job final status to publish to server. */ DETERMINE_FINAL_STATUS(0, false, JobStatusMessages.UNKNOWN_JOB_STATE), /** * Trigger a job directory manifest refresh after the job has launched. */ POST_LAUNCH_MANIFEST_REFRESH(0, true), /** * Trigger a job directory manifest refresh after job setup completed. */ POST_SETUP_MANIFEST_REFRESH(0, true), /** * Trigger a job directory manifest refresh after job process terminated. */ POST_EXECUTION_MANIFEST_REFRESH(0, false); /** * Initial pseudo-state. */ public static final States INITIAL_STATE = READY; /** * Final pseudo-state. */ public static final States FINAL_STATE = DONE; /** * If a state is critical, then upon encountering a {@link FatalJobExecutionException} while in it, execution is * aborted. Whereas for non critical stage execution is not aborted. */ private final boolean criticalState; /** * Determines whether the state transition action is performed or skipped in case execution has been previously * aborted (due to a kill request, or due to a fatal error). */ private final boolean skippedDuringAbortedExecution; /** * The final status message sent to the server when a {@link States#criticalState} state fails. * Not necessary for states that are not required, since they won't cause the job to fail. * These message constants should come from {@link JobStatusMessages}. */ private final String fatalErrorStatusMessage; /** * Number of retries (i.e. does not include initial attempt) in case a state transition throws * {@link RetryableJobExecutionException}. */ @Min(0) private final int transitionRetries; States( final boolean criticalState, final boolean skippedDuringAbortedExecution, @Min(0) final int transitionRetries, final String fatalErrorStatusMessage ) { this.criticalState = criticalState; this.skippedDuringAbortedExecution = skippedDuringAbortedExecution; this.transitionRetries = transitionRetries; this.fatalErrorStatusMessage = fatalErrorStatusMessage; } States( final int transitionRetries, final boolean skippedDuringAbortedExecution, final String fatalErrorStatusMessage ) { this(true, skippedDuringAbortedExecution, transitionRetries, fatalErrorStatusMessage); } States( final int transitionRetries, final boolean skippedDuringAbortedExecution ) { this(false, skippedDuringAbortedExecution, transitionRetries, "Unexpected fatal error in non-critical state"); } }
2,922
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/FatalJobExecutionException.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.statemachine; import lombok.Getter; import javax.annotation.Nullable; /** * Fatal exception that should stop execution early. For example, claiming a job that is not in claimable state. * * @author mprimi * @since 4.0.0 */ @Getter public class FatalJobExecutionException extends RuntimeException { private final States sourceState; /** * Constructor without cause. * * @param sourceState state in which error was encountered * @param message message */ public FatalJobExecutionException( final States sourceState, final String message ) { this(sourceState, message, null); } /** * Constructor. * * @param sourceState state in which error was encountered * @param message message * @param cause cause */ public FatalJobExecutionException( final States sourceState, final String message, @Nullable final Throwable cause ) { super(message, cause); this.sourceState = sourceState; } }
2,923
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/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 state machine. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.statemachine; import javax.annotation.ParametersAreNonnullByDefault;
2,924
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/RetryableJobExecutionException.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.statemachine; /** * Exception thrown by state machine transition for retryable errors (e.g, network error talking to server). * * @author mprimi * @since 4.0.0 */ public class RetryableJobExecutionException extends RuntimeException { /** * Constructor. * * @param message message * @param cause cause */ public RetryableJobExecutionException(final String message, final Throwable cause) { super(message, cause); } }
2,925
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/SetJobStatusFinal.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobStatus; /** * Sets the final job status (success/fail/kill). * * @author mprimi * @since 4.0.0 */ public class SetJobStatusFinal extends UpdateJobStatusStage { /** * Constructor. * * @param agentJobService the agent job service */ public SetJobStatusFinal( final AgentJobService agentJobService ) { super(agentJobService, States.SET_STATUS_FINAL); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { if (executionContext.isSkipFinalStatusUpdate()) { // Final status update should be skipped in case of job remotely marked FAILED executionContext.setCurrentJobStatus(JobStatus.FAILED); } else { super.attemptStageAction(executionContext); } } }
2,926
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/SetJobStatusRunning.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.States; /** * Updates the server job status after launch. * * @author mprimi * @since 4.0.0 */ public class SetJobStatusRunning extends UpdateJobStatusStage { /** * Constructor. * * @param agentJobService the agent job service */ public SetJobStatusRunning( final AgentJobService agentJobService ) { super(agentJobService, States.SET_STATUS_RUNNING); } }
2,927
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ShutdownStage.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.statemachine.stages; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; /** * Performs final shutdown. * * @author mprimi * @since 4.0.0 */ public class ShutdownStage extends ExecutionStage { /** * Constructor. */ public ShutdownStage() { super(States.SHUTDOWN); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { // NOOP as of now } }
2,928
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/CleanupJobDirectoryStage.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.statemachine.stages; import com.netflix.genie.agent.execution.CleanupStrategy; 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.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; /** * Performs cleanup of the job directory after execution. * * @author mprimi * @since 4.0.0 */ @Slf4j public class CleanupJobDirectoryStage extends ExecutionStage { private JobSetupService jobSetupService; /** * Constructor. * * @param jobSetupService job setup service */ public CleanupJobDirectoryStage(final JobSetupService jobSetupService) { super(States.CLEAN); this.jobSetupService = jobSetupService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final File jobDirectory = executionContext.getJobDirectory(); final CleanupStrategy cleanupStrategy = executionContext.getCleanupStrategy(); if (jobDirectory != null) { log.info("Cleaning up job directory (strategy: {})", cleanupStrategy); try { this.jobSetupService.cleanupJobDirectory( jobDirectory.toPath(), cleanupStrategy ); } catch (final IOException e) { throw new RetryableJobExecutionException("Failed to cleanup job directory", e); } } } }
2,929
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ConfigureAgentStage.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.statemachine.stages; import com.netflix.genie.agent.execution.exceptions.ConfigureException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.agent.properties.AgentProperties; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; import java.util.Map; /** * Configures the agent with server-provided runtime parameters that are independent of the job. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ConfigureAgentStage extends ExecutionStage { private final AgentJobService agentJobService; /** * Constructor. * * @param agentJobService the agent job service */ public ConfigureAgentStage( final AgentJobService agentJobService ) { super(States.CONFIGURE_AGENT); this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata(); final AgentProperties agentProperties = executionContext.getAgentProperties(); // Obtain server-provided properties final Map<String, String> serverPropertiesMap; try { serverPropertiesMap = this.agentJobService.configure(agentClientMetadata); } catch (ConfigureException e) { throw new RetryableJobExecutionException("Failed to obtain configuration", e); } for (final Map.Entry<String, String> entry : serverPropertiesMap.entrySet()) { log.info("Received property {}={}", entry.getKey(), entry.getValue()); } // Bind properties received final ConfigurationPropertySource serverPropertiesSource = new MapConfigurationPropertySource(serverPropertiesMap); new Binder(serverPropertiesSource) .bind( AgentProperties.PREFIX, Bindable.ofInstance(agentProperties) ); } }
2,930
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/LaunchJobStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.JobLaunchException; import com.netflix.genie.agent.execution.process.JobProcessManager; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.dto.JobStatusMessages; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import lombok.extern.slf4j.Slf4j; import java.io.File; /** * Launches the job process. * * @author mprimi * @since 4.0.0 */ @Slf4j public class LaunchJobStage extends ExecutionStage { private final JobProcessManager jobProcessManager; /** * Constructor. * * @param jobProcessManager job process manager */ public LaunchJobStage(final JobProcessManager jobProcessManager) { super(States.LAUNCH_JOB); this.jobProcessManager = jobProcessManager; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final File jobDirectory = executionContext.getJobDirectory(); final File jobScript = executionContext.getJobScript(); final boolean runFromJobDirectory = executionContext.isRunFromJobDirectory(); final JobSpecification jobSpecification = executionContext.getJobSpecification(); assert jobDirectory != null; assert jobScript != null; assert jobSpecification != null; final Integer timeout = jobSpecification.getTimeout().orElse(null); final boolean interactive = jobSpecification.isInteractive(); log.info("Launching job"); try { this.jobProcessManager.launchProcess( jobDirectory, jobScript, interactive, timeout, runFromJobDirectory ); } catch (final JobLaunchException e) { throw createFatalException(e); } executionContext.setJobLaunched(true); executionContext.setNextJobStatus(JobStatus.RUNNING); executionContext.setNextJobStatusMessage(JobStatusMessages.JOB_RUNNING); ConsoleLog.getLogger().info("Job launched"); } }
2,931
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StartHeartbeatServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentHeartBeatService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotBlank; /** * Starts the heartbeat service. * * @author mprimi * @since 4.0.0 */ @Slf4j public class StartHeartbeatServiceStage extends StartServiceStage { private final AgentHeartBeatService heartbeatService; /** * Constructor. * * @param heartbeatService heartbeat service */ public StartHeartbeatServiceStage(final AgentHeartBeatService heartbeatService) { super(States.START_HEARTBEAT_SERVICE); this.heartbeatService = heartbeatService; } @Override protected void startService(final @NotBlank String claimedJobId, final ExecutionContext executionContext) { this.heartbeatService.start(claimedJobId); } }
2,932
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/RelocateLogFileStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.AgentLogManager; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.agent.utils.PathUtils; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.nio.file.Path; /** * Moves the agent log file into the job directory from the temporary location. * * @author mprimi * @since 4.0.0 */ @Slf4j public class RelocateLogFileStage extends ExecutionStage { private final AgentLogManager agentLogManager; /** * Constructor. * * @param agentLogManager the agent log manager */ public RelocateLogFileStage(final AgentLogManager agentLogManager) { super(States.RELOCATE_LOG); this.agentLogManager = agentLogManager; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final File jobDirectory = executionContext.getJobDirectory(); assert jobDirectory != null; final Path destinationPath = PathUtils.jobAgentLogFilePath(jobDirectory); log.info("Relocating agent log file to: {}", destinationPath); try { this.agentLogManager.relocateLogFile(destinationPath); } catch (IOException e) { log.error("Failed to relocate agent log file", e); } } }
2,933
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/DetermineJobFinalStatusStage.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.statemachine.stages; import com.netflix.genie.agent.execution.process.JobProcessResult; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.dto.JobStatusMessages; import com.netflix.genie.common.internal.dtos.JobStatus; import lombok.extern.slf4j.Slf4j; import java.util.EnumSet; /** * Sends the server the final job status, if the job reached a state where it is appropriate to do so. * * @author mprimi * @since 4.0.0 */ @Slf4j public class DetermineJobFinalStatusStage extends ExecutionStage { private static final EnumSet<JobStatus> INTERMEDIATE_ACTIVE_STATUSES = EnumSet.of( JobStatus.ACCEPTED, JobStatus.RESERVED, JobStatus.RESOLVED, JobStatus.CLAIMED, JobStatus.INIT, JobStatus.RUNNING ); /** * Constructor. */ public DetermineJobFinalStatusStage() { super(States.DETERMINE_FINAL_STATUS); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobStatus currentJobStatus = executionContext.getCurrentJobStatus(); assert currentJobStatus != null; final boolean launched = executionContext.isJobLaunched(); final boolean killed = executionContext.isJobKilled(); final FatalJobExecutionException fatalJobExecutionException = executionContext.getExecutionAbortedFatalException(); final JobProcessResult jobProcessResult = executionContext.getJobProcessResult(); final JobStatus finalJobStatus; final String finalJobStatusMessage; // This state is never skipped. There are multiple paths leading here. // Look at context and determine the proper final status to send to the server (if any). if (launched && jobProcessResult != null) { // Mark success/failed/killed according to jobProcessResult finalJobStatus = jobProcessResult.getFinalStatus(); finalJobStatusMessage = jobProcessResult.getFinalStatusMessage(); log.info("Job executed, final status is: {}", finalJobStatus); } else if (INTERMEDIATE_ACTIVE_STATUSES.contains(currentJobStatus) && fatalJobExecutionException != null) { // Execution was aborted before getting to launch finalJobStatus = JobStatus.FAILED; finalJobStatusMessage = fatalJobExecutionException.getSourceState().getFatalErrorStatusMessage(); log.info("Job execution failed, last reported state was {}", currentJobStatus); } else if (INTERMEDIATE_ACTIVE_STATUSES.contains(currentJobStatus) && killed) { finalJobStatus = JobStatus.KILLED; finalJobStatusMessage = JobStatusMessages.JOB_KILLED_BY_USER; log.info("Job killed, last reported state was {}", currentJobStatus); } else { log.info("Job did not reach an active state"); finalJobStatus = JobStatus.INVALID; finalJobStatusMessage = JobStatusMessages.UNKNOWN_JOB_STATE; } executionContext.setNextJobStatus(finalJobStatus); executionContext.setNextJobStatusMessage(finalJobStatusMessage); } }
2,934
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StopKillServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentJobKillService; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; /** * Stops the job kill service. * * @author mprimi * @since 4.0.0 */ @Slf4j public class StopKillServiceStage extends StopServiceStage { private AgentJobKillService killService; /** * Constructor. * * @param killService kill service */ public StopKillServiceStage(final AgentJobKillService killService) { super(States.STOP_KILL_SERVICE); this.killService = killService; } @Override protected void stopService() { killService.stop(); } }
2,935
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/UpdateJobStatusStage.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.statemachine.stages; import com.netflix.genie.agent.execution.exceptions.ChangeJobStatusException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import lombok.extern.slf4j.Slf4j; /** * Updates the server-side status of the job. * * @author mprimi * @since 4.0.0 */ @Slf4j abstract class UpdateJobStatusStage extends ExecutionStage { private final AgentJobService agentJobService; /** * Constructor. * * @param agentJobService agent job service * @param state associated state */ protected UpdateJobStatusStage( final AgentJobService agentJobService, final States state ) { super(state); this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final String claimedJobId = executionContext.getReservedJobId(); final JobStatus currentJobStatus = executionContext.getCurrentJobStatus(); final JobStatus nextJobStatus = executionContext.getNextJobStatus(); final String nextJobStatusMessage = executionContext.getNextJobStatusMessage(); assert claimedJobId != null; assert currentJobStatus != null; assert nextJobStatus != null; if (nextJobStatus != JobStatus.INVALID) { assert nextJobStatusMessage != null; log.info("Updating job status to: {} - {}", nextJobStatus, nextJobStatusMessage); try { this.agentJobService.changeJobStatus( claimedJobId, currentJobStatus, nextJobStatus, nextJobStatusMessage ); } catch (final GenieRuntimeException e) { throw createRetryableException(e); } catch (ChangeJobStatusException e) { throw createFatalException(e); } executionContext.setCurrentJobStatus(nextJobStatus); } else { log.info("Skipping job status update"); } } }
2,936
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StartFileServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentFileStreamService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotBlank; import java.io.File; /** * Starts the file streaming service. * * @author mprimi * @since 4.0.0 */ @Slf4j public class StartFileServiceStage extends StartServiceStage { private final AgentFileStreamService agentFileStreamService; /** * Constructor. * * @param agentFileStreamService agent file stream service */ public StartFileServiceStage(final AgentFileStreamService agentFileStreamService) { super(States.START_FILE_STREAM_SERVICE); this.agentFileStreamService = agentFileStreamService; } @Override protected void startService(@NotBlank final String claimedJobId, final ExecutionContext executionContext) { final File jobDirectory = executionContext.getJobDirectory(); assert jobDirectory != null; this.agentFileStreamService.start(claimedJobId, jobDirectory.toPath()); } }
2,937
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/InitializeAgentStage.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.statemachine.stages; import com.netflix.genie.agent.AgentMetadata; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import lombok.extern.slf4j.Slf4j; /** * Performs generic initialization. * * @author mprimi * @since 4.0.0 */ @Slf4j public class InitializeAgentStage extends ExecutionStage { private AgentMetadata agentMetadata; /** * Constructor. * * @param agentMetadata agent metadata */ public InitializeAgentStage(final AgentMetadata agentMetadata) { super(States.INITIALIZE_AGENT); this.agentMetadata = agentMetadata; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { log.info("Creating agent client metadata"); final AgentClientMetadata agentClientMetadata = new AgentClientMetadata( agentMetadata.getAgentHostName(), agentMetadata.getAgentVersion(), Integer.parseInt(agentMetadata.getAgentPid()) ); executionContext.setAgentClientMetadata(agentClientMetadata); } }
2,938
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/CreateJobDirectoryStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; 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.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobSpecification; import lombok.extern.slf4j.Slf4j; import java.io.File; /** * Creates the job directory. * * @author mprimi * @since 4.0.0 */ @Slf4j public class CreateJobDirectoryStage extends ExecutionStage { private final JobSetupService jobSetupService; /** * Constructor. * * @param jobSetupService job setup service */ public CreateJobDirectoryStage(final JobSetupService jobSetupService) { super(States.CREATE_JOB_DIRECTORY); this.jobSetupService = jobSetupService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobSpecification jobSpecification = executionContext.getJobSpecification(); assert jobSpecification != null; log.info("Creating job directory"); final File jobDirectory; try { jobDirectory = this.jobSetupService.createJobDirectory(jobSpecification); } catch (SetUpJobException e) { throw createFatalException(e); } executionContext.setJobDirectory(jobDirectory); ConsoleLog.getLogger().info("Created job directory: {}", jobDirectory); } }
2,939
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StartKillServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentJobKillService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import javax.validation.constraints.NotBlank; /** * Starts the kill service. * * @author mprimi * @since 4.0.0 */ @Slf4j public class StartKillServiceStage extends StartServiceStage { private final AgentJobKillService killService; /** * Constructor. * * @param killService kill service */ public StartKillServiceStage(final AgentJobKillService killService) { super(States.START_KILL_SERVICE); this.killService = killService; } @Override protected void startService(final @NotBlank String claimedJobId, final ExecutionContext executionContext) { this.killService.start(claimedJobId); } }
2,940
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StopFileServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentFileStreamService; import com.netflix.genie.agent.execution.statemachine.States; /** * Stops the file streaming service. * * @author mprimi * @since 4.0.0 */ public class StopFileServiceStage extends StopServiceStage { private AgentFileStreamService agentFileStreamService; /** * Constructor. * * @param agentFileStreamService agent file stream service */ public StopFileServiceStage(final AgentFileStreamService agentFileStreamService) { super(States.STOP_FILES_STREAM_SERVICE); this.agentFileStreamService = agentFileStreamService; } @Override protected void stopService() { this.agentFileStreamService.stop(); } }
2,941
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StopServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; /** * Base class for stages starting a service. */ @Slf4j abstract class StopServiceStage extends ExecutionStage { /** * Constructor. * * @param state the associated state */ StopServiceStage(final States state) { super(state); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { try { log.info("Stopping service in stage {}", this.getClass().getSimpleName()); this.stopService(); } catch (RuntimeException e) { throw createFatalException(e); } } protected abstract void stopService(); }
2,942
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ObtainJobSpecificationStage.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.statemachine.stages; import com.netflix.genie.agent.execution.exceptions.JobSpecificationResolutionException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import lombok.extern.slf4j.Slf4j; /** * Obtains job specification from server. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ObtainJobSpecificationStage extends ExecutionStage { private final AgentJobService agentJobService; /** * Constructor. * * @param agentJobService agent job service */ public ObtainJobSpecificationStage(final AgentJobService agentJobService) { super(States.OBTAIN_JOB_SPECIFICATION); this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final String reservedJobId = executionContext.getReservedJobId(); assert reservedJobId != null; final JobSpecification jobSpecification; try { if (executionContext.isPreResolved()) { log.info("Retrieving pre-resolved job specification"); jobSpecification = this.agentJobService.getJobSpecification(reservedJobId); } else { log.info("Requesting job specification resolution"); jobSpecification = agentJobService.resolveJobSpecification(reservedJobId); executionContext.setCurrentJobStatus(JobStatus.RESOLVED); } } catch (final GenieRuntimeException e) { throw createRetryableException(e); } catch (final JobSpecificationResolutionException e) { throw createFatalException(e); } executionContext.setJobSpecification(jobSpecification); log.info("Successfully obtained specification"); } }
2,943
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/HandshakeStage.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.statemachine.stages; import com.netflix.genie.agent.execution.exceptions.HandshakeException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import lombok.extern.slf4j.Slf4j; /** * Perform server handshake, to ensure server is ok with this agent running a job. * * @author mprimi * @since 4.0.0 */ @Slf4j public class HandshakeStage extends ExecutionStage { private final AgentJobService agentJobService; /** * Constructor. * * @param agentJobService agent job service */ public HandshakeStage( final AgentJobService agentJobService ) { super(States.HANDSHAKE); this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata(); assert agentClientMetadata != null; log.info("Performing client/server handshake"); try { agentJobService.handshake(agentClientMetadata); } catch (final GenieRuntimeException e) { throw createRetryableException(e); } catch (final HandshakeException e) { throw createFatalException(e); } log.info("Shook hands with server"); } }
2,944
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/LogExecutionErrorsStage.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.statemachine.stages; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import java.util.List; /** * Logs execution errors encountered so far. * This stage is positioned before the archive step to ensure the archived log file is useful for post-execution * debugging. * * @author mprimi * @since 4.0.0 */ @Slf4j public class LogExecutionErrorsStage extends com.netflix.genie.agent.execution.statemachine.ExecutionStage { /** * Constructor. */ public LogExecutionErrorsStage() { super(States.LOG_EXECUTION_ERRORS); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final List<ExecutionContext.TransitionExceptionRecord> records; records = executionContext.getTransitionExceptionRecords(); if (records.isEmpty()) { log.info("No transition errors recorded"); } else { log.info("Transition errors recorded so far:"); records.forEach( record -> { final Exception exception = record.getRecordedException(); final States state = record.getState(); log.info( " * {} error in state {}: {} - {}", exception instanceof FatalJobExecutionException ? "Fatal" : "Retryable", state.name(), exception.getClass().getSimpleName(), exception.getMessage() ); Throwable cause = exception.getCause(); while (cause != null) { log.info( " > Cause: {} - {}", cause.getClass().getSimpleName(), cause.getMessage() ); cause = cause.getCause(); } } ); } } }
2,945
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StopHeartbeatServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentHeartBeatService; import com.netflix.genie.agent.execution.statemachine.States; /** * Stops the heartbeat service. * * @author mprimi * @since 4.0.0 */ public class StopHeartbeatServiceStage extends StopServiceStage { private AgentHeartBeatService heartbeatService; /** * Constructor. * * @param heartbeatService heartbeat service */ public StopHeartbeatServiceStage(final AgentHeartBeatService heartbeatService) { super(States.STOP_HEARTBEAT_SERVICE); this.heartbeatService = heartbeatService; } @Override protected void stopService() { heartbeatService.stop(); } }
2,946
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/StartServiceStage.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.statemachine.stages; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import javax.validation.constraints.NotBlank; /** * Base class for stages starting a service. */ @Slf4j abstract class StartServiceStage extends ExecutionStage { /** * Constructor. * * @param state the associated state */ StartServiceStage(final States state) { super(state); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { @NotBlank final String claimedJobId = executionContext.getClaimedJobId(); assert StringUtils.isNotBlank(claimedJobId); try { log.info("Starting service in stage {}", this.getClass().getSimpleName()); this.startService(claimedJobId, executionContext); } catch (RuntimeException e) { throw createFatalException(e); } } protected abstract void startService(@NotBlank String claimedJobId, ExecutionContext executionContext); }
2,947
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ConfigureExecutionStage.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.statemachine.stages; import com.netflix.genie.agent.cli.ArgumentDelegates; import com.netflix.genie.agent.cli.JobRequestConverter; import com.netflix.genie.agent.execution.CleanupStrategy; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; /** * Sets up context state based on the type of execution and other command-line parameters. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ConfigureExecutionStage extends ExecutionStage { private final JobRequestConverter jobRequestConverter; private final ArgumentDelegates.JobRequestArguments jobRequestArguments; private final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments; private final ArgumentDelegates.CleanupArguments cleanupArguments; /** * Constructor. * * @param jobRequestConverter job request converter * @param jobRequestArguments job request arguments group * @param runtimeConfigurationArguments runtime configuration arguments group * @param cleanupArguments cleanup arguments group */ public ConfigureExecutionStage( final JobRequestConverter jobRequestConverter, final ArgumentDelegates.JobRequestArguments jobRequestArguments, final ArgumentDelegates.RuntimeConfigurationArguments runtimeConfigurationArguments, final ArgumentDelegates.CleanupArguments cleanupArguments ) { super(States.CONFIGURE_EXECUTION); this.jobRequestConverter = jobRequestConverter; this.jobRequestArguments = jobRequestArguments; this.runtimeConfigurationArguments = runtimeConfigurationArguments; this.cleanupArguments = cleanupArguments; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { // Determine whether job has pre-resolved job specification final boolean isPreResolved = this.jobRequestArguments.isJobRequestedViaAPI(); executionContext.setPreResolved(isPreResolved); final boolean isRunInJobDirectory = this.runtimeConfigurationArguments.isLaunchInJobDirectory(); executionContext.setRunFromJobDirectory(isRunInJobDirectory); final CleanupStrategy cleanupStrategy = this.cleanupArguments.getCleanupStrategy(); executionContext.setCleanupStrategy(cleanupStrategy); final String requestedJobId = this.jobRequestArguments.getJobId(); if (isPreResolved) { log.info("Configuring execution for pre-resolved job"); if (StringUtils.isBlank(requestedJobId)) { throw createFatalException(new IllegalArgumentException("Missing required argument job id")); } } else { log.info("Configuring execution for CLI job"); // Create job request from arguments if this is not a pre-reserved job try { final AgentJobRequest agentJobRequest = this.jobRequestConverter.agentJobRequestArgsToDTO(jobRequestArguments); executionContext.setAgentJobRequest(agentJobRequest); } catch (final JobRequestConverter.ConversionException e) { throw createFatalException(e); } } // Save the job id requested. // May be blank/null if the request is not for a pre-resolved "API" job. executionContext.setRequestedJobId(requestedJobId); } }
2,948
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/DownloadDependenciesStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; 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.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobSpecification; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.Set; /** * Download dependencies such as binaries and configurations attached to the job and its dependent entities. * * @author mprimi * @since 4.0.0 */ @Slf4j public class DownloadDependenciesStage extends ExecutionStage { private final JobSetupService jobSetupService; /** * Constructor. * * @param jobSetupService job setup service */ public DownloadDependenciesStage(final JobSetupService jobSetupService) { super(States.DOWNLOAD_DEPENDENCIES); this.jobSetupService = jobSetupService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobSpecification jobSpecification = executionContext.getJobSpecification(); final File jobDirectory = executionContext.getJobDirectory(); assert jobSpecification != null; assert jobDirectory != null; log.info("Downloading job dependencies"); final Set<File> downloaded; try { downloaded = this.jobSetupService.downloadJobResources(jobSpecification, jobDirectory); } catch (SetUpJobException e) { throw createFatalException(e); } ConsoleLog.getLogger().info("Downloaded dependencies ({} files)", downloaded.size()); } }
2,949
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ClaimJobStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.JobReservationException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.dto.JobStatusMessages; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import lombok.extern.slf4j.Slf4j; /** * Claim the job, so no other agent can execute it. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ClaimJobStage extends ExecutionStage { private final AgentJobService agentJobService; /** * Constructor. * * @param agentJobService agent job service */ public ClaimJobStage(final AgentJobService agentJobService) { super(States.CLAIM_JOB); this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final String jobId = executionContext.getReservedJobId(); final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata(); assert jobId != null; assert agentClientMetadata != null; log.info("Claiming job"); try { this.agentJobService.claimJob(jobId, agentClientMetadata); } catch (final GenieRuntimeException e) { throw createRetryableException(e); } catch (final JobReservationException e) { throw createFatalException(e); } ConsoleLog.getLogger().info("Successfully claimed job: {}", jobId); // Update context executionContext.setCurrentJobStatus(JobStatus.CLAIMED); executionContext.setClaimedJobId(jobId); executionContext.setNextJobStatus(JobStatus.INIT); executionContext.setNextJobStatusMessage(JobStatusMessages.JOB_INITIALIZING); } }
2,950
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/RefreshManifestStage.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentFileStreamService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import java.time.Duration; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Triggers a manual refresh of the cached files manifest. * * @author mprimi * @since 4.0.0 */ @Slf4j public class RefreshManifestStage extends ExecutionStage { private final AgentFileStreamService agentFileStreamService; /** * Constructor. * * @param agentFileStreamService agent file stream service * @param state the associated state */ public RefreshManifestStage(final AgentFileStreamService agentFileStreamService, final States state) { super(state); this.agentFileStreamService = agentFileStreamService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { if (executionContext.getJobDirectory() != null) { log.info("Forcing a manifest refresh"); final Optional<ScheduledFuture<?>> optionalFuture = this.agentFileStreamService.forceServerSync(); if (optionalFuture.isPresent()) { // Give it a little time to complete, but don't block execution if it doesn't final Duration timeout = executionContext.getAgentProperties().getForceManifestRefreshTimeout(); try { optionalFuture.get().get(timeout.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException | TimeoutException e) { log.warn("Forced manifest refresh timeout: {}", e.getMessage()); } catch (ExecutionException e) { log.error("Failed to force push manifest", e); } } } } }
2,951
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ReserveJobIdStage.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.statemachine.stages; import brave.Tracer; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.GetJobStatusException; import com.netflix.genie.agent.execution.exceptions.JobIdUnavailableException; import com.netflix.genie.agent.execution.exceptions.JobReservationException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; 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.BraveTracingComponents; import lombok.extern.slf4j.Slf4j; /** * Performs job reservation, or ensures the job is pre-reserved and ready to be claimed. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ReserveJobIdStage extends ExecutionStage { private final AgentJobService agentJobService; private final Tracer tracer; private final BraveTagAdapter tagAdapter; /** * Constructor. * * @param agentJobService agent job service. * @param tracingComponents The {@link BraveTracingComponents} instance */ public ReserveJobIdStage( final AgentJobService agentJobService, final BraveTracingComponents tracingComponents ) { super(States.RESERVE_JOB_ID); this.agentJobService = agentJobService; this.tracer = tracingComponents.getTracer(); this.tagAdapter = tracingComponents.getTagAdapter(); } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final String requestedJobId = executionContext.getRequestedJobId(); final String reservedJobId; if (executionContext.isPreResolved()) { assert requestedJobId != null; log.info("Confirming job reservation"); final JobStatus jobStatus; try { jobStatus = this.agentJobService.getJobStatus(requestedJobId); } catch (GetJobStatusException | GenieRuntimeException e) { throw new RetryableJobExecutionException("Failed to retrieve job status", e); } if (jobStatus != JobStatus.ACCEPTED) { throw createFatalException( new IllegalStateException("Unexpected job status: " + jobStatus + " job cannot be claimed") ); } executionContext.setCurrentJobStatus(JobStatus.ACCEPTED); reservedJobId = requestedJobId; } else { log.info("Requesting job id reservation"); final AgentJobRequest jobRequest = executionContext.getAgentJobRequest(); final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata(); assert jobRequest != null; assert agentClientMetadata != null; try { reservedJobId = this.agentJobService.reserveJobId(jobRequest, agentClientMetadata); } catch (final GenieRuntimeException e) { throw createRetryableException(e); } catch (final JobIdUnavailableException | JobReservationException e) { throw createFatalException(e); } executionContext.setCurrentJobStatus(JobStatus.RESERVED); ConsoleLog.getLogger().info("Successfully reserved job id: {}", reservedJobId); } executionContext.setReservedJobId(reservedJobId); this.tagAdapter.tag(this.tracer.currentSpanCustomizer(), TracingConstants.JOB_ID_TAG, reservedJobId); } }
2,952
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/WaitJobCompletionStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.process.JobProcessManager; import com.netflix.genie.agent.execution.process.JobProcessResult; import com.netflix.genie.agent.execution.services.JobMonitorService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobStatus; import lombok.extern.slf4j.Slf4j; /** * Wait for job process to exit. * * @author mprimi * @since 4.0.0 */ @Slf4j public class WaitJobCompletionStage extends ExecutionStage { private final JobProcessManager jobProcessManager; private final JobMonitorService jobMonitorService; /** * Constructor. * * @param jobProcessManager the job process manager * @param jobMonitorService the job monitor service */ public WaitJobCompletionStage( final JobProcessManager jobProcessManager, final JobMonitorService jobMonitorService ) { super(States.WAIT_JOB_COMPLETION); this.jobProcessManager = jobProcessManager; this.jobMonitorService = jobMonitorService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { // In case of abort, this state may be reached even if there was no attempt to launch the process. if (executionContext.isJobLaunched()) { log.info("Monitoring job process"); this.jobMonitorService.start( executionContext.getClaimedJobId(), executionContext.getJobDirectory().toPath() ); final JobProcessResult jobProcessResult; try { jobProcessResult = this.jobProcessManager.waitFor(); } catch (final InterruptedException e) { throw createFatalException(e); } finally { this.jobMonitorService.stop(); } executionContext.setJobProcessResult(jobProcessResult); final JobStatus finalJobStatus = jobProcessResult.getFinalStatus(); ConsoleLog.getLogger().info("Job process completed with final status {}", finalJobStatus); } else { log.debug("Job not launched, skipping"); } } }
2,953
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/CreateJobScriptStage.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.statemachine.stages; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; 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.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.JobSpecification; import lombok.extern.slf4j.Slf4j; import java.io.File; /** * Creates the job script (a.k.a. `run` file). * * @author mprimi * @since 4.0.0 */ @Slf4j public class CreateJobScriptStage extends ExecutionStage { private final JobSetupService jobSetupService; /** * Constructor. * * @param jobSetupService job setup service */ public CreateJobScriptStage(final JobSetupService jobSetupService) { super(States.CREATE_JOB_SCRIPT); this.jobSetupService = jobSetupService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobSpecification jobSpecification = executionContext.getJobSpecification(); final File jobDirectory = executionContext.getJobDirectory(); assert jobSpecification != null; assert jobDirectory != null; log.info("Generating job script (a.k.a. run file)"); final File jobScript; try { jobScript = this.jobSetupService.createJobScript(jobSpecification, jobDirectory); } catch (SetUpJobException e) { throw createFatalException(e); } executionContext.setJobScript(jobScript); } }
2,954
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/SetJobStatusInit.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.statemachine.stages; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.States; /** * Updates job status when job starts initializing. * * @author mprimi * @since 4.0.0 */ public class SetJobStatusInit extends UpdateJobStatusStage { /** * Constructor. * * @param agentJobService the agent job service */ public SetJobStatusInit( final AgentJobService agentJobService ) { super(agentJobService, States.SET_STATUS_INIT); } }
2,955
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/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. * */ /** * Execution stages of Agent state machine. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.statemachine.stages; import javax.annotation.ParametersAreNonnullByDefault;
2,956
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/stages/ArchiveJobOutputsStage.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.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.ChangeJobArchiveStatusException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.exceptions.checked.JobArchiveException; import com.netflix.genie.common.internal.services.JobArchiveService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.net.URI; import java.net.URISyntaxException; /** * Archive job output files and logs, if the job reached a state where it is appropriate to do so. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ArchiveJobOutputsStage extends ExecutionStage { private final JobArchiveService jobArchiveService; private final AgentJobService agentJobService; /** * Constructor. * * @param jobArchiveService job archive service * @param agentJobService agent job service */ public ArchiveJobOutputsStage(final JobArchiveService jobArchiveService, final AgentJobService agentJobService) { super(States.ARCHIVE); this.jobArchiveService = jobArchiveService; this.agentJobService = agentJobService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobSpecification jobSpecification = executionContext.getJobSpecification(); final File jobDirectory = executionContext.getJobDirectory(); if (jobSpecification != null && jobDirectory != null) { final String archiveLocation = jobSpecification.getArchiveLocation().orElse(null); if (StringUtils.isNotBlank(archiveLocation)) { boolean success = false; try { log.info("Archive job folder to: " + archiveLocation); this.jobArchiveService.archiveDirectory( jobDirectory.toPath(), new URI(archiveLocation) ); success = true; } catch (JobArchiveException | URISyntaxException e) { // Swallow the error and move on. log.error("Error archiving job folder", e); ConsoleLog.getLogger().error( "Job file archive error: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage() ); } final String jobId = executionContext.getClaimedJobId(); final ArchiveStatus archiveStatus = success ? ArchiveStatus.ARCHIVED : ArchiveStatus.FAILED; try { this.agentJobService.changeJobArchiveStatus(jobId, archiveStatus); } catch (ChangeJobArchiveStatusException e) { // Swallow the error and move on. log.error("Error updating the archive status", e); } } } } }
2,957
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/listeners/JobExecutionListener.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.statemachine.listeners; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import javax.annotation.Nullable; /** * Listener of job execution. * Notifications are delivered synchronously from the state machine execution thread. * * @author mprimi * @since 4.0.0 */ public interface JobExecutionListener { /** * Invoked when the state machine reaches the next state, before any of the logic for that state is evaluated. * * @param state the state entered */ default void stateEntered(States state) { } /** * Invoked when the state machine is done processing a state and it is about to enter the next one. * * @param state the state exiting */ default void stateExited(States state) { } /** * Invoked before the action associated to a given state is invoked. * * @param state the state whose action is invoked */ default void beforeStateActionAttempt(States state) { } /** * Invoked after the action associated with a given state is invoked. * * @param state the state whose action was invoked * @param exception the exception thrown by the action, or null if there was no error */ default void afterStateActionAttempt(States state, @Nullable Exception exception) { } /** * Invoked when the state machine starts running. */ default void stateMachineStarted() { } /** * Invoked when the state machine stops. */ default void stateMachineStopped() { } /** * Invoked when the action of a given state is skipped because execution was aborted and the state is set to be * skipped in case of aborted execution. * * @param state the state whose action is skipped */ default void stateSkipped(States state) { } /** * Invoked when the state machine encounters a fatal exception while invoking the action for a given state. * * @param state the state whose action produced a fatal exception * @param exception the exception */ default void fatalException(States state, FatalJobExecutionException exception) { } /** * Invoked when the state machine encounters a fatal exception in a critical state, which causes the execution to * abort. * * @param state the state whose action produced a fatal exception * @param exception the exception */ default void executionAborted(States state, FatalJobExecutionException exception) { } /** * Invoked when the state machine is about to wait before retrying the action associated to the given state as a * result of a retryable exception on the previous attempt. * * @param state the state whose action will be retried after a pause * @param retryDelay the retry delay in milliseconds */ default void delayedStateActionRetry(States state, final long retryDelay) { } }
2,958
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/listeners/TracingListener.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.execution.statemachine.listeners; import brave.Tracer; import com.netflix.genie.agent.execution.statemachine.States; /** * A listener which adds data to spans based on the events emitted by the state machine. * * @author tgianos * @since 4.0.0 */ public class TracingListener implements JobExecutionListener { static final String ENTERED_STATE_ANNOTATION_PREFIX = "Entered execution state: "; static final String EXITED_STATE_ANNOTATION_PREFIX = "Exited execution state: "; private final Tracer tracer; /** * Constructor. * * @param tracer The {@link Tracer} instance to use for instrumentation */ public TracingListener(final Tracer tracer) { this.tracer = tracer; } /** * {@inheritDoc} */ @Override public void stateEntered(final States state) { this.tracer.currentSpanCustomizer().annotate(ENTERED_STATE_ANNOTATION_PREFIX + state); } /** * {@inheritDoc} */ @Override public void stateExited(final States state) { this.tracer.currentSpanCustomizer().annotate(EXITED_STATE_ANNOTATION_PREFIX + state); } }
2,959
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/listeners/ConsoleLogListener.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.statemachine.listeners; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import org.slf4j.Logger; import javax.annotation.Nullable; /** * Job execution listener that prints messages visible to the user in the console. * * @author mprimi * @since 4.0.0 */ public class ConsoleLogListener implements JobExecutionListener { private final Logger log; /** * Constructor. */ public ConsoleLogListener() { this.log = ConsoleLog.getLogger(); } /** * {@inheritDoc} */ @Override public void stateEntered(final States state) { log.debug("Entered state: {}", state); } /** * {@inheritDoc} */ @Override public void stateExited(final States state) { log.debug("Exiting state: {}", state); } /** * {@inheritDoc} */ @Override public void beforeStateActionAttempt(final States state) { log.debug("Attempting action: {}", state); switch (state) { case INITIALIZE_AGENT: log.info("Initializing agent..."); break; case HANDSHAKE: log.info("Connecting to server..."); break; case RESERVE_JOB_ID: log.info("Obtaining job id..."); break; case OBTAIN_JOB_SPECIFICATION: log.info("Obtaining job specification..."); break; case CLAIM_JOB: log.info("Claiming job for execution..."); break; case CREATE_JOB_DIRECTORY: log.info("Creating job directory..."); break; case DOWNLOAD_DEPENDENCIES: log.info("Downloading job dependencies..."); break; case LAUNCH_JOB: log.info("Launching job..."); break; case WAIT_JOB_COMPLETION: log.info("Waiting for job completion..."); break; case ARCHIVE: log.info("Archiving job files..."); break; case CLEAN: log.info("Cleaning job directory..."); break; case SHUTDOWN: log.info("Shutting down..."); break; default: // NOOP - Other states are TMI for Console } } /** * {@inheritDoc} */ @Override public void afterStateActionAttempt(final States state, @Nullable final Exception exception) { if (exception != null) { log.warn("{} error: {}", state, exception.getMessage()); } } /** * {@inheritDoc} */ @Override public void stateMachineStarted() { log.info("Starting job execution..."); } /** * {@inheritDoc} */ @Override public void stateMachineStopped() { log.info("Job execution completed"); } /** * {@inheritDoc} */ @Override public void stateSkipped(final States state) { log.debug(" > Skip: {}", state); } /** * {@inheritDoc} */ @Override public void fatalException(final States state, final FatalJobExecutionException exception) { log.debug("{}: {}", state, exception.getMessage()); } /** * {@inheritDoc} */ @Override public void executionAborted(final States state, final FatalJobExecutionException exception) { log.error("Job execution aborted in {}: {}", state, exception.getMessage()); } /** * {@inheritDoc} */ @Override public void delayedStateActionRetry(final States state, final long retryDelay) { log.debug("Retryable error in {}, next attempt in {}ms", state, retryDelay); } }
2,960
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/listeners/LoggingListener.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.statemachine.listeners; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; /** * Listener that logs state machine events and transitions. * * @author mprimi * @since 4.0.0 */ @Slf4j public class LoggingListener implements JobExecutionListener { /** * {@inheritDoc} */ @Override public void stateEntered(final States state) { log.info("Entering state {}", state); } /** * {@inheritDoc} */ @Override public void stateExited(final States state) { log.info("Exiting state {}", state); } /** * {@inheritDoc} */ @Override public void beforeStateActionAttempt(final States state) { log.debug("About to execute state {} action", state); } /** * {@inheritDoc} */ @Override public void afterStateActionAttempt(final States state, @Nullable final Exception exception) { if (exception == null) { log.debug("State {} action", state); } else { log.warn("State {} action threw {}: {}", state, exception.getClass(), exception.getMessage()); } } /** * {@inheritDoc} */ @Override public void stateMachineStarted() { log.info("State machine started"); } /** * {@inheritDoc} */ @Override public void stateMachineStopped() { log.info("State machine stopped"); } /** * {@inheritDoc} */ @Override public void stateSkipped(final States state) { log.warn("State {} action skipped due to aborted execution", state); } /** * {@inheritDoc} */ @Override public void fatalException(final States state, final FatalJobExecutionException exception) { log.error("Fatal exception in state {}: {}", state, exception.getMessage(), exception); } /** * {@inheritDoc} */ @Override public void executionAborted(final States state, final FatalJobExecutionException exception) { log.info("Execution aborted in state {} due to: {}", state, exception.getMessage()); } /** * {@inheritDoc} */ @Override public void delayedStateActionRetry(final States state, final long retryDelay) { log.debug("Retry for state {} action in {}ms", state, retryDelay); } }
2,961
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/statemachine/listeners/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. * */ /** * Listeners for JobExecutionStateMachine. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.statemachine.listeners; import javax.annotation.ParametersAreNonnullByDefault;
2,962
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/JobReservationException.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.exceptions; /** * Failure to reserve a job id for reasons other than the specified job id being already used. * * @author mprimi * @since 4.0.0 */ public class JobReservationException extends Exception { /** * Constructor with message. * * @param message a message */ public JobReservationException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public JobReservationException(final String message, final Throwable cause) { super(message, cause); } }
2,963
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/JobSpecificationResolutionException.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.exceptions; /** * Exception thrown by AgentJobService. * * @author mprimi * @since 4.0.0 */ public class JobSpecificationResolutionException extends Exception { /** * Constructor with message. * * @param message a message */ public JobSpecificationResolutionException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public JobSpecificationResolutionException(final String message, final Throwable cause) { super(message, cause); } }
2,964
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/LockException.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.exceptions; /** * Exception thrown when there is a problem with locks. * * @author standon * @since 4.0.0 */ public class LockException extends Exception { /** * Constructor with message. * * @param message a message */ public LockException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public LockException(final String message, final Throwable cause) { super(message, cause); } }
2,965
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/InvalidStateException.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.exceptions; /** * Unchecked exception thrown in case a state action is executed with an unexpected state. * * @author mprimi * @since 4.0.0 */ public class InvalidStateException extends RuntimeException { /** * Constructor with message. * * @param message a message */ public InvalidStateException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public InvalidStateException(final String message, final Throwable cause) { super(message, cause); } }
2,966
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/ChangeJobArchiveStatusException.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.exceptions; /** * Failure to update the job archive status remotely. * * @author mprimi * @since 4.0.0 */ public class ChangeJobArchiveStatusException extends Exception { /** * Constructor with message. * * @param message message */ public ChangeJobArchiveStatusException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message message * @param cause cause */ public ChangeJobArchiveStatusException(final String message, final Throwable cause) { super(message, cause); } }
2,967
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/ConfigureException.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.exceptions; /** * Failure to obtain configuration properties from server. * * @author mprimi * @since 4.0.0 */ public class ConfigureException extends Exception { /** * Constructor with message. * * @param message a message */ public ConfigureException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public ConfigureException(final String message, final Throwable cause) { super(message, cause); } }
2,968
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/SetUpJobException.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.exceptions; /** * Exception during the set up of a job. * * @author mprimi * @since 4.0.0 */ public class SetUpJobException extends Exception { /** * Construct with message. * * @param messsage a message */ public SetUpJobException(final String messsage) { super(messsage); } /** * Construct with a message and a cause. * * @param message a message * @param cause a cause */ public SetUpJobException(final String message, final Throwable cause) { super(message, cause); } }
2,969
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/HandshakeException.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.execution.exceptions; /** * Failure to handshake with server. * * @author mprimi * @since 4.0.0 */ public class HandshakeException extends Exception { /** * Constructor with message. * * @param message a message */ public HandshakeException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public HandshakeException(final String message, final Throwable cause) { super(message, cause); } }
2,970
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/ChangeJobStatusException.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.exceptions; /** * Failure to update the job status remotely. * * @author mprimi * @since 4.0.0 */ public class ChangeJobStatusException extends Exception { /** * Constructor with message. * * @param message message */ public ChangeJobStatusException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message message * @param cause cause */ public ChangeJobStatusException(final String message, final Throwable cause) { super(message, cause); } }
2,971
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/JobLaunchException.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.exceptions; /** * Exception during job launch. * * @author mprimi * @since 4.0.0 */ public class JobLaunchException extends Exception { /** * Construct with message. * * @param message message */ public JobLaunchException(final String message) { super(message); } /** * Construct with message and cause. * * @param message message * @param cause cause */ public JobLaunchException(final String message, final Throwable cause) { super(message, cause); } }
2,972
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/JobIdUnavailableException.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.exceptions; /** * Exception thrown by AgentJobService when trying to reserve an ID that has already been used. * * @author mprimi * @since 4.0.0 */ public class JobIdUnavailableException extends Exception { /** * Constructor with message. * * @param message a message */ public JobIdUnavailableException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public JobIdUnavailableException(final String message, final Throwable cause) { super(message, cause); } }
2,973
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/GetJobStatusException.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.exceptions; /** * Failure to retrieve job status from the server. * * @author mprimi * @since 4.0.0 */ public class GetJobStatusException extends Exception { /** * Constructor with message. * * @param message message */ public GetJobStatusException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message message * @param cause cause */ public GetJobStatusException(final String message, final Throwable cause) { super(message, cause); } }
2,974
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/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. * */ /** * Execution exceptions. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.exceptions; import javax.annotation.ParametersAreNonnullByDefault;
2,975
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/exceptions/DownloadException.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.exceptions; /** * Exception thrown by services that fail to download dependencies for a job. * * @author mprimi * @since 4.0.0 */ public class DownloadException extends Exception { /** * Constructor with message. * * @param message a message */ public DownloadException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public DownloadException(final String message, final Throwable cause) { super(message, cause); } }
2,976
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/AgentJobKillService.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; import javax.validation.constraints.NotBlank; /** * Register an agent to listen for job kill messages from the server * and respond to them. * * @author standon * @since 4.0.0 */ public interface AgentJobKillService { /** * Start listening for job termination notification. * * @param jobId job id */ void start(@NotBlank(message = "Job id cannot be blank") String jobId); /** * Stop the service. */ void stop(); }
2,977
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/KillService.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; /** * Service responsible for killing the job. * * @author standon * @since 4.0.0 */ public interface KillService { /** * Perform all operations associated with killing the job. * * @param killSource the source of kill */ void kill(KillSource killSource); /** * Enumeration for the source of a request to kill the job. */ enum KillSource { /** * A system signal (SIGINT), for example user ctrl-c or system shutdown. */ SYSTEM_SIGNAL, /** * A request to the server, forwarded to the agent. */ API_KILL_REQUEST, /** * The job has exceeded its max execution duration. */ TIMEOUT, /** * The job has exceeded one of the files limit (files count, file size, etc.). */ FILES_LIMIT, /** * The job status was changed server-side while the job was running. */ REMOTE_STATUS_MONITOR, } }
2,978
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/FetchingCacheService.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; import com.netflix.genie.agent.execution.exceptions.DownloadException; import org.apache.commons.lang3.tuple.Pair; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Set; /** * Interface for a cache that downloads resources via URL and stores them on local disk for later reuse. * * @author mprimi * @since 4.0.0 */ public interface FetchingCacheService { /** * Download a given resource (if not already cached) and copy it to the specified destination. * * @param sourceFileUri the resource URI * @param destinationFile the location on disk where to copy the resource for use * @throws DownloadException if the resource is not found or fails to download * @throws IOException if downloading or copying the file to destination fails */ void get(URI sourceFileUri, File destinationFile) throws DownloadException, IOException; /** * Download a given set of resources (if not already cached) and copy them to the specified destinations. * * @param sourceDestinationPairs a set of resource URIs and their requested local target locations * @throws DownloadException if the resource is not found or fails to download * @throws IOException if downloading or copying the file to destination fails */ void get(Set<Pair<URI, File>> sourceDestinationPairs) throws DownloadException, IOException; }
2,979
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/AgentFileStreamService.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.execution.services; import java.nio.file.Path; import java.util.Optional; import java.util.concurrent.ScheduledFuture; /** * This service regularly produces a manifest of the executing job folder and pushes it to the server. * * @author mprimi * @since 4.0.0 */ public interface AgentFileStreamService { /** * Start the service. * * @param claimedJobId the claimed job id * @param jobDirectoryPath the job directory */ void start(String claimedJobId, Path jobDirectoryPath); /** * Stop the service. */ void stop(); /** * Request the service perform an update outside of the regular schedule to make sure the server has the most * up-to-date view of local files. * * @return a scheduled future optional, which the caller can use to synchronously wait on the operation completion * and outcome. The optional is empty if the task was not scheduled (because the service is not running). */ Optional<ScheduledFuture<?>> forceServerSync(); }
2,980
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/AgentHeartBeatService.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; import javax.validation.constraints.NotBlank; /** * Service that maintains an active connection with a Genie server node by sending heart beats. * The agent messages are tagged with the job id this agent claimed and is executing. * * @author mprimi * @since 4.0.0 */ public interface AgentHeartBeatService { /** * Starts the service. * * @param claimedJobId the job id claimed by this agent */ void start(@NotBlank String claimedJobId); /** * Stop the service. */ void stop(); /** * Whether the agent is currently connected to a Genie node server. * * @return true if the agent has an active, working connection with a Genie server node. */ boolean isConnected(); }
2,981
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/DownloadService.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; import com.netflix.genie.agent.execution.exceptions.DownloadException; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nullable; import java.io.File; import java.net.URI; import java.util.Set; /** * Service to download a set of files to local disk. * * @author mprimi * @since 4.0.0 */ public interface DownloadService { /** * Get a new manifest builder. * * @return a new builder */ Manifest.Builder newManifestBuilder(); /** * Download all files as per provided manifest. * The destination directories present in the manifest are expected to exist. * Existing files will not be overwritten. * * @param downloadsManifest a download manifest * @throws DownloadException if at least one of the downloads fails */ void download(Manifest downloadsManifest) throws DownloadException; /** * Manifest containing source (URIs) and their expected destination on disk after download. * This abstraction is used by different services to set up the job working directory. * <p> * Currently, source URIs must be unique. I.e. it is not possible to have a manifest with the same source * URI and two or more target destinations. */ interface Manifest { /** * Get the set of files representing expected target location for files to be downloaded. * * @return an immutable set of files objects */ Set<File> getTargetFiles(); /** * Get the set of directories that contain all the target files. * * @return an immutable set of file objects */ Set<File> getTargetDirectories(); /** * Get the set of URI s (source files) that were added to the manifest. * * @return an immutable set of URIs */ Set<URI> getSourceFileUris(); /** * Get the manifest entries. * * @return an immutable set of entries in this manifest */ Set<Pair<URI, File>> getEntries(); /** * Return the target location for a given source URI. * * @param sourceFileUri source file URI * @return a File target, or null if the source is not in the manifest */ @Nullable File getTargetLocation(URI sourceFileUri); /** * Builder for Manifest. */ interface Builder { /** * Add a source file specifying a target directory. * The filename for the target is computed by using the last component of the resource path. * * @param sourceFileUri source URISi * @param targetDirectory target directory * @return a builder for chaining */ DownloadService.Manifest.Builder addFileWithTargetDirectory( URI sourceFileUri, File targetDirectory ); /** * Add a source file specifying a target file destination. * * @param sourceFileUri source URI * @param targetFile target file * @return a builder for chaining */ Builder addFileWithTargetFile( URI sourceFileUri, File targetFile ); /** * Build the manifest. * * @return the manifest * @throws IllegalArgumentException if two or more source URIs point to the same target file */ Manifest build(); } } }
2,982
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/JobSetupService.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.execution.services; import com.netflix.genie.agent.execution.CleanupStrategy; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; import com.netflix.genie.common.internal.dtos.JobSpecification; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Set; /** * Service that sets up a directory for a job to execute in. * The setup is broken into 3 stages so that they can be interleaved with other actions. * 1. Create the empty folder structure * 2. Download dependencies and other files in place * 3. Evaluate setup scripts and create the job environment. * This service also performs cleanup of said job directory. * * @author mprimi * @since 4.0.0 */ public interface JobSetupService { /** * Creates a directory for the given job. * Also creates the sub-directories structure common to all jobs. * * @param jobSpecification the job specification * @return the job folder just created * @throws SetUpJobException if the folder (or sub-folders) could not be created or already existed */ File createJobDirectory( JobSpecification jobSpecification ) throws SetUpJobException; /** * Downloads and stages all the job files (dependencies, configurations, ...) into the job directory. * * @param jobSpecification the job specification * @param jobDirectory the job folder * @return the list of setup files staged * @throws SetUpJobException TODO */ Set<File> downloadJobResources( JobSpecification jobSpecification, File jobDirectory ) throws SetUpJobException; /** * Creates the executable script that executes setup and runs the job (a.k.a. run file). * * @param jobSpecification the job specification * @param jobDirectory the job directory * @return the generated executable script file * @throws SetUpJobException if the file cannot be created */ File createJobScript( JobSpecification jobSpecification, File jobDirectory ) throws SetUpJobException; /** * Performs post-execution cleanup of the job directory. * * @param jobDirectory the job directory path * @param cleanupStrategy the cleanup strategy * @throws IOException TODO */ void cleanupJobDirectory( Path jobDirectory, CleanupStrategy cleanupStrategy ) throws IOException; }
2,983
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/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. * */ /** * Services used during job execution components. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.services; import javax.annotation.ParametersAreNonnullByDefault;
2,984
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/JobMonitorService.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; import java.nio.file.Path; /** * Service that monitors the job directory and may decide to kill the job if some limit is exceeded. * For example, if a file grows larger than some amount. * * @author mprimi * @since 4.0.0 */ public interface JobMonitorService { /** * Starts the service. * * @param jobId the job id * @param jobDirectory the job directory */ void start(String jobId, Path jobDirectory); /** * Stop the service. */ void stop(); }
2,985
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/AgentJobService.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; import com.netflix.genie.agent.execution.exceptions.ChangeJobArchiveStatusException; import com.netflix.genie.agent.execution.exceptions.ChangeJobStatusException; import com.netflix.genie.agent.execution.exceptions.ConfigureException; import com.netflix.genie.agent.execution.exceptions.GetJobStatusException; import com.netflix.genie.agent.execution.exceptions.HandshakeException; import com.netflix.genie.agent.execution.exceptions.JobIdUnavailableException; import com.netflix.genie.agent.execution.exceptions.JobReservationException; import com.netflix.genie.agent.execution.exceptions.JobSpecificationResolutionException; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.Map; /** * Agent side job specification service for resolving and retrieving job specifications from the server. * * @author tgianos * @since 4.0.0 */ @Validated public interface AgentJobService { /** * Perform server handshake. Before going any further, ensure the server is reachable and that this agent is * compatible with it. * * @param agentClientMetadata metadata about the client making this request * @throws HandshakeException if the server rejects this client */ void handshake( @Valid AgentClientMetadata agentClientMetadata ) throws HandshakeException; /** * Obtain server-provided configuration properties. * * @param agentClientMetadata metadata about the client making this request * @return a map of properties * @throws ConfigureException if the server properties cannot be obtained */ Map<String, String> configure( @Valid AgentClientMetadata agentClientMetadata ) throws ConfigureException; /** * Request a given job id to be reserved for this job, send along the job details, to be persisted by the server. * The request may or may not contain a job id. * * @param jobRequest the job parameters and agent metadata * @param agentClientMetadata metadata about the client making this request * @return the job id assigned by the server (matches the one in the request, if one was present) * @throws JobReservationException if the server failed to fulfill this request * @throws JobIdUnavailableException if the id requested has already been used */ String reserveJobId( @Valid AgentJobRequest jobRequest, @Valid AgentClientMetadata agentClientMetadata ) throws JobReservationException, JobIdUnavailableException; /** * Given the parameters supplied by the job request attempt to resolve a job specification on the server. * * @param id The id of the job to resolve a job specification for * @return The job specification * @throws JobSpecificationResolutionException if the specification cannot be resolved */ JobSpecification resolveJobSpecification( @NotBlank String id ) throws JobSpecificationResolutionException; /** * Given a job id retrieve the job specification from the server. * * @param id The id of the job to get the specification for * @return The job specification * @throws JobSpecificationResolutionException if the specification cannot be retrieved */ JobSpecification getJobSpecification( @NotBlank String id ) throws JobSpecificationResolutionException; /** * Invoke the job specification resolution logic without persisting anything on the server. * * @param jobRequest The various parameters required to perform the dry run should be contained in this request * @return The job specification * @throws JobSpecificationResolutionException When an error occurred during attempted resolution */ JobSpecification resolveJobSpecificationDryRun( @Valid AgentJobRequest jobRequest ) throws JobSpecificationResolutionException; /** * Claim a given job, telling the server that this agent is about to begin execution. * * @param jobId the id of the job * @param agentClientMetadata metadata for the agent claiming this job * @throws JobReservationException When the the claim request fails is invalid (reasons include: job already * claimed, invalid job ID, failure to reach the server */ void claimJob( @NotBlank String jobId, @Valid AgentClientMetadata agentClientMetadata ) throws JobReservationException; /** * Notify the server of a change of job status. * * @param jobId the id of the job * @param currentJobStatus the expected current status of the job * @param newJobStatus the new status of the job * @param message an optional message tha accompanies this change of status * @throws ChangeJobStatusException when the agent fails to update the job status */ void changeJobStatus( @NotBlank String jobId, JobStatus currentJobStatus, JobStatus newJobStatus, String message ) throws ChangeJobStatusException; /** * Retrieve the current job status for the given job id. * * @param jobId the id of the job * @return the job status seen by the server * @throws GetJobStatusException when the agent fails to retrieve the job status */ JobStatus getJobStatus( @NotBlank String jobId ) throws GetJobStatusException; /** * Notify the server of a change of job files archive status. * * @param jobId the id of the job * @param archiveStatus the new archive status of the job * @throws ChangeJobArchiveStatusException when the agent fails to update the job archive status */ void changeJobArchiveStatus( @NotBlank String jobId, ArchiveStatus archiveStatus ) throws ChangeJobArchiveStatusException; }
2,986
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/DownloadServiceImpl.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.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.agent.execution.exceptions.DownloadException; import com.netflix.genie.agent.execution.services.DownloadService; import com.netflix.genie.agent.execution.services.FetchingCacheService; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Cache-backed download service to retrieve a set of files and place them at an expected location, according * to a given manifest. * * @author mprimi * @since 4.0.0 */ @Slf4j class DownloadServiceImpl implements DownloadService { private final FetchingCacheService fetchingCacheService; DownloadServiceImpl(final FetchingCacheService fetchingCacheService) { this.fetchingCacheService = fetchingCacheService; } /** * {@inheritDoc} */ @Override public Manifest.Builder newManifestBuilder() { return new ManifestImpl.Builder(); } /** * {@inheritDoc} */ @Override public void download(final Manifest downloadsManifest) throws DownloadException { // Validate all destination directories exist for (final File targetDirectory : downloadsManifest.getTargetDirectories()) { if (!targetDirectory.exists()) { throw new DownloadException( "Target directory does not exist: " + targetDirectory.getAbsolutePath() ); } else if (!targetDirectory.isDirectory()) { throw new DownloadException( "Target directory is not a directory: " + targetDirectory.getAbsolutePath() ); } } // Validate all target files don't exist for (final File targetFile : downloadsManifest.getTargetFiles()) { if (targetFile.exists()) { throw new DownloadException("Target file exists: " + targetFile.getAbsolutePath()); } } try { fetchingCacheService.get(downloadsManifest.getEntries()); } catch (final IOException e) { throw new DownloadException("Failed to download", e); } } @Getter private static final class ManifestImpl implements Manifest { private final Map<URI, File> uriFileMap; private final Set<File> targetDirectories; private final Set<File> targetFiles; private final Set<URI> sourceFileUris; private final Set<Pair<URI, File>> entries; private ManifestImpl(final Map<URI, File> uriFileMap) { this.uriFileMap = Collections.unmodifiableMap(uriFileMap); this.targetDirectories = Collections.unmodifiableSet( uriFileMap .values() .stream() .map(File::getParentFile) .collect(Collectors.toSet()) ); this.targetFiles = Collections.unmodifiableSet( Sets.newHashSet(uriFileMap.values()) ); if (targetFiles.size() < uriFileMap.values().size()) { throw new IllegalArgumentException("Two or more files are targeting the same destination location"); } this.sourceFileUris = Collections.unmodifiableSet(uriFileMap.keySet()); this.entries = Collections.unmodifiableSet( uriFileMap.entrySet() .stream() .map(entry -> new ImmutablePair<>(entry.getKey(), entry.getValue())) .collect(Collectors.toSet()) ); } /** * {@inheritDoc} */ @Nullable @Override public File getTargetLocation(final URI sourceFileUri) { return uriFileMap.get(sourceFileUri); } private static final class Builder implements Manifest.Builder { private final Map<URI, File> filesMap; Builder() { this.filesMap = Maps.newHashMap(); } /** * {@inheritDoc} */ @Override public Builder addFileWithTargetDirectory( final URI sourceFileUri, final File targetDirectory ) { final String uriPath = sourceFileUri.getPath(); if (StringUtils.isBlank(uriPath)) { throw new IllegalArgumentException("Uri has empty path: " + sourceFileUri); } final String filename = new File(uriPath).getName(); if (StringUtils.isBlank(filename)) { throw new IllegalArgumentException("Could not determine filename for source: " + sourceFileUri); } final File targetFile = new File(targetDirectory, filename); return addFileWithTargetFile(sourceFileUri, targetFile); } /** * {@inheritDoc} */ @Override public Builder addFileWithTargetFile( final URI sourceFileUri, final File targetFile ) { filesMap.put(sourceFileUri, targetFile); return this; } /** * {@inheritDoc} */ @Override public Manifest build() { return new ManifestImpl(filesMap); } } } }
2,987
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/KillServiceImpl.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.google.common.annotations.VisibleForTesting; import com.netflix.genie.agent.cli.ExitCode; 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.properties.AgentProperties; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; /** * Implementation of {@link KillService}. * * @author standon * @since 4.0.0 */ @Slf4j class KillServiceImpl implements KillService { private final ExecutionContext executionContext; private final AgentProperties agentProperties; private final ThreadFactory threadFactory; private final AtomicBoolean killed = new AtomicBoolean(false); KillServiceImpl(final ExecutionContext executionContext, final AgentProperties agentProperties) { this( executionContext, agentProperties, Thread::new ); } @VisibleForTesting KillServiceImpl( final ExecutionContext executionContext, final AgentProperties agentProperties, final ThreadFactory threadFactory ) { this.executionContext = executionContext; this.agentProperties = agentProperties; this.threadFactory = threadFactory; } /** * {@inheritDoc} */ @Override public void kill(final KillSource killSource) { if (this.killed.compareAndSet(false, true)) { ConsoleLog.getLogger().info("Job kill requested (source: {})", killSource.name()); this.executionContext.getStateMachine().kill(killSource); this.threadFactory.newThread(this::emergencyStop).start(); } } /** * This task is launched when a call to kill() is received. * It's extra insurance that the JVM eventually will shut down. * Hopefully, execution terminates due to regular shutdown procedures before this mechanism kicks-in. */ @SuppressFBWarnings("DM_EXIT") // For calling System.exit private void emergencyStop() { try { Thread.sleep(this.agentProperties.getEmergencyShutdownDelay().toMillis()); } catch (InterruptedException e) { log.warn("Emergency shutdown thread interrupted"); } System.exit(ExitCode.EXEC_ABORTED.getCode()); } }
2,988
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/JobMonitorServiceImpl.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.execution.exceptions.GetJobStatusException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.agent.execution.services.JobMonitorService; import com.netflix.genie.agent.execution.services.KillService; import com.netflix.genie.agent.properties.AgentProperties; import com.netflix.genie.agent.properties.JobMonitorServiceProperties; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.TaskScheduler; import org.springframework.util.unit.DataSize; import java.io.IOException; import java.nio.file.Path; import java.util.Comparator; import java.util.Optional; import java.util.concurrent.ScheduledFuture; /** * Implementation of {@link JobMonitorService} that periodically checks on the size and number of files * using the manifest creator, rather than looking at the actual files. * This implementation is not thread safe. * * @author mprimi * @since 4.0.0 */ @Slf4j class JobMonitorServiceImpl implements JobMonitorService { private final KillService killService; private final JobDirectoryManifestCreatorService manifestCreatorService; private final AgentJobService agentJobService; private final TaskScheduler taskScheduler; private final JobMonitorServiceProperties properties; private ScheduledFuture<?> scheduledCheck; JobMonitorServiceImpl( final KillService killService, final JobDirectoryManifestCreatorService manifestCreatorService, final AgentJobService agentJobService, final TaskScheduler taskScheduler, final AgentProperties agentProperties ) { this.killService = killService; this.manifestCreatorService = manifestCreatorService; this.agentJobService = agentJobService; this.taskScheduler = taskScheduler; this.properties = agentProperties.getJobMonitorService(); } @Override public void start(final String jobId, final Path jobDirectory) { this.scheduledCheck = this.taskScheduler.scheduleAtFixedRate( () -> this.check(jobId, jobDirectory), this.properties.getCheckInterval() ); } @Override public void stop() { if (this.scheduledCheck != null) { this.scheduledCheck.cancel(true); } } private void check(final String jobId, final Path jobDirectory) { if (this.checkFileLimits(jobDirectory)) { this.killService.kill(KillService.KillSource.FILES_LIMIT); } else if (this.checkRemoteJobStatus(jobId)) { this.killService.kill(KillService.KillSource.REMOTE_STATUS_MONITOR); } } private boolean checkFileLimits(final Path jobDirectory) { final DirectoryManifest manifest; try { manifest = this.manifestCreatorService.getDirectoryManifest(jobDirectory); } catch (IOException e) { log.warn("Failed to obtain manifest: {}" + e.getMessage()); return false; } final int files = manifest.getNumFiles(); final int maxFiles = this.properties.getMaxFiles(); if (files > maxFiles) { log.error("Limit exceeded, too many files: {}/{}", files, maxFiles); return true; } final DataSize totalSize = DataSize.ofBytes(manifest.getTotalSizeOfFiles()); final DataSize maxTotalSize = this.properties.getMaxTotalSize(); if (totalSize.toBytes() > maxTotalSize.toBytes()) { log.error("Limit exceeded, job directory too large: {}/{}", totalSize, maxTotalSize); return true; } final Optional<DirectoryManifest.ManifestEntry> largestFile = manifest.getFiles() .stream() .max(Comparator.comparing(DirectoryManifest.ManifestEntry::getSize)); if (largestFile.isPresent()) { final DataSize largestFileSize = DataSize.ofBytes(largestFile.get().getSize()); final DataSize maxFileSize = this.properties.getMaxFileSize(); if (largestFileSize.toBytes() > maxFileSize.toBytes()) { log.error( "Limit exceeded, file too large: {}/{} ({})", largestFileSize, maxFileSize, largestFile.get().getPath() ); return true; } } log.debug("No files limit exceeded"); return false; } private boolean checkRemoteJobStatus(final String jobId) { if (!this.properties.getCheckRemoteJobStatus()) { // Ignore remote status. Can be useful for session-type jobs that should be kept alive even if leader // marked them failed return false; } final JobStatus jobStatus; try { jobStatus = this.agentJobService.getJobStatus(jobId); } catch (GetJobStatusException | GenieRuntimeException e) { log.error("Failed to retrieve job status: {}", e.getMessage(), e); return false; } // While this service is running, the job status should be RUNNING. // Any other status implies a server-side update (probably the leader marking the job failed). if (jobStatus != JobStatus.RUNNING) { log.error("Remote job status changed to: {}", jobStatus); return true; } log.debug("Job status is still RUNNING"); return false; } }
2,989
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/JobSetupServiceImpl.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.execution.services.impl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Lists; import com.netflix.genie.agent.execution.CleanupStrategy; import com.netflix.genie.agent.execution.exceptions.DownloadException; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; import com.netflix.genie.agent.execution.services.DownloadService; import com.netflix.genie.agent.execution.services.JobSetupService; import com.netflix.genie.agent.properties.AgentProperties; import com.netflix.genie.agent.properties.JobSetupServiceProperties; import com.netflix.genie.agent.utils.PathUtils; import com.netflix.genie.common.internal.dtos.ExecutionEnvironment; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.jobs.JobConstants; import com.netflix.genie.common.internal.util.RegexRuleSet; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import org.springframework.util.FileSystemUtils; import java.io.File; import java.io.IOException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; @Slf4j class JobSetupServiceImpl implements JobSetupService { private static final String NEWLINE = System.lineSeparator(); private final DownloadService downloadService; private final JobSetupServiceProperties jobSetupProperties; JobSetupServiceImpl( final DownloadService downloadService, final AgentProperties agentProperties ) { this.downloadService = downloadService; this.jobSetupProperties = agentProperties.getJobSetupService(); } /** * {@inheritDoc} */ @Override public File createJobDirectory(final JobSpecification jobSpecification) throws SetUpJobException { final File jobDirectory = new File( jobSpecification.getJobDirectoryLocation(), jobSpecification.getJob().getId() ); // Create parent folders separately try { Files.createDirectories(jobDirectory.getParentFile().toPath()); } catch (final IOException e) { throw new SetUpJobException("Failed to create jobs directory", e); } // Create the job folder, this call throws if the directory already exists try { Files.createDirectory(jobDirectory.toPath()); } catch (final IOException e) { throw new SetUpJobException("Failed to create job directory", e); } // Get DTOs final List<JobSpecification.ExecutionResource> applications = jobSpecification.getApplications(); final JobSpecification.ExecutionResource cluster = jobSpecification.getCluster(); final JobSpecification.ExecutionResource command = jobSpecification.getCommand(); // Make a list of all entity dirs final List<Path> entityDirectories = Lists.newArrayList( PathUtils.jobClusterDirectoryPath(jobDirectory, cluster.getId()), PathUtils.jobCommandDirectoryPath(jobDirectory, command.getId()) ); applications.stream() .map(JobSpecification.ExecutionResource::getId) .map(appId -> PathUtils.jobApplicationDirectoryPath(jobDirectory, appId)) .forEach(entityDirectories::add); // Make a list of directories to create // (only "leaf" paths, since createDirectories creates missing intermediate dirs final List<Path> directoriesToCreate = Lists.newArrayList(); // Add config and dependencies for each entity entityDirectories.forEach( entityDirectory -> { directoriesToCreate.add(PathUtils.jobEntityDependenciesPath(entityDirectory)); directoriesToCreate.add(PathUtils.jobEntityConfigPath(entityDirectory)); } ); // Add logs dir directoriesToCreate.add(PathUtils.jobGenieLogsDirectoryPath(jobDirectory)); // Create directories for (final Path path : directoriesToCreate) { try { Files.createDirectories(path); } catch (final Exception e) { throw new SetUpJobException("Failed to create directory: " + path, e); } } return jobDirectory; } /** * {@inheritDoc} * * @return */ @Override public Set<File> downloadJobResources( final JobSpecification jobSpecification, final File jobDirectory ) throws SetUpJobException { // Create download manifest for dependencies, configs, setup files for cluster, applications, command, job final DownloadService.Manifest jobDownloadsManifest = createDownloadManifest(jobDirectory, jobSpecification); // Download all files into place try { this.downloadService.download(jobDownloadsManifest); } catch (final DownloadException e) { throw new SetUpJobException("Failed to download job dependencies", e); } return jobDownloadsManifest.getTargetFiles(); } /** * {@inheritDoc} */ @Override public File createJobScript( final JobSpecification jobSpecification, final File jobDirectory ) throws SetUpJobException { final Path scriptPath = PathUtils.jobScriptPath(jobDirectory); final File scriptFile = scriptPath.toFile(); try { // Write the script try ( Writer fileWriter = Files.newBufferedWriter( scriptPath, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.SYNC, StandardOpenOption.DSYNC ) ) { fileWriter.write( new JobScriptComposer(jobSpecification, jobDirectory) .composeScript(this.jobSetupProperties) ); fileWriter.flush(); } // Set script permissions final boolean permissionChangeSuccess = scriptFile.setExecutable(true); if (!permissionChangeSuccess) { throw new SetUpJobException("Could not set job script executable permission"); } return scriptFile; } catch (SecurityException | IOException e) { throw new SetUpJobException("Failed to create job script: " + e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public void cleanupJobDirectory( final Path jobDirectoryPath, final CleanupStrategy cleanupStrategy ) throws IOException { switch (cleanupStrategy) { case NO_CLEANUP: log.info("Skipping cleanup of job directory: {}", jobDirectoryPath); break; case FULL_CLEANUP: log.info("Wiping job directory: {}", jobDirectoryPath); FileSystemUtils.deleteRecursively(jobDirectoryPath); break; case DEPENDENCIES_CLEANUP: final RegexRuleSet cleanupWhitelist = RegexRuleSet.buildWhitelist( Lists.newArrayList( PathUtils.jobClusterDirectoryPath(jobDirectoryPath.toFile(), ".*"), PathUtils.jobCommandDirectoryPath(jobDirectoryPath.toFile(), ".*"), PathUtils.jobApplicationDirectoryPath(jobDirectoryPath.toFile(), ".*") ) .stream() .map(PathUtils::jobEntityDependenciesPath) .map(Path::toString) .map(pathString -> pathString + "/.*") .map(Pattern::compile) .toArray(Pattern[]::new) ); Files.walk(jobDirectoryPath) .filter(path -> cleanupWhitelist.accept(path.toAbsolutePath().toString())) .forEach(path -> { try { log.debug("Deleting {}", path); FileSystemUtils.deleteRecursively(path); } catch (final IOException e) { log.warn("Failed to delete: {}", path.toAbsolutePath().toString(), e); } }); break; default: throw new RuntimeException("Unknown cleanup strategy: " + cleanupStrategy.name()); } } private DownloadService.Manifest createDownloadManifest( final File jobDirectory, final JobSpecification jobSpec ) throws SetUpJobException { // Construct map of files to download and their expected locations in the job directory final DownloadService.Manifest.Builder downloadManifestBuilder = downloadService.newManifestBuilder(); // Applications final List<JobSpecification.ExecutionResource> applications = jobSpec.getApplications(); for (final JobSpecification.ExecutionResource application : applications) { final Path applicationDirectory = PathUtils.jobApplicationDirectoryPath(jobDirectory, application.getId()); addEntitiesFilesToManifest(applicationDirectory, downloadManifestBuilder, application); } // Cluster final JobSpecification.ExecutionResource cluster = jobSpec.getCluster(); final String clusterId = cluster.getId(); final Path clusterDirectory = PathUtils.jobClusterDirectoryPath(jobDirectory, clusterId); addEntitiesFilesToManifest(clusterDirectory, downloadManifestBuilder, cluster); // Command final JobSpecification.ExecutionResource command = jobSpec.getCommand(); final String commandId = command.getId(); final Path commandDirectory = PathUtils.jobCommandDirectoryPath(jobDirectory, commandId); addEntitiesFilesToManifest(commandDirectory, downloadManifestBuilder, command); // Job (does not follow convention, downloads everything in the job root folder). try { final Path jobDirectoryPath = jobDirectory.toPath(); final ExecutionEnvironment jobExecEnvironment = jobSpec.getJob().getExecutionEnvironment(); if (jobExecEnvironment.getSetupFile().isPresent()) { final URI setupFileUri = new URI(jobExecEnvironment.getSetupFile().get()); log.debug( "Adding setup file to download manifest: {} -> {}", setupFileUri, jobDirectoryPath ); downloadManifestBuilder.addFileWithTargetFile( setupFileUri, PathUtils.jobEntitySetupFilePath(jobDirectoryPath).toFile() ); } for (final String dependencyUriString : jobExecEnvironment.getDependencies()) { log.debug( "Adding dependency to download manifest: {} -> {}", dependencyUriString, jobDirectoryPath ); downloadManifestBuilder.addFileWithTargetDirectory( new URI(dependencyUriString), jobDirectory ); } for (final String configUriString : jobExecEnvironment.getConfigs()) { log.debug( "Adding config file to download manifest: {} -> {}", configUriString, jobDirectoryPath ); downloadManifestBuilder.addFileWithTargetDirectory( new URI(configUriString), jobDirectory ); } } catch (final URISyntaxException e) { throw new SetUpJobException("Failed to compose download manifest", e); } // Build manifest return downloadManifestBuilder.build(); } private void addEntitiesFilesToManifest( final Path entityLocalDirectory, final DownloadService.Manifest.Builder downloadManifestBuilder, final JobSpecification.ExecutionResource executionResource ) throws SetUpJobException { try { final ExecutionEnvironment resourceExecutionEnvironment = executionResource.getExecutionEnvironment(); if (resourceExecutionEnvironment.getSetupFile().isPresent()) { final URI setupFileUri = new URI(resourceExecutionEnvironment.getSetupFile().get()); log.debug( "Adding setup file to download manifest: {} -> {}", setupFileUri, entityLocalDirectory ); downloadManifestBuilder.addFileWithTargetFile( setupFileUri, PathUtils.jobEntitySetupFilePath(entityLocalDirectory).toFile() ); } final Path entityDependenciesLocalDirectory = PathUtils.jobEntityDependenciesPath(entityLocalDirectory); for (final String dependencyUriString : resourceExecutionEnvironment.getDependencies()) { log.debug( "Adding dependency to download manifest: {} -> {}", dependencyUriString, entityDependenciesLocalDirectory ); downloadManifestBuilder.addFileWithTargetDirectory( new URI(dependencyUriString), entityDependenciesLocalDirectory.toFile() ); } final Path entityConfigsDirectory = PathUtils.jobEntityConfigPath(entityLocalDirectory); for (final String configUriString : resourceExecutionEnvironment.getConfigs()) { log.debug( "Adding config file to download manifest: {} -> {}", configUriString, entityConfigsDirectory ); downloadManifestBuilder.addFileWithTargetDirectory( new URI(configUriString), entityConfigsDirectory.toFile() ); } } catch (final URISyntaxException e) { throw new SetUpJobException("Failed to compose download manifest", e); } } private static class JobScriptComposer { private static final String SETUP_LOG_ENV_VAR = "__GENIE_SETUP_LOG_FILE"; private static final String ENVIRONMENT_LOG_ENV_VAR = "__GENIE_ENVIRONMENT_DUMP_FILE"; private static final String SETUP_ERROR_FILE_ENV_VAR = "__GENIE_SETUP_ERROR_MARKER_FILE"; private static final String TO_STD_ERR = " >&2"; private static final List<String> TRAPPED_SIGNALS = Lists.newArrayList("SIGTERM", "SIGINT", "SIGHUP"); private static final String GREP_INVERT_MATCH = "--invert-match "; private final String jobId; private final List<Pair<String, String>> setupFileReferences; private final String commandLine; private final List<Pair<String, String>> localEnvironmentVariables; private final List<Pair<String, String>> serverEnvironmentVariables; JobScriptComposer( final JobSpecification jobSpecification, final File jobDirectory ) { this.jobId = jobSpecification.getJob().getId(); // Reference all files in the script in form: "${GENIE_JOB_DIR}/...". // This makes the script easier to relocate (easier to run, re-run on a different system/location). final Path jobDirectoryPath = jobDirectory.toPath().toAbsolutePath(); final String jobSetupLogReference = getPathAsReference( PathUtils.jobSetupLogFilePath(jobDirectory), jobDirectoryPath ); final String jobEnvironmentLogReference = getPathAsReference( PathUtils.jobEnvironmentLogFilePath(jobDirectory), jobDirectoryPath ); final String applicationsDirReference = this.getPathAsReference( PathUtils.jobApplicationsDirectoryPath(jobDirectory), jobDirectoryPath ); final JobSpecification.ExecutionResource cluster = jobSpecification.getCluster(); final String clusterId = cluster.getId(); final Path clusterDirPath = PathUtils.jobClusterDirectoryPath(jobDirectory, clusterId); final String clusterDirReference = this.getPathAsReference(clusterDirPath, jobDirectoryPath); final JobSpecification.ExecutionResource command = jobSpecification.getCommand(); final String commandId = command.getId(); final Path commandDirPath = PathUtils.jobCommandDirectoryPath(jobDirectory, commandId); final String commandDirReference = this.getPathAsReference(commandDirPath, jobDirectoryPath); final String setupErrorFileReference = this.getPathAsReference( PathUtils.jobSetupErrorMarkerFilePath(jobDirectory), jobDirectoryPath ); // Set environment variables generated here this.localEnvironmentVariables = ImmutableList.<Pair<String, String>>builder() .add(ImmutablePair.of(JobConstants.GENIE_JOB_DIR_ENV_VAR, jobDirectoryPath.toString())) .add(ImmutablePair.of(JobConstants.GENIE_APPLICATION_DIR_ENV_VAR, applicationsDirReference)) .add(ImmutablePair.of(JobConstants.GENIE_COMMAND_DIR_ENV_VAR, commandDirReference)) .add(ImmutablePair.of(JobConstants.GENIE_CLUSTER_DIR_ENV_VAR, clusterDirReference)) .add(ImmutablePair.of(SETUP_LOG_ENV_VAR, jobSetupLogReference)) .add(ImmutablePair.of(ENVIRONMENT_LOG_ENV_VAR, jobEnvironmentLogReference)) .add(ImmutablePair.of(SETUP_ERROR_FILE_ENV_VAR, setupErrorFileReference)) .build(); // And add the rest which come down from the server. (Sorted for determinism) this.serverEnvironmentVariables = ImmutableSortedMap.copyOf(jobSpecification.getEnvironmentVariables()) .entrySet() .stream() .map(entry -> ImmutablePair.of(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); // Compose list of execution resources final List<Triple<String, JobSpecification.ExecutionResource, Path>> executionResources = Lists.newArrayList(); executionResources.add( ImmutableTriple.of("cluster", cluster, PathUtils.jobClusterDirectoryPath(jobDirectory, clusterId)) ); jobSpecification.getApplications().forEach( application -> executionResources.add( ImmutableTriple.of( "application", application, PathUtils.jobApplicationDirectoryPath(jobDirectory, application.getId()) ) ) ); executionResources.add( ImmutableTriple.of("command", command, PathUtils.jobCommandDirectoryPath(jobDirectory, commandId)) ); executionResources.add( ImmutableTriple.of("job", jobSpecification.getJob(), jobDirectoryPath) ); // Transform execution resources list to description and file reference list this.setupFileReferences = executionResources.stream() .map( triple -> { final String resourceTypeString = triple.getLeft(); final JobSpecification.ExecutionResource resource = triple.getMiddle(); final String setupFileReference; if (resource.getExecutionEnvironment().getSetupFile().isPresent()) { final Path resourceDirectory = triple.getRight(); final Path setupFilePath = PathUtils.jobEntitySetupFilePath(resourceDirectory); setupFileReference = getPathAsReference(setupFilePath, jobDirectoryPath); } else { setupFileReference = null; } final String resourceDescription = resourceTypeString + " " + resource.getId(); return ImmutablePair.of(resourceDescription, setupFileReference); } ) .collect(Collectors.toList()); // Compose the final command-line this.commandLine = StringUtils.join( ImmutableList.builder() .addAll(jobSpecification.getExecutableArgs()) .addAll(jobSpecification.getJobArgs()) .build(), " " ); } // Transform an absolute path to a string that references $GENIE_JOB_DIR/... private String getPathAsReference(final Path path, final Path jobDirectoryPath) { final Path relativePath = jobDirectoryPath.relativize(path); return "${" + JobConstants.GENIE_JOB_DIR_ENV_VAR + "}/" + relativePath; } String composeScript(final JobSetupServiceProperties jobSetupProperties) { // Assemble the content of the script final StringBuilder sb = new StringBuilder(); // Script Header Section sb .append("#!/usr/bin/env bash").append(NEWLINE) .append(NEWLINE); sb .append("#").append(NEWLINE) .append("# Generated by Genie for job: ").append(this.jobId).append(NEWLINE) .append("#").append(NEWLINE) .append(NEWLINE); sb .append("# Error out if any command fails").append(NEWLINE) .append("set -o errexit").append(NEWLINE) .append("# Error out if any command in a pipeline fails").append(NEWLINE) .append("set -o pipefail").append(NEWLINE) .append("# Error out if unknown variable is used").append(NEWLINE) .append("set -o nounset").append(NEWLINE) .append("# Save original stdout and stderr in fd 6 and 7").append(NEWLINE) .append("exec 6>&1").append(NEWLINE) .append("exec 7>&2").append(NEWLINE) .append(NEWLINE); sb.append(NEWLINE); // Script Signal Handling Section sb .append("# Trap exit signals to ensure children processes are dead before returning").append(NEWLINE) .append("function handle_kill_request {").append(NEWLINE) .append(" echo \"Handling $1 signal\"").append(TO_STD_ERR).append(NEWLINE) .append(" # Update trap").append(NEWLINE) .append(" trap wait ").append(String.join(" ", TRAPPED_SIGNALS)).append(NEWLINE) .append(" # Send SIGTERM to all children").append(NEWLINE) .append(" pkill -P $$ || true").append(NEWLINE) .append(" for ((iteration=1; iteration < 30; iteration++))").append(NEWLINE) .append(" {").append(NEWLINE) .append(" if pkill -0 -P $$ &> /dev/null;").append(NEWLINE) .append(" then").append(NEWLINE) .append(" echo \"Waiting for children to terminate\"").append(TO_STD_ERR).append(NEWLINE) .append(" sleep 1").append(NEWLINE) .append(" else").append(NEWLINE) .append(" echo \"All children terminated\"").append(TO_STD_ERR).append(NEWLINE) .append(" exit 1").append(NEWLINE) .append(" fi").append(NEWLINE) .append(" }").append(NEWLINE) .append(" # Reaching this point means the children did not die. Kill with SIGKILL").append(NEWLINE) .append(" echo \"Terminating all children with SIGKILL\"").append(TO_STD_ERR).append(NEWLINE) .append(" pkill -9 -P $$").append(NEWLINE) .append("}").append(NEWLINE); for (final String signal : TRAPPED_SIGNALS) { sb.append("trap 'handle_kill_request ").append(signal).append("' ").append(signal).append(NEWLINE); } sb.append(NEWLINE); // Script Local environment Section sb.append("# Locally-generated environment variables").append(NEWLINE); sb.append(NEWLINE); this.localEnvironmentVariables.forEach( envVar -> sb .append("export ") .append(envVar.getKey()) .append("=\"") .append(envVar.getValue()) .append("\"") .append(NEWLINE) .append(NEWLINE) ); sb.append(NEWLINE); sb .append("# Mark the beginnig of the setup by creating a marker file").append(NEWLINE) .append("echo \"The job script failed during setup. ") .append("See ${").append(SETUP_LOG_ENV_VAR).append("} for details\" ") .append("> ${").append(SETUP_ERROR_FILE_ENV_VAR).append("}") .append(NEWLINE); sb.append(NEWLINE); sb .append("# During setup, redirect stdout and stderr of this script to a log file").append(NEWLINE) .append("exec > ${__GENIE_SETUP_LOG_FILE}").append(NEWLINE) .append("exec 2>&1").append(NEWLINE); sb.append(NEWLINE); // Script Setup Section sb .append("echo \"Setup start: $(date '+%Y-%m-%d %H:%M:%S')\"") .append(NEWLINE); sb.append(NEWLINE); sb.append("# Server-provided environment variables").append(NEWLINE); sb.append(NEWLINE); this.serverEnvironmentVariables.forEach( envVar -> sb .append("export ") .append(envVar.getKey()) .append("=\"") .append(envVar.getValue()) .append("\"") .append(NEWLINE) .append(NEWLINE) ); sb.append(NEWLINE); this.setupFileReferences.forEach( pair -> { final String resourceDescription = pair.getLeft(); final String setupFileReference = pair.getRight(); if (setupFileReference != null) { sb .append("echo \"Sourcing setup script for ") .append(resourceDescription) .append("\"") .append(NEWLINE) .append("source ") .append(setupFileReference) .append(NEWLINE); } else { sb .append("echo \"No setup script for ") .append(resourceDescription) .append("\"") .append(NEWLINE); } sb.append(NEWLINE); } ); sb.append(NEWLINE); sb .append("echo \"Setup end: $(date '+%Y-%m-%d %H:%M:%S')\"") .append(NEWLINE); sb.append(NEWLINE); sb .append("# Setup completed successfully, delete marker file").append(NEWLINE) .append("rm ${").append(SETUP_ERROR_FILE_ENV_VAR).append("}").append(NEWLINE); sb.append(NEWLINE); sb .append("# Restore the original stdout and stderr. Close fd 6 and 7").append(NEWLINE) .append("exec 1>&6 6>&-").append(NEWLINE) .append("exec 2>&7 7>&-").append(NEWLINE); sb.append(NEWLINE); // Dump environment for debugging sb .append("# Dump environment post-setup") .append(NEWLINE) .append("env | grep -E ") .append(jobSetupProperties.isEnvironmentDumpFilterInverted() ? GREP_INVERT_MATCH : "") .append("--regex='").append(jobSetupProperties.getEnvironmentDumpFilterExpression()).append("'") .append(" | sort > ") .append("${").append(ENVIRONMENT_LOG_ENV_VAR).append("}") .append(NEWLINE); sb.append(NEWLINE); // Script Executable Section // N.B. Command *must* be last line of the script for the exit code to be propagated back correctly! sb .append("# Launch the command") .append(NEWLINE) .append(this.commandLine).append(" <&0 &").append(NEWLINE) .append("wait %1").append(NEWLINE) .append("exit $?").append(NEWLINE) .append(NEWLINE); return sb.toString(); } } }
2,990
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/ServicesAutoConfiguration.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.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.configs.AwsAutoConfiguration; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; 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.Lazy; import org.springframework.core.io.ResourceLoader; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.TaskScheduler; import java.io.IOException; /** * Spring auto configuration for the service tier of an Agent process. * * @author tgianos * @since 4.0.0 */ @Configuration @EnableConfigurationProperties( { AgentProperties.class } ) @AutoConfigureAfter(AwsAutoConfiguration.class) @Slf4j public class ServicesAutoConfiguration { /** * Provide a lazy {@link DownloadService} bean if one hasn't already been defined. * * @param fetchingCacheService The cache service to use * @return A {@link DownloadServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(DownloadService.class) public DownloadService downloadService(final FetchingCacheService fetchingCacheService) { return new DownloadServiceImpl(fetchingCacheService); } /** * Provide a lazy {@link FetchingCacheService} instance if one hasn't already been defined. * * @param resourceLoader The Spring Resource loader to use * @param cacheArguments The cache command line arguments to use * @param fileLockFactory The file lock factory to use * @param taskExecutor The task executor to use * @return A {@link FetchingCacheServiceImpl} instance * @throws IOException On error creating the instance */ @Bean @Lazy @ConditionalOnMissingBean(FetchingCacheService.class) public FetchingCacheService fetchingCacheService( final ResourceLoader resourceLoader, final ArgumentDelegates.CacheArguments cacheArguments, final FileLockFactory fileLockFactory, @Qualifier("sharedAgentTaskExecutor") final TaskExecutor taskExecutor ) throws IOException { return new FetchingCacheServiceImpl( resourceLoader, cacheArguments, fileLockFactory, taskExecutor ); } /** * Provide a lazy {@link KillService} bean if one hasn't already been defined. * * @param executionContext the execution context * @param agentProperties the agent properties * @return A {@link KillServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(KillService.class) public KillService killService( final ExecutionContext executionContext, final AgentProperties agentProperties ) { return new KillServiceImpl(executionContext, agentProperties); } /** * Provide a lazy {@link JobSetupService} bean if one hasn't already been defined. * * @param downloadService the download service * @param agentProperties the agent properties * @return A {@link JobSetupServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(JobSetupService.class) public JobSetupService jobSetupService( final DownloadService downloadService, final AgentProperties agentProperties ) { return new JobSetupServiceImpl(downloadService, agentProperties); } /** * Provide a lazy {@link JobMonitorService} bean if one hasn't already been defined. * * @param killService the kill service * @param manifestCreatorService the manifest creator service * @param agentJobService the agent job service * @param taskScheduler the task scheduler * @param agentProperties the agent properties * @return A {@link JobMonitorServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(JobMonitorService.class) public JobMonitorServiceImpl jobMonitorService( final KillService killService, final JobDirectoryManifestCreatorService manifestCreatorService, final AgentJobService agentJobService, @Qualifier("sharedAgentTaskScheduler") final TaskScheduler taskScheduler, final AgentProperties agentProperties ) { return new JobMonitorServiceImpl( killService, manifestCreatorService, agentJobService, taskScheduler, agentProperties ); } }
2,991
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/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. * */ /** * Implementations of execution services for the Agent. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.services.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,992
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/FetchingCacheServiceImpl.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.google.common.annotations.VisibleForTesting; import com.google.common.io.Files; import com.netflix.genie.agent.cli.ArgumentDelegates; import com.netflix.genie.agent.execution.exceptions.DownloadException; import com.netflix.genie.agent.execution.exceptions.LockException; import com.netflix.genie.agent.execution.services.FetchingCacheService; import com.netflix.genie.agent.utils.locks.CloseableLock; import com.netflix.genie.agent.utils.locks.impl.FileLockFactory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.task.TaskExecutor; import org.springframework.util.DigestUtils; import org.springframework.util.FileCopyUtils; import org.springframework.util.FileSystemUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Set; /** * A cache on local disk that uses URIs as keys and transparently downloads * missing entries. It uses file locks to accomplish the following * <p> * Allows multiple agents reading/writing/deleting in the same cache folder * without corrupting the cache * Downloads new versions of resources once they are available remotely * Deletes the old versions of resources once a new version is successfully downloaded * Recovers from partial downloads of resources in case an agent gets killed in the middle of a download * or a download fails for any other reason * <p> * Does NOT handle concurrency within the same agent (not an issue at the moment) * <p> * Cache structure on local disk * Each resource has a hash to represent it. The version of the resource is the remote last modified * timestamp. For each resource and version, a lock file is created. Each process takes a lock on * this file and then downloads the resource to a data.tmp file. Once the download is complete * data.tmp is atomically moved to data. * For e.g for a hash value of 6d331abc92bc8244bc5d41e2107f303a and last modified = 1525456404 * cache entries would like the following * {base_dir}/6d331abc92bc8244bc5d41e2107f303a/1525456404/data * {base_dir}/6d331abc92bc8244bc5d41e2107f303a/1525456404/lock * <p> * Deletion of older versions * Once a version is successfully downloaded, any older versions are deleted as a best effort * TODO:Use shared file lock for reading and exclusive lock for writing to the cache * * @author standon * @since 4.0.0 */ @Slf4j class FetchingCacheServiceImpl implements FetchingCacheService { private static final String LOCK_FILE_NAME = "lock"; private static final String DATA_FILE_NAME = "data"; private static final String DATA_DOWNLOAD_FILE_NAME = "data.tmp"; private static final String DUMMY_FILE_NAME = "_"; private final ResourceLoader resourceLoader; private final File cacheDirectory; private final FileLockFactory fileLockFactory; private final TaskExecutor cleanUpTaskExecutor; FetchingCacheServiceImpl( final ResourceLoader resourceLoader, final ArgumentDelegates.CacheArguments cacheArguments, final FileLockFactory fileLockFactory, final TaskExecutor cleanUpTaskExecutor ) throws IOException { this.resourceLoader = resourceLoader; this.cacheDirectory = cacheArguments.getCacheDirectory(); this.fileLockFactory = fileLockFactory; this.cleanUpTaskExecutor = cleanUpTaskExecutor; createDirectoryStructureIfNotExists(cacheDirectory); } /** * {@inheritDoc} */ @Override public void get(final URI sourceFileUri, final File destinationFile) throws DownloadException, IOException { try { lookupOrDownload(sourceFileUri, destinationFile); } catch (IOException e) { throw new IOException("failed to download: " + sourceFileUri.toASCIIString(), e); } } /** * {@inheritDoc} */ @Override public void get(final Set<Pair<URI, File>> sourceDestinationPairs) throws DownloadException, IOException { for (final Pair<URI, File> sourceDestinationPair : sourceDestinationPairs) { get(sourceDestinationPair.getKey(), sourceDestinationPair.getValue()); } } /* Get a handle to the resource represented by the sourceFileURI. * The lastModifedTimeStamp represents the version number of the resource. * Create the directory structure with resourceCacheId/version(lastModifiedTimeStamp) * if it does not exist. Touch an empty lock file. Use this file to grab a lock on it. * While under the lock check for the cache data file resourceCacheId/version/DATA_FILE_NAME. * If it exists copy to the target file and release the lock. Else, * download the file to resourceCacheId/version/DATA_DOWNLOAD_FILE_NAME download file. Move it * to the data file(this operation is guaranteed to be atomic by the OS). Copy data * file to target file and release the lock. * Before exiting delete the previous versions of the resource */ private void lookupOrDownload( final URI sourceFileUri, final File destinationFile ) throws DownloadException, IOException { final String uriString = sourceFileUri.toASCIIString(); log.debug("Lookup: {}", uriString); // Unique id to store the resource on local disk final String resourceCacheId = getResourceCacheId(sourceFileUri); // Get a handle to the resource final Resource resource; try { resource = resourceLoader.getResource(uriString); } catch (Throwable t) { log.error( "Failed to retrieve resource: {}, {} - {}", uriString, t.getClass().getSimpleName(), t.getMessage() ); throw t; } if (!resource.exists()) { throw new DownloadException("Resource not found: " + uriString); } final long resourceLastModified = resource.lastModified(); //Handle to resourceCacheId/version final File cacheResourceVersionDir = getCacheResourceVersionDir( resourceCacheId, resourceLastModified ); //Create the resource version dir in cache if it does not exist createDirectoryStructureIfNotExists(cacheResourceVersionDir); try ( CloseableLock lock = fileLockFactory.getLock( touchCacheResourceVersionLockFile( resourceCacheId, resourceLastModified ) ) ) { //Critical section begin lock.lock(); //Handle to the resource cached locally final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile( resourceCacheId, resourceLastModified ); if (!cachedResourceVersionDataFile.exists()) { log.debug( "Cache miss: {} (id: {})", uriString, resourceCacheId ); // Download the resource into the download file in cache // resourceCacheId/version/data.tmp final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile( resourceCacheId, resourceLastModified ); try ( InputStream in = resource.getInputStream(); OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile) ) { FileCopyUtils.copy(in, out); Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile); } } else { log.debug( "Cache hit: {} (id: {})", uriString, resourceCacheId ); } //Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile Files.copy(cachedResourceVersionDataFile, destinationFile); //Critical section end } catch (LockException e) { throw new DownloadException("Error downloading dependency: " + uriString, e); } //Clean up any older versions cleanUpTaskExecutor.execute( new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified) ); } @VisibleForTesting String getResourceCacheId(final URI uri) { return DigestUtils.md5DigestAsHex(uri.toASCIIString().getBytes(StandardCharsets.UTF_8)); } /** * Helper to extract the resource last modified timestamp from the resource * version directory handle. * * @param resourceVersionDir handle to the resource version directory * @return resource last modified timestamp */ private long getResourceLastModified(final File resourceVersionDir) { return Long.parseLong(resourceVersionDir.getName()); } private void createDirectoryStructureIfNotExists(final File dir) throws IOException { if (!dir.exists()) { try { Files.createParentDirs(new File(dir, DUMMY_FILE_NAME)); } catch (final IOException e) { throw new IOException("Failed to create directory: " + dir.getAbsolutePath(), e); } } else if (!dir.isDirectory()) { throw new IOException("This location is not a directory: " + dir.getAbsolutePath()); } } /** * Clean up all resources older than the latest version of a resource. * * @param resourceCacheId resource cache id * @param lastDownloadedResourceModifiedTimestamp timestamp of last successfully downloaded resource. * represents the latest version of the resource * @throws IOException in case deleting the files has an issue */ @VisibleForTesting void cleanUpOlderResourceVersions( final String resourceCacheId, final long lastDownloadedResourceModifiedTimestamp ) throws IOException, LockException { //Get all versions of a resource in the cache final File[] files = getCacheResourceDir(resourceCacheId).listFiles(); //Remove all the versions older than the supplied version - lastDownloadedResourceModifiedTimestamp if (files != null) { for (File file : files) { long resourceLastModified = 0; try { resourceLastModified = getResourceLastModified(file); if (resourceLastModified < lastDownloadedResourceModifiedTimestamp) { cleanUpResourceVersion(file); } } catch (NumberFormatException e) { log.warn("Encountered a dir name which is not long. Ignoring dir - {}", resourceLastModified, e); } } } } /** * Delete a resource version directory after taking appropriate lock. * * @param resourceVersionDir Directory to be deleted * @throws IOException */ private void cleanUpResourceVersion(final File resourceVersionDir) throws LockException, IOException { /* * Acquire a lock on the lock file for the resource version being deleted. * Delete the entire directory for the resource version */ try ( CloseableLock lock = fileLockFactory.getLock( touchCacheResourceVersionLockFile(resourceVersionDir) ) ) { //critical section begin lock.lock(); //Remove the data file. If last download was successful for the resource, only //data file would exist FileSystemUtils.deleteRecursively(getCacheResourceVersionDataFile(resourceVersionDir)); //data.tmp file could exist if the last download of the resource failed in the middle //and after that a newer version was downloaded. So, delete it too FileSystemUtils.deleteRecursively(getCacheResourceVersionDownloadFile(resourceVersionDir)); //critical section end } } /* Returns a handle to the directory for a resource */ private File getCacheResourceDir(final String resourceCacheId) { return new File(cacheDirectory, resourceCacheId); } /* Returns a handle to the directory for a resource version */ @VisibleForTesting File getCacheResourceVersionDir(final String resourceCacheId, final long lastModifiedTimestamp) { return new File(getCacheResourceDir(resourceCacheId), Long.toString(lastModifiedTimestamp)); } /* Returns a handle to the data file of a resource version in the cache */ @VisibleForTesting File getCacheResourceVersionDataFile(final String resourceCacheId, final long lastModifiedTimestamp) { return getCacheResourceVersionDataFile( getCacheResourceVersionDir(resourceCacheId, lastModifiedTimestamp) ); } /* Returns a handle to the data file of a resource version in the cache */ @VisibleForTesting File getCacheResourceVersionDataFile(final File resourceVersionDir) { return new File(resourceVersionDir, DATA_FILE_NAME); } /* Returns a handle to the temporary download file of a resource version in the cache */ @VisibleForTesting File getCacheResourceVersionDownloadFile(final String resourceCacheId, final long lastModifiedTimestamp) { return getCacheResourceVersionDownloadFile( getCacheResourceVersionDir(resourceCacheId, lastModifiedTimestamp) ); } /* Returns a handle to the temporary download file of a resource version in the cache */ @VisibleForTesting File getCacheResourceVersionDownloadFile(final File resourceVersionDir) { return new File(resourceVersionDir, DATA_DOWNLOAD_FILE_NAME); } /* Returns a handle to the lock file of a resource version in the cache */ @VisibleForTesting File getCacheResourceVersionLockFile(final String resourceCacheId, final long lastModifiedTimestamp) { return getCacheResourceVersionLockFile( getCacheResourceVersionDir( resourceCacheId, lastModifiedTimestamp ) ); } private File getCacheResourceVersionLockFile(final File resourceVersionDir) { return new File(resourceVersionDir, LOCK_FILE_NAME); } /* Touch the lock file of a resource version and return a handle to it */ File touchCacheResourceVersionLockFile( final String resourceCacheId, final long lastModifiedTimestamp ) throws IOException { return touchCacheResourceVersionLockFile( getCacheResourceVersionDir( resourceCacheId, lastModifiedTimestamp ) ); } /* Touch the lock file of a resource version and return a handle to it */ private File touchCacheResourceVersionLockFile(final File resourceVersionDir) throws IOException { final File lockFile = getCacheResourceVersionLockFile(resourceVersionDir); Files.touch(lockFile); return lockFile; } /** * Task to clean up the older versions of a resource. */ private class CleanupOlderVersionsTask implements Runnable { //Cache id for the resource private final String resourceCacheId; //lastModified timestamp for the last successfully downloaded resource private final long lastDownloadedResourceModifiedTimestamp; CleanupOlderVersionsTask(final String resourceCacheId, final long lastDownloadedResourceModifiedTimestamp) { this.resourceCacheId = resourceCacheId; this.lastDownloadedResourceModifiedTimestamp = lastDownloadedResourceModifiedTimestamp; } @Override public void run() { try { cleanUpOlderResourceVersions(resourceCacheId, lastDownloadedResourceModifiedTimestamp); } catch (Throwable throwable) { log.error( "Error cleaning up old resource resourceCacheId - {}, resourceLastModified - {}", resourceCacheId, lastDownloadedResourceModifiedTimestamp, throwable ); } } } }
2,993
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/GRpcServicesAutoConfiguration.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.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.common.internal.dtos.converters.JobDirectoryManifestProtoConverter; import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; 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 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.context.annotation.Lazy; import org.springframework.scheduling.TaskScheduler; /** * Spring auto configuration for the various gRPC services required for an agent to communicate with the Genie server. * * @author tgianos * @since 4.0.0 */ @Configuration @EnableConfigurationProperties( { AgentProperties.class } ) public class GRpcServicesAutoConfiguration { /** * Provide a lazy gRPC agent heart beat service if one isn't already defined. * * @param heartBeatServiceStub The heart beat service stub to use * @param taskScheduler The task scheduler to use * @param agentProperties The agent properties * @return A {@link GrpcAgentHeartBeatServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(AgentHeartBeatService.class) public GrpcAgentHeartBeatServiceImpl agentHeartBeatService( final HeartBeatServiceGrpc.HeartBeatServiceStub heartBeatServiceStub, @Qualifier("heartBeatServiceTaskScheduler") final TaskScheduler taskScheduler, final AgentProperties agentProperties ) { return new GrpcAgentHeartBeatServiceImpl( heartBeatServiceStub, taskScheduler, agentProperties.getHeartBeatService() ); } /** * Provide a lazy gRPC agent job kill service bean if one isn't already defined. * * @param jobKillServiceFutureStub The future stub to use for the service communication with the server * @param killService The kill service to use to terminate this agent gracefully * @param taskScheduler The task scheduler to use * @param agentProperties The agent properties * @return A {@link GRpcAgentJobKillServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(AgentJobKillService.class) public GRpcAgentJobKillServiceImpl agentJobKillService( final JobKillServiceGrpc.JobKillServiceFutureStub jobKillServiceFutureStub, final KillService killService, @Qualifier("sharedAgentTaskScheduler") final TaskScheduler taskScheduler, final AgentProperties agentProperties ) { return new GRpcAgentJobKillServiceImpl( jobKillServiceFutureStub, killService, taskScheduler, agentProperties.getJobKillService() ); } /** * Provide a lazy gRPC agent job service bean if one isn't already defined. * * @param jobServiceFutureStub The future stub to use for communication with the server * @param jobServiceProtoConverter The converter to use between DTO and Proto instances * @return A {@link GRpcAgentJobServiceImpl} instance */ @Bean @Lazy @ConditionalOnMissingBean(AgentJobService.class) public GRpcAgentJobServiceImpl agentJobService( final JobServiceGrpc.JobServiceFutureStub jobServiceFutureStub, final JobServiceProtoConverter jobServiceProtoConverter ) { return new GRpcAgentJobServiceImpl(jobServiceFutureStub, jobServiceProtoConverter); } /** * Provide a lazy gRPC agent file stream service if one isn't already defined. * * @param fileStreamServiceStub The stub to use for communications with the server * @param taskScheduler The task scheduler to use * @param jobDirectoryManifestProtoConverter The converter to serialize manifests into messages * @param jobDirectoryManifestCreatorService The job directory manifest service * @param agentProperties The agent properties * @return A {@link AgentFileStreamService} instance */ @Bean @Lazy @ConditionalOnMissingBean(AgentFileStreamService.class) public GRpcAgentFileStreamServiceImpl agentFileStreamService( final FileStreamServiceGrpc.FileStreamServiceStub fileStreamServiceStub, @Qualifier("sharedAgentTaskScheduler") final TaskScheduler taskScheduler, final JobDirectoryManifestProtoConverter jobDirectoryManifestProtoConverter, final JobDirectoryManifestCreatorService jobDirectoryManifestCreatorService, final AgentProperties agentProperties ) { return new GRpcAgentFileStreamServiceImpl( fileStreamServiceStub, taskScheduler, jobDirectoryManifestProtoConverter, jobDirectoryManifestCreatorService, agentProperties.getFileStreamService() ); } }
2,994
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/GRpcAgentFileStreamServiceImpl.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.execution.services.impl.grpc; import com.google.common.collect.Sets; import com.google.protobuf.ByteString; import com.netflix.genie.agent.execution.services.AgentFileStreamService; import com.netflix.genie.agent.properties.FileStreamServiceProperties; import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import com.netflix.genie.common.internal.util.ExponentialBackOffTrigger; import com.netflix.genie.proto.AgentFileMessage; import com.netflix.genie.proto.AgentManifestMessage; import com.netflix.genie.proto.FileStreamServiceGrpc; import com.netflix.genie.proto.ServerAckMessage; import com.netflix.genie.proto.ServerControlMessage; import com.netflix.genie.proto.ServerFileRequestMessage; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Context; import io.grpc.stub.ClientCallStreamObserver; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.TaskScheduler; import javax.annotation.Nullable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Instant; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Implementation of {@link AgentFileStreamService} over gRPC. * Sets up a persistent 2-way stream ('sync') to push manifest updates and receive file requests. * When a file request is received, a creates a new 2 way stream ('transmit') and pushes file chunks, waits for ACK, * sends the next chunk, ... until the file range requested is transmitted. Then the stream is shut down. * * @author mprimi * @since 4.0.0 */ @Slf4j public class GRpcAgentFileStreamServiceImpl implements AgentFileStreamService { private final FileStreamServiceGrpc.FileStreamServiceStub fileStreamServiceStub; private final TaskScheduler taskScheduler; private final ExponentialBackOffTrigger trigger; private final FileStreamServiceProperties properties; private final JobDirectoryManifestProtoConverter manifestProtoConverter; private final StreamObserver<ServerControlMessage> responseObserver; private final Semaphore concurrentTransfersSemaphore; private final Set<FileTransfer> activeFileTransfers; private final JobDirectoryManifestCreatorService jobDirectoryManifestCreatorService; private final int maxStreams; private StreamObserver<AgentManifestMessage> controlStreamObserver; private String jobId; private Path jobDirectoryPath; private AtomicBoolean started = new AtomicBoolean(); private ScheduledFuture<?> scheduledTask; GRpcAgentFileStreamServiceImpl( final FileStreamServiceGrpc.FileStreamServiceStub fileStreamServiceStub, final TaskScheduler taskScheduler, final JobDirectoryManifestProtoConverter manifestProtoConverter, final JobDirectoryManifestCreatorService jobDirectoryManifestCreatorService, final FileStreamServiceProperties properties ) { this.fileStreamServiceStub = fileStreamServiceStub; this.taskScheduler = taskScheduler; this.manifestProtoConverter = manifestProtoConverter; this.jobDirectoryManifestCreatorService = jobDirectoryManifestCreatorService; this.properties = properties; this.trigger = new ExponentialBackOffTrigger(properties.getErrorBackOff()); this.responseObserver = new ServerControlStreamObserver(this); this.maxStreams = properties.getMaxConcurrentStreams(); this.concurrentTransfersSemaphore = new Semaphore(this.maxStreams); this.activeFileTransfers = Sets.newConcurrentHashSet(); } /** * {@inheritDoc} */ @Override public synchronized void start(final String claimedJobId, final Path jobDirectoryRoot) { //Service can be started only once if (!this.started.compareAndSet(false, true)) { throw new IllegalStateException("Service can be started only once"); } this.jobId = claimedJobId; this.jobDirectoryPath = jobDirectoryRoot; this.scheduledTask = this.taskScheduler.schedule(this::pushManifest, trigger); log.debug("Started"); } /** * {@inheritDoc} */ @Override public synchronized void stop() { log.debug("Stopping"); if (this.started.compareAndSet(true, false)) { if (!this.activeFileTransfers.isEmpty()) { this.drain(); } this.scheduledTask.cancel(false); this.scheduledTask = null; this.discardCurrentStream(true); while (!this.activeFileTransfers.isEmpty()) { log.debug("{} transfers are still active after waiting", this.activeFileTransfers.size()); try { final FileTransfer fileTransfer = this.activeFileTransfers.iterator().next(); if (this.activeFileTransfers.remove(fileTransfer)) { fileTransfer.completeTransfer(true, new InterruptedException("Shutting down")); } } catch (NoSuchElementException | ConcurrentModificationException e) { // Swallow. Not unexpected, collection and state may change. } } } log.debug("Stopped"); } /** * {@inheritDoc} */ @Override public synchronized Optional<ScheduledFuture<?>> forceServerSync() { if (started.get()) { try { log.debug("Forcing a manifest refresh"); this.jobDirectoryManifestCreatorService.invalidateCachedDirectoryManifest(jobDirectoryPath); return Optional.of(this.taskScheduler.schedule(this::pushManifest, Instant.now())); } catch (Exception e) { log.error("Failed to force push a fresh manifest", e); } } return Optional.empty(); } private void drain() { final AtomicInteger acquiredPermitsCount = new AtomicInteger(); // Task that attempts to acquire all available transfer permits. // This ensures no new transfers will be started. // If the task completes successfully, it also guarantees there are no in-progress transfers. final Runnable drainTask = () -> { while (acquiredPermitsCount.get() < this.maxStreams) { try { if (this.concurrentTransfersSemaphore.tryAcquire(1, TimeUnit.SECONDS)) { acquiredPermitsCount.incrementAndGet(); } } catch (InterruptedException e) { log.warn("Interrupted while waiting for a permit"); break; } } }; // Submit the task for immediate execution, but do not wait more than a fixed amount of time final ScheduledFuture<?> drainTaskFuture = taskScheduler.schedule(drainTask, Instant.now()); try { drainTaskFuture.get(this.properties.getDrainTimeout().toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Failed to wait for in-flight transfers to complete", e); } final int ongoingTransfers = this.maxStreams - acquiredPermitsCount.get(); if (ongoingTransfers > 0) { log.warn("{} file transfers are still active after waiting for completion", ongoingTransfers); } } private synchronized void pushManifest() { if (started.get()) { final AgentManifestMessage jobFileManifest; try { jobFileManifest = manifestProtoConverter.manifestToProtoMessage( this.jobId, this.jobDirectoryManifestCreatorService.getDirectoryManifest(this.jobDirectoryPath) ); } catch (final IOException e) { log.error("Failed to construct manifest", e); return; } catch (GenieConversionException e) { log.error("Failed to serialize manifest", e); return; } if (this.controlStreamObserver == null) { log.debug("Creating new control stream"); this.controlStreamObserver = fileStreamServiceStub.sync(this.responseObserver); if (this.controlStreamObserver instanceof ClientCallStreamObserver) { ((ClientCallStreamObserver) this.controlStreamObserver) .setMessageCompression(this.properties.isEnableCompression()); } } log.debug("Sending manifest via control stream"); this.controlStreamObserver.onNext(jobFileManifest); } } private void handleControlStreamError(final Throwable t) { log.warn("Control stream error: {}", t.getMessage(), t); this.trigger.reset(); this.discardCurrentStream(false); } private void handleControlStreamCompletion() { log.debug("Control stream completed"); this.discardCurrentStream(false); } private synchronized void discardCurrentStream(final boolean sendStreamCompletion) { if (this.controlStreamObserver != null) { log.debug("Discarding current control stream"); if (sendStreamCompletion) { log.debug("Sending control stream completion"); this.controlStreamObserver.onCompleted(); } this.controlStreamObserver = null; } } private synchronized void handleFileRequest( final String streamId, final String relativePath, final long startOffset, final long endOffset ) { log.debug( "Server is requesting file {} (range: [{}, {}), streamId: {})", relativePath, startOffset, endOffset, streamId ); if (!this.started.get()) { log.warn("Ignoring file request, service shutting down"); return; } final Path absolutePath = this.jobDirectoryPath.resolve(relativePath); if (!Files.exists(absolutePath)) { log.warn("Ignoring request for a file that does not exist: {}", absolutePath); return; } final boolean permitAcquired = this.concurrentTransfersSemaphore.tryAcquire(); if (!permitAcquired) { log.warn("Ignoring file request, too many transfers already in progress"); return; } // Decouple outgoing file transfer from incoming file request Context.current().run( () -> { final FileTransfer fileTransfer = new FileTransfer( this, streamId, absolutePath, startOffset, endOffset, properties.getDataChunkMaxSize().toBytes() ); this.activeFileTransfers.add(fileTransfer); fileTransfer.start(); log.debug("Created and started new file transfer: {}", fileTransfer.streamId); } ); } private void handleTransferComplete(final FileTransfer fileTransfer) { this.activeFileTransfers.remove(fileTransfer); this.concurrentTransfersSemaphore.release(); log.debug("File transfer completed: {}", fileTransfer.streamId); } private static class ServerControlStreamObserver implements StreamObserver<ServerControlMessage> { private final GRpcAgentFileStreamServiceImpl gRpcAgentFileManifestService; ServerControlStreamObserver(final GRpcAgentFileStreamServiceImpl gRpcAgentFileManifestService) { this.gRpcAgentFileManifestService = gRpcAgentFileManifestService; } @Override public void onNext(final ServerControlMessage value) { if (value.getMessageCase() == ServerControlMessage.MessageCase.SERVER_FILE_REQUEST) { log.debug("Received control stream file request"); final ServerFileRequestMessage fileRequest = value.getServerFileRequest(); this.gRpcAgentFileManifestService.handleFileRequest( fileRequest.getStreamId(), fileRequest.getRelativePath(), fileRequest.getStartOffset(), fileRequest.getEndOffset() ); } else { log.warn("Unknown message type: " + value.getMessageCase().name()); } } @Override public void onError(final Throwable t) { log.debug("Received control stream error: {}", t.getClass().getSimpleName()); this.gRpcAgentFileManifestService.handleControlStreamError(t); } @Override public void onCompleted() { log.debug("Received control stream completion"); this.gRpcAgentFileManifestService.handleControlStreamCompletion(); } } private static class FileTransfer implements StreamObserver<ServerAckMessage> { private final GRpcAgentFileStreamServiceImpl gRpcAgentFileStreamService; private final String streamId; private final Path absolutePath; private final long startOffset; private final long endOffset; private final StreamObserver<AgentFileMessage> outboundStreamObserver; private final ByteBuffer readBuffer; private final AtomicBoolean completed = new AtomicBoolean(); private long watermark; FileTransfer( final GRpcAgentFileStreamServiceImpl gRpcAgentFileStreamService, final String streamId, final Path absolutePath, final long startOffset, final long endOffset, final long maxChunkSize ) { this.gRpcAgentFileStreamService = gRpcAgentFileStreamService; this.streamId = streamId; this.absolutePath = absolutePath; this.startOffset = startOffset; this.endOffset = endOffset; this.outboundStreamObserver = this.gRpcAgentFileStreamService.fileStreamServiceStub.transmit(this); this.watermark = startOffset; this.readBuffer = ByteBuffer.allocate(Math.toIntExact(maxChunkSize)); log.debug( "Created new FileTransfer: {} (path: {} range: {}-{})", streamId, absolutePath, startOffset, endOffset ); } void start() { log.debug("Starting file transfer: {}", streamId); try { this.sendChunk(); } catch (IOException e) { log.warn("Failed to send first chunk"); this.completeTransfer(true, e); } } private void completeTransfer(final boolean shutdownStream, @Nullable final Exception error) { if (this.completed.compareAndSet(false, true)) { log.debug( "Completing transfer: {} (shutdown: {}, error: {})", streamId, shutdownStream, error != null ); if (shutdownStream) { if (error != null) { log.debug("Terminating transfer stream {} with error", streamId); this.outboundStreamObserver.onError(error); } else { log.debug("Terminating transfer stream {} without error", streamId); this.outboundStreamObserver.onCompleted(); } } this.gRpcAgentFileStreamService.handleTransferComplete(this); } } @SuppressFBWarnings( value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "https://github.com/spotbugs/spotbugs/issues/756" ) private void sendChunk() throws IOException { if (this.watermark < this.endOffset - 1) { // Reset mark before reading into the buffer readBuffer.rewind(); final int bytesRead; try (FileChannel channel = FileChannel.open(this.absolutePath, StandardOpenOption.READ)) { channel.position(this.watermark); bytesRead = channel.read(readBuffer); } // Reset mark again before copying data out readBuffer.rewind(); final AgentFileMessage chunkMessage = AgentFileMessage.newBuilder() .setStreamId(this.streamId) .setData(ByteString.copyFrom(readBuffer, bytesRead)) .build(); log.debug("Sending next chunk in stream {} ({} bytes)", streamId, bytesRead); this.outboundStreamObserver.onNext(chunkMessage); this.watermark += bytesRead; } else { log.debug("All data transmitted"); this.completeTransfer(true, null); } } @Override public void onNext(final ServerAckMessage value) { log.debug("Received chunk acknowledgement"); try { sendChunk(); } catch (IOException e) { log.warn("Failed to send chunk"); this.completeTransfer(true, e); } } @Override public void onError(final Throwable t) { log.warn("Stream error: {} : {}", t.getClass().getSimpleName(), t.getMessage()); this.completeTransfer(false, null); } @Override public void onCompleted() { log.debug("Stream completed"); this.completeTransfer(false, null); } } }
2,995
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/GRpcAgentJobKillServiceImpl.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.google.common.util.concurrent.ListenableFuture; import com.netflix.genie.agent.execution.services.AgentJobKillService; import com.netflix.genie.agent.execution.services.KillService; import com.netflix.genie.agent.properties.JobKillServiceProperties; import com.netflix.genie.common.internal.util.ExponentialBackOffTrigger; import com.netflix.genie.proto.JobKillRegistrationRequest; import com.netflix.genie.proto.JobKillRegistrationResponse; import com.netflix.genie.proto.JobKillServiceGrpc; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.TaskScheduler; import javax.validation.constraints.NotBlank; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; /** * Implementation of the {@link AgentJobKillService}, listens for kill coming from server using long-polling. * <p> * Note: this implementation still suffers from a serious flaw: because it is implemented with a unary call, * the server will never realize the client is gone if the connection is broken. This can lead to an accumulation of * parked calls on the server. A new protocol (based on a bidirectional stream) is necessary to solve this problem. * * @author mprimi * @since 4.0.0 */ @Slf4j public class GRpcAgentJobKillServiceImpl implements AgentJobKillService { private final JobKillServiceGrpc.JobKillServiceFutureStub client; private final KillService killService; private final TaskScheduler taskScheduler; private final AtomicBoolean started = new AtomicBoolean(false); private final JobKillServiceProperties properties; private final ExponentialBackOffTrigger trigger; private ScheduledFuture<?> periodicTaskScheduledFuture; /** * Constructor. * * @param client The gRPC client to use to call the server * @param killService KillService for killing the agent * @param taskScheduler A task scheduler * @param properties The service properties */ public GRpcAgentJobKillServiceImpl( final JobKillServiceGrpc.JobKillServiceFutureStub client, final KillService killService, final TaskScheduler taskScheduler, final JobKillServiceProperties properties ) { this.client = client; this.killService = killService; this.taskScheduler = taskScheduler; this.properties = properties; this.trigger = new ExponentialBackOffTrigger(this.properties.getResponseCheckBackOff()); } /** * {@inheritDoc} */ @Override public synchronized void start(@NotBlank(message = "Job id cannot be blank") final String jobId) { //Service can be started only once if (started.compareAndSet(false, true)) { final PeriodicTask periodicTask = new PeriodicTask(client, killService, jobId, this.trigger); // Run once immediately periodicTask.run(); // Then run on task scheduler periodically this.periodicTaskScheduledFuture = this.taskScheduler.schedule(periodicTask, this.trigger); } } /** * {@inheritDoc} */ @Override public void stop() { if (this.started.compareAndSet(true, false)) { this.periodicTaskScheduledFuture.cancel(true); this.periodicTaskScheduledFuture = null; } } private static final class PeriodicTask implements Runnable { private final JobKillServiceGrpc.JobKillServiceFutureStub client; private final KillService killService; private final String jobId; private final ExponentialBackOffTrigger trigger; private ListenableFuture<JobKillRegistrationResponse> pendingKillRequestFuture; PeriodicTask( final JobKillServiceGrpc.JobKillServiceFutureStub client, final KillService killService, final String jobId, final ExponentialBackOffTrigger trigger ) { this.client = client; this.killService = killService; this.jobId = jobId; this.trigger = trigger; } /** * {@inheritDoc} */ @Override public void run() { try { this.periodicCheckForKill(); } catch (Throwable t) { log.error("Error in periodic kill check task: {}", t.getMessage(), t); } } private void periodicCheckForKill() throws InterruptedException { if (this.pendingKillRequestFuture == null) { // No pending kill request, create one this.pendingKillRequestFuture = this.client .registerForKillNotification( JobKillRegistrationRequest.newBuilder() .setJobId(jobId) .build() ); } if (!this.pendingKillRequestFuture.isDone()) { // Still waiting for a kill, nothing to do log.debug("Kill request still pending"); } else { // Kill response received or error JobKillRegistrationResponse killResponse = null; Throwable exception = null; try { killResponse = this.pendingKillRequestFuture.get(); } catch (ExecutionException e) { log.warn("Kill request failed"); exception = e.getCause() != null ? e.getCause() : e; } // Delete current pending so a new one will be re-created this.pendingKillRequestFuture = null; if (killResponse != null) { log.info("Received kill signal from server"); this.killService.kill(KillService.KillSource.API_KILL_REQUEST); } if (exception != null) { log.warn("Kill request produced an error", exception); // Re-schedule this task soon this.trigger.reset(); } } } } }
2,996
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/GrpcAgentHeartBeatServiceImpl.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.execution.services.AgentHeartBeatService; import com.netflix.genie.agent.properties.HeartBeatServiceProperties; import com.netflix.genie.proto.AgentHeartBeat; import com.netflix.genie.proto.HeartBeatServiceGrpc; import com.netflix.genie.proto.ServerHeartBeat; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.TaskScheduler; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import java.time.Instant; import java.util.concurrent.ScheduledFuture; /** * gRPC implementation of AgentHeartBeatService. * Sends heartbeats to the server. * Transparently handles disconnections and stream errors by establishing a new stream. * * @author mprimi * @since 4.0.0 */ @Slf4j @Validated class GrpcAgentHeartBeatServiceImpl implements AgentHeartBeatService { private final HeartBeatServiceGrpc.HeartBeatServiceStub client; private final TaskScheduler taskScheduler; private final HeartBeatServiceProperties properties; private boolean isConnected; private StreamObserver<AgentHeartBeat> requestObserver; private ScheduledFuture<?> heartbeatFuture; private String claimedJobId; private AgentHeartBeat heartBeatMessage; GrpcAgentHeartBeatServiceImpl( final HeartBeatServiceGrpc.HeartBeatServiceStub client, @Qualifier("heartBeatServiceTaskExecutor") final TaskScheduler taskScheduler, final HeartBeatServiceProperties properties ) { this.client = client; this.taskScheduler = taskScheduler; this.properties = properties; } /** * {@inheritDoc} */ @Override public synchronized void start(@NotBlank final String jobId) { if (StringUtils.isNotBlank(this.claimedJobId)) { throw new IllegalStateException("Previously started with a different job id"); } this.claimedJobId = jobId; this.heartBeatMessage = AgentHeartBeat.newBuilder() .setClaimedJobId(claimedJobId) .build(); this.heartbeatFuture = taskScheduler.scheduleAtFixedRate( this::sendHeartBeatTask, this.properties.getInterval() ); this.requestObserver = client.heartbeat(new ResponseObserver(this)); } /** * {@inheritDoc} */ @Override public synchronized void stop() { if (this.heartbeatFuture != null) { this.heartbeatFuture.cancel(false); this.heartbeatFuture = null; } if (this.requestObserver != null) { this.requestObserver.onCompleted(); this.requestObserver = null; } } /** * {@inheritDoc} */ @Override public synchronized boolean isConnected() { return isConnected; } private synchronized void setConnected() { this.isConnected = true; } private synchronized void setDisconnected() { this.isConnected = false; // Schedule a stream reset this.taskScheduler.schedule( this::resetStreamTask, Instant.now().plus(this.properties.getErrorRetryDelay()) ); } /** * Regularly scheduled to send heart beats. */ private synchronized void sendHeartBeatTask() { if (requestObserver != null) { requestObserver.onNext(heartBeatMessage); } } /** * Scheduled once after a disconnection or error. */ private synchronized void resetStreamTask() { if (!isConnected) { this.requestObserver = client.heartbeat(new ResponseObserver(this)); } } private static class ResponseObserver implements StreamObserver<com.netflix.genie.proto.ServerHeartBeat> { private final GrpcAgentHeartBeatServiceImpl grpcAgentHeartBeatService; ResponseObserver(final GrpcAgentHeartBeatServiceImpl grpcAgentHeartBeatService) { this.grpcAgentHeartBeatService = grpcAgentHeartBeatService; } @Override public void onNext(final ServerHeartBeat value) { log.debug("Received server heartbeat"); grpcAgentHeartBeatService.setConnected(); } @Override public void onError(final Throwable t) { log.info("Stream error"); grpcAgentHeartBeatService.setDisconnected(); } @Override public void onCompleted() { log.info("Stream completed"); grpcAgentHeartBeatService.setDisconnected(); } } }
2,997
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/GRpcAgentJobServiceImpl.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.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.ListenableFuture; import com.netflix.genie.agent.execution.exceptions.ChangeJobArchiveStatusException; import com.netflix.genie.agent.execution.exceptions.ChangeJobStatusException; import com.netflix.genie.agent.execution.exceptions.ConfigureException; import com.netflix.genie.agent.execution.exceptions.GetJobStatusException; import com.netflix.genie.agent.execution.exceptions.HandshakeException; import com.netflix.genie.agent.execution.exceptions.JobIdUnavailableException; import com.netflix.genie.agent.execution.exceptions.JobReservationException; import com.netflix.genie.agent.execution.exceptions.JobSpecificationResolutionException; import com.netflix.genie.agent.execution.services.AgentJobService; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import com.netflix.genie.proto.ChangeJobArchiveStatusRequest; import com.netflix.genie.proto.ChangeJobStatusError; import com.netflix.genie.proto.ChangeJobStatusRequest; import com.netflix.genie.proto.ChangeJobStatusResponse; import com.netflix.genie.proto.ClaimJobError; import com.netflix.genie.proto.ClaimJobRequest; import com.netflix.genie.proto.ClaimJobResponse; import com.netflix.genie.proto.ConfigureRequest; import com.netflix.genie.proto.ConfigureResponse; import com.netflix.genie.proto.DryRunJobSpecificationRequest; import com.netflix.genie.proto.GetJobStatusRequest; import com.netflix.genie.proto.GetJobStatusResponse; import com.netflix.genie.proto.HandshakeRequest; import com.netflix.genie.proto.HandshakeResponse; import com.netflix.genie.proto.JobServiceGrpc; import com.netflix.genie.proto.JobSpecificationError; import com.netflix.genie.proto.JobSpecificationRequest; import com.netflix.genie.proto.JobSpecificationResponse; import com.netflix.genie.proto.ReserveJobIdError; import com.netflix.genie.proto.ReserveJobIdRequest; import com.netflix.genie.proto.ReserveJobIdResponse; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.Map; import java.util.concurrent.ExecutionException; /** * Client-side implementation of the job service used to obtain job id, specification and update job state. * * @author tgianos * @since 4.0.0 */ @Slf4j class GRpcAgentJobServiceImpl implements AgentJobService { private static final String NO_MESSAGE = "No message"; private final JobServiceGrpc.JobServiceFutureStub client; private final JobServiceProtoConverter jobServiceProtoConverter; /** * Constructor. * * @param client The gRPC client to use to call the server. * Asynchronous version to allow timeouts. * @param jobServiceProtoConverter The proto/DTO converter utility */ GRpcAgentJobServiceImpl( final JobServiceGrpc.JobServiceFutureStub client, final JobServiceProtoConverter jobServiceProtoConverter ) { this.client = client; this.jobServiceProtoConverter = jobServiceProtoConverter; } /** * {@inheritDoc} */ @Override public void handshake( final AgentClientMetadata agentClientMetadata ) throws HandshakeException { final HandshakeRequest request; try { request = jobServiceProtoConverter.toHandshakeRequestProto(agentClientMetadata); } catch (final GenieConversionException e) { throw new HandshakeException("Failed to construct request from parameters", e); } final HandshakeResponse response = handleResponseFuture(this.client.handshake(request)); switch (response.getType()) { case ALLOWED: log.info("Successfully shook hand with server"); break; case REJECTED: log.warn("Server rejected handshake with this agent"); throw new HandshakeException("Server rejected client: " + response.getMessage()); default: throw new GenieRuntimeException( "Error during handshake: " + response.getType().name() + " - " + response.getMessage() ); } } /** * {@inheritDoc} */ @Override public Map<String, String> configure( final AgentClientMetadata agentClientMetadata ) throws ConfigureException { final ConfigureRequest request; try { request = jobServiceProtoConverter.toConfigureRequestProto(agentClientMetadata); } catch (final GenieConversionException e) { throw new ConfigureException("Failed to construct request from parameters", e); } final ConfigureResponse response = handleResponseFuture(this.client.configure(request)); return ImmutableMap.copyOf(response.getPropertiesMap()); } /** * {@inheritDoc} */ @Override public String reserveJobId( final AgentJobRequest agentJobRequest, final AgentClientMetadata agentClientMetadata ) throws JobReservationException, JobIdUnavailableException { final ReserveJobIdRequest request; try { request = jobServiceProtoConverter.toReserveJobIdRequestProto(agentJobRequest, agentClientMetadata); } catch (final GenieConversionException e) { throw new JobReservationException("Failed to construct request from parameters", e); } final ReserveJobIdResponse response = handleResponseFuture(this.client.reserveJobId(request)); switch (response.getResponseCase()) { case ID: log.info("Successfully reserved job id: " + response.getId()); break; case ERROR: throwForReservationError(response.getError()); break; case RESPONSE_NOT_SET: default: throw new GenieRuntimeException("Unexpected server response " + response.toString()); } return response.getId(); } /** * {@inheritDoc} */ @Override public JobSpecification resolveJobSpecification( @NotBlank final String id ) throws JobSpecificationResolutionException { final JobSpecificationRequest request = jobServiceProtoConverter.toJobSpecificationRequestProto(id); final JobSpecificationResponse response = handleResponseFuture(client.resolveJobSpecification(request)); return handleSpecificationResponse(response); } /** * {@inheritDoc} */ @Override public JobSpecification getJobSpecification(@NotBlank final String id) throws JobSpecificationResolutionException { final JobSpecificationRequest request = jobServiceProtoConverter.toJobSpecificationRequestProto(id); final JobSpecificationResponse response = handleResponseFuture(this.client.getJobSpecification(request)); return handleSpecificationResponse(response); } /** * {@inheritDoc} */ @Override public JobSpecification resolveJobSpecificationDryRun( @Valid final AgentJobRequest jobRequest ) throws JobSpecificationResolutionException { final DryRunJobSpecificationRequest request; try { request = jobServiceProtoConverter.toDryRunJobSpecificationRequestProto(jobRequest); } catch (final GenieConversionException e) { throw new JobSpecificationResolutionException("Failed to construct request from parameters", e); } final JobSpecificationResponse response = handleResponseFuture(this.client.resolveJobSpecificationDryRun(request)); return handleSpecificationResponse(response); } /** * {@inheritDoc} */ @Override public void claimJob( @NotBlank final String jobId, @Valid final AgentClientMetadata agentClientMetadata ) throws JobReservationException { final ClaimJobRequest request = jobServiceProtoConverter.toClaimJobRequestProto(jobId, agentClientMetadata); final ClaimJobResponse response = handleResponseFuture(this.client.claimJob(request)); if (!response.getSuccessful()) { throwForClaimJobError(response.getError()); } } /** * {@inheritDoc} */ @Override public void changeJobStatus( final @NotBlank String jobId, final JobStatus currentJobStatus, final JobStatus newJobStatus, @Nullable final String message ) throws ChangeJobStatusException { final ChangeJobStatusRequest request = this.jobServiceProtoConverter.toChangeJobStatusRequestProto( jobId, currentJobStatus, newJobStatus, message == null ? NO_MESSAGE : message ); final ChangeJobStatusResponse response = handleResponseFuture(this.client.changeJobStatus(request)); if (!response.getSuccessful()) { throwForChangeJobStatusError(response.getError()); } } /** * {@inheritDoc} */ @Override public JobStatus getJobStatus(@NotBlank final String jobId) throws GetJobStatusException { final GetJobStatusRequest request = this.jobServiceProtoConverter.toGetJobStatusRequestProto(jobId); final GetJobStatusResponse response = handleResponseFuture((this.client.getJobStatus(request))); final String statusString = response.getStatus(); try { return JobStatus.valueOf(statusString); } catch (IllegalArgumentException e) { throw new GetJobStatusException("Invalid job status in response: " + statusString); } } /** * {@inheritDoc} */ @Override public void changeJobArchiveStatus( @NotBlank final String jobId, final ArchiveStatus archiveStatus ) throws ChangeJobArchiveStatusException { final ChangeJobArchiveStatusRequest request = this.jobServiceProtoConverter.toChangeJobStatusArchiveRequestProto( jobId, archiveStatus ); try { handleResponseFuture(this.client.changeJobArchiveStatus(request)); } catch (GenieRuntimeException e) { throw new ChangeJobArchiveStatusException("Failed to update job archive status", e); } } private JobSpecification handleSpecificationResponse( final JobSpecificationResponse response ) throws JobSpecificationResolutionException { switch (response.getResponseCase()) { case SPECIFICATION: log.info("Successfully obtained job specification"); break; case ERROR: return throwForJobSpecificationError(response.getError()); case RESPONSE_NOT_SET: default: throw new GenieRuntimeException("Unexpected server response " + response.toString()); } return jobServiceProtoConverter.toJobSpecificationDto(response.getSpecification()); } private void throwForClaimJobError(final ClaimJobError error) throws JobReservationException { switch (error.getType()) { case NO_SUCH_JOB: case INVALID_STATUS: case INVALID_REQUEST: case ALREADY_CLAIMED: throw new JobReservationException( "Failed to claim job: " + error.getType().name() + ": " + error.getMessage() ); default: throw new GenieRuntimeException("Unhandled error: " + error.getType() + ": " + error.getMessage()); } } private void throwForReservationError( final ReserveJobIdError error ) throws JobIdUnavailableException, JobReservationException { switch (error.getType()) { case ID_NOT_AVAILABLE: throw new JobIdUnavailableException("The requested job id is already been used"); case SERVER_ERROR: throw new JobReservationException("Server error: " + error.getMessage()); case INVALID_REQUEST: throw new JobReservationException("Invalid request: " + error.getMessage()); case UNKNOWN: default: throw new GenieRuntimeException("Unhandled error: " + error.getType() + ": " + error.getMessage()); } } private JobSpecification throwForJobSpecificationError( final JobSpecificationError error ) throws JobSpecificationResolutionException { switch (error.getType()) { case NO_APPLICATION_FOUND: case NO_CLUSTER_FOUND: case NO_JOB_FOUND: case NO_COMMAND_FOUND: case RESOLUTION_FAILED: throw new JobSpecificationResolutionException( "Failed to obtain specification: " + error.getType().name() + ": " + error.getMessage() ); case RUNTIME_ERROR: throw new GenieRuntimeException( "Transient error resolving job specification: " + error.getMessage()); case UNKNOWN: default: throw new GenieRuntimeException( "Unhandled error: " + error.getType() + ": " + error.getMessage() ); } } private void throwForChangeJobStatusError( final ChangeJobStatusError error ) throws ChangeJobStatusException { switch (error.getType()) { case INVALID_REQUEST: case NO_SUCH_JOB: case INCORRECT_CURRENT_STATUS: throw new ChangeJobStatusException( "Failed to claim job: " + error.getType().name() + ": " + error.getMessage() ); case UNKNOWN: default: throw new GenieRuntimeException( "Unhandled error: " + error.getType() + ": " + error.getMessage() ); } } private <ResponseType> ResponseType handleResponseFuture( final ListenableFuture<ResponseType> responseListenableFuture ) { final ResponseType response; try { response = responseListenableFuture.get(); } catch (final ExecutionException | InterruptedException e) { throw new GenieRuntimeException("Failed to perform request", e); } return response; } }
2,998
0
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl
Create_ds/genie/genie-agent/src/main/java/com/netflix/genie/agent/execution/services/impl/grpc/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. * */ /** * gRPC based implementations of the agent execution services. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.agent.execution.services.impl.grpc; import javax.annotation.ParametersAreNonnullByDefault;
2,999