index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/tasks/node/DiskCleanupTask.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.tasks.node; import com.netflix.genie.common.dto.Job; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.jobs.JobConstants; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.properties.DiskCleanupProperties; import com.netflix.genie.web.properties.JobsProperties; import com.netflix.genie.web.tasks.TaskUtils; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.Executor; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.springframework.core.io.Resource; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.support.CronTrigger; import javax.validation.constraints.NotNull; import java.io.File; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; //TODO: this is now only relevant for {@link com.netflix.genie.web.agent.launchers.impl.LocalAgentLauncherImpl}. // Should refactor as such, rather than having this generic disk cleaner inherited from V3. /** * This task runs on every Genie node and is responsible for cleaning up the local disk so that space can be * recaptured. * * @author tgianos * @since 3.0.0 */ @Slf4j public class DiskCleanupTask implements Runnable { private final DiskCleanupProperties properties; private final File jobsDir; private final PersistenceService persistenceService; private final boolean runAsUser; private final Executor processExecutor; private final AtomicLong numberOfDeletedJobDirs; private final AtomicLong numberOfDirsUnableToDelete; private final Counter unableToGetJobCounter; private final Counter unableToDeleteJobDirCounter; /** * Constructor. Schedules this task to be run by the task scheduler. * * @param properties The disk cleanup properties to use. * @param scheduler The scheduler to use to schedule the cron trigger. * @param jobsDir The resource representing the location of the job directory * @param dataServices The {@link DataServices} instance to use * @param jobsProperties The jobs properties to use * @param processExecutor The process executor to use to delete directories * @param registry The metrics registry * @throws IOException When it is unable to open a file reference to the job directory */ public DiskCleanupTask( @NotNull final DiskCleanupProperties properties, @NotNull final TaskScheduler scheduler, @NotNull final Resource jobsDir, @NotNull final DataServices dataServices, @NotNull final JobsProperties jobsProperties, @NotNull final Executor processExecutor, @NotNull final MeterRegistry registry ) throws IOException { // Job Directory is guaranteed to exist by the MvcConfig bean creation but just in case someone overrides if (!jobsDir.exists()) { throw new IOException("Jobs dir " + jobsDir + " doesn't exist. Unable to create task to cleanup."); } this.properties = properties; this.jobsDir = jobsDir.getFile(); this.persistenceService = dataServices.getPersistenceService(); this.runAsUser = jobsProperties.getUsers().isRunAsUserEnabled(); this.processExecutor = processExecutor; this.numberOfDeletedJobDirs = registry.gauge( "genie.tasks.diskCleanup.numberDeletedJobDirs.gauge", new AtomicLong() ); this.numberOfDirsUnableToDelete = registry.gauge( "genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge", new AtomicLong() ); this.unableToGetJobCounter = registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate"); this.unableToDeleteJobDirCounter = registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate"); // Only schedule the task if we don't need sudo while on a non-unix system if (this.runAsUser && !SystemUtils.IS_OS_UNIX) { log.error("System is not UNIX like. Unable to schedule disk cleanup due to needing Unix commands"); } else { final CronTrigger trigger = new CronTrigger(properties.getExpression(), JobConstants.UTC); scheduler.schedule(this, trigger); } } /** * Checks the disk for jobs on this host. Deletes any job directories that are older than the desired * retention and are complete. */ @Override public void run() { log.info("Running disk cleanup task..."); final File[] jobDirs = this.jobsDir.listFiles(); if (jobDirs == null) { log.warn("No job dirs found. Returning."); this.numberOfDeletedJobDirs.set(0); this.numberOfDirsUnableToDelete.set(0); return; } // For each of the directories figure out if we need to delete the files or not long deletedCount = 0; long unableToDeleteCount = 0; for (final File dir : jobDirs) { if (!dir.isDirectory()) { log.info("File {} isn't a directory. Skipping.", dir.getName()); continue; } final String id = dir.getName(); try { final Job job = this.persistenceService.getJob(id); if (job.getStatus().isActive()) { // Don't want to delete anything still going continue; } // Delete anything with a finish time before today @12 AM UTC - retention final Instant midnightUTC = TaskUtils.getMidnightUTC(); final Instant retentionThreshold = midnightUTC.minus(this.properties.getRetention(), ChronoUnit.DAYS); final Optional<Instant> finished = job.getFinished(); if (finished.isPresent() && finished.get().isBefore(retentionThreshold)) { log.info("Attempting to delete job directory for job {}", id); if (this.runAsUser) { final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("rm"); commandLine.addArgument("-rf"); commandLine.addArgument(dir.getAbsolutePath()); this.processExecutor.execute(commandLine); } else { // Save forking a process ourselves if we don't have to FileUtils.deleteDirectory(dir); } deletedCount++; log.info("Successfully deleted job directory for job {}", id); } } catch (final GenieException ge) { log.error("Unable to get job {}. Continuing.", id, ge); this.unableToGetJobCounter.increment(); unableToDeleteCount++; } catch (final IOException ioe) { log.error("Unable to delete job directory for job with id: {}", id, ioe); this.unableToDeleteJobDirCounter.increment(); unableToDeleteCount++; } } this.numberOfDeletedJobDirs.set(deletedCount); this.numberOfDirsUnableToDelete.set(unableToDeleteCount); } }
2,500
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes involved with presenting external APIs. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.apis; import javax.annotation.ParametersAreNonnullByDefault;
2,501
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes and interfaces for presenting the REST APIs for Genie. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.apis.rest; import javax.annotation.ParametersAreNonnullByDefault;
2,502
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * V3 REST API support. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.apis.rest.v3; import javax.annotation.ParametersAreNonnullByDefault;
2,503
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/JobRestController.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteStreams; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.dto.Job; import com.netflix.genie.common.dto.JobExecution; import com.netflix.genie.common.dto.JobMetadata; import com.netflix.genie.common.dto.JobRequest; import com.netflix.genie.common.dto.JobStatus; import com.netflix.genie.common.dto.JobStatusMessages; import com.netflix.genie.common.dto.search.JobSearchResult; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieNotFoundException; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.exceptions.GenieServerUnavailableException; import com.netflix.genie.common.exceptions.GenieUserLimitExceededException; import com.netflix.genie.common.internal.dtos.ApiClientMetadata; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobRequestMetadata; import com.netflix.genie.common.internal.dtos.converters.DtoConverters; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.common.internal.jobs.JobConstants; import com.netflix.genie.common.internal.util.GenieHostInfo; import com.netflix.genie.web.agent.services.AgentRoutingService; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobExecutionModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobMetadataModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobRequestModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobSearchResultModelAssembler; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.dtos.JobSubmission; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.properties.JobsActiveLimitProperties; import com.netflix.genie.web.properties.JobsProperties; import com.netflix.genie.web.services.AttachmentService; import com.netflix.genie.web.services.JobDirectoryServerService; import com.netflix.genie.web.services.JobKillService; import com.netflix.genie.web.services.JobLaunchService; import com.netflix.genie.web.util.MetricsConstants; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.PagedModel; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.annotation.Nullable; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.net.MalformedURLException; import java.net.URL; import java.time.Instant; import java.util.Arrays; import java.util.EnumSet; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * REST end-point for supporting jobs. * * @author amsharma * @author tgianos * @since 3.0.0 */ @RestController @RequestMapping(value = "/api/v3/jobs") @Slf4j public class JobRestController { private static final String TRANSFER_ENCODING_HEADER = "Transfer-Encoding"; private static final String FORWARDED_FOR_HEADER = "X-Forwarded-For"; private static final String NAME_HEADER_COOKIE = "cookie"; private static final String JOB_API_BASE_PATH = "/api/v3/jobs/"; private static final String COMMA = ","; private static final String EMPTY_STRING = ""; private static final String USER_JOB_LIMIT_EXCEEDED_COUNTER_NAME = "genie.jobs.submit.rejected.jobs-limit.counter"; private static final Pattern HTTP_HEADER_FILTER_PATTERN = Pattern.compile("^GENIE_.*"); private final JobLaunchService jobLaunchService; private final ApplicationModelAssembler applicationModelAssembler; private final ClusterModelAssembler clusterModelAssembler; private final CommandModelAssembler commandModelAssembler; private final JobModelAssembler jobModelAssembler; private final JobRequestModelAssembler jobRequestModelAssembler; private final JobExecutionModelAssembler jobExecutionModelAssembler; private final JobMetadataModelAssembler jobMetadataModelAssembler; private final JobSearchResultModelAssembler jobSearchResultModelAssembler; private final String hostname; private final RestTemplate restTemplate; private final JobDirectoryServerService jobDirectoryServerService; private final JobsProperties jobsProperties; private final AgentRoutingService agentRoutingService; private final PersistenceService persistenceService; private final Environment environment; private final AttachmentService attachmentService; private final JobKillService jobKillService; // Metrics private final MeterRegistry registry; private final Counter submitJobWithoutAttachmentsRate; private final Counter submitJobWithAttachmentsRate; /** * Constructor. * * @param jobLaunchService The {@link JobLaunchService} implementation to use * @param dataServices The {@link DataServices} instance to use * @param entityModelAssemblers The encapsulation of all the V3 resource assemblers * @param genieHostInfo Information about the host that the Genie process is running on * @param restTemplate The rest template for http requests * @param jobDirectoryServerService The service to handle serving back job directory resources * @param jobsProperties All the properties associated with jobs * @param registry The metrics registry to use * @param agentRoutingService Agent routing service * @param environment The application environment to pull dynamic properties from * @param attachmentService The attachment service to use to save attachments. * @param jobKillService The service to kill running jobs */ @Autowired @SuppressWarnings("checkstyle:parameternumber") public JobRestController( final JobLaunchService jobLaunchService, final DataServices dataServices, final EntityModelAssemblers entityModelAssemblers, final GenieHostInfo genieHostInfo, @Qualifier("genieRestTemplate") final RestTemplate restTemplate, final JobDirectoryServerService jobDirectoryServerService, final JobsProperties jobsProperties, final MeterRegistry registry, final AgentRoutingService agentRoutingService, final Environment environment, final AttachmentService attachmentService, final JobKillService jobKillService ) { this.jobLaunchService = jobLaunchService; this.applicationModelAssembler = entityModelAssemblers.getApplicationModelAssembler(); this.clusterModelAssembler = entityModelAssemblers.getClusterModelAssembler(); this.commandModelAssembler = entityModelAssemblers.getCommandModelAssembler(); this.jobModelAssembler = entityModelAssemblers.getJobModelAssembler(); this.jobRequestModelAssembler = entityModelAssemblers.getJobRequestModelAssembler(); this.jobExecutionModelAssembler = entityModelAssemblers.getJobExecutionModelAssembler(); this.jobMetadataModelAssembler = entityModelAssemblers.getJobMetadataModelAssembler(); this.jobSearchResultModelAssembler = entityModelAssemblers.getJobSearchResultModelAssembler(); this.hostname = genieHostInfo.getHostname(); this.restTemplate = restTemplate; this.jobDirectoryServerService = jobDirectoryServerService; this.jobsProperties = jobsProperties; this.agentRoutingService = agentRoutingService; this.persistenceService = dataServices.getPersistenceService(); this.environment = environment; this.attachmentService = attachmentService; this.jobKillService = jobKillService; this.registry = registry; // Set up the metrics this.submitJobWithoutAttachmentsRate = registry.counter("genie.api.v3.jobs.submitJobWithoutAttachments.rate"); this.submitJobWithAttachmentsRate = registry.counter("genie.api.v3.jobs.submitJobWithAttachments.rate"); } /** * Submit a new job. * * @param jobRequest The job request information * @param clientHost client host sending the request * @param userAgent The user agent string * @param httpServletRequest The http servlet request * @return The submitted job * @throws GenieException For any error * @throws GenieCheckedException For V4 Agent Execution errors */ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.ACCEPTED) public ResponseEntity<Void> submitJob( @Valid @RequestBody final JobRequest jobRequest, @RequestHeader(value = FORWARDED_FOR_HEADER, required = false) @Nullable final String clientHost, @RequestHeader(value = HttpHeaders.USER_AGENT, required = false) @Nullable final String userAgent, final HttpServletRequest httpServletRequest ) throws GenieException, GenieCheckedException { log.info("[submitJob] Called json method type to submit job: {}", jobRequest); this.submitJobWithoutAttachmentsRate.increment(); return this.handleSubmitJob(jobRequest, null, clientHost, userAgent, httpServletRequest); } /** * Submit a new job with attachments. * * @param jobRequest The job request information * @param attachments The attachments for the job * @param clientHost client host sending the request * @param userAgent The user agent string * @param httpServletRequest The http servlet request * @return The submitted job * @throws GenieException For any error * @throws GenieCheckedException For V4 Agent Execution errors */ @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseStatus(HttpStatus.ACCEPTED) public ResponseEntity<Void> submitJob( @Valid @RequestPart("request") final JobRequest jobRequest, @RequestPart(value = "attachment", required = false) @Nullable final MultipartFile[] attachments, @RequestHeader(value = FORWARDED_FOR_HEADER, required = false) @Nullable final String clientHost, @RequestHeader(value = HttpHeaders.USER_AGENT, required = false) @Nullable final String userAgent, final HttpServletRequest httpServletRequest ) throws GenieException, GenieCheckedException { log.info( "[submitJob] Called multipart method to submit job: {}, with {} attachments", jobRequest, attachments == null ? 0 : attachments.length ); this.submitJobWithAttachmentsRate.increment(); return this.handleSubmitJob(jobRequest, attachments, clientHost, userAgent, httpServletRequest); } private ResponseEntity<Void> handleSubmitJob( final JobRequest jobRequest, @Nullable final MultipartFile[] attachments, @Nullable final String clientHost, @Nullable final String userAgent, final HttpServletRequest httpServletRequest ) throws GenieException, GenieCheckedException { // This node may reject this job this.checkRejectJob(jobRequest); // get client's host from the context final String localClientHost; if (StringUtils.isNotBlank(clientHost)) { localClientHost = clientHost.split(COMMA)[0]; } else { localClientHost = httpServletRequest.getRemoteAddr(); } // Get attachments metadata int numAttachments = 0; long totalSizeOfAttachments = 0L; if (attachments != null) { numAttachments = attachments.length; for (final MultipartFile attachment : attachments) { totalSizeOfAttachments += attachment.getSize(); } } final JobRequestMetadata metadata = new JobRequestMetadata( new ApiClientMetadata(localClientHost, userAgent), null, numAttachments, totalSizeOfAttachments, this.getGenieHeaders(httpServletRequest) ); final JobSubmission.Builder jobSubmissionBuilder = new JobSubmission.Builder( DtoConverters.toV4JobRequest(jobRequest), metadata ); if (attachments != null) { jobSubmissionBuilder.withAttachments( this.attachmentService.saveAttachments( jobRequest.getId().orElse(null), Arrays .stream(attachments) .map(MultipartFile::getResource) .collect(Collectors.toSet()) ) ); } final String jobId = this.jobLaunchService.launchJob(jobSubmissionBuilder.build()); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(jobId) .toUri() ); return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED); } private Map<String, String> getGenieHeaders(final HttpServletRequest httpServletRequest) { final ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder(); final Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (HTTP_HEADER_FILTER_PATTERN.matcher(headerName).matches()) { final String headerValue = httpServletRequest.getHeader(headerName); if (headerValue != null) { mapBuilder.put(headerName, headerValue); } } } return mapBuilder.build(); } // TODO: refactor this ad-hoc checks into a component allowing more flexible logic (and can be replaced/extended) private void checkRejectJob( final JobRequest jobRequest ) throws GenieServerUnavailableException, GenieUserLimitExceededException { if (!this.environment.getProperty(JobConstants.JOB_SUBMISSION_ENABLED_PROPERTY_KEY, Boolean.class, true)) { // Job Submission is disabled throw new GenieServerUnavailableException( this.environment.getProperty( JobConstants.JOB_SUBMISSION_DISABLED_MESSAGE_KEY, JobConstants.JOB_SUBMISSION_DISABLED_DEFAULT_MESSAGE ) ); } final JobsActiveLimitProperties activeLimit = this.jobsProperties.getActiveLimit(); if (activeLimit.isEnabled()) { final String user = jobRequest.getUser(); log.debug("Checking user limits for {}", user); final long activeJobsLimit = activeLimit.getUserLimit(user); final long activeJobsCount = this.persistenceService.getActiveJobCountForUser(user); if (activeJobsCount >= activeJobsLimit) { this.registry.counter( USER_JOB_LIMIT_EXCEEDED_COUNTER_NAME, MetricsConstants.TagKeys.USER, user, MetricsConstants.TagKeys.JOBS_USER_LIMIT, String.valueOf(activeJobsLimit) ).increment(); throw GenieUserLimitExceededException.createForActiveJobsLimit( user, activeJobsCount, activeJobsLimit ); } } } /** * Get job information for given job id. * * @param id id for job to look up * @return the Job * @throws GenieException For any error */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) public EntityModel<Job> getJob(@PathVariable("id") final String id) throws GenieException { log.info("[getJob] Called for job with id: {}", id); return this.jobModelAssembler.toModel(this.persistenceService.getJob(id)); } /** * Get the status of the given job if it exists. * * @param id The id of the job to get status for * @return The status of the job as one of: {@link JobStatus} * @throws NotFoundException When no job with {@literal id} exists */ @GetMapping(value = "/{id}/status", produces = MediaType.APPLICATION_JSON_VALUE) public JsonNode getJobStatus(@PathVariable("id") final String id) throws NotFoundException { log.info("[getJobStatus] Called for job with id: {}", id); final JsonNodeFactory factory = JsonNodeFactory.instance; return factory .objectNode() .set( "status", factory.textNode(DtoConverters.toV3JobStatus(this.persistenceService.getJobStatus(id)).toString()) ); } /** * Get jobs for given filter criteria. * * @param id id for job * @param name name of job (can be a SQL-style pattern such as HIVE%) * @param user user who submitted job * @param statuses statuses of jobs to find * @param tags tags for the job * @param clusterName the name of the cluster * @param clusterId the id of the cluster * @param commandName the name of the command run by the job * @param commandId the id of the command run by the job * @param minStarted The time which the job had to start after in order to be return (inclusive) * @param maxStarted The time which the job had to start before in order to be returned (exclusive) * @param minFinished The time which the job had to finish after in order to be return (inclusive) * @param maxFinished The time which the job had to finish before in order to be returned (exclusive) * @param grouping The grouping the job should be a member of * @param groupingInstance The grouping instance the job should be a member of * @param page page information for job * @param assembler The paged resources assembler to use * @return successful response, or one with HTTP error code * @throws GenieException For any error */ @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @SuppressWarnings("checkstyle:parameternumber") public PagedModel<EntityModel<JobSearchResult>> findJobs( @RequestParam(value = "id", required = false) @Nullable final String id, @RequestParam(value = "name", required = false) @Nullable final String name, @RequestParam(value = "user", required = false) @Nullable final String user, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses, @RequestParam(value = "tag", required = false) @Nullable final Set<String> tags, @RequestParam(value = "clusterName", required = false) @Nullable final String clusterName, @RequestParam(value = "clusterId", required = false) @Nullable final String clusterId, @RequestParam(value = "commandName", required = false) @Nullable final String commandName, @RequestParam(value = "commandId", required = false) @Nullable final String commandId, @RequestParam(value = "minStarted", required = false) @Nullable final Long minStarted, @RequestParam(value = "maxStarted", required = false) @Nullable final Long maxStarted, @RequestParam(value = "minFinished", required = false) @Nullable final Long minFinished, @RequestParam(value = "maxFinished", required = false) @Nullable final Long maxFinished, @RequestParam(value = "grouping", required = false) @Nullable final String grouping, @RequestParam(value = "groupingInstance", required = false) @Nullable final String groupingInstance, @PageableDefault(sort = {"created"}, direction = Sort.Direction.DESC) final Pageable page, final PagedResourcesAssembler<JobSearchResult> assembler ) throws GenieException { log.info( "[getJobs] Called with " + "[id | jobName | user | statuses | clusterName " + "| clusterId | minStarted | maxStarted | minFinished | maxFinished | grouping | groupingInstance " + "| page]\n" + "{} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {}", id, name, user, statuses, tags, clusterName, clusterId, commandName, commandId, minStarted, maxStarted, minFinished, maxFinished, grouping, groupingInstance, page ); Set<JobStatus> enumStatuses = null; if (statuses != null && !statuses.isEmpty()) { enumStatuses = EnumSet.noneOf(JobStatus.class); for (final String status : statuses) { if (StringUtils.isNotBlank(status)) { enumStatuses.add(JobStatus.parse(status)); } } } // Build the self link which will be used for the next, previous, etc links final Link self = WebMvcLinkBuilder .linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .findJobs( id, name, user, statuses, tags, clusterName, clusterId, commandName, commandId, minStarted, maxStarted, minFinished, maxFinished, grouping, groupingInstance, page, assembler ) ).withSelfRel(); return assembler.toModel( this.persistenceService.findJobs( id, name, user, enumStatuses, tags, clusterName, clusterId, commandName, commandId, minStarted == null ? null : Instant.ofEpochMilli(minStarted), maxStarted == null ? null : Instant.ofEpochMilli(maxStarted), minFinished == null ? null : Instant.ofEpochMilli(minFinished), maxFinished == null ? null : Instant.ofEpochMilli(maxFinished), grouping, groupingInstance, page ), this.jobSearchResultModelAssembler, self ); } /** * Kill job based on given job ID. * * @param id id for job to kill * @param forwardedFrom The host this request was forwarded from if present * @param request the servlet request * @throws GenieServerException For any error */ @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.ACCEPTED) public void killJob( @PathVariable("id") final String id, @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) @Nullable final String forwardedFrom, final HttpServletRequest request ) throws GenieException { log.info( "[killJob] Called for job: {}.{}", id, forwardedFrom == null ? EMPTY_STRING : " Forwarded from " + forwardedFrom ); this.jobKillService.killJob(id, JobStatusMessages.JOB_KILLED_BY_USER, request); } /** * Get the original job request. * * @param id The id of the job * @return The job request * @throws NotFoundException If no job with {@literal id} exists */ @GetMapping(value = "/{id}/request", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<JobRequest> getJobRequest(@PathVariable("id") final String id) throws NotFoundException { log.info("[getJobRequest] Called for job request with id {}", id); return this.jobRequestModelAssembler.toModel( new JobRequestModelAssembler.JobRequestWrapper( id, DtoConverters.toV3JobRequest(this.persistenceService.getJobRequest(id)) ) ); } /** * Get the execution information about a job. * * @param id The id of the job * @return The job execution * @throws GenieException On any internal error */ @GetMapping(value = "/{id}/execution", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<JobExecution> getJobExecution( @PathVariable("id") final String id ) throws GenieException { log.info("[getJobExecution] Called for job execution with id {}", id); return this.jobExecutionModelAssembler.toModel(this.persistenceService.getJobExecution(id)); } /** * Get the metadata information about a job. * * @param id The id of the job * @return The job metadata * @throws GenieException On any internal error * @since 3.3.5 */ @GetMapping(value = "/{id}/metadata", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<JobMetadata> getJobMetadata(@PathVariable("id") final String id) throws GenieException { log.info("[getJobMetadata] Called for job metadata with id {}", id); return this.jobMetadataModelAssembler.toModel(this.persistenceService.getJobMetadata(id)); } /** * Get the cluster the job was run on or is currently running on. * * @param id The id of the job to get the cluster for * @return The cluster * @throws NotFoundException When either the job or the cluster aren't found */ @GetMapping(value = "/{id}/cluster", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Cluster> getJobCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getJobCluster] Called for job with id {}", id); return this.clusterModelAssembler.toModel(DtoConverters.toV3Cluster(this.persistenceService.getJobCluster(id))); } /** * Get the command the job was run with or is currently running with. * * @param id The id of the job to get the command for * @return The command * @throws NotFoundException When either the job or the command aren't found */ @GetMapping(value = "/{id}/command", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Command> getJobCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("[getJobCommand] Called for job with id {}", id); return this.commandModelAssembler.toModel(DtoConverters.toV3Command(this.persistenceService.getJobCommand(id))); } /** * Get the applications used ot run the job. * * @param id The id of the job to get the applications for * @return The applications * @throws NotFoundException When either the job or the applications aren't found */ @GetMapping(value = "/{id}/applications", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityModel<Application>> getJobApplications( @PathVariable("id") final String id ) throws NotFoundException { log.info("[getJobApplications] Called for job with id {}", id); return this.persistenceService .getJobApplications(id) .stream() .map(DtoConverters::toV3Application) .map(this.applicationModelAssembler::toModel) .collect(Collectors.toList()); } /** * Get the job output directory. * * @param id The id of the job to get output for * @param forwardedFrom The host this request was forwarded from if present * @param request the servlet request * @param response the servlet response * @throws NotFoundException When no job with {@literal id} exists * @throws GenieException on any Genie internal error */ @GetMapping( value = { "/{id}/output", "/{id}/output/", "/{id}/output/**" } ) public void getJobOutput( @PathVariable("id") final String id, @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) @Nullable final String forwardedFrom, final HttpServletRequest request, final HttpServletResponse response ) throws GenieException, NotFoundException { final String path = ControllerUtils.getRemainingPath(request); log.info( "[getJobOutput] Called to get output path: \"{}\" for job: \"{}\".{}", path, id, forwardedFrom == null ? EMPTY_STRING : " Requested forwarded from: " + forwardedFrom ); final URL baseUrl; try { baseUrl = forwardedFrom == null ? ControllerUtils.getRequestRoot(request, path) : ControllerUtils.getRequestRoot(new URL(forwardedFrom), path); } catch (final MalformedURLException e) { throw new GenieServerException("Unable to parse base request url", e); } final ArchiveStatus archiveStatus = this.persistenceService.getJobArchiveStatus(id); if (archiveStatus == ArchiveStatus.PENDING) { final String jobHostname; try { jobHostname = this.agentRoutingService .getHostnameForAgentConnection(id) .orElseThrow(() -> new NotFoundException("No hostname found for job - " + id)); } catch (NotFoundException e) { throw new GenieServerException("Failed to route request", e); } final boolean shouldForward = !this.hostname.equals(jobHostname); final boolean canForward = forwardedFrom == null && this.jobsProperties.getForwarding().isEnabled(); if (shouldForward && canForward) { // Forward request to another node forwardRequest(id, path, jobHostname, request, response); return; } else if (!canForward && shouldForward) { // Should forward but can't throw new GenieServerException("Job files are not local, but forwarding is disabled"); } } // In any other case, delegate the request to the service log.debug("Fetching requested resource \"{}\" for job \"{}\"", path, id); this.jobDirectoryServerService.serveResource(id, baseUrl, path, request, response); } private void forwardRequest( final String id, final String path, final String jobHostname, final HttpServletRequest request, final HttpServletResponse response ) throws GenieException { log.info("Job {} is not run on this node. Forwarding to {}", id, jobHostname); final String forwardHost = this.buildForwardHost(jobHostname); try { this.restTemplate.execute( forwardHost + JOB_API_BASE_PATH + id + "/output/" + path, HttpMethod.GET, forwardRequest -> copyRequestHeaders(request, forwardRequest), (ResponseExtractor<Void>) forwardResponse -> { response.setStatus(forwardResponse.getStatusCode().value()); copyResponseHeaders(response, forwardResponse); // Documentation I could find pointed to the HttpEntity reading the bytes off // the stream so this should resolve memory problems if the file returned is large ByteStreams.copy(forwardResponse.getBody(), response.getOutputStream()); return null; } ); } catch (final HttpClientErrorException.NotFound e) { throw new GenieNotFoundException("Not Found (via: " + forwardHost + ")", e); } catch (final HttpStatusCodeException e) { throw new GenieException(e.getStatusCode().value(), "Proxied request failed: " + e.getMessage(), e); } catch (final Exception e) { log.error("Failed getting the remote job output from {}. Error: {}", forwardHost, e.getMessage()); throw new GenieServerException("Proxied request error:" + e.getMessage(), e); } } private String buildForwardHost(final String jobHostname) { return this.jobsProperties.getForwarding().getScheme() + "://" + jobHostname + ":" + this.jobsProperties.getForwarding().getPort(); } private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) { // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header. final HttpHeaders headers = forwardRequest.getHeaders(); final Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (!NAME_HEADER_COOKIE.equals(headerName)) { final String headerValue = request.getHeader(headerName); log.debug("Request Header: name = {} value = {}", headerName, headerValue); headers.add(headerName, headerValue); } } } // Lets add the cookie as an header final Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { StringBuilder builder = null; for (final Cookie cookie : request.getCookies()) { if (builder == null) { builder = new StringBuilder(); } else { builder.append(","); } builder.append(cookie.getName()).append("=").append(cookie.getValue()); } if (builder != null) { final String cookieValue = builder.toString(); headers.add(NAME_HEADER_COOKIE, cookieValue); log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue); } } // This method only called when need to forward so add the forwarded from header headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString()); } private void copyResponseHeaders(final HttpServletResponse response, final ClientHttpResponse forwardResponse) { final HttpHeaders headers = forwardResponse.getHeaders(); for (final Map.Entry<String, String> header : headers.toSingleValueMap().entrySet()) { // // Do not add transfer encoding header since it forces Apache to truncate the response. Ideally we should // only copy headers that are needed. // if (!TRANSFER_ENCODING_HEADER.equalsIgnoreCase(header.getKey())) { response.setHeader(header.getKey(), header.getValue()); } } } }
2,504
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/RootRestController.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.RootModelAssembler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.MediaTypes; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * Rest controller for the V3 API root. * * @author tgianos * @since 3.0.0 */ @RestController @RequestMapping(value = "/api/v3") @Slf4j public class RootRestController { private final RootModelAssembler rootModelAssembler; private final Map<String, String> metadata; /** * Constructor. * * @param rootModelAssembler The assembler to use to construct resources. */ @Autowired public RootRestController(final RootModelAssembler rootModelAssembler) { this.rootModelAssembler = rootModelAssembler; this.metadata = new HashMap<>(); this.metadata.put("description", "Genie V3 API"); } /** * Get a simple HAL+JSON object which represents the various links available in Genie REST API as an entry point. * * @return the root resource containing various links to the real APIs */ @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Map<String, String>> getRoot() { return this.rootModelAssembler.toModel(this.metadata); } }
2,505
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/ClusterRestController.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchException; import com.google.common.collect.Lists; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.ClusterStatus; import com.netflix.genie.common.internal.dtos.converters.DtoConverters; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.exceptions.checked.PreconditionFailedException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.PagedModel; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.annotation.Nullable; import javax.validation.Valid; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * REST end-point for supporting clusters. * * @author tgianos * @since 3.0.0 */ @RestController @RequestMapping(value = "/api/v3/clusters") @Slf4j public class ClusterRestController { private static final List<EntityModel<Command>> EMPTY_COMMAND_LIST = new ArrayList<>(0); private final PersistenceService persistenceService; private final ClusterModelAssembler clusterModelAssembler; /** * Constructor. * * @param dataServices The {@link DataServices} encapsulation instance to use. * @param entityModelAssemblers The encapsulation of all available V3 resource assemblers */ @Autowired public ClusterRestController(final DataServices dataServices, final EntityModelAssemblers entityModelAssemblers) { this.persistenceService = dataServices.getPersistenceService(); this.clusterModelAssembler = entityModelAssemblers.getClusterModelAssembler(); } /** * Create cluster configuration. * * @param cluster contains the cluster information to create * @return The created cluster * @throws IdAlreadyExistsException If there is a conflict for the id */ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Void> createCluster( @RequestBody @Valid final Cluster cluster ) throws IdAlreadyExistsException { log.info("[createCluster] Called to create new cluster {}", cluster); final String id = this.persistenceService.saveCluster(DtoConverters.toV4ClusterRequest(cluster)); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(id) .toUri() ); return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED); } /** * Get cluster configuration from unique id. * * @param id id for the cluster * @return the cluster * @throws NotFoundException If no cluster with {@literal id} exists */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Cluster> getCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getCluster] Called with id: {}", id); return this.clusterModelAssembler.toModel( DtoConverters.toV3Cluster(this.persistenceService.getCluster(id)) ); } /** * Get cluster config based on user params. If empty strings are passed for * they are treated as nulls (not false). * * @param name cluster name (can be a pattern) * @param statuses valid types - Types.ClusterStatus * @param tags tags for the cluster * @param minUpdateTime min time when cluster configuration was updated * @param maxUpdateTime max time when cluster configuration was updated * @param page The page to get * @param assembler The paged resources assembler to use * @return the Clusters found matching the criteria * @throws GenieException For any error */ @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public PagedModel<EntityModel<Cluster>> getClusters( @RequestParam(value = "name", required = false) @Nullable final String name, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses, @RequestParam(value = "tag", required = false) @Nullable final Set<String> tags, @RequestParam(value = "minUpdateTime", required = false) @Nullable final Long minUpdateTime, @RequestParam(value = "maxUpdateTime", required = false) @Nullable final Long maxUpdateTime, @PageableDefault(size = 64, sort = {"updated"}, direction = Sort.Direction.DESC) final Pageable page, final PagedResourcesAssembler<Cluster> assembler ) throws GenieException { log.info( "[getClusters] Called to find clusters [name | statuses | tags | minUpdateTime | maxUpdateTime | page]\n" + "{} | {} | {} | {} | {} | {}", name, statuses, tags, minUpdateTime, maxUpdateTime, page ); //Create this conversion internal in case someone uses lower case by accident? Set<ClusterStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(ClusterStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4ClusterStatus(com.netflix.genie.common.dto.ClusterStatus.parse(status)) ); } } final Page<Cluster> clusters; if (tags != null && tags.stream().filter(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX)).count() >= 1L) { // TODO: This doesn't take into account others as compounded find...not sure if good or bad final List<Cluster> clusterList = Lists.newArrayList(); final int prefixLength = DtoConverters.GENIE_ID_PREFIX.length(); tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX)) .forEach( tag -> { final String id = tag.substring(prefixLength); try { clusterList.add(DtoConverters.toV3Cluster(this.persistenceService.getCluster(id))); } catch (final NotFoundException ge) { log.debug("No cluster with id {} found", id, ge); } } ); clusters = new PageImpl<>(clusterList); } else if (tags != null && tags.stream().anyMatch(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX))) { final Set<String> finalTags = tags .stream() .filter(tag -> !tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .collect(Collectors.toSet()); if (name == null) { final Optional<String> finalName = tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .map(tag -> tag.substring(DtoConverters.GENIE_NAME_PREFIX.length())) .findFirst(); clusters = this.persistenceService .findClusters( finalName.orElse(null), enumStatuses, finalTags, minUpdateTime == null ? null : Instant.ofEpochMilli(minUpdateTime), maxUpdateTime == null ? null : Instant.ofEpochMilli(maxUpdateTime), page ) .map(DtoConverters::toV3Cluster); } else { clusters = this.persistenceService .findClusters( name, enumStatuses, finalTags, minUpdateTime == null ? null : Instant.ofEpochMilli(minUpdateTime), maxUpdateTime == null ? null : Instant.ofEpochMilli(maxUpdateTime), page ) .map(DtoConverters::toV3Cluster); } } else { clusters = this.persistenceService .findClusters( name, enumStatuses, tags, minUpdateTime == null ? null : Instant.ofEpochMilli(minUpdateTime), maxUpdateTime == null ? null : Instant.ofEpochMilli(maxUpdateTime), page ) .map(DtoConverters::toV3Cluster); } // Build the self link which will be used for the next, previous, etc links final Link self = WebMvcLinkBuilder .linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getClusters( name, statuses, tags, minUpdateTime, maxUpdateTime, page, assembler ) ).withSelfRel(); return assembler.toModel(clusters, this.clusterModelAssembler, self); } /** * Update a cluster configuration. * * @param id unique if for cluster to update * @param updateCluster contains the cluster information to update * @throws NotFoundException If no cluster with {@literal id} exists * @throws PreconditionFailedException If the ids don't match */ @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateCluster( @PathVariable("id") final String id, @RequestBody final Cluster updateCluster ) throws NotFoundException, PreconditionFailedException { log.info("[updateCluster] Called with id {} update fields {}", id, updateCluster); this.persistenceService.updateCluster(id, DtoConverters.toV4Cluster(updateCluster)); } /** * Patch a cluster using JSON Patch. * * @param id The id of the cluster to patch * @param patch The JSON Patch instructions * @throws NotFoundException If no cluster with {@literal id} exists * @throws PreconditionFailedException If the ids don't match * @throws GenieServerException If the patch can't be applied */ @PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void patchCluster( @PathVariable("id") final String id, @RequestBody final JsonPatch patch ) throws NotFoundException, PreconditionFailedException, GenieServerException { log.info("[patchCluster] Called with id {} with patch {}", id, patch); final Cluster currentCluster = DtoConverters.toV3Cluster(this.persistenceService.getCluster(id)); try { log.debug("Will patch cluster {}. Original state: {}", id, currentCluster); final JsonNode clusterNode = GenieObjectMapper.getMapper().valueToTree(currentCluster); final JsonNode postPatchNode = patch.apply(clusterNode); final Cluster patchedCluster = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Cluster.class); log.debug("Finished patching cluster {}. New state: {}", id, patchedCluster); this.persistenceService.updateCluster(id, DtoConverters.toV4Cluster(patchedCluster)); } catch (final JsonPatchException | IOException e) { log.error("Unable to patch cluster {} with patch {} due to exception.", id, patch, e); throw new GenieServerException(e.getLocalizedMessage(), e); } } /** * Delete a cluster configuration. * * @param id unique id for cluster to delete * @throws PreconditionFailedException If the cluster can't be deleted due to constraints */ @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteCluster(@PathVariable("id") final String id) throws PreconditionFailedException { log.info("[deleteCluster] Called for id: {}", id); this.persistenceService.deleteCluster(id); } /** * Delete all clusters from database. * * @throws PreconditionFailedException If any cluster can't be deleted due to a constraint in the system */ @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteAllClusters() throws PreconditionFailedException { log.warn("[deleteAllClusters] Called"); this.persistenceService.deleteAllClusters(); } /** * Add new configuration files to a given cluster. * * @param id The id of the cluster to add the configuration file to. Not null/empty/blank. * @param configs The configuration files to add. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @PostMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addConfigsForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("[addConfigsForCluster] Called with id {} and config {}", id, configs); this.persistenceService.addConfigsToResource( id, configs, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Get all the configuration files for a given cluster. * * @param id The id of the cluster to get the configuration files for. Not NULL/empty/blank. * @return The active set of configuration files. * @throws NotFoundException If no cluster with {@literal id} exists */ @GetMapping(value = "/{id}/configs", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getConfigsForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getConfigsForCluster] Called with id {}", id); return this.persistenceService.getConfigsForResource( id, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Update the configuration files for a given cluster. * * @param id The id of the cluster to update the configuration files for. Not null/empty/blank. * @param configs The configuration files to replace existing configuration files with. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @PutMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateConfigsForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("[updateConfigsForCluster] Called with id {} and configs {}", id, configs); this.persistenceService.updateConfigsForResource( id, configs, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Delete the all configuration files from a given cluster. * * @param id The id of the cluster to delete the configuration files from. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @DeleteMapping(value = "/{id}/configs") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllConfigsForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[removeAllConfigsForCluster] Called with id {}", id); this.persistenceService.removeAllConfigsForResource( id, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Add new dependency files for a given cluster. * * @param id The id of the cluster to add the dependency file to. Not null/empty/blank. * @param dependencies The dependency files to add. Not null. * @throws NotFoundException If no cluster with {@literal id} exists */ @PostMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addDependenciesForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("[addDependenciesForCluster] Called with id {} and dependencies {}", id, dependencies); this.persistenceService.addDependenciesToResource( id, dependencies, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Get all the dependency files for a given cluster. * * @param id The id of the cluster to get the dependency files for. Not NULL/empty/blank * @return The set of dependency files * @throws NotFoundException If no cluster with {@literal id} exists */ @GetMapping(value = "/{id}/dependencies", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getDependenciesForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getDependenciesForCluster] Called with id {}", id); return this.persistenceService.getDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Update the dependency files for a given cluster. * * @param id The id of the cluster to update the dependency files for. Not null/empty/blank. * @param dependencies The dependency files to replace existing dependency files with. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @PutMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateDependenciesForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("[updateDependenciesForCluster] Called with id {} and dependencies {}", id, dependencies); this.persistenceService.updateDependenciesForResource( id, dependencies, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Delete the all dependency files from a given cluster. * * @param id The id of the cluster to delete the dependency files from. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @DeleteMapping(value = "/{id}/dependencies") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllDependenciesForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[removeAllDependenciesForCluster] Called with id {}", id); this.persistenceService.removeAllDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Add new tags to a given cluster. * * @param id The id of the cluster to add the tags to. Not null/empty/blank. * @param tags The tags to add. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @PostMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addTagsForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("[addTagsForCluster] Called with id {} and tags {}", id, tags); this.persistenceService.addTagsToResource(id, tags, com.netflix.genie.common.internal.dtos.Cluster.class); } /** * Get all the tags for a given cluster. * * @param id The id of the cluster to get the tags for. Not NULL/empty/blank. * @return The active set of tags. * @throws NotFoundException If no cluster with {@literal id} exists */ @GetMapping(value = "/{id}/tags", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getTagsForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[getTagsForCluster] Called with id {}", id); // Left this way for v3 tag conversion return DtoConverters.toV3Cluster(this.persistenceService.getCluster(id)).getTags(); } /** * Update the tags for a given cluster. * * @param id The id of the cluster to update the tags for. Not null/empty/blank. * @param tags The tags to replace existing configuration files with. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @PutMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateTagsForCluster( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("[updateTagsForCluster] Called with id {} and tags {}", id, tags); this.persistenceService.updateTagsForResource( id, tags, com.netflix.genie.common.internal.dtos.Cluster.class ); } /** * Delete the all tags from a given cluster. * * @param id The id of the cluster to delete the tags from. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @DeleteMapping(value = "/{id}/tags") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllTagsForCluster(@PathVariable("id") final String id) throws NotFoundException { log.info("[removeAllTagsForCluster] Called with id {}", id); this.persistenceService.removeAllTagsForResource(id, com.netflix.genie.common.internal.dtos.Cluster.class); } /** * Remove an tag from a given cluster. * * @param id The id of the cluster to delete the tag from. Not null/empty/blank. * @param tag The tag to remove. Not null/empty/blank. * @throws NotFoundException If no cluster with {@literal id} exists */ @DeleteMapping(value = "/{id}/tags/{tag}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeTagForCluster( @PathVariable("id") final String id, @PathVariable("tag") final String tag ) throws NotFoundException { log.info("[removeTagForCluster] Called with id {} and tag {}", id, tag); this.persistenceService.removeTagForResource(id, tag, com.netflix.genie.common.internal.dtos.Cluster.class); } /** * Add new commandIds to the given cluster. This is a no-op as of 4.0.0. * * @param id The id of the cluster to add the commandIds to. Not null/empty/blank. * @param commandIds The ids of the commandIds to add. Not null. */ @PostMapping(value = "/{id}/commands", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addCommandsForCluster( @PathVariable("id") final String id, @RequestBody final List<String> commandIds ) { log.info("[addCommandsForCluster] Called with id {} and commandIds {}. No-op.", id, commandIds); } /** * Get all the commands configured for a given cluster. This is a no-op as of 4.0.0. * * @param id The id of the cluster to get the command files for. Not NULL/empty/blank. * @param statuses The various statuses to return commandIds for. * @return The active set of commandIds for the cluster. * @throws NotFoundException If the cluster doesn't exist */ @GetMapping(value = "/{id}/commands", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityModel<Command>> getCommandsForCluster( @PathVariable("id") final String id, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses ) throws NotFoundException { log.info("[getCommandsForCluster] Called with id {} status {}. No-op.", id, statuses); // Keep the contract where if the cluster doesn't exist a 404 is thrown. May be slightly slower but // more accurate. this.persistenceService.getCluster(id); return EMPTY_COMMAND_LIST; } /** * Set the commandIds for a given cluster. This is a no-op as of 4.0.0. * * @param id The id of the cluster to update the configuration files for. Not null/empty/blank. * @param commandIds The ids of the commands to replace existing commands with. Not null/empty/blank. */ @PutMapping(value = "/{id}/commands", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void setCommandsForCluster( @PathVariable("id") final String id, @RequestBody final List<String> commandIds ) { log.info("[setCommandsForCluster] Called with id {} and commandIds {}. No-op.", id, commandIds); } /** * Remove the all commandIds from a given cluster. This is a no-op as of 4.0.0. * * @param id The id of the cluster to delete the commandIds from. Not null/empty/blank. */ @DeleteMapping(value = "/{id}/commands") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllCommandsForCluster(@PathVariable("id") final String id) { log.info("[removeAllCommandsForCluster] Called with id {}. No-op.", id); } /** * Remove a command from a given cluster. This is a no-op as of 4.0.0. * * @param id The id of the cluster to delete the command from. Not null/empty/blank. * @param commandId The id of the command to remove. Not null/empty/blank. */ @DeleteMapping(value = "/{id}/commands/{commandId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeCommandForCluster( @PathVariable("id") final String id, @PathVariable("commandId") final String commandId ) { log.info("[removeCommandForCluster] Called with id {} and command id {}. No-op.", id, commandId); } }
2,506
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/GenieExceptionMapper.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.google.common.collect.Sets; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.exceptions.GenieUserLimitExceededException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieApplicationNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieClusterNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieCommandNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieIdAlreadyExistsException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobSpecificationNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException; import com.netflix.genie.web.exceptions.checked.AttachmentTooLargeException; import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException; import com.netflix.genie.web.exceptions.checked.JobNotFoundException; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.exceptions.checked.PreconditionFailedException; import com.netflix.genie.web.util.MetricsConstants; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.validation.ConstraintViolationException; import java.util.Set; /** * Exception mapper for Genie Exceptions. * * @author tgianos * @since 3.0.0 */ @Slf4j @ControllerAdvice public class GenieExceptionMapper { // TODO: Not changing this while changing controller package due to need to keep dashboards in sync but we should // rename it going forward - TJG 7/17/19 static final String CONTROLLER_EXCEPTION_COUNTER_NAME = "genie.web.controllers.exception"; private static final String USER_NAME_TAG_KEY = "user"; private static final String LIMIT_TAG_KEY = "limit"; private final MeterRegistry registry; /** * Constructor. * * @param registry The metrics registry */ @Autowired public GenieExceptionMapper(final MeterRegistry registry) { this.registry = registry; } /** * Handle Genie Exceptions. * * @param e The exception to handle * @return An {@link ResponseEntity} instance */ @ExceptionHandler(GenieException.class) public ResponseEntity<GenieException> handleGenieException(final GenieException e) { this.countExceptionAndLog(e); HttpStatus status = HttpStatus.resolve(e.getErrorCode()); if (status == null) { status = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(e, status); } /** * Handle Genie runtime exceptions. * * @param e The Genie exception to handle * @return A {@link ResponseEntity} with the exception mapped to a {@link HttpStatus} */ @ExceptionHandler(GenieRuntimeException.class) public ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e) { this.countExceptionAndLog(e); if ( e instanceof GenieApplicationNotFoundException || e instanceof GenieCommandNotFoundException || e instanceof GenieClusterNotFoundException || e instanceof GenieJobNotFoundException || e instanceof GenieJobSpecificationNotFoundException ) { return new ResponseEntity<>(e, HttpStatus.NOT_FOUND); } else if (e instanceof GenieIdAlreadyExistsException) { return new ResponseEntity<>(e, HttpStatus.CONFLICT); } else { return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Handle {@link GenieCheckedException} instances. * * @param e The exception to map * @return A {@link ResponseEntity} with the exception mapped to a {@link HttpStatus} */ @ExceptionHandler(GenieCheckedException.class) public ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e) { this.countExceptionAndLog(e); if (e instanceof GenieJobResolutionException) { // Mapped to Precondition failed to maintain existing contract with V3 return new ResponseEntity<>(e, HttpStatus.PRECONDITION_FAILED); } else if (e instanceof IdAlreadyExistsException) { return new ResponseEntity<>(e, HttpStatus.CONFLICT); } else if (e instanceof JobNotFoundException | e instanceof NotFoundException) { return new ResponseEntity<>(e, HttpStatus.NOT_FOUND); } else if (e instanceof PreconditionFailedException) { return new ResponseEntity<>(e, HttpStatus.BAD_REQUEST); } else if (e instanceof AttachmentTooLargeException) { return new ResponseEntity<>(e, HttpStatus.PAYLOAD_TOO_LARGE); } else { return new ResponseEntity<>(e, HttpStatus.INTERNAL_SERVER_ERROR); } } /** * Handle constraint violation exceptions. * * @param cve The exception to handle * @return A {@link ResponseEntity} instance */ @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ) { this.countExceptionAndLog(cve); return new ResponseEntity<>( new GeniePreconditionException(cve.getMessage(), cve), HttpStatus.PRECONDITION_FAILED ); } /** * Handle MethodArgumentNotValid exceptions. * * @param e The exception to handle * @return A {@link ResponseEntity} instance */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException( final MethodArgumentNotValidException e ) { this.countExceptionAndLog(e); return new ResponseEntity<>( new GeniePreconditionException(e.getMessage(), e), HttpStatus.PRECONDITION_FAILED ); } private void countExceptionAndLog(final Exception e) { final Set<Tag> tags = Sets.newHashSet( Tags.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, e.getClass().getCanonicalName()) ); if (e instanceof GenieUserLimitExceededException) { final GenieUserLimitExceededException userLimitExceededException = (GenieUserLimitExceededException) e; tags.add(Tag.of(USER_NAME_TAG_KEY, userLimitExceededException.getUser())); tags.add(Tag.of(LIMIT_TAG_KEY, userLimitExceededException.getExceededLimitName())); } this.registry.counter(CONTROLLER_EXCEPTION_COUNTER_NAME, tags).increment(); log.error("{}: {}", e.getClass().getSimpleName(), e.getLocalizedMessage()); log.debug("{}: {}", e.getClass().getCanonicalName(), e.getMessage(), e); } }
2,507
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/CommandRestController.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchException; import com.google.common.collect.Lists; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.dto.ResolvedResources; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.ClusterStatus; import com.netflix.genie.common.internal.dtos.CommandStatus; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.common.internal.dtos.converters.DtoConverters; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.exceptions.checked.PreconditionFailedException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.PagedModel; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Min; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * REST end-point for supporting commands. * * @author amsharma * @author tgianos * @since 3.0.0 */ @RestController @RequestMapping(value = "/api/v3/commands") @Slf4j public class CommandRestController { private final PersistenceService persistenceService; private final CommandModelAssembler commandModelAssembler; private final ApplicationModelAssembler applicationModelAssembler; private final ClusterModelAssembler clusterModelAssembler; /** * Constructor. * * @param dataServices The {@link DataServices} encapsulation instance to use * @param entityModelAssemblers The encapsulation of all available V3 resource assemblers */ @Autowired public CommandRestController(final DataServices dataServices, final EntityModelAssemblers entityModelAssemblers) { this.persistenceService = dataServices.getPersistenceService(); this.commandModelAssembler = entityModelAssemblers.getCommandModelAssembler(); this.applicationModelAssembler = entityModelAssemblers.getApplicationModelAssembler(); this.clusterModelAssembler = entityModelAssemblers.getClusterModelAssembler(); } /** * Create a Command configuration. * * @param command The command configuration to create * @return The command created * @throws IdAlreadyExistsException When the command id was already used */ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Void> createCommand( @RequestBody @Valid final Command command ) throws IdAlreadyExistsException { log.info("Called to create new command {}", command); final String id = this.persistenceService.saveCommand(DtoConverters.toV4CommandRequest(command)); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(id) .toUri() ); return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED); } /** * Get Command configuration for given id. * * @param id unique id for command configuration * @return The command configuration * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Command> getCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called to get command with id {}", id); return this.commandModelAssembler.toModel( DtoConverters.toV3Command(this.persistenceService.getCommand(id)) ); } /** * Get Command configuration based on user parameters. * * @param name Name for command (optional) * @param user The user who created the configuration (optional) * @param statuses The statuses of the commands to get (optional) * @param tags The set of tags you want the command for. * @param page The page to get * @param assembler The paged resources assembler to use * @return All the Commands matching the criteria or all if no criteria * @throws GenieException For any error */ @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public PagedModel<EntityModel<Command>> getCommands( @RequestParam(value = "name", required = false) @Nullable final String name, @RequestParam(value = "user", required = false) @Nullable final String user, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses, @RequestParam(value = "tag", required = false) @Nullable final Set<String> tags, @PageableDefault(size = 64, sort = {"updated"}, direction = Sort.Direction.DESC) final Pageable page, final PagedResourcesAssembler<Command> assembler ) throws GenieException { log.info( "Called [name | user | status | tags | page]\n{} | {} | {} | {} | {}", name, user, statuses, tags, page ); Set<CommandStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(CommandStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4CommandStatus(com.netflix.genie.common.dto.CommandStatus.parse(status)) ); } } final Page<Command> commands; if (tags != null && tags.stream().anyMatch(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX))) { // TODO: This doesn't take into account others as compounded find...not sure if good or bad final List<Command> commandList = Lists.newArrayList(); final int prefixLength = DtoConverters.GENIE_ID_PREFIX.length(); tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX)) .forEach( tag -> { final String id = tag.substring(prefixLength); try { commandList.add(DtoConverters.toV3Command(this.persistenceService.getCommand(id))); } catch (final NotFoundException ge) { log.debug("No command with id {} found", id, ge); } } ); commands = new PageImpl<>(commandList); } else if (tags != null && tags.stream().anyMatch(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX))) { final Set<String> finalTags = tags .stream() .filter(tag -> !tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .collect(Collectors.toSet()); if (name == null) { final Optional<String> finalName = tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .map(tag -> tag.substring(DtoConverters.GENIE_NAME_PREFIX.length())) .findFirst(); commands = this.persistenceService .findCommands( finalName.orElse(null), user, enumStatuses, finalTags, page ) .map(DtoConverters::toV3Command); } else { commands = this.persistenceService .findCommands( name, user, enumStatuses, finalTags, page ) .map(DtoConverters::toV3Command); } } else { commands = this.persistenceService .findCommands( name, user, enumStatuses, tags, page ) .map(DtoConverters::toV3Command); } // Build the self link which will be used for the next, previous, etc links final Link self = WebMvcLinkBuilder .linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getCommands( name, user, statuses, tags, page, assembler ) ).withSelfRel(); return assembler.toModel( commands, this.commandModelAssembler, self ); } /** * Update command configuration. * * @param id unique id for the configuration to update. * @param updateCommand the information to update the command with * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws PreconditionFailedException When {@literal id} and the {@literal updateCommand} id don't match */ @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateCommand( @PathVariable("id") final String id, @RequestBody final Command updateCommand ) throws NotFoundException, PreconditionFailedException { log.debug("Called to update command {}", updateCommand); this.persistenceService.updateCommand(id, DtoConverters.toV4Command(updateCommand)); } /** * Patch a command using JSON Patch. * * @param id The id of the command to patch * @param patch The JSON Patch instructions * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws PreconditionFailedException When {@literal id} and the {@literal updateCommand} id don't match * @throws GenieServerException When the patch can't be applied */ @PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void patchCommand( @PathVariable("id") final String id, @RequestBody final JsonPatch patch ) throws NotFoundException, PreconditionFailedException, GenieServerException { log.info("Called to patch command {} with patch {}", id, patch); final Command currentCommand = DtoConverters.toV3Command(this.persistenceService.getCommand(id)); try { log.debug("Will patch cluster {}. Original state: {}", id, currentCommand); final JsonNode commandNode = GenieObjectMapper.getMapper().valueToTree(currentCommand); final JsonNode postPatchNode = patch.apply(commandNode); final Command patchedCommand = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Command.class); log.debug("Finished patching command {}. New state: {}", id, patchedCommand); this.persistenceService.updateCommand(id, DtoConverters.toV4Command(patchedCommand)); } catch (final JsonPatchException | IOException e) { log.error("Unable to patch command {} with patch {} due to exception.", id, patch, e); throw new GenieServerException(e.getLocalizedMessage(), e); } } /** * Delete all applications from database. * * @throws PreconditionFailedException When deleting one of the commands would violated a consistency issue */ @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteAllCommands() throws PreconditionFailedException { log.warn("Called to delete all commands."); this.persistenceService.deleteAllCommands(); } /** * Delete a command. * * @param id unique id for configuration to delete * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called to delete command with id {}", id); this.persistenceService.deleteCommand(id); } /** * Add new configuration files to a given command. * * @param id The id of the command to add the configuration file to. Not null/empty/blank. * @param configs The configuration files to add. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PostMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addConfigsForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("Called with id {} and config {}", id, configs); this.persistenceService.addConfigsToResource( id, configs, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Get all the configuration files for a given command. * * @param id The id of the command to get the configuration files for. Not NULL/empty/blank. * @return The active set of configuration files. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/configs", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getConfigsForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); return this.persistenceService.getConfigsForResource( id, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Update the configuration files for a given command. * * @param id The id of the command to update the configuration files for. Not null/empty/blank. * @param configs The configuration files to replace existing configuration files with. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PutMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateConfigsForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("Called with id {} and configs {}", id, configs); this.persistenceService.updateConfigsForResource( id, configs, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Delete the all configuration files from a given command. * * @param id The id of the command to delete the configuration files from. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/configs") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllConfigsForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllConfigsForResource( id, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Add new dependency files for a given command. * * @param id The id of the command to add the dependency file to. Not null/empty/blank. * @param dependencies The dependency files to add. Not null. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PostMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addDependenciesForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("Called with id {} and dependencies {}", id, dependencies); this.persistenceService.addDependenciesToResource( id, dependencies, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Get all the dependency files for a given command. * * @param id The id of the command to get the dependency files for. Not NULL/empty/blank. * @return The set of dependency files. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/dependencies", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getDependenciesForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); return this.persistenceService.getDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Update the dependency files for a given command. * * @param id The id of the command to update the dependency files for. Not null/empty/blank. * @param dependencies The dependency files to replace existing dependency files with. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PutMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateDependenciesForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("Called with id {} and dependencies {}", id, dependencies); this.persistenceService.updateDependenciesForResource( id, dependencies, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Delete the all dependency files from a given command. * * @param id The id of the command to delete the dependency files from. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/dependencies") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllDependenciesForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Add new tags to a given command. * * @param id The id of the command to add the tags to. Not null/empty/blank. * @param tags The tags to add. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PostMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addTagsForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("Called with id {} and tags {}", id, tags); this.persistenceService.addTagsToResource( id, tags, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Get all the tags for a given command. * * @param id The id of the command to get the tags for. Not NULL/empty/blank. * @return The active set of tags. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/tags", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getTagsForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); // Kept this way for V3 tag conversion return DtoConverters.toV3Command(this.persistenceService.getCommand(id)).getTags(); } /** * Update the tags for a given command. * * @param id The id of the command to update the tags for. Not null/empty/blank. * @param tags The tags to replace existing tags with. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PutMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateTagsForCommand( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("Called with id {} and tags {}", id, tags); this.persistenceService.updateTagsForResource( id, tags, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Delete the all tags from a given command. * * @param id The id of the command to delete the tags from. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/tags") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllTagsForCommand(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllTagsForResource(id, com.netflix.genie.common.internal.dtos.Command.class); } /** * Remove an tag from a given command. * * @param id The id of the command to delete the tag from. Not null/empty/blank. * @param tag The tag to remove. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/tags/{tag}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeTagForCommand( @PathVariable("id") final String id, @PathVariable("tag") final String tag ) throws NotFoundException { log.info("Called with id {} and tag {}", id, tag); this.persistenceService.removeTagForResource( id, tag, com.netflix.genie.common.internal.dtos.Command.class ); } /** * Add applications for the given command. * * @param id The id of the command to add the applications to. Not null/empty/blank. * @param applicationIds The ids of the applications to add. Not null. No duplicates * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws PreconditionFailedException If there are any duplicate applications in the list or when combined with * existing applications associated with the command */ @PostMapping(value = "/{id}/applications", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addApplicationsForCommand( @PathVariable("id") final String id, @RequestBody final List<String> applicationIds ) throws NotFoundException, PreconditionFailedException { log.info("Called with id {} and application {}", id, applicationIds); this.persistenceService.addApplicationsForCommand(id, applicationIds); } /** * Get the applications configured for a given command. * * @param id The id of the command to get the application files for. Not NULL/empty/blank. * @return The active applications for the command. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/applications", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityModel<Application>> getApplicationsForCommand( @PathVariable("id") final String id ) throws NotFoundException { log.info("Called with id {}", id); return this.persistenceService.getApplicationsForCommand(id) .stream() .map(DtoConverters::toV3Application) .map(this.applicationModelAssembler::toModel) .collect(Collectors.toList()); } /** * Set the applications for the given command. * * @param id The id of the command to add the applications to. Not null/empty/blank. * @param applicationIds The ids of the applications to set in order. Not null. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws PreconditionFailedException If there are any duplicate applications in the list */ @PutMapping(value = "/{id}/applications", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void setApplicationsForCommand( @PathVariable("id") final String id, @RequestBody final List<String> applicationIds ) throws NotFoundException, PreconditionFailedException { log.info("Called with id {} and application {}", id, applicationIds); this.persistenceService.setApplicationsForCommand(id, applicationIds); } /** * Remove the applications from a given command. * * @param id The id of the command to delete the applications from. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws PreconditionFailedException If constraints block removal */ @DeleteMapping(value = "/{id}/applications") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllApplicationsForCommand( @PathVariable("id") final String id ) throws NotFoundException, PreconditionFailedException { log.info("Called with id '{}'", id); this.persistenceService.removeApplicationsForCommand(id); } /** * Remove the application from a given command. * * @param id The id of the command to delete the application from. Not null/empty/blank. * @param appId The id of the application to remove from the command. Not null/empty/blank. * @throws NotFoundException When no {@link Command} with the given {@literal id} exists or no application exists */ @DeleteMapping(value = "/{id}/applications/{appId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeApplicationForCommand( @PathVariable("id") final String id, @PathVariable("appId") final String appId ) throws NotFoundException { log.info("Called with id '{}' and app id {}", id, appId); this.persistenceService.removeApplicationForCommand(id, appId); } /** * Get all the clusters this command is associated with. * * @param id The id of the command to get the clusters for. Not NULL/empty/blank. * @param statuses The statuses of the clusters to get * @return The list of clusters * @throws NotFoundException When no {@link Command} with the given {@literal id} exists * @throws GeniePreconditionException If a supplied status is not valid */ @GetMapping(value = "/{id}/clusters", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<EntityModel<Cluster>> getClustersForCommand( @PathVariable("id") final String id, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses ) throws NotFoundException, GeniePreconditionException { log.info("Called with id {} and statuses {}", id, statuses); Set<ClusterStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(ClusterStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4ClusterStatus(com.netflix.genie.common.dto.ClusterStatus.parse(status)) ); } } return this.persistenceService.getClustersForCommand(id, enumStatuses) .stream() .map(DtoConverters::toV3Cluster) .map(this.clusterModelAssembler::toModel) .collect(Collectors.toSet()); } /** * Get all the {@link Criterion} currently associated with the command in priority order. * * @param id The id of the command to get the criteria for * @return The criteria * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/clusterCriteria", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<Criterion> getClusterCriteriaForCommand( @PathVariable("id") final String id ) throws NotFoundException { log.info("Called for command {}", id); return this.persistenceService.getClusterCriteriaForCommand(id); } /** * Remove all the {@link Criterion} currently associated with the command. * * @param id The id of the command to remove the criteria for * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/clusterCriteria") @ResponseStatus(HttpStatus.OK) public void removeAllClusterCriteriaFromCommand( @PathVariable("id") final String id ) throws NotFoundException { log.info("Called for command {}", id); this.persistenceService.removeAllClusterCriteriaForCommand(id); } /** * Add a new {@link Criterion} as the lowest priority criterion for the given command. * * @param id The id of the command to add the new criterion to * @param criterion The {@link Criterion} to add * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PostMapping(value = "/{id}/clusterCriteria", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public void addClusterCriterionForCommand( @PathVariable("id") final String id, @RequestBody @Valid final Criterion criterion ) throws NotFoundException { log.info("Called to add {} as the lowest priority cluster criterion for command {}", criterion, id); this.persistenceService.addClusterCriterionForCommand(id, criterion); } /** * Set all new cluster criteria for the given command. * * @param id The id of the command to add the new criteria to * @param clusterCriteria The list of {@link Criterion} in priority order to set for the given command * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PutMapping(value = "/{id}/clusterCriteria", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public void setClusterCriteriaForCommand( @PathVariable("id") final String id, @RequestBody @Valid final List<Criterion> clusterCriteria ) throws NotFoundException { log.info("Called to set {} as the cluster criteria for command {}", clusterCriteria, id); this.persistenceService.setClusterCriteriaForCommand(id, clusterCriteria); } /** * Insert a new cluster criterion for the given command at the supplied priority. * * @param id The id of the command to add the new criterion for * @param priority The priority (min 0) to insert the criterion at in the list * @param criterion The {@link Criterion} to add * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @PutMapping(value = "/{id}/clusterCriteria/{priority}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public void insertClusterCriterionForCommand( @PathVariable("id") final String id, @PathVariable("priority") @Min(0) final int priority, @RequestBody @Valid final Criterion criterion ) throws NotFoundException { log.info("Called to insert new criterion {} for command {} with priority {}", criterion, id, priority); this.persistenceService.addClusterCriterionForCommand(id, criterion, priority); } /** * Remove the criterion with the given priority from the given command. * * @param id The id of the command to remove the criterion from * @param priority The priority (min 0, max number of existing criteria minus one) of the criterion to remove * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @DeleteMapping(value = "/{id}/clusterCriteria/{priority}") @ResponseStatus(HttpStatus.OK) public void removeClusterCriterionFromCommand( @PathVariable("id") final String id, @PathVariable("priority") @Min(0) final int priority ) throws NotFoundException { log.info("Called to remove the criterion from command {} with priority {}", id, priority); this.persistenceService.removeClusterCriterionForCommand(id, priority); } /** * For a given {@link Command} retrieve the {@link Criterion} and attempt to resolve all the {@link Cluster}'s the * criteria would currently match within the database. * * @param id The id of the command to get the criterion from * @param addDefaultStatus Whether the system should add the default {@link ClusterStatus} to the {@link Criterion} * if no status currently is within the {@link Criterion}. The default value is * {@literal true} which will currently add the status {@link ClusterStatus#UP} * @return A list {@link ResolvedResources} of each criterion to the {@link Cluster}'s it resolved to * @throws NotFoundException When no {@link Command} with the given {@literal id} exists */ @GetMapping(value = "/{id}/resolvedClusters", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<ResolvedResources<Cluster>> resolveClustersForCommandClusterCriteria( @PathVariable("id") final String id, @RequestParam(value = "addDefaultStatus", defaultValue = "true") final Boolean addDefaultStatus ) throws NotFoundException { log.info("Called to resolve clusters for command {}", id); final List<Criterion> criteria = this.persistenceService.getClusterCriteriaForCommand(id); final List<ResolvedResources<Cluster>> resolvedResources = Lists.newArrayList(); for (final Criterion criterion : criteria) { resolvedResources.add( new ResolvedResources<>( DtoConverters.toV3Criterion(criterion), this.persistenceService .findClustersMatchingCriterion(criterion, addDefaultStatus) .stream() .map(DtoConverters::toV3Cluster) .collect(Collectors.toSet()) ) ); } return resolvedResources; } }
2,508
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes that represent the REST-ful resources provided by Genie. * * @author tgianos */ package com.netflix.genie.web.apis.rest.v3.controllers;
2,509
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/ApplicationRestController.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchException; import com.google.common.collect.Lists; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.ApplicationStatus; import com.netflix.genie.common.internal.dtos.CommandStatus; import com.netflix.genie.common.internal.dtos.converters.DtoConverters; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler; import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.exceptions.checked.PreconditionFailedException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.PagedModel; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.annotation.Nullable; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * REST end-point for supporting Applications. * * @author tgianos * @since 3.0.0 */ @RestController @RequestMapping(value = "/api/v3/applications") @Slf4j public class ApplicationRestController { private final PersistenceService persistenceService; private final ApplicationModelAssembler applicationModelAssembler; private final CommandModelAssembler commandModelAssembler; /** * Constructor. * * @param dataServices The {@link DataServices} encapsulation instance to use * @param entityModelAssemblers The encapsulation of all the available V3 resource assemblers */ @Autowired public ApplicationRestController( final DataServices dataServices, final EntityModelAssemblers entityModelAssemblers ) { this.persistenceService = dataServices.getPersistenceService(); this.applicationModelAssembler = entityModelAssemblers.getApplicationModelAssembler(); this.commandModelAssembler = entityModelAssemblers.getCommandModelAssembler(); } /** * Create an Application. * * @param app The application to create * @return The created application configuration * @throws IdAlreadyExistsException If the ID was already in use */ @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Void> createApplication(@RequestBody final Application app) throws IdAlreadyExistsException { log.info("Called to create new application: {}", app); final String id = this.persistenceService.saveApplication(DtoConverters.toV4ApplicationRequest(app)); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand(id) .toUri() ); return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED); } /** * Delete all applications from database. * * @throws PreconditionFailedException If any of the applications were still linked to a command */ @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteAllApplications() throws PreconditionFailedException { log.warn("Called to delete all Applications"); this.persistenceService.deleteAllApplications(); } /** * Get Applications based on user parameters. * * @param name name for configuration (optional) * @param user The user who created the application (optional) * @param statuses The statuses of the applications (optional) * @param tags The set of tags you want the application for. (optional) * @param type The type of applications to get (optional) * @param page The page to get * @param assembler The paged resources assembler to use * @return All applications matching the criteria * @throws GenieException For any error */ @GetMapping(produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public PagedModel<EntityModel<Application>> getApplications( @RequestParam(value = "name", required = false) @Nullable final String name, @RequestParam(value = "user", required = false) @Nullable final String user, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses, @RequestParam(value = "tag", required = false) @Nullable final Set<String> tags, @RequestParam(value = "type", required = false) @Nullable final String type, @PageableDefault(sort = {"updated"}, direction = Sort.Direction.DESC) final Pageable page, final PagedResourcesAssembler<Application> assembler ) throws GenieException { log.info( "Finding applications [name | user | status | tags | type | pageable]\n{} | {} | {} | {} | | {} | {}", name, user, statuses, tags, type, page ); Set<ApplicationStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(ApplicationStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4ApplicationStatus(com.netflix.genie.common.dto.ApplicationStatus.parse(status)) ); } } final Page<Application> applications; if (tags != null && tags.stream().anyMatch(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX))) { // TODO: This doesn't take into account others as compounded find...not sure if good or bad final List<Application> applicationList = Lists.newArrayList(); final int prefixLength = DtoConverters.GENIE_ID_PREFIX.length(); tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_ID_PREFIX)) .forEach( tag -> { final String id = tag.substring(prefixLength); try { applicationList.add( DtoConverters.toV3Application(this.persistenceService.getApplication(id)) ); } catch (final NotFoundException ge) { log.debug("No application with id {} found", id, ge); } } ); applications = new PageImpl<>(applicationList); } else if (tags != null && tags.stream().filter(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)).count() >= 1L) { final Set<String> finalTags = tags .stream() .filter(tag -> !tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .collect(Collectors.toSet()); if (name == null) { final Optional<String> finalName = tags .stream() .filter(tag -> tag.startsWith(DtoConverters.GENIE_NAME_PREFIX)) .map(tag -> tag.substring(DtoConverters.GENIE_NAME_PREFIX.length())) .findFirst(); applications = this.persistenceService .findApplications(finalName.orElse(null), user, enumStatuses, finalTags, type, page) .map(DtoConverters::toV3Application); } else { applications = this.persistenceService .findApplications(name, user, enumStatuses, finalTags, type, page) .map(DtoConverters::toV3Application); } } else { applications = this.persistenceService .findApplications(name, user, enumStatuses, tags, type, page) .map(DtoConverters::toV3Application); } final Link self = WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getApplications(name, user, statuses, tags, type, page, assembler) ).withSelfRel(); return assembler.toModel( applications, this.applicationModelAssembler, self ); } /** * Get Application for given id. * * @param id unique id for application configuration * @return The application configuration * @throws NotFoundException If no application exists with the given id */ @GetMapping(value = "/{id}", produces = MediaTypes.HAL_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public EntityModel<Application> getApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called to get Application for id {}", id); return this.applicationModelAssembler.toModel( DtoConverters.toV3Application(this.persistenceService.getApplication(id)) ); } /** * Update application. * * @param id unique id for configuration to update * @param updateApp contains the application information to update * @throws NotFoundException If no application with the given id exists * @throws PreconditionFailedException When the id in the update doesn't match */ @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateApplication( @PathVariable("id") final String id, @RequestBody final Application updateApp ) throws NotFoundException, PreconditionFailedException { log.info("called to update application {} with info {}", id, updateApp); this.persistenceService.updateApplication(id, DtoConverters.toV4Application(updateApp)); } /** * Patch an application using JSON Patch. * * @param id The id of the application to patch * @param patch The JSON Patch instructions * @throws NotFoundException If no application with the given id exists * @throws PreconditionFailedException When the id in the update doesn't match * @throws GenieServerException If the patch can't be successfully applied */ @PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void patchApplication( @PathVariable("id") final String id, @RequestBody final JsonPatch patch ) throws NotFoundException, PreconditionFailedException, GenieServerException { log.info("Called to patch application {} with patch {}", id, patch); final Application currentApp = DtoConverters.toV3Application(this.persistenceService.getApplication(id)); try { log.debug("Will patch application {}. Original state: {}", id, currentApp); final JsonNode applicationNode = GenieObjectMapper.getMapper().valueToTree(currentApp); final JsonNode postPatchNode = patch.apply(applicationNode); final Application patchedApp = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Application.class); log.debug("Finished patching application {}. New state: {}", id, patchedApp); this.persistenceService.updateApplication(id, DtoConverters.toV4Application(patchedApp)); } catch (final JsonPatchException | IOException e) { log.error("Unable to patch application {} with patch {} due to exception.", id, patch, e); throw new GenieServerException(e.getLocalizedMessage(), e); } } /** * Delete an application configuration from database. * * @param id unique id of configuration to delete * @throws PreconditionFailedException If the application is still tied to a command */ @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteApplication(@PathVariable("id") final String id) throws PreconditionFailedException { log.info("Delete an application with id {}", id); this.persistenceService.deleteApplication(id); } /** * Add new configuration files to a given application. * * @param id The id of the application to add the configuration file to. Not * null/empty/blank. * @param configs The configuration files to add. Not null/empty/blank. * @throws NotFoundException If no application with the given id exists */ @PostMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addConfigsToApplication( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("Called with id {} and config {}", id, configs); this.persistenceService.addConfigsToResource( id, configs, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Get all the configuration files for a given application. * * @param id The id of the application to get the configuration files for. * Not NULL/empty/blank. * @return The active set of configuration files. * @throws NotFoundException If no application with the given id exists */ @GetMapping(value = "/{id}/configs", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getConfigsForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); return this.persistenceService.getConfigsForResource( id, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Update the configuration files for a given application. * * @param id The id of the application to update the configuration files * for. Not null/empty/blank. * @param configs The configuration files to replace existing configuration * files with. Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @PutMapping(value = "/{id}/configs", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateConfigsForApplication( @PathVariable("id") final String id, @RequestBody final Set<String> configs ) throws NotFoundException { log.info("Called with id {} and configs {}", id, configs); this.persistenceService.updateConfigsForResource( id, configs, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Delete the all configuration files from a given application. * * @param id The id of the application to delete the configuration files * from. Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @DeleteMapping(value = "/{id}/configs") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllConfigsForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllConfigsForResource( id, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Add new dependency files for a given application. * * @param id The id of the application to add the dependency file to. Not * null/empty/blank. * @param dependencies The dependency files to add. Not null. * @throws NotFoundException If no application with the given ID exists */ @PostMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addDependenciesForApplication( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("Called with id {} and dependencies {}", id, dependencies); this.persistenceService.addDependenciesToResource( id, dependencies, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Get all the dependency files for a given application. * * @param id The id of the application to get the dependency files for. Not * NULL/empty/blank. * @return The set of dependency files. * @throws NotFoundException If no application with the given ID exists */ @GetMapping(value = "/{id}/dependencies", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getDependenciesForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); return this.persistenceService.getDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Update the dependency files for a given application. * * @param id The id of the application to update the dependency files for. Not * null/empty/blank. * @param dependencies The dependency files to replace existing dependency files with. Not * null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @PutMapping(value = "/{id}/dependencies", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateDependenciesForApplication( @PathVariable("id") final String id, @RequestBody final Set<String> dependencies ) throws NotFoundException { log.info("Called with id {} and dependencies {}", id, dependencies); this.persistenceService.updateDependenciesForResource( id, dependencies, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Delete the all dependency files from a given application. * * @param id The id of the application to delete the dependency files from. Not * null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @DeleteMapping(value = "/{id}/dependencies") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllDependenciesForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllDependenciesForResource( id, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Add new tags to a given application. * * @param id The id of the application to add the tags to. Not * null/empty/blank. * @param tags The tags to add. Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @PostMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void addTagsForApplication( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("Called with id {} and config {}", id, tags); this.persistenceService.addTagsToResource( id, tags, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Get all the tags for a given application. * * @param id The id of the application to get the tags for. Not * NULL/empty/blank. * @return The active set of tags. * @throws NotFoundException If no application with the given ID exists */ @GetMapping(value = "/{id}/tags", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public Set<String> getTagsForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); // This is done so that the v3 tags (genie.id, genie.name) are added properly return DtoConverters.toV3Application(this.persistenceService.getApplication(id)).getTags(); } /** * Update the tags for a given application. * * @param id The id of the application to update the tags for. * Not null/empty/blank. * @param tags The tags to replace existing configuration * files with. Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @PutMapping(value = "/{id}/tags", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateTagsForApplication( @PathVariable("id") final String id, @RequestBody final Set<String> tags ) throws NotFoundException { log.info("Called with id {} and tags {}", id, tags); this.persistenceService.updateTagsForResource( id, tags, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Delete the all tags from a given application. * * @param id The id of the application to delete the tags from. * Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @DeleteMapping(value = "/{id}/tags") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeAllTagsForApplication(@PathVariable("id") final String id) throws NotFoundException { log.info("Called with id {}", id); this.persistenceService.removeAllTagsForResource( id, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Remove an tag from a given application. * * @param id The id of the application to delete the tag from. Not * null/empty/blank. * @param tag The tag to remove. Not null/empty/blank. * @throws NotFoundException If no application with the given ID exists */ @DeleteMapping(value = "/{id}/tags/{tag}") @ResponseStatus(HttpStatus.NO_CONTENT) public void removeTagForApplication( @PathVariable("id") final String id, @PathVariable("tag") final String tag ) throws NotFoundException { log.info("Called with id {} and tag {}", id, tag); this.persistenceService.removeTagForResource( id, tag, com.netflix.genie.common.internal.dtos.Application.class ); } /** * Get all the commands this application is associated with. * * @param id The id of the application to get the commands for. Not * NULL/empty/blank. * @param statuses The various statuses of the commands to retrieve * @return The set of commands. * @throws NotFoundException If no application with the given ID exists * @throws GeniePreconditionException When the statuses can't be parsed successfully */ @GetMapping(value = "/{id}/commands", produces = MediaTypes.HAL_JSON_VALUE) public Set<EntityModel<Command>> getCommandsForApplication( @PathVariable("id") final String id, @RequestParam(value = "status", required = false) @Nullable final Set<String> statuses ) throws NotFoundException, GeniePreconditionException { log.info("Called with id {} and statuses {}", id, statuses); Set<CommandStatus> enumStatuses = null; if (statuses != null) { enumStatuses = EnumSet.noneOf(CommandStatus.class); for (final String status : statuses) { enumStatuses.add( DtoConverters.toV4CommandStatus(com.netflix.genie.common.dto.CommandStatus.parse(status)) ); } } return this.persistenceService.getCommandsForApplication(id, enumStatuses) .stream() .map(DtoConverters::toV3Command) .map(this.commandModelAssembler::toModel) .collect(Collectors.toSet()); } }
2,510
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/controllers/ControllerUtils.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.controllers; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.HandlerMapping; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import java.net.MalformedURLException; import java.net.URL; /** * Utility methods re-used in various controllers. * * @author tgianos * @since 3.0.0 */ @Slf4j public final class ControllerUtils { private static final String EMPTY_STRING = ""; /** * Constructor. */ private ControllerUtils() { } /** * Get the remaining path from a given request. e.g. if the request went to a method with the matching pattern of * /api/v3/jobs/{id}/output/** and the request was /api/v3/jobs/{id}/output/blah.txt the return value of this * method would be blah.txt. * * @param request The http servlet request. * @return The remaining path */ public static String getRemainingPath(final HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path != null) { final String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); log.debug("bestMatchPattern = {}", bestMatchPattern); path = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path); } path = path == null ? EMPTY_STRING : path; log.debug("Remaining path = {}", path); return path; } /** * Given a HTTP {@code request} and a {@code path} this method will return the root of the request minus the path. * Generally the path will be derived from {@link #getRemainingPath(HttpServletRequest)} and this method will be * called subsequently. * <p> * If the request URL is {@code https://myhost/api/v3/jobs/12345/output/genie/run?myparam=4#BLAH} and the path is * {@code genie/run} this method should return {@code https://myhost/api/v3/jobs/12345/output/}. * <p> * All query parameters and references will be stripped off. * * @param request The HTTP request to get information from * @param path The path that should be removed from the end of the request URL * @return The base of the request * @throws MalformedURLException if for some reason the URL provided in {@code request} is invalid * @since 4.0.0 */ static URL getRequestRoot( final HttpServletRequest request, @Nullable final String path ) throws MalformedURLException { return getRequestRoot(new URL(request.getRequestURL().toString()), path); } /** * Given a HTTP {@code request} and a {@code path} this method will return the root of the request minus the path. * Generally the path will be derived from {@link #getRemainingPath(HttpServletRequest)} and this method will be * called subsequently. * <p> * If the request URL is {@code https://myhost/api/v3/jobs/12345/output/genie/run?myparam=4#BLAH} and the path is * {@code genie/run} this method should return {@code https://myhost/api/v3/jobs/12345/output/}. * <p> * All query parameters and references will be stripped off. * * @param request The HTTP request to get information from * @param path The path that should be removed from the end of the request URL * @return The base of the request * @throws MalformedURLException If we're unable to create a new valid URL after removing the path * @since 4.0.0 */ static URL getRequestRoot(final URL request, @Nullable final String path) throws MalformedURLException { final String currentPath = request.getPath(); final String newPath = StringUtils.removeEnd(currentPath, path); return new URL(request.getProtocol(), request.getHost(), request.getPort(), newPath); } }
2,511
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.Job; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Job resources out of job DTOs. * * @author tgianos * @since 3.0.0 */ public class JobModelAssembler implements RepresentationModelAssembler<Job, EntityModel<Job>> { private static final String REQUEST_LINK = "request"; private static final String EXECUTION_LINK = "execution"; private static final String OUTPUT_LINK = "output"; private static final String STATUS_LINK = "status"; private static final String METADATA_LINK = "metadata"; private static final String CLUSTER_LINK = "cluster"; private static final String COMMAND_LINK = "command"; private static final String APPLICATIONS_LINK = "applications"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<Job> toModel(final Job job) { final String id = job.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Job> jobModel = EntityModel.of(job); try { jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(id) ).withSelfRel() ); // TODO: https://github.com/spring-projects/spring-hateoas/issues/186 should be fixed in .20 currently .19 // jobResource.add( // ControllerLinkBuilder.linkTo( // JobRestController.class, // JobRestController.class.getMethod( // "getJobOutput", // String.class, // String.class, // HttpServletRequest.class, // HttpServletResponse.class // ), // job.getId(), // null, // null, // null // ).withRel("output") // ); jobModel.add( WebMvcLinkBuilder .linkTo(JobRestController.class) .slash(id) .slash(OUTPUT_LINK) .withRel(OUTPUT_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobRequest(id) ).withRel(REQUEST_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobExecution(id) ).withRel(EXECUTION_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobMetadata(id) ).withRel(METADATA_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobStatus(id) ).withRel(STATUS_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobCluster(id) ).withRel(CLUSTER_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobCommand(id) ).withRel(COMMAND_LINK) ); jobModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobApplications(id) ).withRel(APPLICATIONS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobModel; } }
2,512
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/RootModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.ApplicationRestController; import com.netflix.genie.web.apis.rest.v3.controllers.ClusterRestController; import com.netflix.genie.web.apis.rest.v3.controllers.CommandRestController; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import com.netflix.genie.web.apis.rest.v3.controllers.RootRestController; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; import java.util.Map; /** * Assembles root resource from a JsonNode. * * @author tgianos * @since 3.0.0 */ public class RootModelAssembler implements RepresentationModelAssembler<Map<String, String>, EntityModel<Map<String, String>>> { private static final String APPLICATIONS_LINK = "applications"; private static final String COMMANDS_LINK = "commands"; private static final String CLUSTERS_LINK = "clusters"; private static final String JOBS_LINK = "jobs"; /** * {@inheritDoc} */ @Override @SuppressFBWarnings("NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS") @Nonnull public EntityModel<Map<String, String>> toModel(final Map<String, String> metadata) { final EntityModel<Map<String, String>> rootResource = EntityModel.of(metadata); try { rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(RootRestController.class) .getRoot() ).withSelfRel() ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .createApplication(null) ).withRel(APPLICATIONS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .createCommand(null) ).withRel(COMMANDS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .createCluster(null) ).withRel(CLUSTERS_LINK) ); rootResource.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .submitJob(null, null, null, null) ).withRel(JOBS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return rootResource; } }
2,513
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobSearchResultModelAssembler.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.search.JobSearchResult; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Job resources out of job search result DTOs. * * @author tgianos * @since 3.0.0 */ public class JobSearchResultModelAssembler implements RepresentationModelAssembler<JobSearchResult, EntityModel<JobSearchResult>> { /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<JobSearchResult> toModel(final JobSearchResult job) { final EntityModel<JobSearchResult> jobSearchResultModel = EntityModel.of(job); try { jobSearchResultModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(job.getId()) ).withSelfRel() ); } catch (final GenieException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobSearchResultModel; } }
2,514
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/ClusterModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.Cluster; import com.netflix.genie.web.apis.rest.v3.controllers.ClusterRestController; import com.netflix.genie.web.exceptions.checked.NotFoundException; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Cluster resources out of clusters. * * @author tgianos * @since 3.0.0 */ public class ClusterModelAssembler implements RepresentationModelAssembler<Cluster, EntityModel<Cluster>> { private static final String COMMANDS_LINK = "commands"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<Cluster> toModel(final Cluster cluster) { final String id = cluster.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Cluster> clusterModel = EntityModel.of(cluster); try { clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCluster(id) ).withSelfRel() ); clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCommandsForCluster(id, null) ).withRel(COMMANDS_LINK) ); } catch (final NotFoundException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return clusterModel; } }
2,515
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/EntityModelAssemblers.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * A simple container DTO for passing all known resource assemblers around. * * @author tgianos * @since 4.0.0 */ @RequiredArgsConstructor @Getter public class EntityModelAssemblers { private final ApplicationModelAssembler applicationModelAssembler; private final ClusterModelAssembler clusterModelAssembler; private final CommandModelAssembler commandModelAssembler; private final JobExecutionModelAssembler jobExecutionModelAssembler; private final JobMetadataModelAssembler jobMetadataModelAssembler; private final JobRequestModelAssembler jobRequestModelAssembler; private final JobModelAssembler jobModelAssembler; private final JobSearchResultModelAssembler jobSearchResultModelAssembler; private final RootModelAssembler rootModelAssembler; }
2,516
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobMetadataModelAssembler.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.JobMetadata; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Job Request resources out of JobRequest DTOs. * * @author tgianos * @since 3.3.5 */ public class JobMetadataModelAssembler implements RepresentationModelAssembler<JobMetadata, EntityModel<JobMetadata>> { private static final String JOB_LINK = "job"; private static final String REQUEST_LINK = "request"; private static final String OUTPUT_LINK = "output"; private static final String STATUS_LINK = "status"; private static final String EXECUTION_LINK = "execution"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<JobMetadata> toModel(final JobMetadata jobMetadata) { final String id = jobMetadata.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<JobMetadata> jobMetadataModel = EntityModel.of(jobMetadata); try { jobMetadataModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobMetadata(id) ).withSelfRel() ); jobMetadataModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(id) ).withRel(JOB_LINK) ); jobMetadataModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobRequest(id) ).withRel(REQUEST_LINK) ); jobMetadataModel.add( WebMvcLinkBuilder .linkTo(JobRestController.class) .slash(id) .slash(OUTPUT_LINK) .withRel(OUTPUT_LINK) ); jobMetadataModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobStatus(id) ).withRel(STATUS_LINK) ); jobMetadataModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobExecution(id) ).withRel(EXECUTION_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobMetadataModel; } }
2,517
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobExecutionModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.JobExecution; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Job Request resources out of JobRequest DTOs. * * @author tgianos * @since 3.0.0 */ public class JobExecutionModelAssembler implements RepresentationModelAssembler<JobExecution, EntityModel<JobExecution>> { private static final String JOB_LINK = "job"; private static final String REQUEST_LINK = "request"; private static final String OUTPUT_LINK = "output"; private static final String STATUS_LINK = "status"; private static final String METADATA_LINK = "metadata"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<JobExecution> toModel(final JobExecution jobExecution) { final String id = jobExecution.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<JobExecution> jobExecutionModel = EntityModel.of(jobExecution); try { jobExecutionModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobExecution(id) ).withSelfRel() ); jobExecutionModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(id) ).withRel(JOB_LINK) ); jobExecutionModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobRequest(id) ).withRel(REQUEST_LINK) ); // TODO: https://github.com/spring-projects/spring-hateoas/issues/186 should be fixed in .20 currently .19 // jobExecutionResource.add( // ControllerLinkBuilder.linkTo( // JobRestController.class, // JobRestController.class.getMethod( // "getJobOutput", // String.class, // String.class, // HttpServletRequest.class, // HttpServletResponse.class // ), // id, // null, // null, // null // ).withRel("output") // ); jobExecutionModel.add( WebMvcLinkBuilder .linkTo(JobRestController.class) .slash(id) .slash(OUTPUT_LINK) .withRel(OUTPUT_LINK) ); jobExecutionModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobStatus(id) ).withRel(STATUS_LINK) ); jobExecutionModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobMetadata(id) ).withRel(METADATA_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobExecutionModel; } }
2,518
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/CommandModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.Command; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.CommandRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Command resources out of commands. * * @author tgianos * @since 3.0.0 */ public class CommandModelAssembler implements RepresentationModelAssembler<Command, EntityModel<Command>> { private static final String APPLICATIONS_LINK = "applications"; private static final String CLUSTERS_LINK = "clusters"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<Command> toModel(final Command command) { final String id = command.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Command> commandModel = EntityModel.of(command); try { commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getCommand(id) ).withSelfRel() ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getApplicationsForCommand(id) ).withRel(APPLICATIONS_LINK) ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getClustersForCommand(id, null) ).withRel(CLUSTERS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return commandModel; } }
2,519
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/JobRequestModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.JobRequest; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; import com.netflix.genie.web.apis.rest.v3.controllers.JobRestController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Job Request resources out of JobRequest DTOs. * * @author tgianos * @since 3.0.0 */ public class JobRequestModelAssembler implements RepresentationModelAssembler<JobRequestModelAssembler.JobRequestWrapper, EntityModel<JobRequest>> { private static final String JOB_LINK = "job"; private static final String EXECUTION_LINK = "execution"; private static final String OUTPUT_LINK = "output"; private static final String STATUS_LINK = "status"; private static final String METADATA_LINK = "metadata"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<JobRequest> toModel(final JobRequestWrapper wrapper) { final String id = wrapper.getId(); final EntityModel<JobRequest> jobRequestModel = EntityModel.of(wrapper.getJobRequest()); try { jobRequestModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobRequest(id) ).withSelfRel() ); jobRequestModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(id) ).withRel(JOB_LINK) ); jobRequestModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobExecution(id) ).withRel(EXECUTION_LINK) ); // TODO: https://github.com/spring-projects/spring-hateoas/issues/186 should be fixed in .20 currently .19 // jobRequestResource.add( // ControllerLinkBuilder.linkTo( // JobRestController.class, // JobRestController.class.getMethod( // "getJobOutput", // String.class, // String.class, // HttpServletRequest.class, // HttpServletResponse.class // ), // id, // null, // null, // null // ).withRel("output") // ); jobRequestModel.add( WebMvcLinkBuilder .linkTo(JobRestController.class) .slash(id) .slash(OUTPUT_LINK) .withRel(OUTPUT_LINK) ); jobRequestModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobStatus(id) ).withRel(STATUS_LINK) ); jobRequestModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJobMetadata(id) ).withRel(METADATA_LINK) ); } catch (final GenieException | GenieCheckedException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return jobRequestModel; } /** * A simple wrapper class because the job request may not have an id available (there wasn't one * originally sent) so need to use the one the system provided later in order to generate the links properly. * * @author tgianos * @since 4.3.0 */ public static class JobRequestWrapper { private final String id; private final JobRequest jobRequest; /** * Constructor. * * @param id The actual id of the job * @param jobRequest The original job request */ public JobRequestWrapper(final String id, final JobRequest jobRequest) { this.id = id; this.jobRequest = jobRequest; } /** * Get the actual id of the job the system assigned after job submission if none was already supplied. * * @return The jobs' unique id */ public String getId() { return this.id; } /** * Get the original job request sent to the system by the user. * * @return The {@link JobRequest} */ public JobRequest getJobRequest() { return this.jobRequest; } } }
2,520
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/ApplicationModelAssembler.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import com.netflix.genie.common.dto.Application; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.web.apis.rest.v3.controllers.ApplicationRestController; import com.netflix.genie.web.exceptions.checked.NotFoundException; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import javax.annotation.Nonnull; /** * Assembles Application resources out of applications. * * @author tgianos * @since 3.0.0 */ public class ApplicationModelAssembler implements RepresentationModelAssembler<Application, EntityModel<Application>> { private static final String COMMANDS_LINK = "commands"; /** * {@inheritDoc} */ @Override @Nonnull public EntityModel<Application> toModel(final Application application) { final String id = application.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Application> applicationModel = EntityModel.of(application); try { applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getApplication(id) ).withSelfRel() ); applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getCommandsForApplication(id, null) ).withRel(COMMANDS_LINK) ); } catch (final GenieException | NotFoundException ge) { // If we can't convert it we might as well force a server exception throw new RuntimeException(ge); } return applicationModel; } }
2,521
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/apis/rest/v3/hateoas/assemblers/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes used to assemble entity models from resources. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.apis.rest.v3.hateoas.assemblers; import javax.annotation.ParametersAreNonnullByDefault;
2,522
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/UNIXUtils.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.Executor; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.io.IOException; /** * Utility class for UNIX user and file permissions. * <p> * N.B. These are some old routines moved out from JobKickoffTask for reuse as part of V3 to V4 migration. * This class is expected to be deleted once execution is delegated to Agent. * * @author mprimi * @since 4.0.0 */ @Slf4j public final class UNIXUtils { private static final String SUDO = "sudo"; /** * Private constructor. */ private UNIXUtils() { } /** * Create user on the system. * * @param user user id * @param group group id * @param executor the command executor * @throws IOException If the user or group could not be created. */ public static synchronized void createUser( final String user, @Nullable final String group, final Executor executor ) throws IOException { // First check if user already exists final CommandLine idCheckCommandLine = new CommandLine("id") .addArgument("-u") .addArgument(user); try { executor.execute(idCheckCommandLine); log.debug("User already exists"); } catch (final IOException ioe) { log.debug("User does not exist. Creating it now."); // Determine if the group is valid by checking that its not null and not same as user. final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user); // Create the group for the user if its not the same as the user. if (isGroupValid) { log.debug("Group and User are different so creating group now."); final CommandLine groupCreateCommandLine = new CommandLine(SUDO).addArgument("groupadd") .addArgument(group); // We create the group and ignore the error as it will fail if group already exists. // If the failure is due to some other reason, then user creation will fail and we catch that. try { log.debug("Running command to create group: [{}]", groupCreateCommandLine); executor.execute(groupCreateCommandLine); } catch (IOException ioexception) { log.debug("Group creation threw an error as it might already exist", ioexception); } } final CommandLine userCreateCommandLine = new CommandLine(SUDO) .addArgument("useradd") .addArgument(user); if (isGroupValid) { userCreateCommandLine .addArgument("-G") .addArgument(group); } userCreateCommandLine .addArgument("-M"); log.debug("Running command to create user: [{}]", userCreateCommandLine); executor.execute(userCreateCommandLine); } } /** * Change the ownership of a directory (recursively). * * @param dir The directory to change the ownership of. * @param user Userid of the user. * @param executor the command executor * @throws IOException if the operation fails */ public static void changeOwnershipOfDirectory( final String dir, final String user, final Executor executor ) throws IOException { final CommandLine commandLine = new CommandLine(SUDO) .addArgument("chown") .addArgument("-R") .addArgument(user) .addArgument(dir); executor.execute(commandLine); } }
2,523
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/StreamBuffer.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.util; import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.NotImplementedException; import javax.annotation.concurrent.ThreadSafe; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicReference; /** * A temporary in-memory structure to hold in-transit data. * Provides an {@code InputStream} for reading, reading blocks until data becomes available or the buffer is closed. * <p> * To avoid in-memory data growing excessively, this buffer stores a single "chunk" at the time. * Only after a chunk is consumed, a new one can be appended. * <p> * To support range requests in a memory-efficient way, {@link StreamBufferInputStream} also allows skipping the first * {@code skipOffset - 1} bytes without allocating memory (or worse: downloading the actual bytes only to have them * thrown away to get to the actual range) * * @author mprimi * @since 4.0.0 */ @ThreadSafe @Slf4j public class StreamBuffer { private final Object lock = new Object(); private final AtomicReference<StreamBufferInputStream> inputStreamRef = new AtomicReference<>(); private boolean closed; private ByteString currentChunk; private int currentChunkWatermark; private Throwable closeCause; /** * Constructor. * * @param skipOffset index of the first actual byte to return ( */ public StreamBuffer(final long skipOffset) { this.inputStreamRef.set(new StreamBufferInputStream(this, skipOffset)); } /** * Close this buffer before all data is written due to an error. * Reading will return the end of stream marker after the current chunk (if any) has been consumed. * * @param t the cause for the buffer to be closed. */ public void closeForError(final Throwable t) { log.error("Closing buffer due to error: " + t.getClass().getSimpleName() + ": " + t.getMessage()); synchronized (this.lock) { this.closeCause = t; this.closeForCompleted(); } } /** * Close this buffer because all expected data has been written * Reading will return the end of stream marker after all data has been consumed. */ public void closeForCompleted() { synchronized (this.lock) { this.closed = true; this.lock.notifyAll(); } } /** * Append a chunk of data for consumption. * This call may block and not return until some data is read/consumed. * * @param data the data to write into the buffer * @throws IllegalStateException if writing is attempted after the buffer has been closed */ public void write(final ByteString data) { synchronized (this.lock) { while (!tryWrite(data)) { try { this.lock.wait(); } catch (InterruptedException e) { log.warn("Interrupted while waiting to write next chunk of data"); } } } } /** * Try to append a chunk of data for consumption. * If the previous buffer is still not drained, then does not block and returns false. * * @param data the data to write into the buffer * @return true if the data was added to the buffer, false otherwise * @throws IllegalStateException if writing is attempted after the buffer has been closed */ public boolean tryWrite(final ByteString data) { synchronized (this.lock) { if (this.closed) { throw new IllegalStateException("Attempting to write after closing"); } else if (this.currentChunk == null) { // Save this chunk so it can be consumed this.currentChunk = data; this.currentChunkWatermark = 0; // Wake up reading thread this.lock.notifyAll(); return true; } else { // Previous chunk of data is still being consumed. this.lock.notifyAll(); return false; } } } /** * Obtain the input stream to read this data. * * @return the input stream * @throws IllegalStateException if invoked multiple times */ public InputStream getInputStream() { final InputStream inputStream = this.inputStreamRef.getAndSet(null); if (inputStream == null) { throw new IllegalStateException("Input stream for this buffer is no longer available"); } return inputStream; } private int read(final byte[] destination) throws IOException { synchronized (this.lock) { while (true) { if (currentChunk != null) { // Read from current chunk into destination final int leftInCurrentChunk = this.currentChunk.size() - this.currentChunkWatermark; final int bytesRead = Math.min(leftInCurrentChunk, destination.length); this.currentChunk.substring(currentChunkWatermark, currentChunkWatermark + bytesRead) .copyTo(destination, 0); // Update watermark this.currentChunkWatermark += bytesRead; // Is chunk completely consumed? if (this.currentChunkWatermark == this.currentChunk.size()) { // Make room for the next one this.currentChunk = null; // Wake the writer thread this.lock.notifyAll(); } return bytesRead; } else if (this.closed) { // There won't be another chunk appended log.debug("Buffer was closed"); if (this.closeCause != null) { // Throw rather than returning -1 in case of error, so the request is shut down immediately throw new IOException(this.closeCause.getMessage()); } else { // All data was consumed return -1; } } else { try { this.lock.wait(); } catch (InterruptedException e) { log.warn("Interrupted while attempting read"); return 0; } } } } } private static class StreamBufferInputStream extends InputStream { private final StreamBuffer streamBuffer; private long skipBytesLeft; StreamBufferInputStream(final StreamBuffer streamBuffer, final long skipOffset) { this.streamBuffer = streamBuffer; this.skipBytesLeft = skipOffset; } /** * {@inheritDoc} */ @Override public int read() { // Overriding other read() methods and hoping nobody is referring to this one directly. throw new NotImplementedException("Not implemented"); } /** * {@inheritDoc} */ @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException("Invalid read( b[" + b.length + "], " + off + ", " + len + ")"); } // Efficiently skip over range of bytes that should be ignored if (this.skipBytesLeft > 0) { final int maxSkipBytes = this.skipBytesLeft <= Integer.MAX_VALUE ? (int) this.skipBytesLeft : Integer.MAX_VALUE; final int skippedBytesRead = Math.min(len, maxSkipBytes); System.arraycopy(new byte[skippedBytesRead], 0, b, off, skippedBytesRead); this.skipBytesLeft -= skippedBytesRead; return skippedBytesRead; } final byte[] temporary = new byte[len]; final int bytesRead = this.streamBuffer.read(temporary); if (bytesRead > 0) { System.arraycopy(temporary, 0, b, off, bytesRead); } return bytesRead; } @Override public long skip(final long n) throws IOException { long skipped = 0; if (this.skipBytesLeft > 0) { skipped = Math.min(n, this.skipBytesLeft); this.skipBytesLeft -= skipped; } if (skipped < n) { skipped += super.skip(n - skipped); } return skipped; } } }
2,524
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/MetricsUtils.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.util; import com.google.common.collect.Sets; import io.micrometer.core.instrument.Tag; import java.util.Set; /** * Utility methods for metrics. * * @author mprimi * @since 3.1.0 */ public final class MetricsUtils { private static final Tag SUCCESS_STATUS_TAG = Tag.of( MetricsConstants.TagKeys.STATUS, MetricsConstants.TagValues.SUCCESS ); private static final Tag FAILURE_STATUS_TAG = Tag.of( MetricsConstants.TagKeys.STATUS, MetricsConstants.TagValues.FAILURE ); /** * Utility class private constructor. */ private MetricsUtils() { } /** * Convenience method that creates a tag set pre-populated with success status. * * @return a new set containing success tags */ public static Set<Tag> newSuccessTagsSet() { final Set<Tag> tags = Sets.newHashSet(); addSuccessTags(tags); return tags; } /** * Convenience method to add success tag to an existing set of tags. * * @param tags the set of tags to add success tags to */ public static void addSuccessTags(final Set<Tag> tags) { tags.add(SUCCESS_STATUS_TAG); } /** * Convenience method that creates a tag set pre-populated with failure status and exception details. * * @param t the exception * @return a new set containing failure tags */ public static Set<Tag> newFailureTagsSetForException(final Throwable t) { final Set<Tag> tags = Sets.newHashSet(); addFailureTagsWithException(tags, t); return tags; } /** * Convenience method to add failure status and exception cause to an existing set of tags. * * @param tags the set of existing tags * @param throwable the exception to be tagged */ public static void addFailureTagsWithException( final Set<Tag> tags, final Throwable throwable ) { tags.add(FAILURE_STATUS_TAG); tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, throwable.getClass().getCanonicalName())); } }
2,525
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/ExecutorFactory.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.util; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; /** * A factory for {@link org.apache.commons.exec.Executor} instances. * * @author tgianos * @since 4.0.0 */ public class ExecutorFactory { /** * Create a new {@link Executor} implementation instance. * * @param detached Whether the streams for processes run on this executor should be detached (ignored) or not * @return A {@link Executor} instance */ public Executor newInstance(final boolean detached) { final Executor executor = new DefaultExecutor(); if (detached) { executor.setStreamHandler(new PumpStreamHandler(null, null)); } return executor; } }
2,526
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/MetricsConstants.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.util; /** * Used to store constants related to metric names. * * @author tgianos * @since 3.0.0 */ public final class MetricsConstants { /** * Utility class private constructor. */ private MetricsConstants() { } /** * Inner class for constants used as key to tag metrics. */ public static final class TagKeys { /** * Key to tag metrics with exception class. */ public static final String EXCEPTION_CLASS = "exceptionClass"; /** * Key to tag metrics with class of agent launcher. */ public static final String AGENT_LAUNCHER_CLASS = "agentLauncherClass"; /** * Key to tag metrics with cluster ID. */ public static final String CLUSTER_ID = "clusterId"; /** * Key to tag metrics with cluster name. */ public static final String CLUSTER_NAME = "clusterName"; /** * Key to tag metrics with command ID. */ public static final String COMMAND_ID = "commandId"; /** * Key to tag metrics with command name. */ public static final String COMMAND_NAME = "commandName"; /** * Key to tag a class name. */ public static final String CLASS_NAME = "class"; /** * Key to tag the status of a request or operation. */ public static final String STATUS = "status"; /** * Key to tag a username. */ public static final String USER = "user"; /** * Key to tag the user concurrent job limit. */ public static final String JOBS_USER_LIMIT = "jobsUserLimit"; /** * Key to tag the origin/source state of a state transition. */ public static final String FROM_STATE = "fromState"; /** * Key to tag the destination/target state of a state transition. */ public static final String TO_STATE = "toState"; /** * Key to tag the URI for a given script resource. */ public static final String SCRIPT_URI = "scriptUri"; /** * Utility class private constructor. */ private TagKeys() { } } /** * Constants used as metrics tags values by various classes. */ public static final class TagValues { /** * Tag value to denote success (used with TagKeys.STATUS). */ public static final String SUCCESS = "success"; /** * Tag value to denote failure (used with TagKeys.STATUS). */ public static final String FAILURE = "failure"; /** * Utility class private constructor. */ private TagValues() { } } }
2,527
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/util/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * General utility classes. * * @author tgianos */ @ParametersAreNonnullByDefault package com.netflix.genie.web.util; import javax.annotation.ParametersAreNonnullByDefault;
2,528
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/health/GenieCpuHealthIndicator.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.health; import com.netflix.genie.web.properties.HealthProperties; import com.sun.management.OperatingSystemMXBean; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.scheduling.TaskScheduler; import javax.validation.constraints.NotNull; import java.lang.management.ManagementFactory; /** * Health indicator for system cpu usage. Mark the service out-of-service if it crosses the threshold. * * @author amajumdar * @since 3.0.0 */ @Slf4j public class GenieCpuHealthIndicator implements HealthIndicator { private static final String CPU_LOAD = "cpuLoad"; private final double maxCpuLoadPercent; private final int maxCpuLoadConsecutiveOccurrences; private final OperatingSystemMXBean operatingSystemMXBean; private final DistributionSummary summaryCpuMetric; private int cpuLoadConsecutiveOccurrences; /** * Constructor. * * @param healthProperties The maximum physical memory threshold * @param registry Registry * @param taskScheduler task scheduler */ public GenieCpuHealthIndicator( @NotNull final HealthProperties healthProperties, @NotNull final MeterRegistry registry, @NotNull final TaskScheduler taskScheduler ) { this( healthProperties.getMaxCpuLoadPercent(), healthProperties.getMaxCpuLoadConsecutiveOccurrences(), (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(), registry.summary("genie.cpuLoad"), taskScheduler ); } GenieCpuHealthIndicator( final double maxCpuLoadPercent, final int maxCpuLoadConsecutiveOccurrences, final OperatingSystemMXBean operatingSystemMXBean, final DistributionSummary summaryCpuMetric, final TaskScheduler taskScheduler ) { this.maxCpuLoadPercent = maxCpuLoadPercent; this.maxCpuLoadConsecutiveOccurrences = maxCpuLoadConsecutiveOccurrences; this.operatingSystemMXBean = operatingSystemMXBean; this.summaryCpuMetric = summaryCpuMetric; this.summaryCpuMetric.record((long) (operatingSystemMXBean.getSystemCpuLoad() * 100)); taskScheduler.scheduleAtFixedRate(() -> this.summaryCpuMetric .record((long) (operatingSystemMXBean.getSystemCpuLoad() * 100)), 5000); } @Override public Health health() { // Use the distribution summary to get an average of the cpu metrics. final long cpuCount = this.summaryCpuMetric.count(); final double cpuTotal = this.summaryCpuMetric.totalAmount(); final double currentCpuLoadPercent = cpuCount == 0 ? operatingSystemMXBean.getSystemCpuLoad() : (cpuTotal / (double) cpuCount); if (currentCpuLoadPercent > maxCpuLoadPercent) { cpuLoadConsecutiveOccurrences++; } else { cpuLoadConsecutiveOccurrences = 0; } // Mark the service down only after a consecutive number of cpu load occurrences. if (cpuLoadConsecutiveOccurrences >= maxCpuLoadConsecutiveOccurrences) { log.warn("CPU usage {} crossed the threshold of {}", currentCpuLoadPercent, maxCpuLoadPercent); return Health .down() .withDetail(CPU_LOAD, currentCpuLoadPercent) .build(); } else { return Health .up() .withDetail(CPU_LOAD, currentCpuLoadPercent) .build(); } } }
2,529
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/health/GenieAgentHealthIndicator.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.health; import com.netflix.genie.web.agent.services.AgentConnectionTrackingService; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; /** * Provides a health indicator relative to the behavior of Genie Agents and this Server. * * @author tgianos * @since 4.0.0 */ public class GenieAgentHealthIndicator implements HealthIndicator { static final String NUM_CONNECTED_AGENTS = "numConnectedAgents"; private final AgentConnectionTrackingService agentConnectionTrackingService; /** * Constructor. * * @param agentConnectionTrackingService The service tracking live agent connections */ public GenieAgentHealthIndicator(final AgentConnectionTrackingService agentConnectionTrackingService) { this.agentConnectionTrackingService = agentConnectionTrackingService; } /** * {@inheritDoc} */ @Override public Health health() { final Health.Builder builder = new Health.Builder(); // TODO: For now just set it to always be up till we have better metrics. Likely want to tie this to gRPC // health or something else related there. Or if number of connections exceeds something we're // comfortable with builder.up(); builder.withDetail(NUM_CONNECTED_AGENTS, this.agentConnectionTrackingService.getConnectedAgentsCount()); return builder.build(); } }
2,530
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/health/package-info.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes for reporting health information to actuator. * * @author tgianos * @since 3.0.0 */ package com.netflix.genie.web.health;
2,531
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources/package-info.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes to work with/on HTTP resources. * * @author tgianos * @since 3.0.0 */ package com.netflix.genie.web.resources;
2,532
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources/writers/DefaultDirectoryWriter.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.resources.writers; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.collect.Lists; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.util.JsonUtils; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.catalina.util.ServerInfo; import org.apache.catalina.util.TomcatCSS; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.URL; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.File; import java.io.IOException; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Comparator; import java.util.List; /** * A default directory writer implementation. * * @author tgianos * @since 3.0.0 */ public class DefaultDirectoryWriter implements DirectoryWriter { /** * Given the provided information render as an HTML string. * * @param directoryName The name of the directory * @param directory The directory information to serialize * @return A string of valid HTML * @see org.apache.catalina.servlets.DefaultServlet */ public static String directoryToHTML(final String directoryName, final Directory directory) { final StringBuilder builder = new StringBuilder(); // Render the page header builder.append("<!DOCTYPE html>"); builder.append("<html>"); builder.append("<head>"); builder.append("<title>"); builder.append(directoryName); builder.append("</title>"); builder.append("<style type=\"text/css\"><!--"); builder.append(TomcatCSS.TOMCAT_CSS); builder.append("--></style> "); builder.append("</head>"); // Body builder.append("<body>"); builder.append("<h1>").append(directoryName).append("</h1>"); builder.append("<HR size=\"1\" noshade=\"noshade\">"); builder.append("<table width=\"100%\" cellspacing=\"0\"" + " cellpadding=\"5\" align=\"center\">"); // Render the column headings builder.append("<tr>"); builder.append("<td align=\"left\"><font size=\"+1\"><strong>"); builder.append("Filename"); builder.append("</strong></font></td>"); builder.append("<td align=\"right\"><font size=\"+1\"><strong>"); builder.append("Size"); builder.append("</strong></font></td>"); builder.append("<td align=\"right\"><font size=\"+1\"><strong>"); builder.append("Last Modified"); builder.append("</strong></font></td>"); builder.append("</tr>"); // Write parent if necessary if (directory.getParent() != null) { writeFileHtml(builder, false, directory.getParent(), true); } boolean shade = true; // Write directories if (directory.getDirectories() != null) { for (final Entry entry : directory.getDirectories()) { writeFileHtml(builder, shade, entry, true); shade = !shade; } } // Write files if (directory.getFiles() != null) { for (final Entry entry : directory.getFiles()) { writeFileHtml(builder, shade, entry, false); shade = !shade; } } // Render the page footer builder.append("</table>"); builder.append("<HR size=\"1\" noshade=\"noshade\">"); // TODO: replace with something related to Genie builder.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); builder.append("</body>"); builder.append("</html>"); return builder.toString(); } private static void writeFileHtml( final StringBuilder builder, final boolean shade, final Entry entry, final boolean isDirectory ) { builder.append("<tr"); if (shade) { builder.append(" bgcolor=\"#eeeeee\""); } builder.append(">"); builder.append("<td align=\"left\">&nbsp;&nbsp;"); builder.append("<a href=\"").append(entry.getUrl()).append("\">"); builder.append("<tt>").append(entry.getName()).append("</tt></a></td>"); builder.append("<td align=\"right\"><tt>"); if (isDirectory) { builder.append("-"); } else { builder.append(FileUtils.byteCountToDisplaySize(entry.getSize())); } builder.append("</tt></td>"); final String lastModified = DateTimeFormatter .RFC_1123_DATE_TIME .format(entry.getLastModified().atOffset(ZoneOffset.UTC)); builder.append("<td align=\"right\"><tt>").append(lastModified).append("</tt></td>"); builder.append("</tr>"); } /** * {@inheritDoc} * * @see org.apache.catalina.servlets.DefaultServlet */ @Override public String toHtml( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws IOException { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return directoryToHTML(directory.getName(), dir); } /** * {@inheritDoc} */ @Override public String toJson( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws Exception { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return GenieObjectMapper.getMapper().writeValueAsString(dir); } protected Directory getDirectory(final File directory, final String requestUrl, final boolean includeParent) { if (!directory.isDirectory()) { throw new IllegalArgumentException("Input directory is not a valid directory. Unable to continue."); } if (StringUtils.isBlank(requestUrl)) { throw new IllegalArgumentException("No request url entered. Unable to continue."); } final Directory dir = new Directory(); if (includeParent) { final Entry parent = new Entry(); String url = requestUrl; if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 2); } // Rip off the last directory url = url.substring(0, url.lastIndexOf('/')); parent.setName("../"); parent.setUrl(url); parent.setSize(0L); parent.setLastModified(Instant.ofEpochMilli(directory.getParentFile().getAbsoluteFile().lastModified())); dir.setParent(parent); } final File[] files = directory.listFiles(); dir.setDirectories(Lists.newArrayList()); dir.setFiles(Lists.newArrayList()); final String baseURL = requestUrl.endsWith("/") ? requestUrl : requestUrl + "/"; if (files != null) { for (final File file : files) { final Entry entry = new Entry(); entry.setLastModified(Instant.ofEpochMilli(file.getAbsoluteFile().lastModified())); if (file.isDirectory()) { entry.setName(file.getName() + "/"); entry.setUrl(baseURL + file.getName() + "/"); entry.setSize(0L); dir.getDirectories().add(entry); } else { entry.setName(file.getName()); entry.setUrl(baseURL + file.getName()); entry.setSize(file.getAbsoluteFile().length()); dir.getFiles().add(entry); } } } dir.getDirectories().sort( Comparator.comparing(Entry::getName) ); dir.getFiles().sort( Comparator.comparing(Entry::getName) ); return dir; } /** * DTO for representing a directory contents. * * @author tgianos * @since 3.0.0 */ @Data public static class Directory { private Entry parent; private List<Entry> directories; private List<Entry> files; } /** * DTO for representing information about an entry within a job directory. * * @author tgianos * @since 3.0.0 */ @Data @EqualsAndHashCode(exclude = {"lastModified"}) public static class Entry { @NotBlank private String name; @URL private String url; @Min(0) private long size; @NotNull @JsonSerialize(using = JsonUtils.InstantMillisecondSerializer.class) private Instant lastModified; } }
2,533
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources/writers/DirectoryWriter.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.resources.writers; import org.hibernate.validator.constraints.URL; import javax.validation.constraints.NotNull; import java.io.File; /** * Interface for methods to convert a directory to various String representations. * * @author tgianos * @since 3.0.0 */ public interface DirectoryWriter { /** * Convert a given directory to an String containing a full valid HTML page. * * @param directory The directory to convert. Not null. Is directory. * @param requestURL The URL of the request that kicked off this process * @param includeParent Whether the conversion should include reference to the parent directory. * @return String HTML representation of the directory * @throws Exception for any conversion problem */ String toHtml( @NotNull File directory, @URL String requestURL, boolean includeParent ) throws Exception; /** * Convert a given directory to an String of JSON. * * @param directory The directory to convert. Not null. Is directory. * @param requestURL The URL of the request that kicked off this process * @param includeParent Whether the conversion should include reference to the parent directory. * @return String HTML representation of the directory * @throws Exception for any conversion problem */ String toJson( @NotNull File directory, @URL String requestURL, boolean includeParent ) throws Exception; }
2,534
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/resources/writers/package-info.java
/* * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Interfaces and implementations to convert a directory to given representations. * * @author tgianos * @since 3.0.0 */ package com.netflix.genie.web.resources.writers;
2,535
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Module for classes, interfaces and services for communicating with Genie Agent instances. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent; import javax.annotation.ParametersAreNonnullByDefault;
2,536
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Any APIs the server will expose for the Agent to connect to. These are kept separate from the ones in the main * APIs package as those are for end users and these are for more Genie system internals. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.apis; import javax.annotation.ParametersAreNonnullByDefault;
2,537
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Remote procedure call APIs. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.apis.rpc; import javax.annotation.ParametersAreNonnullByDefault;
2,538
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * V4 Agent APIs. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.apis.rpc.v4; import javax.annotation.ParametersAreNonnullByDefault;
2,539
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/interceptors/SimpleLoggingInterceptor.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.interceptors; import io.grpc.ForwardingServerCall; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; import lombok.extern.slf4j.Slf4j; /** * Proof of concept server interceptor that logs gRPC requests and errors. */ @Slf4j public class SimpleLoggingInterceptor implements ServerInterceptor { private static final String NO_CAUSE = "Error cause is unknown"; /** * {@inheritDoc} */ @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next ) { return next.startCall(new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) { /** * {@inheritDoc} */ @Override public void request(final int numMessages) { log.debug("gRPC call: {}", call.getMethodDescriptor().getFullMethodName()); super.request(numMessages); } /** * {@inheritDoc} */ @Override public void close(final Status status, final Metadata trailers) { if (!status.isOk()) { log.warn( "gRPC error: {} -> {}: {}", call.getMethodDescriptor().getFullMethodName(), status.getCode().value(), (status.getCause() != null ? status.getCause().getMessage() : NO_CAUSE), status.getCause() ); } super.close(status, trailers); } }, headers); } }
2,540
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/interceptors/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Custom interceptors for the gRPC server. * * @author mprimi * @since 4.0.0 */ package com.netflix.genie.web.agent.apis.rpc.v4.interceptors;
2,541
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/GRpcJobServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobRequest; 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.unchecked.GenieJobNotFoundException; import com.netflix.genie.proto.ChangeJobArchiveStatusRequest; import com.netflix.genie.proto.ChangeJobArchiveStatusResponse; import com.netflix.genie.proto.ChangeJobStatusRequest; import com.netflix.genie.proto.ChangeJobStatusResponse; 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.JobSpecificationRequest; import com.netflix.genie.proto.JobSpecificationResponse; import com.netflix.genie.proto.ReserveJobIdRequest; import com.netflix.genie.proto.ReserveJobIdResponse; import com.netflix.genie.web.agent.services.AgentJobService; import com.netflix.genie.web.util.MetricsUtils; import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Extension of {@link JobServiceGrpc.JobServiceImplBase} to provide * functionality for resolving and fetching specifications for jobs to be run by the Genie Agent. * * @author tgianos * @since 4.0.0 */ @Slf4j public class GRpcJobServiceImpl extends JobServiceGrpc.JobServiceImplBase { private static final String AGENT_VERSION_TAG = "agentVersion"; private static final String STATUS_FROM_TAG = "statusFrom"; private static final String STATUS_TO_TAG = "statusTo"; private static final String UNKNOWN_VERSION = "unknown"; private static final String TIMERS_PREFIX = "genie.rpc.job"; private static final String HANDSHAKE_TIMER = TIMERS_PREFIX + ".handshake.timer"; private static final String CONFIGURE_TIMER = TIMERS_PREFIX + ".configure.timer"; private static final String RESERVE_TIMER = TIMERS_PREFIX + ".reserve.timer"; private static final String RESOLVE_TIMER = TIMERS_PREFIX + ".resolve.timer"; private static final String GET_SPECIFICATION_TIMER = TIMERS_PREFIX + ".getSpecification.timer"; private static final String DRY_RUN_RESOLVE_TIMER = TIMERS_PREFIX + ".dryRunResolve.timer"; private static final String CLAIM_TIMER = TIMERS_PREFIX + ".claim.timer"; private static final String CHANGE_STATUS_TIMER = TIMERS_PREFIX + ".changeStatus.timer"; private static final String GET_STATUS_TIMER = TIMERS_PREFIX + ".getStatus.timer"; private static final String CHANGE_ARCHIVE_STATUS_TIMER = TIMERS_PREFIX + ".changeArchiveStatus.timer"; private final AgentJobService agentJobService; private final JobServiceProtoConverter jobServiceProtoConverter; private final JobServiceProtoErrorComposer protoErrorComposer; private final MeterRegistry meterRegistry; /** * Constructor. * * @param agentJobService The implementation of the {@link AgentJobService} to use * @param jobServiceProtoConverter DTO/Proto converter * @param protoErrorComposer proto error message composer * @param meterRegistry meter registry */ public GRpcJobServiceImpl( final AgentJobService agentJobService, final JobServiceProtoConverter jobServiceProtoConverter, final JobServiceProtoErrorComposer protoErrorComposer, final MeterRegistry meterRegistry ) { this.agentJobService = agentJobService; this.jobServiceProtoConverter = jobServiceProtoConverter; this.protoErrorComposer = protoErrorComposer; this.meterRegistry = meterRegistry; } /** * This API gives the server a chance to reject a client/agent based on its metadata (version, location, ...). * * @param request The request containing client metadata * @param responseObserver To send the response */ @Override public void handshake( final HandshakeRequest request, final StreamObserver<HandshakeResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final AgentClientMetadata agentMetadata = jobServiceProtoConverter.toAgentClientMetadataDto(request.getAgentMetadata()); tags.add(Tag.of(AGENT_VERSION_TAG, agentMetadata.getVersion().orElse(UNKNOWN_VERSION))); agentJobService.handshake(agentMetadata); responseObserver.onNext( HandshakeResponse.newBuilder() .setMessage("Agent is allowed to proceed") .setType(HandshakeResponse.Type.ALLOWED) .build() ); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error(e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoHandshakeResponse(e)); } finally { meterRegistry .timer(HANDSHAKE_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * This API provides runtime configuration to the agent (example: timeouts, parallelism, etc.). * * @param request The agent request * @param responseObserver To send the response */ @Override public void configure( final ConfigureRequest request, final StreamObserver<ConfigureResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final AgentClientMetadata agentMetadata = jobServiceProtoConverter.toAgentClientMetadataDto(request.getAgentMetadata()); tags.add(Tag.of(AGENT_VERSION_TAG, agentMetadata.getVersion().orElse(UNKNOWN_VERSION))); final Map<String, String> agentProperties = agentJobService.getAgentProperties(agentMetadata); responseObserver.onNext( ConfigureResponse.newBuilder() .putAllProperties(agentProperties) .build() ); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error(e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoConfigureResponse(e)); } finally { meterRegistry .timer(CONFIGURE_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * This API will reserve a job id using the supplied metadata in the request and return the reserved job id. * * @param request The request containing all the metadata necessary to reserve a job id in the system * @param responseObserver To send the response */ @Override public void reserveJobId( final ReserveJobIdRequest request, final StreamObserver<ReserveJobIdResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final JobRequest jobRequest = jobServiceProtoConverter.toJobRequestDto(request); final AgentClientMetadata agentClientMetadata = jobServiceProtoConverter.toAgentClientMetadataDto(request.getAgentMetadata()); tags.add(Tag.of(AGENT_VERSION_TAG, agentClientMetadata.getVersion().orElse(UNKNOWN_VERSION))); final String jobId = this.agentJobService.reserveJobId(jobRequest, agentClientMetadata); responseObserver.onNext( ReserveJobIdResponse.newBuilder() .setId(jobId) .build() ); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error(e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoReserveJobIdResponse(e)); } finally { meterRegistry .timer(RESERVE_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * This API will take a request to resolve a Job Specification and given the inputs figure out all the details * needed to flesh out a job specification for the Agent to run. The request parameters will be stored in the * database. * * @param request The request information * @param responseObserver How to send a response */ @Override public void resolveJobSpecification( final JobSpecificationRequest request, final StreamObserver<JobSpecificationResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final String id = request.getId(); final JobSpecification jobSpec = this.agentJobService.resolveJobSpecification(id); responseObserver.onNext(jobServiceProtoConverter.toJobSpecificationResponseProto(jobSpec)); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error(e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoJobSpecificationResponse(e)); } finally { meterRegistry .timer(RESOLVE_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * Assuming a specification has already been resolved the agent will call this API with a job id to fetch the * specification. * * @param request The request containing the job id to return the specification for * @param responseObserver How to send a response */ @Override public void getJobSpecification( final JobSpecificationRequest request, final StreamObserver<JobSpecificationResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final String id = request.getId(); final JobSpecification jobSpecification = this.agentJobService.getJobSpecification(id); responseObserver.onNext(jobServiceProtoConverter.toJobSpecificationResponseProto(jobSpecification)); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error(e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoJobSpecificationResponse(e)); } finally { meterRegistry .timer(GET_SPECIFICATION_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * The agent requests that a job specification be resolved without impacting any state in the database. This * operation is completely transient and just reflects what the job specification would look like given the * current state of the system and the input parameters. * * @param request The request containing all the metadata required to resolve a job specification * @param responseObserver The observer to send a response with */ @Override public void resolveJobSpecificationDryRun( final DryRunJobSpecificationRequest request, final StreamObserver<JobSpecificationResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final JobRequest jobRequest = jobServiceProtoConverter.toJobRequestDto(request); final JobSpecification jobSpecification = this.agentJobService.dryRunJobSpecificationResolution(jobRequest); responseObserver.onNext(jobServiceProtoConverter.toJobSpecificationResponseProto(jobSpecification)); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error("Error resolving job specification for request " + request, e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoJobSpecificationResponse(e)); } finally { meterRegistry .timer(DRY_RUN_RESOLVE_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * When an agent is claiming responsibility and ownership for a job this API is called. * * @param request The request containing the job id being claimed and other pertinent metadata * @param responseObserver The observer to send a response with */ @Override public void claimJob( final ClaimJobRequest request, final StreamObserver<ClaimJobResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final String id = request.getId(); final AgentClientMetadata clientMetadata = jobServiceProtoConverter.toAgentClientMetadataDto(request.getAgentMetadata()); tags.add(Tag.of(AGENT_VERSION_TAG, clientMetadata.getVersion().orElse(UNKNOWN_VERSION))); this.agentJobService.claimJob(id, clientMetadata); responseObserver.onNext(ClaimJobResponse.newBuilder().setSuccessful(true).build()); MetricsUtils.addSuccessTags(tags); } catch (final Exception e) { log.error("Error claiming job for request " + request, e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(this.protoErrorComposer.toProtoClaimJobResponse(e)); } finally { meterRegistry .timer(CLAIM_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * When the agent wants to tell the system that the status of a job is changed this API is called. * * @param request The request containing the necessary metadata to change job status for a given job * @param responseObserver The observer to send a response with */ @Override public void changeJobStatus( final ChangeJobStatusRequest request, final StreamObserver<ChangeJobStatusResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final String id = request.getId(); final JobStatus currentStatus = JobStatus.valueOf(request.getCurrentStatus().toUpperCase()); final JobStatus newStatus = JobStatus.valueOf(request.getNewStatus().toUpperCase()); final String newStatusMessage = request.getNewStatusMessage(); tags.add(Tag.of(STATUS_FROM_TAG, currentStatus.name())); tags.add(Tag.of(STATUS_TO_TAG, newStatus.name())); this.agentJobService.updateJobStatus(id, currentStatus, newStatus, newStatusMessage); responseObserver.onNext(ChangeJobStatusResponse.newBuilder().setSuccessful(true).build()); MetricsUtils.addSuccessTags(tags); } catch (Exception e) { log.error("Error changing job status for request " + request, e); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onNext(protoErrorComposer.toProtoChangeJobStatusResponse(e)); } finally { meterRegistry .timer(CHANGE_STATUS_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } responseObserver.onCompleted(); } /** * When the agent wants to confirm it's status is still the expected one (i.e. that the leader didn't mark the * job failed). * * @param request The request containing the job id to look up * @param responseObserver The observer to send a response with */ @Override public void getJobStatus( final GetJobStatusRequest request, final StreamObserver<GetJobStatusResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); final String id = request.getId(); try { final JobStatus status = this.agentJobService.getJobStatus(id); responseObserver.onNext(GetJobStatusResponse.newBuilder().setStatus(status.name()).build()); responseObserver.onCompleted(); MetricsUtils.addSuccessTags(tags); } catch (Exception e) { log.error("Error retrieving job {} status: {}", id, e.getMessage()); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onError(e); } finally { meterRegistry .timer(GET_STATUS_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } /** * When the agent wants to set the archival status of a job post-execution (i.e. archived successfully, or failed * to archive). * * @param request The request containing the job id to look up * @param responseObserver The observer to send a response with */ @Override public void changeJobArchiveStatus( final ChangeJobArchiveStatusRequest request, final StreamObserver<ChangeJobArchiveStatusResponse> responseObserver ) { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); final String id = request.getId(); final ArchiveStatus newArchiveStatus = ArchiveStatus.valueOf(request.getNewStatus()); tags.add(Tag.of(STATUS_TO_TAG, newArchiveStatus.name())); try { this.agentJobService.updateJobArchiveStatus(id, newArchiveStatus); responseObserver.onNext(ChangeJobArchiveStatusResponse.newBuilder().build()); responseObserver.onCompleted(); MetricsUtils.addSuccessTags(tags); } catch (GenieJobNotFoundException e) { log.error("Cannot update archive status of job {}, job not found", id); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onError(Status.NOT_FOUND.withCause(e).asException()); } catch (Exception e) { log.error("Error retrieving job {} status: {}", id, e.getMessage()); MetricsUtils.addFailureTagsWithException(tags, e); responseObserver.onError(e); } finally { meterRegistry .timer(CHANGE_ARCHIVE_STATUS_TIMER, tags) .record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } }
2,542
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/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.web.agent.apis.rpc.v4.endpoints; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.protobuf.ByteString; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; 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 com.netflix.genie.web.agent.resources.AgentFileResourceImpl; import com.netflix.genie.web.agent.services.AgentFileStreamService; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.properties.AgentFileStreamProperties; import com.netflix.genie.web.util.StreamBuffer; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.MeterRegistry; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpRange; import org.springframework.scheduling.TaskScheduler; import javax.annotation.Nullable; import javax.naming.LimitExceededException; import java.io.InputStream; import java.net.URI; import java.nio.file.Path; import java.time.Instant; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * {@link AgentFileStreamService} gRPC implementation. * Receives and caches manifests from connected agents. * Allows requesting a file, which is returned in the form of a {@link AgentFileResource}. * <p> * Implementation overview: * Each agent maintains a single "control" bidirectional stream (through the 'sync' RPC method). * This stream is used by the agent to regularly push manifests. * And it is used by the server to request files. * <p> * When a file is requested, the agent opens a separate "transfer" bidirectional stream (through the 'transmit' RPC * method) for that file transfer and starts sending chunks (currently one at the time), the server sends * acknowledgements in the same stream. * <p> * This service returns a resource immediately, but maintains a handle on a buffer where data is written as it is * received. * * @author mprimi * @since 4.0.0 */ @Slf4j public class GRpcAgentFileStreamServiceImpl extends FileStreamServiceGrpc.FileStreamServiceImplBase implements AgentFileStreamService { private static final String METRICS_PREFIX = "genie.agents.fileTransfers"; private static final String TRANSFER_COUNTER = METRICS_PREFIX + ".requested.counter"; private static final String TRANSFER_LIMIT_EXCEEDED_COUNTER = METRICS_PREFIX + ".rejected.counter"; private static final String MANIFEST_CACHE_SIZE_GAUGE = METRICS_PREFIX + ".manifestCache.size"; private static final String CONTROL_STREAMS_GAUGE = METRICS_PREFIX + ".controlStreams.size"; private static final String TRANSFER_TIMEOUT_COUNTER = METRICS_PREFIX + ".timeout.counter"; private static final String TRANSFER_SIZE_DISTRIBUTION = METRICS_PREFIX + ".transferSize.summary"; private static final String ACTIVE_TRANSFER_GAUGE = METRICS_PREFIX + ".activeTransfers.size"; private final ControlStreamManager controlStreamsManager; private final TransferManager transferManager; private final Counter fileTransferLimitExceededCounter; /** * Constructor. * * @param converter The {@link JobDirectoryManifestProtoConverter} instance to use * @param taskScheduler A {@link TaskScheduler} instance to use * @param properties The service properties * @param registry The meter registry */ public GRpcAgentFileStreamServiceImpl( final JobDirectoryManifestProtoConverter converter, final TaskScheduler taskScheduler, final AgentFileStreamProperties properties, final MeterRegistry registry ) { this.fileTransferLimitExceededCounter = registry.counter(TRANSFER_LIMIT_EXCEEDED_COUNTER); this.controlStreamsManager = new ControlStreamManager(converter, properties, registry); this.transferManager = new TransferManager(controlStreamsManager, taskScheduler, properties, registry); } /** * {@inheritDoc} */ @Override public Optional<AgentFileResource> getResource( final String jobId, final Path relativePath, final URI uri, @Nullable final HttpRange range ) { if (range == null) { log.warn("Attempting to stream file with no range: {} of job: {}", relativePath, jobId); } log.debug("Attempting to stream file: {} of job: {}", relativePath, jobId); final Optional<DirectoryManifest> optionalManifest = this.getManifest(jobId); if (!optionalManifest.isPresent()) { log.warn("No manifest found for job: {}" + jobId); return Optional.empty(); } final DirectoryManifest manifest = optionalManifest.get(); final DirectoryManifest.ManifestEntry manifestEntry = manifest.getEntry(relativePath.toString()).orElse(null); if (manifestEntry == null) { // File does not exist according to manifest log.warn( "Requesting a file ({}) that does not exist in the manifest for job id: {}: ", relativePath, jobId ); return Optional.of(AgentFileResourceImpl.forNonExistingResource()); } final FileTransfer fileTransfer; try { // Attempt to start a file transfer fileTransfer = this.transferManager.startFileTransfer( jobId, manifestEntry, relativePath, range ); } catch (NotFoundException e) { log.warn("No available stream to request file {} from agent running job: {}", relativePath, jobId); return Optional.empty(); } catch (LimitExceededException e) { log.warn("No available slots to request file {} from agent running job: {}", relativePath, jobId); this.fileTransferLimitExceededCounter.increment(); return Optional.empty(); } catch (IndexOutOfBoundsException e) { log.warn("Cannot serve large file {} from agent running job: {}", relativePath, jobId); return Optional.empty(); } // Return the resource return Optional.of( AgentFileResourceImpl.forAgentFile( uri, manifestEntry.getSize(), manifestEntry.getLastModifiedTime(), relativePath, jobId, fileTransfer.getInputStream() ) ); } /** * {@inheritDoc} */ @Override public Optional<DirectoryManifest> getManifest(final String jobId) { return Optional.ofNullable(this.controlStreamsManager.getManifest(jobId)); } /** * {@inheritDoc} */ @Override public StreamObserver<AgentManifestMessage> sync(final StreamObserver<ServerControlMessage> responseObserver) { return this.controlStreamsManager.handleNewControlStream(responseObserver); } /** * {@inheritDoc} */ @Override public StreamObserver<AgentFileMessage> transmit(final StreamObserver<ServerAckMessage> responseObserver) { return this.transferManager.handleNewTransferStream(responseObserver); } // Manages control streams, in theory one for each agent connected to this node private static final class ControlStreamManager { private final Map<String, ControlStreamObserver> controlStreamMap = Maps.newHashMap(); private final Cache<String, DirectoryManifest> manifestCache; private final JobDirectoryManifestProtoConverter converter; private final Counter fileTansferCounter; private final MeterRegistry registry; private ControlStreamManager( final JobDirectoryManifestProtoConverter converter, final AgentFileStreamProperties properties, final MeterRegistry registry ) { this.converter = converter; this.manifestCache = Caffeine.newBuilder() .expireAfterWrite(properties.getManifestCacheExpiration()) .build(); this.fileTansferCounter = registry.counter(TRANSFER_COUNTER); this.registry = registry; } private synchronized void requestFile( final String jobId, final String fileTransferId, final String relativePath, final long startOffset, final long endOffset ) throws NotFoundException, IndexOutOfBoundsException { final ControlStreamObserver controlStreamObserver = this.controlStreamMap.get(jobId); if (controlStreamObserver == null) { throw new NotFoundException("No active stream control stream for job: " + jobId); } this.fileTansferCounter.increment(); if (!controlStreamObserver.allowLargeFiles.get() && (startOffset > Integer.MAX_VALUE || endOffset > Integer.MAX_VALUE)) { // Agents that are not marked with 'allowLargeFiles' use a version of the protocol that uses // int32. They cannot serve file if the range goes beyond the 2GB mark. // The two casts to int below can potentially overflow, but that is ok because such request will only // be sent to an agent that ignores those fields. throw new IndexOutOfBoundsException("Outdated agent does not support ranges beyond the 2GB mark"); } // Send the file request controlStreamObserver.responseObserver.onNext( ServerControlMessage.newBuilder() .setServerFileRequest( ServerFileRequestMessage.newBuilder() .setStreamId(fileTransferId) .setRelativePath(relativePath) .setDeprecatedStartOffset((int) startOffset) // Possible integer overflow .setDeprecatedEndOffset((int) endOffset) // Possible integer overflow .setStartOffset(startOffset) .setEndOffset(endOffset) .build() ) .build() ); } private StreamObserver<AgentManifestMessage> handleNewControlStream( final StreamObserver<ServerControlMessage> responseObserver ) { log.debug("New agent control stream established"); return new ControlStreamObserver(this, responseObserver); } private DirectoryManifest getManifest(final String jobId) { return this.manifestCache.getIfPresent(jobId); } private synchronized void updateManifestAndStream( final ControlStreamObserver controlStreamObserver, final String jobId, final DirectoryManifest manifest ) { // Keep the most recent manifest for each job id this.manifestCache.put(jobId, manifest); // Keep the most recent control stream for each job id final ControlStreamObserver previousObserver = this.controlStreamMap.put(jobId, controlStreamObserver); if (previousObserver != null && previousObserver != controlStreamObserver) { // If the older one is still present, close it previousObserver.closeStreamWithError( new IllegalStateException("A new stream was registered for the same job id: " + jobId) ); } this.registry.gauge(MANIFEST_CACHE_SIZE_GAUGE, this.manifestCache.estimatedSize()); this.registry.gauge(CONTROL_STREAMS_GAUGE, this.controlStreamMap.size()); } private synchronized void removeControlStream( final ControlStreamObserver controlStreamObserver, @Nullable final Throwable t ) { log.debug("Control stream {}", t == null ? "completed" : "error: " + t.getMessage()); final boolean foundAndRemoved = this.controlStreamMap .entrySet() .removeIf(entry -> entry.getValue() == controlStreamObserver); if (foundAndRemoved) { log.debug( "Removed a control stream due to {}", t == null ? "completion" : "error: " + t.getMessage() ); } } } private static final class ControlStreamObserver implements StreamObserver<AgentManifestMessage> { private final ControlStreamManager controlStreamManager; private final StreamObserver<ServerControlMessage> responseObserver; private final AtomicBoolean allowLargeFiles = new AtomicBoolean(false); private ControlStreamObserver( final ControlStreamManager controlStreamManager, final StreamObserver<ServerControlMessage> responseObserver ) { this.controlStreamManager = controlStreamManager; this.responseObserver = responseObserver; } /** * {@inheritDoc} */ @Override public void onNext(final AgentManifestMessage value) { final String jobId = value.getJobId(); this.allowLargeFiles.set(value.getLargeFilesSupported()); DirectoryManifest manifest = null; try { manifest = this.controlStreamManager.converter.toManifest(value); } catch (GenieConversionException e) { log.warn("Failed to parse manifest for job id: {}", jobId, e); } if (manifest != null) { this.controlStreamManager.updateManifestAndStream(this, jobId, manifest); } } /** * {@inheritDoc} */ @Override public void onError(final Throwable t) { // Drop the stream, no other actions necessary this.controlStreamManager.removeControlStream(this, t); } /** * {@inheritDoc} */ @Override public void onCompleted() { // Drop the stream, no other actions necessary this.controlStreamManager.removeControlStream(this, null); this.responseObserver.onCompleted(); } public void closeStreamWithError(final Throwable e) { this.responseObserver.onError(e); } } // Manages in-progress file transfers private static final class TransferManager { private final Map<String, FileTransfer> activeTransfers = Maps.newHashMap(); private final Set<AgentFileChunkObserver> unclaimedTransferStreams = Sets.newHashSet(); // Little hack to get private inner class private final Class<? extends HttpRange> suffixRangeClass = HttpRange.createSuffixRange(1).getClass(); private final ControlStreamManager controlStreamsManager; private final TaskScheduler taskScheduler; private final AgentFileStreamProperties properties; private final Counter transferTimeOutCounter; private final DistributionSummary transferSizeDistribution; private final MeterRegistry registry; private TransferManager( final ControlStreamManager controlStreamsManager, final TaskScheduler taskScheduler, final AgentFileStreamProperties properties, final MeterRegistry registry ) { this.controlStreamsManager = controlStreamsManager; this.taskScheduler = taskScheduler; this.properties = properties; this.registry = registry; this.transferTimeOutCounter = registry.counter(TRANSFER_TIMEOUT_COUNTER); this.transferSizeDistribution = registry.summary(TRANSFER_SIZE_DISTRIBUTION); this.taskScheduler.scheduleAtFixedRate( this::reapStalledTransfers, this.properties.getStalledTransferCheckInterval() ); } private synchronized void reapStalledTransfers() { final AtomicInteger stalledTrasfersCounter = new AtomicInteger(); final Instant now = Instant.now(); // Iterate active transfers, shut down and remove the ones that are not making progress this.activeTransfers.entrySet().removeIf( entry -> { final String transferId = entry.getKey(); final FileTransfer transfer = entry.getValue(); final Instant deadline = transfer.lastAckTimestamp.plus(this.properties.getStalledTransferTimeout()); if (now.isAfter(deadline)) { stalledTrasfersCounter.incrementAndGet(); log.warn("Transfer {} is stalled of job {}, shutting it down", transferId, entry.getValue().jobId); final TimeoutException exception = new TimeoutException("Transfer not making progress"); // Shut down stream, if one was associated to this transfer final AgentFileChunkObserver observer = transfer.getAgentFileChunkObserver(); if (observer != null) { observer.getResponseObserver().onError(exception); } // Close the buffer transfer.closeWithError(exception); // Remove from active transfers return true; } else { // Do not remove from active, made progress recently enough. return false; } } ); this.transferTimeOutCounter.increment(stalledTrasfersCounter.get()); this.registry.gauge(ACTIVE_TRANSFER_GAUGE, this.activeTransfers.size()); } private synchronized FileTransfer startFileTransfer( final String jobId, final DirectoryManifest.ManifestEntry manifestEntry, final Path relativePath, @Nullable final HttpRange range ) throws NotFoundException, LimitExceededException { // Create a unique ID for this file transfer final String fileTransferId = UUID.randomUUID().toString(); log.debug( "Initiating transfer {} for file: {} of job: {}", fileTransferId, relativePath, jobId ); // No need to use a semaphore since class is synchronized if (this.activeTransfers.size() >= properties.getMaxConcurrentTransfers()) { log.warn("Rejecting request for {}:{}, too many active transfers", jobId, relativePath); throw new LimitExceededException("Too many concurrent downloads"); } final long fileSize = manifestEntry.getSize(); // Http range is inclusive, agent protocol is not. // Convert from one to the other. final long startOffset; final long endOffset; if (range == null) { startOffset = 0; endOffset = fileSize; } else if (range.getClass() == this.suffixRangeClass) { startOffset = range.getRangeStart(fileSize); endOffset = fileSize; } else { startOffset = Math.min(fileSize, range.getRangeStart(fileSize)); endOffset = 1 + range.getRangeEnd(fileSize); } log.debug("Transfer {} effective range {}-{}: of job: {} ", fileTransferId, startOffset, endOffset, jobId); // Allocate and park the buffer that will store the data in transit. final StreamBuffer buffer = new StreamBuffer(startOffset); // Create a file transfer final FileTransfer fileTransfer = new FileTransfer( fileTransferId, jobId, relativePath, startOffset, endOffset, fileSize, buffer ); this.transferSizeDistribution.record(endOffset - startOffset); if (endOffset - startOffset == 0) { log.debug("Transfer {} is empty, completing of job: {}", fileTransferId, jobId); // When requesting an empty file (or a range of 0 bytes), short-circuit and just return an empty // buffer, without tracking it as active transfer. buffer.closeForCompleted(); } else { log.debug("Tracking new transfer {} of job: {}", fileTransferId, jobId); // Expecting some data. Track this stream and its buffer so incoming chunks can be appended. this.activeTransfers.put(fileTransferId, fileTransfer); log.debug("Requesting start of transfer {} of job: {}", fileTransferId, jobId); // Request file over control channel try { this.controlStreamsManager.requestFile( jobId, fileTransferId, relativePath.toString(), startOffset, endOffset ); } catch (IndexOutOfBoundsException | NotFoundException e) { log.error( "Failed to request file {}:{}, terminating transfer {}: {}", jobId, relativePath, fileTransferId, e.getMessage() ); this.activeTransfers.remove(fileTransferId, fileTransfer); buffer.closeForError(e); throw e; } } return fileTransfer; } private synchronized StreamObserver<AgentFileMessage> handleNewTransferStream( final StreamObserver<ServerAckMessage> responseObserver ) { log.info("New file transfer stream established"); final AgentFileChunkObserver agentFileChunkObserver = new AgentFileChunkObserver(this, responseObserver); // Observer are not associated to a specific transfer until the first message is received this.unclaimedTransferStreams.add(agentFileChunkObserver); // Schedule a timeout for this stream to get associated with a pending transfer taskScheduler.schedule( () -> this.handleUnclaimedStreamTimeout(agentFileChunkObserver), Instant.now().plus(properties.getUnclaimedStreamStartTimeout()) ); return agentFileChunkObserver; } private synchronized void handleUnclaimedStreamTimeout(final AgentFileChunkObserver agentFileChunkObserver) { final boolean streamUnclaimed = this.unclaimedTransferStreams.remove(agentFileChunkObserver); if (streamUnclaimed) { // If found in the unclaimed set, this stream did not send any message yet, shut down the stream log.warn("Shutting down unclaimed transfer stream"); agentFileChunkObserver.getResponseObserver().onError( new TimeoutException("No messages received in stream") ); this.transferTimeOutCounter.increment(); } } private synchronized void handleFileChunk( final String transferStreamId, final AgentFileChunkObserver agentFileChunkObserver, final ByteString data ) { final FileTransfer fileTransfer = this.activeTransfers.get(transferStreamId); final boolean unclaimedStream = this.unclaimedTransferStreams.remove(agentFileChunkObserver); if (fileTransfer != null) { if (unclaimedStream) { // There is a transfer pending, and this stream just sent the first chunk of data // Associate the stream to the file transfer fileTransfer.claimStreamObserver(agentFileChunkObserver); } // Write and ack in a different thread, to avoid locking this during a potentially blocking operation this.taskScheduler.schedule( () -> this.writeDataAndAck(fileTransfer, data), new Date() // Ack: use date rather than instant to make the distinction easier in tests ); } else { log.warn("Received a chunk for a transfer no longer in progress: {}", transferStreamId); } } private synchronized void removeTransferStream( final AgentFileChunkObserver agentFileChunkObserver, @Nullable final Throwable t ) { log.info("Removing file transfer: {}", t == null ? "completed" : t.getMessage()); // Received error or completion on a transfer stream. final FileTransfer fileTransfer = this.findFileTransfer(agentFileChunkObserver); if (fileTransfer != null) { // Transfer is no longer active, remove it final boolean removed = this.activeTransfers.remove(fileTransfer.getTransferId(), fileTransfer); if (removed && t == null) { fileTransfer.close(); } else if (removed) { fileTransfer.closeWithError(t); } // If not removed, another thread already got to it, for example due to timeout. Nothing to do } else { // Stream is not associated with a file transfer, may be unclaimed. // Remove it so the timeout task does not try to close it again. this.unclaimedTransferStreams.remove(agentFileChunkObserver); } } private synchronized FileTransfer findFileTransfer(final AgentFileChunkObserver agentFileChunkObserver) { // Find a transfer by iterating over the active ones. // Could keep a map indexed by observers, but this should be fine since it's only called when a stream // terminates. for (final FileTransfer fileTransfer : this.activeTransfers.values()) { if (fileTransfer.getAgentFileChunkObserver() == agentFileChunkObserver) { return fileTransfer; } } return null; } // N.B. this should not synchronized to avoid locking up the transfer manager private void writeDataAndAck(final FileTransfer fileTransfer, final ByteString data) { final String fileTransferId = fileTransfer.getTransferId(); try { // Try to write. May fail if buffer consumer is slow and buffer is not drained yet. if (fileTransfer.append(data)) { log.debug("Wrote chunk of transfer {} to buffer. Sending ack", fileTransferId); fileTransfer.sendAck(); } else { // Try again in a little bit this.taskScheduler.schedule( () -> this.writeDataAndAck(fileTransfer, data), Instant.now().plus(this.properties.getWriteRetryDelay()) ); } } catch (IllegalStateException e) { // Eventually retries will stop because the transfer times out due to lack of progress log.warn("Buffer of transfer {} of job {} is closed", fileTransferId, fileTransfer.jobId); } } } private static final class FileTransfer { private final String jobId; @Getter private final String transferId; private final StreamBuffer buffer; private final String description; @Getter private AgentFileChunkObserver agentFileChunkObserver; private State state = State.NEW; private Instant lastAckTimestamp; private FileTransfer( final String transferId, final String jobId, final Path relativePath, final long startOffset, final long endOffset, final long fileSize, final StreamBuffer buffer ) { this.jobId = jobId; this.transferId = transferId; this.buffer = buffer; this.lastAckTimestamp = Instant.now(); this.description = "FileTransfer " + transferId + ", agent://" + jobId + "/" + relativePath + " " + "(range: (" + startOffset + "-" + endOffset + "] file.size: " + fileSize + ")"; } @Override public String toString() { return "" + this.state + " " + this.description; } private void claimStreamObserver(final AgentFileChunkObserver observer) { this.state = State.IN_PROGRESS; this.agentFileChunkObserver = observer; } private InputStream getInputStream() { return this.buffer.getInputStream(); } private boolean append(final ByteString data) { return buffer.tryWrite(data); } private void closeWithError(final Throwable t) { this.state = State.FAILED; this.buffer.closeForError(t); } private void close() { this.state = State.COMPLETED; this.buffer.closeForCompleted(); } private void sendAck() { this.getAgentFileChunkObserver().getResponseObserver().onNext( ServerAckMessage.newBuilder().build() ); this.lastAckTimestamp = Instant.now(); } private enum State { NEW, IN_PROGRESS, COMPLETED, FAILED } } private static final class AgentFileChunkObserver implements StreamObserver<AgentFileMessage> { private final TransferManager transferManager; @Getter private final StreamObserver<ServerAckMessage> responseObserver; AgentFileChunkObserver( final TransferManager transferManager, final StreamObserver<ServerAckMessage> responseObserver ) { this.transferManager = transferManager; this.responseObserver = responseObserver; } /** * {@inheritDoc} */ @Override public void onNext(final AgentFileMessage value) { final String transferStreamId = value.getStreamId(); log.debug("Received file chunk of transfer: {}", transferStreamId); this.transferManager.handleFileChunk(transferStreamId, this, value.getData()); } /** * {@inheritDoc} */ @Override public void onError(final Throwable t) { this.transferManager.removeTransferStream(this, t); } /** * {@inheritDoc} */ @Override public void onCompleted() { this.transferManager.removeTransferStream(this, null); this.responseObserver.onCompleted(); } } }
2,543
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/GRpcPingServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import com.google.protobuf.util.Timestamps; import com.netflix.genie.common.internal.util.GenieHostInfo; import com.netflix.genie.proto.PingRequest; import com.netflix.genie.proto.PingServiceGrpc; import com.netflix.genie.proto.PongResponse; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * Implementation of the Ping service definition. * * @author mprimi * @since 4.0.0 */ @Slf4j public class GRpcPingServiceImpl extends PingServiceGrpc.PingServiceImplBase { private final String hostName; /** * Constructor. * * @param genieHostInfo The information about the host that this Genie instance is running on */ public GRpcPingServiceImpl(final GenieHostInfo genieHostInfo) { this.hostName = genieHostInfo.getHostname(); } /** * {@inheritDoc} */ @Override public void ping( final PingRequest request, final StreamObserver<PongResponse> responseObserver ) { final PongResponse response = PongResponse.newBuilder() .setRequestId(request.getRequestId()) .setTimestamp(Timestamps.fromMillis(System.currentTimeMillis())) .putServerMetadata(ServerMetadataKeys.SERVER_NAME, hostName) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); final StringBuilder sb = new StringBuilder(); sb.append( String.format( "Received ping with id: '%s' from client: '%s' and timestamp: '%s'. ", request.getRequestId(), request.getSourceName(), Timestamps.toString(request.getTimestamp()) ) ); sb.append("Client metadata: [ "); for (final Map.Entry<String, String> clientMetadataEntry : request.getClientMetadataMap().entrySet()) { sb .append("{") .append(clientMetadataEntry.getKey()) .append(" : ") .append(clientMetadataEntry.getValue()) .append("}, "); } sb.append("]"); log.info(sb.toString()); } static final class ServerMetadataKeys { static final String SERVER_NAME = "hostName"; } }
2,544
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/GRpcJobKillServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import com.google.common.annotations.VisibleForTesting; import com.netflix.genie.common.exceptions.GenieServerException; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException; import com.netflix.genie.proto.JobKillRegistrationRequest; import com.netflix.genie.proto.JobKillRegistrationResponse; import com.netflix.genie.proto.JobKillServiceGrpc; import com.netflix.genie.web.agent.services.AgentRoutingService; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.services.JobKillService; import com.netflix.genie.web.services.RequestForwardingService; import io.grpc.stub.ServerCallStreamObserver; import io.grpc.stub.StreamObserver; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.scheduling.annotation.Scheduled; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Implementation of {@link JobKillService} which uses parked gRPC requests to tell the agent to * shutdown via a user kill request if the job is in an active state. * * @author tgianos * @since 4.0.0 */ @Slf4j public class GRpcJobKillServiceImpl extends JobKillServiceGrpc.JobKillServiceImplBase implements JobKillService { @VisibleForTesting @Getter(AccessLevel.PACKAGE) private final Map<String, StreamObserver<JobKillRegistrationResponse>> parkedJobKillResponseObservers; private final PersistenceService persistenceService; private final AgentRoutingService agentRoutingService; private final RequestForwardingService requestForwardingService; /** * Constructor. * * @param dataServices The {@link DataServices} instance to use * @param agentRoutingService The {@link AgentRoutingService} instance to use to find where agents are * connected * @param requestForwardingService The service to use to forward requests to other Genie nodes */ public GRpcJobKillServiceImpl( final DataServices dataServices, final AgentRoutingService agentRoutingService, final RequestForwardingService requestForwardingService ) { this.persistenceService = dataServices.getPersistenceService(); this.parkedJobKillResponseObservers = new ConcurrentHashMap<>(); this.agentRoutingService = agentRoutingService; this.requestForwardingService = requestForwardingService; } /** * Register to be notified when a kill request for the job is received. * * @param request Request to register for getting notified when server gets a job kill request. * @param responseObserver The response observer */ @Override public void registerForKillNotification( final JobKillRegistrationRequest request, final StreamObserver<JobKillRegistrationResponse> responseObserver ) { final StreamObserver<JobKillRegistrationResponse> existingObserver = this.parkedJobKillResponseObservers.put( request.getJobId(), responseObserver ); // If a previous observer/request is present close that request if (existingObserver != null) { existingObserver.onCompleted(); } } /** * {@inheritDoc} */ @Override @Retryable( value = { GenieInvalidStatusException.class, GenieServerException.class }, backoff = @Backoff(delay = 1000) ) public void killJob( final String jobId, final String reason, @Nullable final HttpServletRequest request ) throws GenieJobNotFoundException, GenieServerException { final JobStatus currentJobStatus; try { currentJobStatus = this.persistenceService.getJobStatus(jobId); } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } if (currentJobStatus.isFinished()) { log.info("Job {} was already finished when the kill request arrived. Nothing to do.", jobId); } else if (JobStatus.getStatusesBeforeClaimed().contains(currentJobStatus)) { // Agent hasn't come up and claimed job yet. Setting to killed should prevent agent from starting try { this.persistenceService.updateJobStatus(jobId, currentJobStatus, JobStatus.KILLED, reason); } catch (final GenieInvalidStatusException e) { // This is the case where somewhere else in the system the status was changed before we could kill // Should retry entire method as job may have transitioned to a finished state log.error( "Unable to set job status for {} to {} due to current status not being expected {}", jobId, JobStatus.KILLED, currentJobStatus ); throw e; } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } } else if (currentJobStatus.isActive()) { // If we get here the Job should not currently be regarded as finished AND an agent has come up and // connected to one of the Genie servers, possibly this one if (this.agentRoutingService.isAgentConnectionLocal(jobId)) { // Agent should be connected here so we should have a response observer to use final StreamObserver<JobKillRegistrationResponse> responseObserver = this.parkedJobKillResponseObservers.remove(jobId); if (responseObserver == null) { // This might happen when the agent has gone but its status is not updated // In this case, we force updating the job status to KILLED. log.warn("Tried to kill Job {}, but expected local agent connection not found. " + "Trying to force updating the job status to {}", jobId, JobStatus.KILLED ); try { this.persistenceService.updateJobStatus(jobId, currentJobStatus, JobStatus.KILLED, reason); log.info("Succeeded to force updating the status of Job {} to {}", jobId, JobStatus.KILLED ); } catch (final GenieInvalidStatusException e) { log.error( "Failed to force updating the status of Job {} to {} " + "due to current status not being expected {}", jobId, JobStatus.KILLED, currentJobStatus ); throw e; } catch (final NotFoundException e) { log.error( "Failed to force updating the status of Job {} to {} due to job not found", jobId, JobStatus.KILLED ); throw new GenieJobNotFoundException(e); } } else { responseObserver.onNext(JobKillRegistrationResponse.newBuilder().build()); responseObserver.onCompleted(); log.info("Agent notified for killing job {}", jobId); } } else { // Agent is running somewhere else try to forward the request final String hostname = this.agentRoutingService .getHostnameForAgentConnection(jobId) .orElseThrow( // Note: this should retry as we may have hit a case where agent is transitioning nodes // it is connected to () -> new GenieServerException( "Unable to locate host where agent is connected for job " + jobId ) ); log.info( "Agent for job {} currently connected to {}. Attempting to forward kill request", jobId, hostname ); this.requestForwardingService.kill(hostname, jobId, request); } } else { // The job is in some unknown state throw exception that forces method to try again log.error("{} is an unhandled state for job {}", currentJobStatus, jobId); throw new GenieServerException( "Job " + jobId + " is currently in " + currentJobStatus + " status, which isn't currently handled" ); } } /** * Remove orphaned kill observers from local map. * <p> * The logic as currently implemented is to have the Agent, once handshake is complete, open a connection to * the server which results in parking a response observer in the map stored in this implementation. Upon receiving * a kill request for the correct job this class will use the observer to send the "response" to the agent which * will begin shut down process. The issue is that if the agent disconnects from this server the server will never * realize it's gone and these observers will build up in the map in memory forever. This method will periodically * go through the map and determine if the observers are still valid and remove any that aren't. * * @see "GRpcAgentJobKillServiceImpl" */ @Scheduled(fixedDelay = 30_000L, initialDelay = 30_000L) public void cleanupOrphanedObservers() { for (final String jobId : this.parkedJobKillResponseObservers.keySet()) { try { if (!this.agentRoutingService.isAgentConnectionLocal(jobId)) { final StreamObserver<JobKillRegistrationResponse> observer = this.parkedJobKillResponseObservers .remove(jobId); cancelObserverIfNecessary(observer); } } catch (final Exception unexpectedException) { log.error("Got unexpected exception while trying to cleanup jobID {}. Moving on. " + "Exception: {}", jobId, unexpectedException); } } } /** * Converts StreamObserver into ServerCallStreamObserver in order to tell * whether the observer is cancelled or not. * * @param observer Observer for which we would check the status * @return Boolean value: true if observer has status CANCELLED */ @VisibleForTesting protected boolean isStreamObserverCancelled(final StreamObserver<JobKillRegistrationResponse> observer) { return ((ServerCallStreamObserver<JobKillRegistrationResponse>) observer).isCancelled(); } /** * If observer is null or already cancelled - do nothing. * Otherwise call onCompleted. * * @param observer */ private void cancelObserverIfNecessary(final StreamObserver<JobKillRegistrationResponse> observer) { if (observer != null && !isStreamObserverCancelled(observer)) { try { observer.onCompleted(); } catch (final Exception observerException) { log.error("Got exception while trying to complete streamObserver during cleanup" + "for jobID {}. Exception: {}", "jobId", observerException); } } } }
2,545
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/GRpcHeartBeatServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.proto.AgentHeartBeat; import com.netflix.genie.proto.HeartBeatServiceGrpc; import com.netflix.genie.proto.ServerHeartBeat; import com.netflix.genie.web.agent.services.AgentConnectionTrackingService; import com.netflix.genie.web.agent.services.AgentRoutingService; import com.netflix.genie.web.properties.HeartBeatProperties; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.scheduling.TaskScheduler; import javax.annotation.PreDestroy; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ScheduledFuture; /** * An edge gRPC service that uses bi-directional streaming. * This is useful to reliably track which connection is handled by which server and to detect disconnections on both * ends. * * @author mprimi * @since 4.0.0 */ @Slf4j public class GRpcHeartBeatServiceImpl extends HeartBeatServiceGrpc.HeartBeatServiceImplBase { private static final String HEARTBEATING_GAUGE_NAME = "genie.agents.heartbeating.gauge"; private final AgentConnectionTrackingService agentConnectionTrackingService; private final HeartBeatProperties properties; private final Map<String, AgentStreamRecord> activeStreamsMap = Maps.newHashMap(); private final ScheduledFuture<?> sendHeartbeatsFuture; private final MeterRegistry registry; /** * Constructor. * * @param agentConnectionTrackingService The {@link AgentRoutingService} implementation to use * @param properties The service properties * @param taskScheduler The {@link TaskScheduler} instance to use * @param registry The meter registry */ public GRpcHeartBeatServiceImpl( final AgentConnectionTrackingService agentConnectionTrackingService, final HeartBeatProperties properties, final TaskScheduler taskScheduler, final MeterRegistry registry ) { this.agentConnectionTrackingService = agentConnectionTrackingService; this.properties = properties; this.sendHeartbeatsFuture = taskScheduler.scheduleWithFixedDelay( this::sendHeartbeats, this.properties.getSendInterval() ); this.registry = registry; this.registry.gaugeMapSize(HEARTBEATING_GAUGE_NAME, Sets.newHashSet(), activeStreamsMap); } /** * Shutdown this service. */ @PreDestroy public synchronized void shutdown() { if (sendHeartbeatsFuture != null) { sendHeartbeatsFuture.cancel(false); } synchronized (activeStreamsMap) { for (final Map.Entry<String, AgentStreamRecord> agentStreamRecordEntry : activeStreamsMap.entrySet()) { final String streamId = agentStreamRecordEntry.getKey(); final AgentStreamRecord agentStreamRecord = agentStreamRecordEntry.getValue(); if (agentStreamRecord.hasJobId()) { final String jobId = agentStreamRecord.getJobId(); log.debug("Unregistering stream of job: {} (stream id: {})", jobId, streamId); this.agentConnectionTrackingService.notifyDisconnected(streamId, jobId); } } for (final AgentStreamRecord agentStreamRecord : activeStreamsMap.values()) { agentStreamRecord.responseObserver.onCompleted(); } activeStreamsMap.clear(); } } /** * Regularly scheduled to send heartbeat to the client. * Using the connection ensures server-side eventually detects a broken connection. */ private void sendHeartbeats() { final Set<String> brokenStreams = Sets.newHashSet(); synchronized (activeStreamsMap) { for (final Map.Entry<String, AgentStreamRecord> entry : this.activeStreamsMap.entrySet()) { final String streamId = entry.getKey(); final AgentStreamRecord agentStreamRecord = entry.getValue(); try { agentStreamRecord.responseObserver.onNext(ServerHeartBeat.getDefaultInstance()); } catch (StatusRuntimeException | IllegalStateException e) { log.warn("Stream {} of job {} is broken", streamId, agentStreamRecord.getJobId()); log.debug("Error probing job {} stream {}", agentStreamRecord.getJobId(), streamId, e); brokenStreams.add(streamId); } } } for (final String streamId : brokenStreams) { synchronized (activeStreamsMap) { final AgentStreamRecord agentStreamRecord = this.activeStreamsMap.remove(streamId); if (agentStreamRecord != null) { log.debug("Removed broken stream {} of job {}", streamId, agentStreamRecord.getJobId()); if (agentStreamRecord.hasJobId()) { this.agentConnectionTrackingService.notifyDisconnected(streamId, agentStreamRecord.getJobId()); } } } } } /** * {@inheritDoc} */ @Override public StreamObserver<AgentHeartBeat> heartbeat( final StreamObserver<ServerHeartBeat> responseObserver ) { // Handle new stream / client connection final String streamId = UUID.randomUUID().toString(); final RequestObserver requestObserver = new RequestObserver(this, streamId); synchronized (activeStreamsMap) { // Create a record for this connection activeStreamsMap.put(streamId, new AgentStreamRecord(responseObserver)); } return requestObserver; } private void handleAgentHeartBeat( final String streamId, final AgentHeartBeat agentHeartBeat ) { // Pull the record, if one exists final AgentStreamRecord agentStreamRecord; synchronized (activeStreamsMap) { agentStreamRecord = activeStreamsMap.get(streamId); } final String claimedJobId = agentHeartBeat.getClaimedJobId(); if (agentStreamRecord == null) { log.warn("Received heartbeat from an unknown stream"); } else if (StringUtils.isBlank(claimedJobId)) { log.warn("Ignoring heartbeat lacking job id"); } else { log.debug("Received heartbeat from job: {} (stream id: {})", claimedJobId, streamId); final boolean isFirstHeartBeat = agentStreamRecord.updateRecord(claimedJobId); if (isFirstHeartBeat) { log.info("Received first heartbeat from job: {}", claimedJobId); } this.agentConnectionTrackingService.notifyHeartbeat(streamId, claimedJobId); } } private void handleStreamCompletion(final String streamId) { // Pull the record, if one exists final AgentStreamRecord agentStreamRecord; synchronized (activeStreamsMap) { agentStreamRecord = activeStreamsMap.remove(streamId); } if (agentStreamRecord == null) { log.warn("Received completion from an unknown stream"); } else { log.debug("Received completion from stream {}", streamId); if (agentStreamRecord.hasJobId()) { this.agentConnectionTrackingService.notifyDisconnected(streamId, agentStreamRecord.getJobId()); } agentStreamRecord.responseObserver.onCompleted(); } } private void handleStreamError(final String streamId, final Throwable t) { // Pull the record, if one exists final AgentStreamRecord agentStreamRecord; synchronized (activeStreamsMap) { agentStreamRecord = activeStreamsMap.remove(streamId); } if (agentStreamRecord == null) { log.warn("Received error from an unknown stream"); } else { log.debug("Received error from stream {}", streamId); if (agentStreamRecord.hasJobId()) { this.agentConnectionTrackingService.notifyDisconnected(streamId, agentStreamRecord.getJobId()); } } } private static class AgentStreamRecord { private final StreamObserver<ServerHeartBeat> responseObserver; private String claimedJobId; AgentStreamRecord( final StreamObserver<ServerHeartBeat> responseObserver ) { this.responseObserver = responseObserver; } synchronized boolean updateRecord(final String jobId) { if (hasJobId() || StringUtils.isBlank(jobId)) { return false; } else { this.claimedJobId = jobId; return true; } } String getJobId() { return claimedJobId; } boolean hasJobId() { return !StringUtils.isBlank(claimedJobId); } } private static class RequestObserver implements StreamObserver<AgentHeartBeat> { private final GRpcHeartBeatServiceImpl grpcHeartBeatService; private final String streamId; RequestObserver( final GRpcHeartBeatServiceImpl grpcHeartBeatService, final String streamId ) { this.grpcHeartBeatService = grpcHeartBeatService; this.streamId = streamId; } @Override public void onNext(final AgentHeartBeat agentHeartBeat) { grpcHeartBeatService.handleAgentHeartBeat(streamId, agentHeartBeat); } @Override public void onError(final Throwable t) { grpcHeartBeatService.handleStreamError(streamId, t); } @Override public void onCompleted() { grpcHeartBeatService.handleStreamCompletion(streamId); } } }
2,546
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/JobServiceProtoErrorComposer.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import com.google.common.collect.ImmutableMap; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieAgentRejectedException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieApplicationNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieClusterNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieCommandNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieIdAlreadyExistsException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobAlreadyClaimedException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobResolutionRuntimeException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobSpecificationNotFoundException; import com.netflix.genie.proto.ChangeJobStatusError; import com.netflix.genie.proto.ChangeJobStatusResponse; import com.netflix.genie.proto.ClaimJobError; import com.netflix.genie.proto.ClaimJobResponse; import com.netflix.genie.proto.ConfigureResponse; import com.netflix.genie.proto.HandshakeResponse; import com.netflix.genie.proto.JobSpecificationError; import com.netflix.genie.proto.JobSpecificationResponse; import com.netflix.genie.proto.ReserveJobIdError; import com.netflix.genie.proto.ReserveJobIdResponse; import javax.validation.ConstraintViolationException; import java.util.Map; /** * Utility/helper to map exceptions into protocol responses. * * @author mprimi * @since 4.0.0 */ public class JobServiceProtoErrorComposer { private static final String NO_ERROR_MESSAGE_PROVIDED = "Unknown error"; private static final Map<Class<? extends Exception>, ReserveJobIdError.Type> RESERVE_JOB_ID_ERROR_MAP = ImmutableMap.<Class<? extends Exception>, ReserveJobIdError.Type>builder() .put(GenieConversionException.class, ReserveJobIdError.Type.INVALID_REQUEST) .put(GenieIdAlreadyExistsException.class, ReserveJobIdError.Type.ID_NOT_AVAILABLE) .build(); private static final Map<Class<? extends Exception>, JobSpecificationError.Type> JOB_SPECIFICATION_ERROR_MAP = ImmutableMap.<Class<? extends Exception>, JobSpecificationError.Type>builder() .put(GenieJobNotFoundException.class, JobSpecificationError.Type.NO_JOB_FOUND) .put(GenieClusterNotFoundException.class, JobSpecificationError.Type.NO_CLUSTER_FOUND) .put(GenieCommandNotFoundException.class, JobSpecificationError.Type.NO_COMMAND_FOUND) .put(GenieApplicationNotFoundException.class, JobSpecificationError.Type.NO_APPLICATION_FOUND) .put(GenieJobSpecificationNotFoundException.class, JobSpecificationError.Type.NO_SPECIFICATION_FOUND) .put(ConstraintViolationException.class, JobSpecificationError.Type.INVALID_REQUEST) .put(GenieJobResolutionException.class, JobSpecificationError.Type.RESOLUTION_FAILED) .put(GeniePreconditionException.class, JobSpecificationError.Type.RESOLUTION_FAILED) .put(GenieJobResolutionRuntimeException.class, JobSpecificationError.Type.RUNTIME_ERROR) .build(); private static final Map<Class<? extends Exception>, ClaimJobError.Type> CLAIM_JOB_ERROR_MAP = ImmutableMap.<Class<? extends Exception>, ClaimJobError.Type>builder() .put(GenieJobAlreadyClaimedException.class, ClaimJobError.Type.ALREADY_CLAIMED) .put(GenieJobNotFoundException.class, ClaimJobError.Type.NO_SUCH_JOB) .put(GenieInvalidStatusException.class, ClaimJobError.Type.INVALID_STATUS) .put(ConstraintViolationException.class, ClaimJobError.Type.INVALID_REQUEST) .put(IllegalArgumentException.class, ClaimJobError.Type.INVALID_REQUEST) .build(); private static final Map<Class<? extends Exception>, ChangeJobStatusError.Type> CHANGE_JOB_STATUS_ERROR_MAP = ImmutableMap.<Class<? extends Exception>, ChangeJobStatusError.Type>builder() .put(GenieJobNotFoundException.class, ChangeJobStatusError.Type.NO_SUCH_JOB) .put(GenieInvalidStatusException.class, ChangeJobStatusError.Type.INCORRECT_CURRENT_STATUS) .put(GeniePreconditionException.class, ChangeJobStatusError.Type.INVALID_REQUEST) .put(ConstraintViolationException.class, ChangeJobStatusError.Type.INVALID_REQUEST) .put(IllegalArgumentException.class, ChangeJobStatusError.Type.INVALID_REQUEST) .build(); private static final Map<Class<? extends Exception>, HandshakeResponse.Type> HANDSHAKE_ERROR_MAP = ImmutableMap.<Class<? extends Exception>, HandshakeResponse.Type>builder() .put(ConstraintViolationException.class, HandshakeResponse.Type.INVALID_REQUEST) .put(GenieAgentRejectedException.class, HandshakeResponse.Type.REJECTED) .build(); private static <T> T getErrorType( final Exception e, final Map<Class<? extends Exception>, T> typeMap, final T defaultValue ) { for (final Map.Entry<Class<? extends Exception>, T> typeMapEntry : typeMap.entrySet()) { if (typeMapEntry.getKey().isInstance(e)) { return typeMapEntry.getValue(); } } return defaultValue; } private static String getMessage(final Exception e) { return e.getClass().getCanonicalName() + ":" + (e.getMessage() == null ? NO_ERROR_MESSAGE_PROVIDED : e.getMessage()); } /** * Build a {@link ReserveJobIdResponse} out of the given {@link Exception}. * * @param e The server exception * @return The response */ ReserveJobIdResponse toProtoReserveJobIdResponse(final Exception e) { return ReserveJobIdResponse.newBuilder() .setError( ReserveJobIdError.newBuilder() .setMessage(getMessage(e)) .setType(getErrorType(e, RESERVE_JOB_ID_ERROR_MAP, ReserveJobIdError.Type.UNKNOWN)) ).build(); } /** * Build a {@link JobSpecificationResponse} out of the given {@link Exception}. * * @param e The server exception * @return The response */ JobSpecificationResponse toProtoJobSpecificationResponse(final Exception e) { // Job resolution errors are wrapped in GenieJobResolutionException so try to get the root cause final Exception cause; if (e instanceof GenieJobResolutionException && e.getCause() != null && e.getCause() instanceof Exception) { cause = (Exception) e.getCause(); } else { cause = e; } return JobSpecificationResponse .newBuilder() .setError( JobSpecificationError .newBuilder() .setMessage(getMessage(cause)) .setType(getErrorType(cause, JOB_SPECIFICATION_ERROR_MAP, JobSpecificationError.Type.UNKNOWN)) ) .build(); } /** * Build a {@link ClaimJobResponse} out of the given {@link Exception}. * * @param e The server exception * @return The response */ ClaimJobResponse toProtoClaimJobResponse(final Exception e) { return ClaimJobResponse.newBuilder() .setSuccessful(false) .setError( ClaimJobError.newBuilder() .setMessage(getMessage(e)) .setType(getErrorType(e, CLAIM_JOB_ERROR_MAP, ClaimJobError.Type.UNKNOWN)) ) .build(); } /** * Build a {@link ChangeJobStatusResponse} out of the given {@link Exception}. * * @param e The server exception * @return The response */ ChangeJobStatusResponse toProtoChangeJobStatusResponse(final Exception e) { return ChangeJobStatusResponse.newBuilder() .setSuccessful(false) .setError( ChangeJobStatusError.newBuilder() .setMessage(getMessage(e)) .setType(getErrorType(e, CHANGE_JOB_STATUS_ERROR_MAP, ChangeJobStatusError.Type.UNKNOWN)) ) .build(); } /** * Build a {@link HandshakeResponse} out of the given {@link Exception}. * * @param e The server exception * @return The response */ HandshakeResponse toProtoHandshakeResponse(final Exception e) { return HandshakeResponse.newBuilder() .setMessage(getMessage(e)) .setType(getErrorType(e, HANDSHAKE_ERROR_MAP, HandshakeResponse.Type.SERVER_ERROR)) .build(); } /** * Build a {@link ConfigureResponse} out of the given {@link Exception}. * Because the configuration is optional, send back an empty message. * * @param e The server exception * @return The response */ ConfigureResponse toProtoConfigureResponse(final Exception e) { return ConfigureResponse.newBuilder() .build(); } }
2,547
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/v4/endpoints/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 V4 gRPC service interfaces. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.apis.rpc.v4.endpoints; import javax.annotation.ParametersAreNonnullByDefault;
2,548
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/servers/GRpcServerManager.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.servers; import io.grpc.Server; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.TimeUnit; /** * A wrapper around a {@link Server} instance which implements {@link AutoCloseable} to control startup and shutdown * along with the application. * * @author tgianos * @since 4.0.0 */ @Slf4j public class GRpcServerManager implements AutoCloseable { private final Server server; /** * Constructor. * * @param server The {@link Server} instance to manage * @throws IllegalStateException If the server can't be started */ public GRpcServerManager(final Server server) throws IllegalStateException { this.server = server; GRpcServerUtils.startServer(this.server); } /** * {@inheritDoc} */ @Override public void close() { if (!this.server.isShutdown()) { this.server.shutdownNow(); } try { if (this.server.awaitTermination(30L, TimeUnit.SECONDS)) { log.info("Successfully shut down the gRPC server"); } else { log.error("Unable to successfully shutdown the gRPC server in time allotted"); } } catch (final InterruptedException ie) { log.error("Unable to shutdown gRPC server due to being interrupted", ie); } } /** * Get the port the gRPC {@link Server} is listening on. * * @return The port or -1 if the server isn't currently listening on any port. */ public int getServerPort() { // Note: Since you can't construct one of these managers without it starting the server the // IllegalStateException defined in getPort() of the server shouldn't be possible here so it's not // documented as being thrown return this.server.getPort(); } }
2,549
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/servers/GRpcServerUtils.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.apis.rpc.servers; import io.grpc.Server; import lombok.extern.slf4j.Slf4j; import java.io.IOException; /** * Utilities for working with a gRPC {@link Server} instance. * * @author tgianos * @since 4.0.0 */ @Slf4j @SuppressWarnings("FinalClass") public class GRpcServerUtils { /** * Utility class. */ private GRpcServerUtils() { } /** * Attempt to start a gRpc server on this node. * * @param server The server to start * @return The port the server is running on. * @throws IllegalStateException If we're unable to start the server */ public static int startServer(final Server server) throws IllegalStateException { try { server.start(); final int port = server.getPort(); log.info("Successfully started gRPC server on port {}", port); return port; } catch (final IllegalStateException ise) { final int port = server.getPort(); log.info("Server already started on port {}", port); return port; } catch (final IOException ioe) { throw new IllegalStateException("Unable to start gRPC server on port " + server.getPort(), ioe); } } }
2,550
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/apis/rpc/servers/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implementations and helper classes for creating and managing a gRPC server. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.apis.rpc.servers; import javax.annotation.ParametersAreNonnullByDefault;
2,551
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/resources/AgentFileProtocolResolverRegistrar.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.resources; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; /** * Registers AgentFileProtocolResolver in the application context. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentFileProtocolResolverRegistrar implements ApplicationContextAware { private final AgentFileProtocolResolver agentFileProtocolResolver; /** * Constructor. * * @param agentFileProtocolResolver the resolver to register */ public AgentFileProtocolResolverRegistrar(final AgentFileProtocolResolver agentFileProtocolResolver) { this.agentFileProtocolResolver = agentFileProtocolResolver; } /** * {@inheritDoc} */ @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof ConfigurableApplicationContext) { final ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext; log.info( "Adding instance of {} to the set of protocol resolvers", this.agentFileProtocolResolver.getClass().getCanonicalName() ); configurableApplicationContext.addProtocolResolver(this.agentFileProtocolResolver); } else { throw new BeanNotOfRequiredTypeException( "applicationContext", ConfigurableApplicationContext.class, ApplicationContext.class ); } } }
2,552
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/resources/AgentFileProtocolResolver.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.resources; import com.netflix.genie.web.agent.services.AgentFileStreamService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.apache.http.client.utils.URIBuilder; import org.springframework.core.io.ProtocolResolver; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpRange; import javax.annotation.Nullable; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /** * Resource resolver for files local to an agent running a job that can be streamed to the server and served via API. * The URI for such resources is: {@literal agent://<jobId>/<relativePath>}. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentFileProtocolResolver implements ProtocolResolver { private static final String URI_SCHEME = "agent"; private static final Path ROOT_PATH = Paths.get(".").toAbsolutePath().getRoot(); private final AgentFileStreamService agentFileStreamService; /** * Constructor. * * @param agentFileStreamService the agent file stream service */ public AgentFileProtocolResolver( final AgentFileStreamService agentFileStreamService ) { this.agentFileStreamService = agentFileStreamService; } /** * Create a URI for the given remote agent file. * * @param jobId the job id * @param path the path of the file within the job directory * @param rangeHeader the request range header (as per RFC 7233) * @return a {@link URI} representing the remote agent file * @throws URISyntaxException if constructing the URI fails */ public static URI createUri( final String jobId, final String path, @Nullable final String rangeHeader ) throws URISyntaxException { final String encodedJobId = Base64.encodeBase64URLSafeString(jobId.getBytes(Charset.defaultCharset())); return new URIBuilder() .setScheme(URI_SCHEME) .setHost(encodedJobId) .setPath(path) .setFragment(rangeHeader) .build(); } private static String getAgentResourceURIFileJobId(final URI agentUri) { if (!URI_SCHEME.equals(agentUri.getScheme())) { throw new IllegalArgumentException("Not a valid Agent resource URI: " + agentUri); } return new String(Base64.decodeBase64(agentUri.getHost()), Charset.defaultCharset()); } private static String getAgentResourceURIFilePath(final URI agentUri) { if (!URI_SCHEME.equals(agentUri.getScheme())) { throw new IllegalArgumentException("Not a valid Agent resource URI: " + agentUri); } return agentUri.getPath(); } /** * {@inheritDoc} */ @Override public Resource resolve(final String location, final ResourceLoader resourceLoader) { log.debug("Attempting to resolve if {} is an Agent file resource or not", location); final URI uri; final String jobId; final Path relativePath; try { uri = URI.create(location); jobId = getAgentResourceURIFileJobId(uri); relativePath = ROOT_PATH.relativize(Paths.get(getAgentResourceURIFilePath(uri))).normalize(); } catch (final IllegalArgumentException | NullPointerException e) { log.debug("{} is not a valid Agent resource (Error message: {}).", location, e.getMessage()); return null; } final String rangeHeader = uri.getFragment(); final List<HttpRange> ranges; try { ranges = HttpRange.parseRanges(rangeHeader); } catch (final IllegalArgumentException | NullPointerException e) { log.warn("Invalid range header '{}' (Error message: {}).", rangeHeader, e.getMessage()); return null; } if (ranges.size() > 1) { log.warn("Multiple HTTP ranges not supported"); return null; } final HttpRange rangeOrNull = ranges.isEmpty() ? null : ranges.get(0); final AgentFileStreamService.AgentFileResource resourceOrNull = agentFileStreamService.getResource(jobId, relativePath, uri, rangeOrNull).orElse(null); if (resourceOrNull != null) { log.debug("Returning resource: {}", resourceOrNull.getDescription()); } return resourceOrNull; } }
2,553
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/resources/AgentFileResourceImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.resources; import com.netflix.genie.web.agent.services.AgentFileStreamService; import org.springframework.core.io.Resource; import javax.annotation.Nullable; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.time.Instant; /** * Implementation of {@link Resource} for files local to an agent running a job that can be * requested and streamed to the server (so they can be served via API). * * @author mprimi * @since 4.0.0 */ public final class AgentFileResourceImpl implements AgentFileStreamService.AgentFileResource { private final boolean exists; private final URI uri; private final long contentLength; private final long lastModified; private final String filename; private final String description; private final InputStream inputStream; private AgentFileResourceImpl( final boolean exists, @Nullable final URI uri, final long contentLength, final long lastModified, @Nullable final String filename, final String description, @Nullable final InputStream inputStream ) { this.exists = exists; this.uri = uri; this.contentLength = contentLength; this.lastModified = lastModified; this.filename = filename; this.description = description; this.inputStream = inputStream; } /** * Factory method to create a placeholder resource for a remote file that does not exist. * * @return a {@link AgentFileStreamService.AgentFileResource} */ public static AgentFileResourceImpl forNonExistingResource() { final String description = AgentFileResourceImpl.class.getSimpleName() + " [ non-existent ]"; return new AgentFileResourceImpl( false, null, -1, -1, null, description, null ); } /** * Factory method to create a resource for a remote file. * * @param uri the resource URI * @param size the size of the file, as per latest manifest * @param lastModifiedTime the last modification time, as per latest manifest * @param relativePath the path of the file relative to the root of the job directory * @param jobId the id of the job this file belongs to * @param inputStream the input stream to read this file content * @return a {@link AgentFileStreamService.AgentFileResource} */ public static AgentFileStreamService.AgentFileResource forAgentFile( final URI uri, final long size, final Instant lastModifiedTime, final Path relativePath, final String jobId, final InputStream inputStream ) { final String description = AgentFileResourceImpl.class.getSimpleName() + " [" + " jobId:" + jobId + ", " + " relativePath: " + relativePath + " ]"; final Path filenamePath = relativePath.getFileName(); if (filenamePath == null) { throw new IllegalArgumentException("Invalid relative path, not a file"); } return new AgentFileResourceImpl( true, uri, size, lastModifiedTime.toEpochMilli(), filenamePath.toString(), description, inputStream ); } /** * {@inheritDoc} */ @Override public boolean exists() { return this.exists; } /** * {@inheritDoc} */ @Override public boolean isOpen() { return true; } /** * {@inheritDoc} */ @Override public URL getURL() throws IOException { //TODO: Doable, could resolve to API URL. Unclear what value this would add. throw new IOException("Cannot resolve to a URL"); } /** * {@inheritDoc} */ @Override public URI getURI() throws IOException { if (!this.exists()) { throw new IOException("Cannot determine URI of non-existent resource"); } return this.uri; } /** * {@inheritDoc} */ @Override public File getFile() throws IOException { throw new FileNotFoundException("Resource is not a local file"); } /** * {@inheritDoc} */ @Override public long contentLength() throws IOException { if (!this.exists()) { throw new IOException("Cannot determine size of non-existent resource"); } return this.contentLength; } /** * {@inheritDoc} */ @Override public long lastModified() throws IOException { if (!this.exists()) { throw new IOException("Cannot determine modification time of non-existent resource"); } return this.lastModified; } /** * {@inheritDoc} */ @Override public Resource createRelative(final String relativePath) throws IOException { //TODO: Doable if a reference to AgentFileStreamService is kept. Unclear what value this would add. throw new IOException("Cannot create resource from relative path"); } /** * {@inheritDoc} */ @Override public String getFilename() { if (!this.exists()) { return null; } return this.filename; } /** * {@inheritDoc} */ @Override public String getDescription() { return this.description; } /** * {@inheritDoc} */ @Override public InputStream getInputStream() throws IOException { if (!this.exists()) { throw new FileNotFoundException("Resource does not exist"); } return this.inputStream; } }
2,554
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/resources/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Spring {@link org.springframework.core.io.Resource} abstraction applied to file streamed during a running agent job. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.resources; import javax.annotation.ParametersAreNonnullByDefault;
2,555
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/AgentLauncher.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.launchers; import com.fasterxml.jackson.databind.JsonNode; import com.netflix.genie.web.dtos.ResolvedJob; import com.netflix.genie.web.exceptions.checked.AgentLaunchException; import org.springframework.boot.actuate.health.HealthIndicator; import javax.annotation.Nullable; import java.util.Optional; /** * A interface which implementations will launch instances of an agent in some manner in order to run a job. * * @author tgianos * @since 4.0.0 */ public interface AgentLauncher extends HealthIndicator { /** * Shared name of a timer that can be used by launchers to record how long it took them to perform their * respective launch. */ String LAUNCH_TIMER = "genie.agents.launchers.launch.timer"; /** * Shared key for a tag that can be added to the timer metric to add the implementation class in order to aid in * adding a convenient dimension. * * @see #LAUNCH_TIMER */ String LAUNCHER_CLASS_KEY = "launcherClass"; /** * Shared key representing the class that key for the Launcher Ext context the API can return. */ String LAUNCHER_CLASS_EXT_FIELD = "launcherClass"; /** * Shared key representing the hostname of the Genie server the Agent Launcher was executed on. */ String SOURCE_HOST_EXT_FIELD = "sourceHostname"; /** * Launch an agent to execute the given {@link ResolvedJob} information. * * @param resolvedJob The {@link ResolvedJob} information for the agent to act on * @param requestedLauncherExt The launcher requested extension, or null * @return an optional {@link JsonNode} with the launcher context about the launched job * @throws AgentLaunchException For any error launching an Agent instance to run the job */ Optional<JsonNode> launchAgent( ResolvedJob resolvedJob, @Nullable JsonNode requestedLauncherExt ) throws AgentLaunchException; }
2,556
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Interfaces and utilities which are used to launch instances of the Genie Agent somewhere to service a job. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.launchers; import javax.annotation.ParametersAreNonnullByDefault;
2,557
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/impl/TitusAgentLauncherImpl.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.launchers.impl; import brave.Span; import brave.Tracer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.github.benmanes.caffeine.cache.Cache; import com.google.common.base.Strings; import com.netflix.genie.common.internal.dtos.ComputeResources; import com.netflix.genie.common.internal.dtos.Image; import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents; import com.netflix.genie.common.internal.util.GenieHostInfo; import com.netflix.genie.web.agent.launchers.AgentLauncher; import com.netflix.genie.web.agent.launchers.dtos.TitusBatchJobRequest; import com.netflix.genie.web.agent.launchers.dtos.TitusBatchJobResponse; import com.netflix.genie.web.dtos.ResolvedJob; import com.netflix.genie.web.exceptions.checked.AgentLaunchException; import com.netflix.genie.web.properties.TitusAgentLauncherProperties; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.classify.Classifier; import org.springframework.core.convert.ConversionService; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryPolicy; import org.springframework.retry.policy.ExceptionClassifierRetryPolicy; import org.springframework.retry.policy.NeverRetryPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.unit.DataSize; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; import javax.annotation.Nullable; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Agent launcher that spawns a job in a dedicated container through Titus. * * @author mprimi * @see <a href="https://netflix.github.io/titus/">Titus OSS Project</a> * @since 4.0.0 */ public class TitusAgentLauncherImpl implements AgentLauncher { static final int MEGABYTE_TO_MEGABIT = 8; private static final String GENIE_USER_ATTR = "genie.user"; private static final String GENIE_SOURCE_HOST_ATTR = "genie.sourceHost"; private static final String GENIE_ENDPOINT_ATTR = "genie.endpoint"; private static final String GENIE_JOB_ID_ATTR = "genie.jobId"; private static final String TITUS_API_JOB_PATH = "/api/v3/jobs"; private static final String TITUS_JOB_ID_EXT_FIELD = "titusId"; private static final String TITUS_JOB_REQUEST_EXT_FIELD = "titusRequest"; private static final String TITUS_JOB_RESPONSE_EXT_FIELD = "titusResponse"; private static final String THIS_CLASS = TitusAgentLauncherImpl.class.getCanonicalName(); private static final Tag CLASS_TAG = Tag.of(LAUNCHER_CLASS_KEY, THIS_CLASS); private static final int TITUS_JOB_BATCH_SIZE = 1; private static final int DEFAULT_JOB_CPU = 1; private static final int DEFAULT_JOB_GPU = 0; private static final long DEFAULT_JOB_MEMORY = 1_536L; private static final long DEFAULT_JOB_DISK = 10_000L; private static final long DEFAULT_JOB_NETWORK = 16_000L; private static final BiFunction<List<String>, Map<String, String>, List<String>> REPLACE_PLACEHOLDERS = (template, placeholders) -> template .stream() .map(s -> placeholders.getOrDefault(s, s)) .collect(Collectors.toList()); private static final Logger LOG = LoggerFactory.getLogger(TitusAgentLauncherImpl.class); // For Titus network mode details, see // https://github.com/Netflix/titus-api-definitions/blob/master/doc/titus-v3-spec.md#networkconfigurationnetworkmode private static final String TITUS_NETWORK_MODE_IPV4 = "Ipv4Only"; private static final String TITUS_NETWORK_MODE_DUAL_STACK = "Ipv6AndIpv4"; private static final String TITUS_NETWORK_MODE_DUAL_STACK_FALLBACK = "Ipv6AndIpv4Fallback"; private static final String TITUS_NETWORK_MODE_IPV6 = "Ipv6Only"; private static final String TITUS_NETWORK_MODE_HIGH_SCALE = "HighScale"; private final RestTemplate restTemplate; private final RetryTemplate retryTemplate; private final Cache<String, String> healthIndicatorCache; private final GenieHostInfo genieHostInfo; private final TitusAgentLauncherProperties titusAgentLauncherProperties; private final Environment environment; private final TitusJobRequestAdapter jobRequestAdapter; private final boolean hasDataSizeConverters; private final Binder binder; private final MeterRegistry registry; private final Tracer tracer; private final BraveTracePropagator tracePropagator; /** * Constructor. * * @param restTemplate the rest template * @param retryTemplate The {@link RetryTemplate} to use when making Titus API calls * @param jobRequestAdapter The implementation of {@link TitusJobRequestAdapter} to use * @param healthIndicatorCache a cache to store metadata about recently launched jobs * @param genieHostInfo the metadata about the local server and host * @param titusAgentLauncherProperties the configuration properties * @param tracingComponents The {@link BraveTracingComponents} instance to use for distributed tracing * @param environment The application environment to pull dynamic properties from * @param registry the metric registry */ public TitusAgentLauncherImpl( final RestTemplate restTemplate, final RetryTemplate retryTemplate, final TitusJobRequestAdapter jobRequestAdapter, final Cache<String, String> healthIndicatorCache, final GenieHostInfo genieHostInfo, final TitusAgentLauncherProperties titusAgentLauncherProperties, final BraveTracingComponents tracingComponents, final Environment environment, final MeterRegistry registry ) { this.restTemplate = restTemplate; this.retryTemplate = retryTemplate; this.healthIndicatorCache = healthIndicatorCache; this.genieHostInfo = genieHostInfo; this.titusAgentLauncherProperties = titusAgentLauncherProperties; this.jobRequestAdapter = jobRequestAdapter; this.tracer = tracingComponents.getTracer(); this.tracePropagator = tracingComponents.getTracePropagator(); this.environment = environment; if (this.environment instanceof ConfigurableEnvironment) { final ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) this.environment; final ConversionService conversionService = configurableEnvironment.getConversionService(); this.hasDataSizeConverters = conversionService.canConvert(String.class, DataSize.class) && conversionService.canConvert(Integer.class, DataSize.class); } else { this.hasDataSizeConverters = false; } this.binder = Binder.get(this.environment); this.registry = registry; } /** * {@inheritDoc} */ @Override public Optional<JsonNode> launchAgent( final ResolvedJob resolvedJob, @Nullable final JsonNode requestedLauncherExt ) throws AgentLaunchException { final long start = System.nanoTime(); LOG.info("Received request to launch Titus agent to run job: {}", resolvedJob); final Set<Tag> tags = new HashSet<>(); tags.add(CLASS_TAG); final String jobId = resolvedJob.getJobSpecification().getJob().getId(); String titusJobId = null; try { final TitusBatchJobRequest titusJobRequest = this.createJobRequest(resolvedJob); final TitusBatchJobResponse titusResponse = this.retryTemplate.execute( (RetryCallback<TitusBatchJobResponse, Throwable>) context -> restTemplate.postForObject( titusAgentLauncherProperties.getEndpoint().toString() + TITUS_API_JOB_PATH, titusJobRequest, TitusBatchJobResponse.class ) ); if (titusResponse == null) { throw new AgentLaunchException("Failed to request creation of Titus job for job " + jobId); } titusJobId = titusResponse.getId().orElseThrow( () -> new AgentLaunchException( "Failed to create titus job for job " + jobId + " - Titus Status Code:" + titusResponse.getStatusCode().orElse(null) + ", Titus response message:" + titusResponse.getMessage().orElse("") ) ); LOG.info("Created Titus job {} to execute Genie job {}", titusJobId, jobId); MetricsUtils.addSuccessTags(tags); return Optional.of( JsonNodeFactory.instance.objectNode() .put(LAUNCHER_CLASS_EXT_FIELD, THIS_CLASS) .put(SOURCE_HOST_EXT_FIELD, this.genieHostInfo.getHostname()) .put(TITUS_JOB_ID_EXT_FIELD, titusJobId) .putPOJO(TITUS_JOB_REQUEST_EXT_FIELD, titusJobRequest) .putPOJO(TITUS_JOB_RESPONSE_EXT_FIELD, titusResponse) ); } catch (Throwable t) { LOG.error("Failed to launch job on Titus", t); MetricsUtils.addFailureTagsWithException(tags, t); throw new AgentLaunchException("Failed to create titus job for job " + jobId, t); } finally { this.registry.timer(LAUNCH_TIMER, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); this.healthIndicatorCache.put(jobId, StringUtils.isBlank(titusJobId) ? "-" : titusJobId); } } /** * {@inheritDoc} */ @Override public Health health() { return Health.up() .withDetails(this.healthIndicatorCache.asMap()) .build(); } private TitusBatchJobRequest createJobRequest(final ResolvedJob resolvedJob) throws AgentLaunchException { final String jobId = resolvedJob.getJobSpecification().getJob().getId(); // Map placeholders in entry point template to their values final Map<String, String> placeholdersMap = Map.of( TitusAgentLauncherProperties.JOB_ID_PLACEHOLDER, jobId, TitusAgentLauncherProperties.SERVER_HOST_PLACEHOLDER, this.titusAgentLauncherProperties.getGenieServerHost(), TitusAgentLauncherProperties.SERVER_PORT_PLACEHOLDER, String.valueOf(this.titusAgentLauncherProperties.getGenieServerPort()) ); // Substitute all placeholders with their values for the container entry point and command final List<String> entryPoint = REPLACE_PLACEHOLDERS.apply( this.titusAgentLauncherProperties.getEntryPointTemplate(), placeholdersMap ); final List<String> command = REPLACE_PLACEHOLDERS.apply( this.titusAgentLauncherProperties.getCommandTemplate(), placeholdersMap ); final Duration runtimeLimit = this.titusAgentLauncherProperties.getRuntimeLimit(); final Map<String, String> jobAttributes = this.createJobAttributes(jobId, resolvedJob); final TitusBatchJobRequest.TitusBatchJobRequestBuilder requestBuilder = TitusBatchJobRequest.builder() .owner( TitusBatchJobRequest.Owner .builder() .teamEmail(this.titusAgentLauncherProperties.getOwnerEmail()) .build() ) .applicationName(this.titusAgentLauncherProperties.getApplicationName()) .capacityGroup( this.environment.getProperty( TitusAgentLauncherProperties.CAPACITY_GROUP_PROPERTY, String.class, this.titusAgentLauncherProperties.getCapacityGroup() ) ) .attributes(jobAttributes) .container( TitusBatchJobRequest.Container .builder() .resources(this.getTitusResources(resolvedJob)) .securityProfile( TitusBatchJobRequest.SecurityProfile.builder() .attributes(new HashMap<>(this.titusAgentLauncherProperties.getSecurityAttributes())) .securityGroups(new ArrayList<>(this.titusAgentLauncherProperties.getSecurityGroups())) .iamRole(this.titusAgentLauncherProperties.getIAmRole()) .build() ) .image(this.getTitusImage(resolvedJob)) .entryPoint(entryPoint) .command(command) .env(this.createJobEnvironment()) .attributes( this.binder .bind( TitusAgentLauncherProperties.CONTAINER_ATTRIBUTES_PROPERTY, Bindable.mapOf(String.class, String.class) ) .orElse(new HashMap<>()) ) .build() ) .batch( TitusBatchJobRequest.Batch.builder() .size(TITUS_JOB_BATCH_SIZE) .retryPolicy( TitusBatchJobRequest.RetryPolicy.builder() .immediate( TitusBatchJobRequest.Immediate .builder() .retries( this.environment.getProperty( TitusAgentLauncherProperties.RETRIES_PROPERTY, Integer.class, this.titusAgentLauncherProperties.getRetries() ) ) .build() ) .build() ) .runtimeLimitSec(runtimeLimit.getSeconds()) .build() ) .disruptionBudget( TitusBatchJobRequest.DisruptionBudget.builder() .selfManaged( TitusBatchJobRequest.SelfManaged.builder() .relocationTimeMs(runtimeLimit.toMillis()) .build() ) .build() ) .jobGroupInfo( TitusBatchJobRequest.JobGroupInfo.builder() .stack(this.titusAgentLauncherProperties.getStack()) .detail(this.titusAgentLauncherProperties.getDetail()) .sequence(this.titusAgentLauncherProperties.getSequence()) .build() ); final Optional<String> networkConfiguration = validateNetworkConfiguration(this.environment.getProperty( TitusAgentLauncherProperties.CONTAINER_NETWORK_MODE, String.class)); networkConfiguration.ifPresent(config -> requestBuilder.networkConfiguration( TitusBatchJobRequest.NetworkConfiguration.builder().networkMode(config).build())); final TitusBatchJobRequest request = requestBuilder.build(); // Run the request through the security adapter to add any necessary context this.jobRequestAdapter.modifyJobRequest(request, resolvedJob); return request; } private Optional<String> validateNetworkConfiguration(@Nullable final String networkConfig) { if (Strings.isNullOrEmpty(networkConfig)) { return Optional.empty(); } switch (networkConfig) { case TITUS_NETWORK_MODE_IPV4: case TITUS_NETWORK_MODE_DUAL_STACK: case TITUS_NETWORK_MODE_DUAL_STACK_FALLBACK: case TITUS_NETWORK_MODE_IPV6: case TITUS_NETWORK_MODE_HIGH_SCALE: return Optional.of(networkConfig); default: return Optional.empty(); } } /** * Helper method to avoid runtime errors if for some reason the DataSize converters aren't loaded. * * @param propertyKey The key to get from the environment * @param defaultValue The default value to apply * @return The resolved value */ private DataSize getDataSizeProperty(final String propertyKey, final DataSize defaultValue) { if (this.hasDataSizeConverters) { return this.environment.getProperty(propertyKey, DataSize.class, defaultValue); } else { final String propValue = this.environment.getProperty(propertyKey); if (propValue != null) { try { return DataSize.parse(propValue); } catch (final IllegalArgumentException e) { LOG.error( "Unable to parse value of {} as DataSize. Falling back to default value {}", propertyKey, defaultValue, e ); } } return defaultValue; } } private Map<String, String> createJobAttributes(final String jobId, final ResolvedJob resolvedJob) { final Map<String, String> jobAttributes = new HashMap<>(); jobAttributes.put(GENIE_USER_ATTR, resolvedJob.getJobMetadata().getUser()); jobAttributes.put(GENIE_SOURCE_HOST_ATTR, this.genieHostInfo.getHostname()); jobAttributes.put(GENIE_ENDPOINT_ATTR, this.titusAgentLauncherProperties.getGenieServerHost()); jobAttributes.put(GENIE_JOB_ID_ATTR, jobId); jobAttributes.putAll( this.binder .bind( TitusAgentLauncherProperties.ADDITIONAL_JOB_ATTRIBUTES_PROPERTY, Bindable.mapOf(String.class, String.class) ) .orElse(new HashMap<>()) ); return jobAttributes; } private Map<String, String> createJobEnvironment() { final Map<String, String> jobEnvironment = this.binder .bind( TitusAgentLauncherProperties.ADDITIONAL_ENVIRONMENT_PROPERTY, Bindable.mapOf(String.class, String.class) ) .orElse(new HashMap<>()); final Span currentSpan = this.tracer.currentSpan(); if (currentSpan != null) { jobEnvironment.putAll(this.tracePropagator.injectForAgent(currentSpan.context())); } return jobEnvironment; } private TitusBatchJobRequest.Resources getTitusResources(final ResolvedJob resolvedJob) { // TODO: Address defaults? final ComputeResources computeResources = resolvedJob.getJobEnvironment().getComputeResources(); final int cpu = Math.max( this.environment.getProperty( TitusAgentLauncherProperties.MINIMUM_CPU_PROPERTY, Integer.class, this.titusAgentLauncherProperties.getMinimumCPU() ), computeResources.getCpu().orElse(DEFAULT_JOB_CPU) + this.environment.getProperty( TitusAgentLauncherProperties.ADDITIONAL_CPU_PROPERTY, Integer.class, this.titusAgentLauncherProperties.getAdditionalCPU() ) ); final int gpus = Math.max( this.environment.getProperty( TitusAgentLauncherProperties.MINIMUM_GPU_PROPERTY, Integer.class, this.titusAgentLauncherProperties.getMinimumGPU() ), computeResources.getGpu().orElse(DEFAULT_JOB_GPU) + this.environment.getProperty( TitusAgentLauncherProperties.ADDITIONAL_GPU_PROPERTY, Integer.class, this.titusAgentLauncherProperties.getAdditionalGPU() ) ); final long memory = Math.max( this.getDataSizeProperty( TitusAgentLauncherProperties.MINIMUM_MEMORY_PROPERTY, this.titusAgentLauncherProperties.getMinimumMemory() ).toMegabytes(), computeResources.getMemoryMb().orElse(DEFAULT_JOB_MEMORY) + this.getDataSizeProperty( TitusAgentLauncherProperties.ADDITIONAL_MEMORY_PROPERTY, this.titusAgentLauncherProperties.getAdditionalMemory() ).toMegabytes() ); final long diskSize = Math.max( this.getDataSizeProperty( TitusAgentLauncherProperties.MINIMUM_DISK_SIZE_PROPERTY, this.titusAgentLauncherProperties.getMinimumDiskSize() ).toMegabytes(), computeResources.getDiskMb().orElse(DEFAULT_JOB_DISK) + this.getDataSizeProperty( TitusAgentLauncherProperties.ADDITIONAL_DISK_SIZE_PROPERTY, this.titusAgentLauncherProperties.getAdditionalDiskSize() ).toMegabytes() ); final long networkMbps = Math.max( this.getDataSizeProperty( TitusAgentLauncherProperties.MINIMUM_BANDWIDTH_PROPERTY, this.titusAgentLauncherProperties.getMinimumBandwidth() ).toMegabytes() * MEGABYTE_TO_MEGABIT, computeResources.getNetworkMbps().orElse(DEFAULT_JOB_NETWORK) + this.getDataSizeProperty( TitusAgentLauncherProperties.ADDITIONAL_BANDWIDTH_PROPERTY, this.titusAgentLauncherProperties.getAdditionalBandwidth() ).toMegabytes() * MEGABYTE_TO_MEGABIT ); return TitusBatchJobRequest.Resources.builder() .cpu(cpu) .gpu(gpus) .memoryMB(memory) .diskMB(diskSize) .networkMbps(networkMbps) .build(); } private TitusBatchJobRequest.Image getTitusImage(final ResolvedJob resolvedJob) { final Map<String, Image> images = resolvedJob.getJobEnvironment().getImages(); final String defaultImageName = this.environment.getProperty( TitusAgentLauncherProperties.IMAGE_NAME_PROPERTY, String.class, this.titusAgentLauncherProperties.getImageName() ); final String defaultImageTag = this.environment.getProperty( TitusAgentLauncherProperties.IMAGE_TAG_PROPERTY, String.class, this.titusAgentLauncherProperties.getImageTag() ); final Image image = images.getOrDefault( this.environment.getProperty( TitusAgentLauncherProperties.AGENT_IMAGE_KEY_PROPERTY, String.class, this.titusAgentLauncherProperties.getAgentImageKey() ), new Image.Builder() .withName(defaultImageName) .withTag(defaultImageTag) .build() ); return TitusBatchJobRequest.Image.builder() .name(image.getName().orElse(defaultImageName)) .tag(image.getTag().orElse(defaultImageTag)) .build(); } /** * An interface that should be implemented by any class which wants to modify the Titus job request before it is * sent. * <p> * NOTE: This is a very initial implementation/idea and highly subject to change as we work through additional * security concerns * * @author tgianos * @since 4.0.0 */ public interface TitusJobRequestAdapter { /** * Given the current {@link TitusBatchJobRequest} and the {@link ResolvedJob} that the agent container * is expected to execute this method should manipulate (if necessary) the {@literal request} as needed for the * given Titus installation Genie is calling. * * @param request The {@link TitusBatchJobRequest} state after everything default has been set and created * and is ready to be sent to the Titus jobs API * @param resolvedJob The Genie {@link ResolvedJob} that the Titus request is responsible for executing * @throws AgentLaunchException For any errors */ default void modifyJobRequest( TitusBatchJobRequest request, ResolvedJob resolvedJob ) throws AgentLaunchException { } } /** * A retry policy that has different behavior based on the type of exception thrown by the rest client during * calls to the Titus API. * * @author tgianos * @since 4.0.0 */ public static class TitusAPIRetryPolicy extends ExceptionClassifierRetryPolicy { private static final long serialVersionUID = -7978685711081275362L; /** * Constructor. * * @param retryCodes The {@link HttpStatus} codes which should be retried if an API call to Titus fails * @param maxAttempts The maximum number of retry attempts that should be made upon call failure */ public TitusAPIRetryPolicy(final Set<HttpStatus> retryCodes, final int maxAttempts) { final NeverRetryPolicy neverRetryPolicy = new NeverRetryPolicy(); final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(maxAttempts); this.setExceptionClassifier( (Classifier<Throwable, RetryPolicy>) classifiable -> { if (classifiable instanceof HttpStatusCodeException) { final HttpStatusCodeException httpException = (HttpStatusCodeException) classifiable; final HttpStatus status = httpException.getStatusCode(); if (retryCodes.contains(status)) { return simpleRetryPolicy; } } return neverRetryPolicy; } ); } } }
2,558
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/impl/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implmentations of interfaces which are used to launch instances of the Genie Agent somewhere to service a job. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.launchers.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,559
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/impl/LocalAgentLauncherImpl.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.launchers.impl; import brave.Span; import brave.Tracer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.dtos.JobMetadata; import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents; import com.netflix.genie.web.agent.launchers.AgentLauncher; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.JobInfoAggregate; import com.netflix.genie.web.dtos.ResolvedJob; import com.netflix.genie.web.exceptions.checked.AgentLaunchException; import com.netflix.genie.web.introspection.GenieWebHostInfo; import com.netflix.genie.web.introspection.GenieWebRpcInfo; import com.netflix.genie.web.properties.LocalAgentLauncherProperties; import com.netflix.genie.web.util.ExecutorFactory; import com.netflix.genie.web.util.MetricsUtils; import com.netflix.genie.web.util.UNIXUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecuteResultHandler; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.Executor; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.lang3.SystemUtils; import org.springframework.boot.actuate.health.Health; import javax.annotation.Nullable; import javax.validation.Valid; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Implementation of {@link AgentLauncher} which launched Agent instances on the local Genie hardware. * * @author tgianos * @since 4.0.0 */ @Slf4j public class LocalAgentLauncherImpl implements AgentLauncher { private static final String NUMBER_ACTIVE_JOBS_KEY = "numActiveJobs"; private static final String ALLOCATED_MEMORY_KEY = "allocatedMemory"; private static final String USED_MEMORY_KEY = "usedMemory"; private static final String AVAILABLE_MEMORY_KEY = "availableMemory"; private static final String AVAILABLE_MAX_JOB_CAPACITY_KEY = "availableMaxJobCapacity"; private static final Map<String, String> INFO_UNAVAILABLE_DETAILS = Map.of( "jobInfoUnavailable", "Unable to retrieve host job information. State unknown." ); private static final String RUN_USER_PLACEHOLDER = "<GENIE_USER>"; private static final String SETS_ID = "setsid"; private static final Object MEMORY_CHECK_LOCK = new Object(); private static final String THIS_CLASS = LocalAgentLauncherImpl.class.getCanonicalName(); private static final Tag CLASS_TAG = Tag.of(LAUNCHER_CLASS_KEY, THIS_CLASS); private static final long DEFAULT_JOB_MEMORY = 1_536L; private final String hostname; private final PersistenceService persistenceService; private final LocalAgentLauncherProperties launcherProperties; private final ExecutorFactory executorFactory; private final MeterRegistry registry; private final Executor sharedExecutor; private final int rpcPort; private final LoadingCache<String, JobInfoAggregate> jobInfoCache; private final JsonNode launcherExt; private final AtomicLong numActiveJobs; private final AtomicLong usedMemory; private final Tracer tracer; private final BraveTracePropagator tracePropagator; /** * Constructor. * * @param hostInfo The {@link GenieWebHostInfo} instance * @param rpcInfo The {@link GenieWebRpcInfo} instance * @param dataServices The {@link DataServices} encapsulation instance to use * @param launcherProperties The properties from the configuration that control agent behavior * @param executorFactory A {@link ExecutorFactory} to create {@link org.apache.commons.exec.Executor} * instances * @param tracingComponents The {@link BraveTracingComponents} instance to use * @param registry Metrics repository */ public LocalAgentLauncherImpl( final GenieWebHostInfo hostInfo, final GenieWebRpcInfo rpcInfo, final DataServices dataServices, final LocalAgentLauncherProperties launcherProperties, final ExecutorFactory executorFactory, final BraveTracingComponents tracingComponents, final MeterRegistry registry ) { this.hostname = hostInfo.getHostname(); this.rpcPort = rpcInfo.getRpcPort(); this.persistenceService = dataServices.getPersistenceService(); this.launcherProperties = launcherProperties; this.executorFactory = executorFactory; this.registry = registry; this.sharedExecutor = this.executorFactory.newInstance(false); this.numActiveJobs = new AtomicLong(0L); this.usedMemory = new AtomicLong(0L); this.tracer = tracingComponents.getTracer(); this.tracePropagator = tracingComponents.getTracePropagator(); final Set<Tag> tags = Sets.newHashSet( Tag.of("launcherClass", this.getClass().getSimpleName()) ); // TODO: These metrics should either be renamed or tagged so that it's easier to slice and dice them // Currently we have a single launcher but as more come this won't represent necessarily what the name // implies. Even now there are agent jobs not launched through the API which are not captured in this // metric and thus it doesn't accurately give a number of the active jobs in the system instead it gives // only active jobs running locally on a given node. I'm not renaming it now (5/28/2020) since we don't // yet have a firm plan in place for a) handling multiple launcher and b) if a leadership task should // publish the number of running jobs and other aggregate metrics from the system. Leaving these named // this way also makes it so we don't have to modify as many dashboards or auto scaling policies ATM this.registry.gauge("genie.jobs.active.gauge", tags, this.numActiveJobs); this.registry.gauge("genie.jobs.memory.used.gauge", tags, this.usedMemory); // Leverage a loading cache to handle the timed async fetching for us rather than creating a thread // on a scheduler etc. This also provides atomicity. // Note that this is not intended to be used for exact calculations and more for metrics and health checks // as the data could be somewhat stale this.jobInfoCache = Caffeine .newBuilder() // The refresh fails silently this will protect from stale data .expireAfterWrite(this.launcherProperties.getHostInfoExpireAfter()) .refreshAfterWrite(this.launcherProperties.getHostInfoRefreshAfter()) .initialCapacity(1) .build( host -> { final JobInfoAggregate info = this.persistenceService.getHostJobInformation(host); // this should always be the case but just in case if (info != null) { // Proactively update the metric reporting this.numActiveJobs.set(info.getNumberOfActiveJobs()); this.usedMemory.set(info.getTotalMemoryAllocated()); } return info; } ); this.launcherExt = JsonNodeFactory.instance.objectNode() .put(LAUNCHER_CLASS_EXT_FIELD, THIS_CLASS) .put(SOURCE_HOST_EXT_FIELD, this.hostname); // Force the initial fetch so that all subsequent fetches will be non-blocking try { this.jobInfoCache.get(this.hostname); } catch (final Exception e) { log.error("Unable to fetch initial job information", e); } } /** * {@inheritDoc} */ @Override public Optional<JsonNode> launchAgent( @Valid final ResolvedJob resolvedJob, @Nullable final JsonNode requestedLauncherExt ) throws AgentLaunchException { final long start = System.nanoTime(); log.info("Received request to launch local agent to run job: {}", resolvedJob); final Set<Tag> tags = new HashSet<>(); tags.add(CLASS_TAG); try { final JobMetadata jobMetadata = resolvedJob.getJobMetadata(); final String user = jobMetadata.getUser(); if (this.launcherProperties.isRunAsUserEnabled()) { final String group = jobMetadata.getGroup().orElse(null); try { UNIXUtils.createUser(user, group, this.sharedExecutor); } catch (IOException e) { log.error("Failed to create user {}: {}", jobMetadata.getUser(), e.getMessage(), e); throw new AgentLaunchException(e); } } // Check error conditions final long jobMemory = resolvedJob .getJobEnvironment() .getComputeResources() .getMemoryMb() .orElse(DEFAULT_JOB_MEMORY); final String jobId = resolvedJob.getJobSpecification().getJob().getId(); // Job was resolved with more memory allocated than the system was configured to allow if (jobMemory > this.launcherProperties.getMaxJobMemory()) { throw new AgentLaunchException( "Unable to launch job as the requested job memory (" + jobMemory + "MB) exceeds the maximum allowed by the configuration of the system (" + this.launcherProperties.getMaxJobMemory() + "MB)" ); } final CommandLine commandLine = this.createCommandLine( ImmutableMap.of( LocalAgentLauncherProperties.SERVER_HOST_PLACEHOLDER, this.launcherProperties.getServerHostname(), LocalAgentLauncherProperties.SERVER_PORT_PLACEHOLDER, Integer.toString(this.rpcPort), LocalAgentLauncherProperties.JOB_ID_PLACEHOLDER, jobId, RUN_USER_PLACEHOLDER, user, LocalAgentLauncherProperties.AGENT_JAR_PLACEHOLDER, this.launcherProperties.getAgentJarPath() ) ); // One at a time to ensure we don't overflow configured max synchronized (MEMORY_CHECK_LOCK) { final long usedMemoryOnHost = this.persistenceService.getUsedMemoryOnHost(this.hostname); final long expectedUsedMemoryOnHost = usedMemoryOnHost + jobMemory; if (expectedUsedMemoryOnHost > this.launcherProperties.getMaxTotalJobMemory()) { throw new AgentLaunchException( "Running job " + jobId + " with " + jobMemory + "MB of memory would cause there to be more memory used than the configured amount of " + this.launcherProperties.getMaxTotalJobMemory() + "MB. " + usedMemoryOnHost + "MB worth of jobs are currently running on this node." ); } } // Inherit server environment final Map<String, String> environment = Maps.newHashMap(System.getenv()); // Add extra environment from configuration, if any environment.putAll(this.launcherProperties.getAdditionalEnvironment()); // Add tracing context so agent continues trace final Span currentSpan = this.tracer.currentSpan(); if (currentSpan != null) { environment.putAll(this.tracePropagator.injectForAgent(currentSpan.context())); } log.debug("Launching agent: {}, env: {}", commandLine, environment); // TODO: What happens if the server crashes? Does the process live on? Make sure this is totally detached final Executor executor = this.executorFactory.newInstance(true); if (this.launcherProperties.isProcessOutputCaptureEnabled()) { final String debugOutputPath = System.getProperty(SystemUtils.JAVA_IO_TMPDIR, "/tmp") + "/agent-job-" + jobId + ".txt"; try { final FileOutputStream fileOutput = new FileOutputStream(debugOutputPath, false); executor.setStreamHandler(new PumpStreamHandler(fileOutput)); } catch (final FileNotFoundException e) { log.error("Failed to create agent process output file", e); throw new AgentLaunchException(e); } } log.info("Launching agent for job {}", jobId); final AgentResultHandler resultHandler = new AgentResultHandler(jobId); try { executor.execute(commandLine, environment, resultHandler); } catch (final IOException ioe) { throw new AgentLaunchException( "Unable to launch agent using command: " + commandLine.toString(), ioe ); } MetricsUtils.addSuccessTags(tags); return Optional.of(this.launcherExt); } catch (final AgentLaunchException e) { MetricsUtils.addFailureTagsWithException(tags, e); throw e; } catch (final Exception e) { log.error("Unable to launch local agent due to {}", e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); throw new AgentLaunchException("Unable to launch local agent due to unhandled error", e); } finally { this.registry.timer(LAUNCH_TIMER, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } /** * {@inheritDoc} */ @Override public Health health() { final JobInfoAggregate jobInfo; try { jobInfo = this.jobInfoCache.get(this.hostname); } catch (final Exception e) { log.error("Computing host info threw exception", e); // Could do unknown but if the persistence tier threw an exception we're likely down anyway return Health.down(e).build(); } // This should never happen but if it does it's likely a problem deeper in system (persistence tier) if (jobInfo == null) { log.error("Unable to retrieve host info from cache"); return Health.unknown().withDetails(INFO_UNAVAILABLE_DETAILS).build(); } // Use allocated memory to make the host go OOS early enough that we don't throw as many exceptions on // accepted jobs during launch final long memoryAllocated = jobInfo.getTotalMemoryAllocated(); final long availableMemory = this.launcherProperties.getMaxTotalJobMemory() - memoryAllocated; final long maxJobMemory = this.launcherProperties.getMaxJobMemory(); final Health.Builder builder; // If we can fit one more max job in we're still healthy if (availableMemory >= maxJobMemory) { builder = Health.up(); } else { builder = Health.down(); } return builder .withDetail(NUMBER_ACTIVE_JOBS_KEY, jobInfo.getNumberOfActiveJobs()) .withDetail(ALLOCATED_MEMORY_KEY, memoryAllocated) .withDetail(AVAILABLE_MEMORY_KEY, availableMemory) .withDetail(USED_MEMORY_KEY, jobInfo.getTotalMemoryUsed()) .withDetail( AVAILABLE_MAX_JOB_CAPACITY_KEY, (availableMemory >= 0 && maxJobMemory > 0) ? (availableMemory / maxJobMemory) : 0) .build(); } private CommandLine createCommandLine( final Map<String, String> argumentValueReplacements ) { final List<String> commandLineTemplate = Lists.newArrayList(); // Run detached with setsid on Linux if (SystemUtils.IS_OS_LINUX) { commandLineTemplate.add(SETS_ID); } // Run as different user with sudo if (this.launcherProperties.isRunAsUserEnabled()) { commandLineTemplate.addAll(Lists.newArrayList("sudo", "-E", "-u", RUN_USER_PLACEHOLDER)); } // Agent command line to launch agent (i.e. JVM and its options) commandLineTemplate.addAll(this.launcherProperties.getLaunchCommandTemplate()); final CommandLine commandLine = new CommandLine(commandLineTemplate.get(0)); for (int i = 1; i < commandLineTemplate.size(); i++) { final String argument = commandLineTemplate.get(i); // If the argument placeholder is a key in the map, replace it with the corresponding value. // Otherwise it's not a placeholder, add it as-is to the command-line. commandLine.addArgument(argumentValueReplacements.getOrDefault(argument, argument)); } return commandLine; } /** * Simple {@link org.apache.commons.exec.ExecuteResultHandler} implementation that logs completion. * * @author tgianos * @since 4.0.0 */ @Slf4j @VisibleForTesting static class AgentResultHandler extends DefaultExecuteResultHandler { private final String jobId; /** * Constructor. * * @param jobId The id of the job the agent this handler is attached to is running */ AgentResultHandler(final String jobId) { this.jobId = jobId; } /** * {@inheritDoc} */ @Override public void onProcessComplete(final int exitValue) { super.onProcessComplete(exitValue); log.info("Agent process for job {} completed with exit value {}", this.jobId, exitValue); } /** * {@inheritDoc} */ @Override public void onProcessFailed(final ExecuteException e) { super.onProcessFailed(e); log.error("Agent process failed for job {} due to {}", this.jobId, e.getMessage(), e); } } }
2,560
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/dtos/TitusBatchJobRequest.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.launchers.dtos; import lombok.Builder; import lombok.Data; import lombok.NonNull; import org.apache.logging.log4j.util.Strings; import javax.annotation.Nullable; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Map; /** * Titus job request POJO. * * @author mprimi * @since 4.0.0 */ // TODO: This class and the nested classes likely could benefit from a builder pattern but I'm just too busy to tackle // this right now so going to do some hacky things to get migration unblocked. Also it's very hardcoded to be // specifically what is needed for Titus API calls within Netflix and not perhaps Titus api calls in general. // An example of this is iAmRole is required but if the OSS Titus isn't run on AWS or that field isn't actually // required by the API what should someone put here? The API needs to be reviewed and fields that are optional // made optional and those that are required made clear they are required. Right now everything is required or // unclear. Making everything mutable for now. // - TJG 2/26/2020 @Data @Builder public class TitusBatchJobRequest { @NotNull @NonNull private Owner owner; @NotNull @NonNull private Map<String, String> attributes; @NotNull @NonNull private Container container; @NotNull @NonNull private Batch batch; @NotNull @NonNull private DisruptionBudget disruptionBudget; @NotNull @NonNull private String applicationName; @NotNull @NonNull private String capacityGroup; @NotNull @NonNull private JobGroupInfo jobGroupInfo; @Nullable private NetworkConfiguration networkConfiguration; /** * Titus job owner POJO. */ @Data @Builder public static class Owner { @NotNull @NonNull private String teamEmail; } /** * Titus job container DTO. */ @Data @Builder public static class Container { @NotNull @NotNull private Resources resources; @NotNull @NonNull private SecurityProfile securityProfile; @NotNull @NonNull private Image image; @NotNull @NonNull private List<String> entryPoint; @NotNull @NonNull private List<String> command; @NotNull @NonNull private Map<String, String> env; @NotNull @NonNull private Map<String, String> attributes; @Nullable private ContainerConstraints softConstraints; @Nullable private ContainerConstraints hardConstraints; } /** * Titus job container resources POJO. */ @Data @Builder public static class Resources { private int cpu; private int gpu; private long memoryMB; private long diskMB; private long networkMbps; } /** * Titus job security profile. */ @Data @Builder public static class SecurityProfile { @NotNull @NonNull private Map<String, String> attributes; @NotNull @NonNull private List<String> securityGroups; @NotNull @NonNull private String iamRole; } /** * Titus job container constraints. */ @Data @Builder public static class ContainerConstraints { @NotNull @NonNull private Map<String, String> constraints; @NotNull @NonNull @Builder.Default() private String expression = Strings.EMPTY; } /** * Titus job container image. */ @Data @Builder public static class Image { @NotEmpty @NonNull private String name; @NotEmpty @NonNull private String tag; } /** * Titus batch job parameters. */ @Data @Builder public static class Batch { @NotNull @NonNull private RetryPolicy retryPolicy; @Min(1) private int size; private long runtimeLimitSec; } /** * Titus job network configuration. */ @Data @Builder public static class NetworkConfiguration { private String networkMode; } /** * Titus job disruption budget. */ @Data @Builder public static class DisruptionBudget { @NotNull @NonNull private SelfManaged selfManaged; } /** * Titus job retry policy. */ @Data @Builder public static class RetryPolicy { @NotNull @NonNull private Immediate immediate; } /** * Titus job retry policy detail. */ @Data @Builder public static class Immediate { @Min(0) private int retries; } /** * Titus job disruption budget detail. */ @Data @Builder public static class SelfManaged { @Min(1) private long relocationTimeMs; } /** * Job Group information. */ @Data @Builder public static class JobGroupInfo { private String stack; private String detail; private String sequence; } }
2,561
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/dtos/TitusBatchJobResponse.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.launchers.dtos; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.Optional; /** * Titus job response POJO. * * @author mprimi * @since 4.0.0 */ public class TitusBatchJobResponse { private String id; private Integer statusCode; private String message; /** * Get the ID of the Titus job. * * @return The ID */ public Optional<String> getId() { return Optional.ofNullable(this.id); } /** * Set the id of the titus job. * * @param id The new id */ public void setId(@Nullable final String id) { this.id = StringUtils.isNotBlank(id) ? id : null; } /** * Get the status code if there was one. * * @return The status code wrapped in {@link Optional} else {@link Optional#empty()} */ public Optional<Integer> getStatusCode() { return Optional.ofNullable(this.statusCode); } /** * Set the status code. * * @param statusCode The new status code */ public void setStatusCode(@Nullable final Integer statusCode) { this.statusCode = statusCode; } /** * Get the message if there was one. * * @return The message wrapped in {@link Optional} else {@link Optional#empty()} */ public Optional<String> getMessage() { return Optional.ofNullable(this.message); } /** * Set the message if there was one. * * @param message The new message */ public void setMessage(@Nullable final String message) { this.message = message; } }
2,562
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/launchers/dtos/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Data objects specific to implementations of {@link com.netflix.genie.web.agent.launchers.AgentLauncher}. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.launchers.dtos; import javax.annotation.ParametersAreNonnullByDefault;
2,563
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/InspectionReport.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors; import lombok.AllArgsConstructor; import lombok.Getter; /** * Representation of the outcome of an inspection performed by an {@link AgentMetadataInspector}. * * @author mprimi * @since 4.0.0 */ @AllArgsConstructor @Getter public class InspectionReport { private final Decision decision; private final String message; /** * Factory method for {@link InspectionReport}. * * @param message a message * @return a new {@link InspectionReport} */ public static InspectionReport newRejection(final String message) { return new InspectionReport(Decision.REJECT, message); } /** * Factory method for {@link InspectionReport}. * * @param message a message * @return a new {@link InspectionReport} */ public static InspectionReport newAcceptance(final String message) { return new InspectionReport(Decision.ACCEPT, message); } /** * The possible outcomes of an inspection. */ public enum Decision { /** * Subject passed the inspection and is allowed to proceed. */ ACCEPT, /** * Subject failed the inspection and is not allowed to proceed. */ REJECT; /** * Invert the decision. * * @param decision The decision to flip * @return The opposite decision */ public static Decision flip(final Decision decision) { switch (decision) { case REJECT: return ACCEPT; case ACCEPT: return REJECT; default: throw new RuntimeException("Unexpected: " + decision.name()); } } } }
2,564
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/AgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; /** * Component that inspects an Agent client metadata and makes decision on whether it is allowed to proceed. */ @Validated public interface AgentMetadataInspector { /** * Perform inspection of an Agent client metadata. * * @param agentClientMetadata the agent client metadata * @return the inspection outcome */ InspectionReport inspect(@Valid AgentClientMetadata agentClientMetadata); }
2,565
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Interfaces and classes used to inspect metadata coming from an Agent. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.inspectors; import javax.annotation.ParametersAreNonnullByDefault;
2,566
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/RejectAllJobsAgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.jobs.JobConstants; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import org.springframework.core.env.Environment; import javax.validation.Valid; /** * An {@link AgentMetadataInspector} that accepts or rejects all agents based on the value of an environment property. * This mechanism allows temporarily disabling all new inbound jobs while at the same time keeping the servers running. * * @author mprimi * @since 4.0.0 */ public class RejectAllJobsAgentMetadataInspector implements AgentMetadataInspector { private static final String JOB_SUBMISSION_IS_ENABLED_MESSAGE = "Job submission is enabled"; private Environment environment; /** * Constructor. * * @param environment the environment */ public RejectAllJobsAgentMetadataInspector(final Environment environment) { this.environment = environment; } /** * {@inheritDoc} */ @Override public InspectionReport inspect(@Valid final AgentClientMetadata agentClientMetadata) { final boolean jobSubmissionEnabled = this.environment.getProperty( JobConstants.JOB_SUBMISSION_ENABLED_PROPERTY_KEY, Boolean.class, true ); if (jobSubmissionEnabled) { return new InspectionReport( InspectionReport.Decision.ACCEPT, JOB_SUBMISSION_IS_ENABLED_MESSAGE ); } else { final String message = environment.getProperty( JobConstants.JOB_SUBMISSION_DISABLED_MESSAGE_KEY, String.class, JobConstants.JOB_SUBMISSION_DISABLED_DEFAULT_MESSAGE ); return new InspectionReport( InspectionReport.Decision.REJECT, message ); } } }
2,567
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/MinimumVersionAgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import com.netflix.genie.web.properties.AgentFilterProperties; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import javax.validation.Valid; /** * An {@link AgentMetadataInspector} that rejects agents whose version is older than a given version. * * @author mprimi * @since 4.0.0 */ public class MinimumVersionAgentMetadataInspector implements AgentMetadataInspector { private final AgentFilterProperties agentFilterProperties; /** * Constructor. * * @param agentFilterProperties agent filter properties */ public MinimumVersionAgentMetadataInspector(final AgentFilterProperties agentFilterProperties) { this.agentFilterProperties = agentFilterProperties; } /** * {@inheritDoc} */ @Override public InspectionReport inspect(@Valid final AgentClientMetadata agentClientMetadata) { final String minimumVersionString = this.agentFilterProperties.getMinimumVersion(); final String agentVersionString = agentClientMetadata.getVersion().orElse(null); if (StringUtils.isBlank(minimumVersionString)) { return InspectionReport.newAcceptance("Minimum version requirement not set"); } else if (StringUtils.isBlank(agentVersionString)) { return InspectionReport.newRejection("Agent version not set"); } else { final ArtifactVersion minimumVersion = new DefaultArtifactVersion(minimumVersionString); final ArtifactVersion agentVersion = new DefaultArtifactVersion(agentVersionString); final boolean deprecated = minimumVersion.compareTo(agentVersion) > 0; return new InspectionReport( deprecated ? InspectionReport.Decision.REJECT : InspectionReport.Decision.ACCEPT, String.format( "Agent version: %s is %s than minimum: %s", agentVersionString, deprecated ? "older" : "newer or equal", minimumVersionString ) ); } } }
2,568
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/WhitelistedVersionAgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import com.netflix.genie.web.properties.AgentFilterProperties; import javax.validation.Valid; /** * An {@link AgentMetadataInspector} that accepts agent whose version matches a regular expression * (obtained via properties) and rejects everything else. * * @author mprimi * @since 4.0.0 */ public class WhitelistedVersionAgentMetadataInspector extends BaseRegexAgentMetadataInspector { private final AgentFilterProperties agentFilterProperties; /** * Constructor. * * @param agentFilterProperties version filter properties */ public WhitelistedVersionAgentMetadataInspector(final AgentFilterProperties agentFilterProperties) { super(InspectionReport.Decision.ACCEPT); this.agentFilterProperties = agentFilterProperties; } /** * {@inheritDoc} */ @Override public InspectionReport inspect(@Valid final AgentClientMetadata agentClientMetadata) { return super.inspectWithPattern( agentFilterProperties.getWhitelistedVersions(), agentClientMetadata.getVersion().orElse(null) ); } }
2,569
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/BlacklistedVersionAgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import com.netflix.genie.web.properties.AgentFilterProperties; import javax.validation.Valid; /** * An {@link AgentMetadataInspector} that rejects agent whose version matches a regular expression * (obtained via properties) and accepts everything else. * * @author mprimi * @since 4.0.0 */ public class BlacklistedVersionAgentMetadataInspector extends BaseRegexAgentMetadataInspector { private final AgentFilterProperties agentFilterProperties; /** * Constructor. * * @param agentFilterProperties version filter properties */ public BlacklistedVersionAgentMetadataInspector(final AgentFilterProperties agentFilterProperties) { super(InspectionReport.Decision.REJECT); this.agentFilterProperties = agentFilterProperties; } /** * {@inheritDoc} */ @Override public InspectionReport inspect(@Valid final AgentClientMetadata agentClientMetadata) { return super.inspectWithPattern( agentFilterProperties.getBlacklistedVersions(), agentClientMetadata.getVersion().orElse(null) ); } }
2,570
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implementations for inspectors. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.inspectors.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,571
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/inspectors/impl/BaseRegexAgentMetadataInspector.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.inspectors.impl; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Abstract base class for {@link AgentMetadataInspector} based on regex matching. * Can be configure to accept or reject in case of match and do the opposite in case of no match. * If a valid regex is not provided, this inspector accepts. * * @author mprimi * @since 4.0.0 */ @Slf4j abstract class BaseRegexAgentMetadataInspector implements AgentMetadataInspector { private final AtomicReference<Pattern> patternReference = new AtomicReference<>(); private final InspectionReport.Decision decisionIfMatch; private String lastCompiledPattern; BaseRegexAgentMetadataInspector( final InspectionReport.Decision decisionIfMatch ) { this.decisionIfMatch = decisionIfMatch; } InspectionReport inspectWithPattern( @Nullable final String currentPatternString, @Nullable final String metadataAttribute ) { final Pattern currentPattern = maybeReloadPattern(currentPatternString); if (currentPattern == null) { return InspectionReport.newAcceptance("Pattern not not set"); } else if (StringUtils.isBlank(metadataAttribute)) { return InspectionReport.newRejection("Metadata attribute not set"); } else if (currentPattern.matcher(metadataAttribute).matches()) { return new InspectionReport( decisionIfMatch, "Attribute: " + metadataAttribute + " matches: " + currentPattern.pattern() ); } else { return new InspectionReport( InspectionReport.Decision.flip(decisionIfMatch), "Attribute: " + metadataAttribute + " does not match: " + currentPattern.pattern() ); } } private Pattern maybeReloadPattern(@Nullable final String currentPatternString) { synchronized (this) { if (StringUtils.isBlank(currentPatternString)) { patternReference.set(null); lastCompiledPattern = null; } else if (!currentPatternString.equals(lastCompiledPattern)) { try { final Pattern newPattern = Pattern.compile(currentPatternString); patternReference.set(newPattern); } catch (final PatternSyntaxException e) { patternReference.set(null); log.error("Failed to load pattern: {}", currentPatternString, e); } lastCompiledPattern = currentPatternString; } } return patternReference.get(); } }
2,572
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/AgentRoutingService.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import java.util.Optional; /** * Service that tracks agent connections on the local Genie node and provides routing information for * agent connected to other nodes. * * @author mprimi * @since 4.0.0 */ @Validated public interface AgentRoutingService { /** * Look up the hostname of the Genie node currently handling the agent connection for a given job. * * @param jobId the job id * @return a boxed hostname string, empty if the connection for the given job id is not found */ Optional<String> getHostnameForAgentConnection(@NotBlank String jobId); /** * Tells whether the agent running a given job is connected to the local node. * * @param jobId the job id * @return true if the agent has an active connection to this node */ boolean isAgentConnectionLocal(@NotBlank String jobId); /** * Handle a new agent connection. * * @param jobId the job id the connected agent is running */ void handleClientConnected(@NotBlank String jobId); /** * Handle connected agent disconnection. * * @param jobId the job id the disconnected agent is running */ void handleClientDisconnected(@NotBlank String jobId); /** * Whether the agent executing a given job is currently connected. * * @param jobId the job id * @return true if an agent running the job is connected */ boolean isAgentConnected(String jobId); }
2,573
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/AgentConfigurationService.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services; import java.util.Map; /** * Service that provides agent runtime configuration (i.e. independent of the job being executed). * * @author mprimi * @since 4.0.0 */ public interface AgentConfigurationService { /** * Produce a list of properties to be sent down to the agents running jobs. * * @return a map of properties and values */ Map<String, String> getAgentProperties(); }
2,574
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/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.web.agent.services; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import org.springframework.core.io.Resource; import org.springframework.http.HttpRange; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import java.net.URI; import java.nio.file.Path; import java.util.Optional; /** * Service to retrieve files from a remote agent while the latter is executing a job. * The file is returned as a {@link Resource} so it can be, for example, returned by the server via web API. * * @author mprimi * @since 4.0.0 */ public interface AgentFileStreamService { /** * Returns a Resource for the given job file boxed in an {@link Optional}. * If the service is unable to determine whether the file exists, the optional is empty. * In all other cases, the optional is not empty. However the resource may return false to {@code exist()} calls * (if the file is not believed to exist on the agent) or false to {@code isReadable()} if the file cannot be * streamed for other reasons. * * @param jobId the job id * @param relativePath the relative path in the job directory * @param uri the file uri //TODO redundant * @param range the list of ranges requested (RFC 7233) or null if no range is specified * @return an optional {@link Resource} */ Optional<AgentFileResource> getResource( @NotBlank String jobId, Path relativePath, URI uri, @Nullable HttpRange range ); /** * Returns the manifest for a given job, boxed in an {@link Optional}. * The manifest may not be present if the agent is not connected to this node (for example because execution has * completed, or because the agent is connected to a different node). * * @param jobId the job id * @return an optional {@link DirectoryManifest} */ Optional<DirectoryManifest> getManifest(String jobId); /** * A {@link Resource} for files local to a remote agent. * * @author mprimi * @since 4.0.0 */ interface AgentFileResource extends Resource { } }
2,575
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/AgentFilterService.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.web.agent.inspectors.InspectionReport; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; /** * Service to block agent/clients that the server wants to refuse service to. * For example, blacklist clients running a deprecated or incompatible versions. * * @author mprimi * @since 4.0.0 */ @Validated public interface AgentFilterService { /** * Inspect the Agent metadata and decide whether to allow this client to proceed. * * @param agentClientMetadata the agent client metadata * @return an inspection report */ InspectionReport inspectAgentMetadata(@Valid AgentClientMetadata agentClientMetadata); }
2,576
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/AgentConnectionTrackingService.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services; /** * Tracks active connections and heartbeats coming from agents actively executing a job. * * @author mprimi * @since 4.0.0 */ public interface AgentConnectionTrackingService { /** * Handle a heartbeat. * * @param streamId the unique id of the connection * @param claimedJobId the job id claimed by the agent */ void notifyHeartbeat(String streamId, String claimedJobId); /** * Handle a disconnection. * * @param streamId the unique id of the connection * @param claimedJobId the job id claimed by the agent */ void notifyDisconnected(String streamId, String claimedJobId); /** * Get the count of locally connected agents. * * @return the number of agents connected. */ long getConnectedAgentsCount(); }
2,577
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Services specific to the Agent module of the Genie web application. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.services; import javax.annotation.ParametersAreNonnullByDefault;
2,578
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/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.web.agent.services; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieAgentRejectedException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieIdAlreadyExistsException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobAlreadyClaimedException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobResolutionRuntimeException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobSpecificationNotFoundException; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.Map; /** * A Service to collect the logic for implementing calls from the Agent when a job is launched via the CLI. * * @author tgianos * @since 4.0.0 */ @Validated public interface AgentJobService { /** * Shake hands and allow a client or reject it based on the supplied {@link AgentClientMetadata}. * * @param agentMetadata The metadata about the agent starting to run a given job * @throws GenieAgentRejectedException If the server rejects the client based on its metadata * @throws ConstraintViolationException If the arguments fail validation */ void handshake(@Valid AgentClientMetadata agentMetadata); /** * Provide configuration properties for an agent that is beginning to execute a job. * * @param agentMetadata The metadata about the agent starting to run a given job * @return a map of properties for the agent * @throws ConstraintViolationException If the arguments fail validation */ Map<String, String> getAgentProperties(@Valid AgentClientMetadata agentMetadata); /** * Reserve a job id and persist job details in the database based on the supplied {@link JobRequest}. * * @param jobRequest The job request containing all the metadata needed to reserve a job id * @param agentClientMetadata The metadata about the agent driving this job request * @return The unique id of the job which was saved in the database * @throws GenieIdAlreadyExistsException If the id requested along with the job request is already in use * @throws ConstraintViolationException If the arguments fail validation */ String reserveJobId(@Valid JobRequest jobRequest, @Valid AgentClientMetadata agentClientMetadata); /** * Resolve the job specification for job identified by the given id. This method will persist the job specification * details to the database. * * @param id The id of the job to resolve the specification for. Must already have a reserved an id in the database * @return The job specification if one could be resolved * @throws GenieJobResolutionException On error resolving the job given the input parameters and system state * @throws ConstraintViolationException If the arguments fail validation * @throws GenieJobResolutionRuntimeException If job resolution fails due to a runtime error (as opposed to * unsatisfiable constraints) */ JobSpecification resolveJobSpecification( @NotBlank String id ) throws GenieJobResolutionException, GenieJobResolutionRuntimeException; /** * Get a job specification if has been resolved. * * @param id the id of the job to retrieve the specification for * @return The job specification for the job * @throws GenieJobNotFoundException If the job has not yet had its ID reserved and/or can't be found * @throws GenieJobSpecificationNotFoundException If the job exists but the specification hasn't been * resolved or saved yet * @throws ConstraintViolationException If the arguments fail validation */ JobSpecification getJobSpecification(@NotBlank String id); /** * Run the job specification resolution algorithm on the given input but save nothing in the system. * * @param jobRequest The job request containing all the metadata needed to resolve a job specification * @return The job specification that would have been resolved for the given input * @throws GenieJobResolutionException On error resolving the job given the input parameters and system state * @throws ConstraintViolationException If the arguments fail validation */ JobSpecification dryRunJobSpecificationResolution(@Valid JobRequest jobRequest) throws GenieJobResolutionException; /** * Set a job identified by {@code id} to be owned by the agent identified by {@code agentClientMetadata}. The * job status in the system will be set to {@link com.netflix.genie.common.dto.JobStatus#CLAIMED} * * @param id The id of the job to claim. Must exist in the system. * @param agentClientMetadata The metadata about the client claiming the job * @throws GenieJobNotFoundException if no job with the given {@code id} exists * @throws GenieJobAlreadyClaimedException if the job with the given {@code id} already has been claimed * @throws GenieInvalidStatusException if the current job status is not * {@link com.netflix.genie.common.dto.JobStatus#RESOLVED} * @throws ConstraintViolationException If the arguments fail validation */ void claimJob(@NotBlank String id, @Valid AgentClientMetadata agentClientMetadata); /** * Update the status of the job identified with {@code id} to be {@code newStatus} provided that the current status * of the job matches {@code newStatus}. Optionally a status message can be provided to provide more details to * users. If the {@code newStatus} is {@link JobStatus#RUNNING} the start time will be set. If the {@code newStatus} * is a member of {@link JobStatus#getFinishedStatuses()} and the job had a started time set the finished time of * the job will be set. * * @param id The id of the job to update status for. Must exist in the system. * @param currentStatus The status the caller to this API thinks the job currently has * @param newStatus The new status the caller would like to update the status to * @param newStatusMessage An optional status message to associate with this change * @throws GenieJobNotFoundException if no job with the given {@code id} exists * @throws GenieInvalidStatusException if the current status of the job identified by {@code id} in the system * doesn't match the supplied {@code currentStatus}. * Also if the {@code currentStatus} equals the {@code newStatus}. * @throws ConstraintViolationException If the arguments fail validation */ void updateJobStatus( @NotBlank String id, JobStatus currentStatus, JobStatus newStatus, @Nullable String newStatusMessage ); /** * Retrieve the status of the job identified with {@code id}. * * @param id The id of the job to look up. * @return the current status of the job, as seen by this node * @throws GenieJobNotFoundException if no job with the given {@code id} exists * @throws ConstraintViolationException If the arguments fail validation */ JobStatus getJobStatus(@NotBlank String id); /** * Update the archive status status of the job identified with {@code id} to be {@code newStatus}. * Notice this is a 'blind write', the currently persisted value will always be overwritten. * * @param id The id of the job to update status for. Must exist in the system. * @param newArchiveStatus The new archive status the caller would like to update the status to * @throws GenieJobNotFoundException if no job with the given {@code id} exists * @throws ConstraintViolationException If the arguments fail validation */ void updateJobArchiveStatus( @NotBlank String id, ArchiveStatus newArchiveStatus ); }
2,579
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentConfigurationServiceImpl.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.agent.services.AgentConfigurationService; import com.netflix.genie.web.properties.AgentConfigurationProperties; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * This implementation of {@link AgentConfigurationService} forwards properties set on the server that match a given * set of regular expressions, plus any additional ones specified in configuration. * It utilizes a cache to avoid recomputing the set of properties and values for every request. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentConfigurationServiceImpl implements AgentConfigurationService { private static final String RELOAD_PROPERTIES_TIMER = "genie.services.agentConfiguration.reloadProperties.timer"; private static final String PROPERTIES_COUNT_TAG = "numProperties"; private final AgentConfigurationProperties agentConfigurationProperties; private final MeterRegistry registry; private final PropertiesMapCache propertiesMapCache; /** * Constructor. * * @param agentConfigurationProperties the properties * @param propertyMapCache the property map cache * @param registry the metrics registry */ public AgentConfigurationServiceImpl( final AgentConfigurationProperties agentConfigurationProperties, final PropertiesMapCache propertyMapCache, final MeterRegistry registry ) { this.agentConfigurationProperties = agentConfigurationProperties; this.propertiesMapCache = propertyMapCache; this.registry = registry; } /** * {@inheritDoc} */ @Override public Map<String, String> getAgentProperties() { final Set<Tag> tags = Sets.newHashSet(); final long start = System.nanoTime(); try { final Map<String, String> propertiesMap = this.propertiesMapCache.get(); tags.add(Tag.of(PROPERTIES_COUNT_TAG, String.valueOf(propertiesMap.size()))); MetricsUtils.addSuccessTags(tags); return propertiesMap; } catch (Throwable t) { MetricsUtils.addFailureTagsWithException(tags, t); throw t; } finally { final long end = System.nanoTime(); this.registry.timer(RELOAD_PROPERTIES_TIMER, tags).record(end - start, TimeUnit.NANOSECONDS); } } }
2,580
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentRoutingServiceSingleNodeImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.util.GenieHostInfo; import com.netflix.genie.web.agent.services.AgentRoutingService; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import java.util.Optional; import java.util.Set; /** * Implementation of {@link AgentRoutingService} that assumes a single Genie node and tracks connections in-memory. * * @author mprimi * @since 4.0.0 */ @Validated @Slf4j public class AgentRoutingServiceSingleNodeImpl implements AgentRoutingService { private final GenieHostInfo genieHostInfo; private final Set<String> connectedAgents = Sets.newConcurrentHashSet(); /** * Constructor. * * @param genieHostInfo local genie node host information */ public AgentRoutingServiceSingleNodeImpl(final GenieHostInfo genieHostInfo) { this.genieHostInfo = genieHostInfo; } /** * {@inheritDoc} */ @Override public Optional<String> getHostnameForAgentConnection(final @NotBlank String jobId) { return isAgentConnected(jobId) ? Optional.of(this.genieHostInfo.getHostname()) : Optional.empty(); } /** * {@inheritDoc} */ @Override public boolean isAgentConnectionLocal(final @NotBlank String jobId) { return isAgentConnected(jobId); } /** * {@inheritDoc} */ @Override public void handleClientConnected(@NotBlank final String jobId) { log.info("Agent executing job {} connected", jobId); this.connectedAgents.add(jobId); } /** * {@inheritDoc} */ @Override public void handleClientDisconnected(@NotBlank final String jobId) { log.info("Agent executing job {} disconnected", jobId); this.connectedAgents.remove(jobId); } /** * {@inheritDoc} */ @Override public boolean isAgentConnected(final String jobId) { return this.connectedAgents.contains(jobId); } }
2,581
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentRoutingServiceCuratorDiscoveryImpl.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.util.GenieHostInfo; import com.netflix.genie.web.agent.services.AgentRoutingService; import com.netflix.genie.web.properties.AgentRoutingServiceProperties; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.zookeeper.KeeperException; import org.springframework.scheduling.TaskScheduler; import javax.validation.constraints.NotBlank; import java.time.Instant; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Implementation of {@link AgentRoutingService} that relies on Curator's Discovery extension. * Rather than the traditional use of this recipe (register a service for the node itself, this class registers one * service instance for each agent locally connected. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentRoutingServiceCuratorDiscoveryImpl implements AgentRoutingService { private static final String SERVICE_NAME = "agent_connections"; private static final String METRICS_PREFIX = "genie.agents.connections."; private static final String CONNECTED_AGENTS_GAUGE_NAME = METRICS_PREFIX + "connected.gauge"; private static final String REGISTERED_AGENTS_GAUGE_NAME = METRICS_PREFIX + "registered.gauge"; private static final String ZOOKEEPER_SESSION_STATE_COUNTER_NAME = METRICS_PREFIX + "zookeeperSessionState.counter"; private static final String AGENT_REGISTERED_TIMER_NAME = METRICS_PREFIX + "registered.timer"; private static final String AGENT_UNREGISTERED_TIMER_NAME = METRICS_PREFIX + "unregistered.timer"; private static final String AGENT_REFRESH_TIMER_NAME = METRICS_PREFIX + "refreshed.timer"; private static final String AGENT_CONNECTED_COUNTER_NAME = METRICS_PREFIX + "connected.counter"; private static final String AGENT_DISCONNECTED_COUNTER_NAME = METRICS_PREFIX + "disconnected.counter"; private static final String AGENT_LOOKUP_TIMER_NAME = METRICS_PREFIX + "lookup.timer"; private static final String ZK_CONNECTION_STATE_TAG_NAME = "connectionState"; private static final String ROUTE_FOUND_TAG_NAME = "found"; private static final Set<Tag> EMPTY_TAG_SET = ImmutableSet.of(); private final String localHostname; private final ServiceDiscovery<Agent> serviceDiscovery; private final TaskScheduler taskScheduler; private final MeterRegistry registry; private final AgentRoutingServiceProperties properties; private final Set<String> connectedAgentsSet; private final Map<String, ServiceInstance<Agent>> registeredAgentsMap; private final PriorityBlockingQueue<RegisterMutation> registrationQueue; private final AtomicReference<Thread> registrationTaskThread; private final ThreadFactory threadFactory; /** * Constructor. * * @param genieHostInfo The genie local host information * @param serviceDiscovery The service discovery client * @param taskScheduler The task scheduler * @param listenableCuratorConnectionState The listenable curator client connection status * @param registry The metrics registry * @param properties The service properties */ public AgentRoutingServiceCuratorDiscoveryImpl( final GenieHostInfo genieHostInfo, final ServiceDiscovery<Agent> serviceDiscovery, final TaskScheduler taskScheduler, final Listenable<ConnectionStateListener> listenableCuratorConnectionState, final MeterRegistry registry, final AgentRoutingServiceProperties properties ) { this( genieHostInfo, serviceDiscovery, taskScheduler, listenableCuratorConnectionState, registry, properties, new ThreadFactory() { private final AtomicLong threadCounter = new AtomicLong(); @Override public Thread newThread(final Runnable r) { return new Thread( r, this.getClass().getSimpleName() + "-registration-" + threadCounter.incrementAndGet() ); } } ); } @VisibleForTesting AgentRoutingServiceCuratorDiscoveryImpl( final GenieHostInfo genieHostInfo, final ServiceDiscovery<Agent> serviceDiscovery, final TaskScheduler taskScheduler, final Listenable<ConnectionStateListener> listenableCuratorConnectionState, final MeterRegistry registry, final AgentRoutingServiceProperties properties, final ThreadFactory threadFactory ) { this.localHostname = genieHostInfo.getHostname(); this.serviceDiscovery = serviceDiscovery; this.taskScheduler = taskScheduler; this.registry = registry; this.threadFactory = threadFactory; this.properties = properties; this.registeredAgentsMap = Maps.newConcurrentMap(); this.connectedAgentsSet = Sets.newConcurrentHashSet(); this.registrationQueue = new PriorityBlockingQueue<>(); this.registrationTaskThread = new AtomicReference<>(); // Create gauge metric for agents connected and registered registry.gauge(CONNECTED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.connectedAgentsSet, Set::size); registry.gaugeMapSize(REGISTERED_AGENTS_GAUGE_NAME, EMPTY_TAG_SET, this.registeredAgentsMap); // Listen for Curator session state changes listenableCuratorConnectionState.addListener(this::handleConnectionStateChange); // The curator client is passed already connected. // See: org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration this.startRegistrationThread(); } private void startRegistrationThread() { final Thread newThread = this.threadFactory.newThread(this::registrationTask); final Thread oldThread = this.registrationTaskThread.getAndSet(newThread); if (oldThread != null) { oldThread.interrupt(); } newThread.start(); } private void stopRegistrationThread() { final Thread thread = this.registrationTaskThread.getAndSet(null); if (thread != null) { thread.interrupt(); } } // Thread task that consumes registration queue items and applies the corresponding mutation with Curator client. // This thread is stopped with an interrupt if the client is disconnected. private void registrationTask() { while (true) { try { processNextRegistrationMutation(); } catch (InterruptedException e) { break; } } log.debug("Registration thread terminating"); } private void processNextRegistrationMutation() throws InterruptedException { RegisterMutation mutation = null; try { // Blocking mutation = this.registrationQueue.take(); final String jobId = mutation.getJobId(); // Check if agent is still connected by the time this mutation is taken from the queue to // be processed. final boolean agentIsConnected = this.connectedAgentsSet.contains(mutation.getJobId()); if (agentIsConnected) { // Register or re-register agent connection if (mutation.isRefresh()) { refreshAgentConnection(jobId); } else { registerAgentConnection(jobId); } // Schedule a future refresh for this agent connection this.taskScheduler.schedule( () -> this.registrationQueue.add(RegisterMutation.refresh(jobId)), Instant.now().plus(this.properties.getRefreshInterval()) ); } else { // Unregister agent connection unregisterAgentConnection(jobId); } } catch (InterruptedException e) { log.warn("Registration task interrupted", e); if (mutation != null) { // Re-enqueue mutation that was in-progress when interrupted this.registrationQueue.add(mutation); } throw e; } } private void registerAgentConnection(final String jobId) throws InterruptedException { log.debug("Registering route for job: {}", jobId); final ServiceInstance<Agent> serviceInstance = new ServiceInstance<>( SERVICE_NAME, jobId, localHostname, null, null, new Agent(jobId), Instant.now().getEpochSecond(), ServiceType.DYNAMIC, null ); Set<Tag> tags = MetricsUtils.newSuccessTagsSet(); final long start = System.nanoTime(); try { this.serviceDiscovery.registerService(serviceInstance); this.registeredAgentsMap.put(jobId, serviceInstance); } catch (InterruptedException e) { // Ensure interrupt is not swallowed by the generic catch log.debug("Interrupted while registering {}", jobId); tags = MetricsUtils.newFailureTagsSetForException(e); throw e; } catch (Exception e) { log.error("Failed to register agent executing job: {}", jobId, e); tags = MetricsUtils.newFailureTagsSetForException(e); } finally { this.registry.timer( AGENT_REGISTERED_TIMER_NAME, tags ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } private void refreshAgentConnection(final String jobId) throws InterruptedException { log.debug("Refreshing route for job: {}", jobId); final ServiceInstance<Agent> serviceInstance = this.registeredAgentsMap.get(jobId); if (serviceInstance == null) { log.warn("Instance record not found for job {}", jobId); this.registerAgentConnection(jobId); return; } Set<Tag> tags = MetricsUtils.newSuccessTagsSet(); final long start = System.nanoTime(); try { this.serviceDiscovery.updateService(serviceInstance); } catch (KeeperException.NoNodeException e) { log.warn("Failed to update registration of agent executing job id: {}", jobId); // Failed because expected existing node is not present. Create it. this.registerAgentConnection(jobId); } catch (InterruptedException e) { // Ensure interrupt is not swallowed by the generic catch log.debug("Interrupted while refreshing {}", jobId); tags = MetricsUtils.newFailureTagsSetForException(e); throw e; } catch (Exception e) { log.error("Failed to refresh agent executing job id: {}", jobId); tags = MetricsUtils.newFailureTagsSetForException(e); } finally { this.registry.timer( AGENT_REFRESH_TIMER_NAME, tags ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } private void unregisterAgentConnection(final String jobId) throws InterruptedException { final ServiceInstance<Agent> serviceInstance = this.registeredAgentsMap.get(jobId); if (serviceInstance == null) { log.debug("Skipping unregistration, already removed"); return; } log.debug("Unregistering route for job: {}", jobId); Set<Tag> tags = MetricsUtils.newSuccessTagsSet(); final long start = System.nanoTime(); try { this.serviceDiscovery.unregisterService(serviceInstance); this.registeredAgentsMap.remove(jobId); } catch (InterruptedException e) { // Ensure interrupt is not swallowed by the generic catch log.debug("Interrupted while unregistering {}", jobId); tags = MetricsUtils.newFailureTagsSetForException(e); throw e; } catch (Exception e) { log.error("Failed to unregister agent executing job id: {}", jobId); tags = MetricsUtils.newFailureTagsSetForException(e); } finally { this.registry.timer( AGENT_UNREGISTERED_TIMER_NAME, tags ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } private void handleConnectionStateChange(final CuratorFramework client, final ConnectionState newState) { this.registry.counter( ZOOKEEPER_SESSION_STATE_COUNTER_NAME, Sets.newHashSet(Tag.of(ZK_CONNECTION_STATE_TAG_NAME, newState.name())) ).increment(); log.info("Zookeeper/Curator client: {}", newState); switch (newState) { case CONNECTED: case RECONNECTED: startRegistrationThread(); break; case LOST: case SUSPENDED: stopRegistrationThread(); break; default: log.warn("Zookeeper/Curator unhandled connection state: {}", newState); } } /** * {@inheritDoc} */ @Override public Optional<String> getHostnameForAgentConnection(@NotBlank final String jobId) { log.debug("Looking up agent executing job: {}", jobId); if (isAgentConnectionLocal(jobId)) { return Optional.of(localHostname); } final long start = System.nanoTime(); final Set<Tag> tags = Sets.newHashSet(); String address = null; try { final ServiceInstance<Agent> instance = serviceDiscovery.queryForInstance(SERVICE_NAME, jobId); if (instance == null) { log.debug("Could not find agent connection for job {}", jobId); } else { address = instance.getAddress(); } MetricsUtils.addSuccessTags(tags); } catch (Exception e) { log.error("Error looking up agent connection for job {}", jobId, e); address = null; MetricsUtils.addFailureTagsWithException(tags, e); } finally { tags.add(Tag.of(ROUTE_FOUND_TAG_NAME, String.valueOf(address != null))); this.registry.timer( AGENT_LOOKUP_TIMER_NAME, tags ).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } return Optional.ofNullable(address); } /** * {@inheritDoc} */ @Override public boolean isAgentConnectionLocal(@NotBlank final String jobId) { return this.connectedAgentsSet.contains(jobId); } @Override public void handleClientConnected(@NotBlank final String jobId) { log.debug("Adding to routing table (pending registration): {}", jobId); final boolean isNew = this.connectedAgentsSet.add(jobId); this.registrationQueue.add(RegisterMutation.update(jobId)); if (isNew) { this.registry.counter(AGENT_CONNECTED_COUNTER_NAME).increment(); } } @Override public void handleClientDisconnected(@NotBlank final String jobId) { log.debug("Removing from routing table (pending un-registration): {}", jobId); final boolean removed = this.connectedAgentsSet.remove(jobId); this.registrationQueue.add(RegisterMutation.update(jobId)); if (removed) { this.registry.counter(AGENT_DISCONNECTED_COUNTER_NAME).increment(); } } /** * {@inheritDoc} */ @Override public boolean isAgentConnected(final String jobId) { return this.getHostnameForAgentConnection(jobId).isPresent(); } /** * Payload for typed {@link ServiceDiscovery}. */ @Getter @EqualsAndHashCode public static final class Agent { // This field is superfluous, but added because serialization fails on empty beans private final String jobId; // Jackson deserialization requires this dummy constructor private Agent() { this.jobId = null; } /** * Constructor. * * @param jobId The job id */ public Agent(@JsonProperty(value = "jobId", required = true) final String jobId) { this.jobId = jobId; } } @Getter @EqualsAndHashCode private static final class RegisterMutation implements Comparable<RegisterMutation> { private final String jobId; private final boolean refresh; private final long timestamp; private RegisterMutation(final String jobId, final boolean refresh) { this.jobId = jobId; this.refresh = refresh; this.timestamp = System.nanoTime(); } static RegisterMutation refresh(final String jobId) { return new RegisterMutation(jobId, true); } static RegisterMutation update(final String jobId) { return new RegisterMutation(jobId, false); } /** * {@inheritDoc} */ @Override public int compareTo(final RegisterMutation other) { if (this.isRefresh() == other.isRefresh()) { final long timestampDifference = this.getTimestamp() - other.getTimestamp(); if (timestampDifference == 0) { return this.getJobId().compareTo(other.getJobId()); } else { return timestamp > 0 ? 1 : -1; } } else { return this.isRefresh() ? 1 : -1; } } } }
2,582
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentJobServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.dtos.JobRequestMetadata; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieAgentRejectedException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieIdAlreadyExistsException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobResolutionRuntimeException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobSpecificationNotFoundException; import com.netflix.genie.web.agent.inspectors.InspectionReport; import com.netflix.genie.web.agent.services.AgentConfigurationService; import com.netflix.genie.web.agent.services.AgentFilterService; import com.netflix.genie.web.agent.services.AgentJobService; import com.netflix.genie.web.data.services.DataServices; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.dtos.JobSubmission; import com.netflix.genie.web.dtos.ResolvedJob; import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException; import com.netflix.genie.web.exceptions.checked.NotFoundException; import com.netflix.genie.web.services.JobResolverService; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.HashSet; import java.util.Map; import java.util.UUID; /** * Default implementation of {@link AgentJobService}. * * @author tgianos * @since 4.0.0 */ @Validated @Transactional public class AgentJobServiceImpl implements AgentJobService { private static final String AGENT_JOB_SERVICE_METRIC_PREFIX = "genie.services.agentJob."; private static final String HANDSHAKE_COUNTER_METRIC_NAME = AGENT_JOB_SERVICE_METRIC_PREFIX + "handshake.counter"; private static final String GET_AGENT_PROPERTIES_COUNTER_METRIC_NAME = AGENT_JOB_SERVICE_METRIC_PREFIX + "getAgentProperties.counter"; private static final String AGENT_VERSION_METRIC_TAG_NAME = "agentVersion"; private static final String HANDSHAKE_DECISION_METRIC_TAG_NAME = "handshakeDecision"; private final PersistenceService persistenceService; private final JobResolverService jobResolverService; private final AgentFilterService agentFilterService; private final AgentConfigurationService agentConfigurationService; private final MeterRegistry meterRegistry; /** * Constructor. * * @param dataServices The {@link DataServices} instance to use * @param jobResolverService The specification service to use * @param agentFilterService The agent filter service to use * @param agentConfigurationService The agent configuration service * @param meterRegistry The metrics registry to use */ public AgentJobServiceImpl( final DataServices dataServices, final JobResolverService jobResolverService, final AgentFilterService agentFilterService, final AgentConfigurationService agentConfigurationService, final MeterRegistry meterRegistry ) { this.persistenceService = dataServices.getPersistenceService(); this.jobResolverService = jobResolverService; this.agentFilterService = agentFilterService; this.agentConfigurationService = agentConfigurationService; this.meterRegistry = meterRegistry; } /** * {@inheritDoc} */ @Override public void handshake( @Valid final AgentClientMetadata agentClientMetadata ) throws GenieAgentRejectedException { final HashSet<Tag> tags = Sets.newHashSet( Tag.of(AGENT_VERSION_METRIC_TAG_NAME, agentClientMetadata.getVersion().orElse("null")) ); final InspectionReport report; try { report = agentFilterService.inspectAgentMetadata(agentClientMetadata); } catch (final Exception e) { MetricsUtils.addFailureTagsWithException(tags, e); meterRegistry.counter(HANDSHAKE_COUNTER_METRIC_NAME, tags).increment(); throw e; } MetricsUtils.addSuccessTags(tags); tags.add(Tag.of(HANDSHAKE_DECISION_METRIC_TAG_NAME, report.getDecision().name())); meterRegistry.counter(HANDSHAKE_COUNTER_METRIC_NAME, tags).increment(); if (report.getDecision() == InspectionReport.Decision.REJECT) { throw new GenieAgentRejectedException("Agent rejected: " + report.getMessage()); } } /** * {@inheritDoc} */ @Override public Map<String, String> getAgentProperties( @Valid final AgentClientMetadata agentClientMetadata ) { final HashSet<Tag> tags = Sets.newHashSet( Tag.of(AGENT_VERSION_METRIC_TAG_NAME, agentClientMetadata.getVersion().orElse("null")) ); try { final Map<String, String> agentPropertiesMap = this.agentConfigurationService.getAgentProperties(); MetricsUtils.addSuccessTags(tags); return agentPropertiesMap; } catch (final Exception e) { MetricsUtils.addFailureTagsWithException(tags, e); throw e; } finally { this.meterRegistry.counter(GET_AGENT_PROPERTIES_COUNTER_METRIC_NAME, tags).increment(); } } /** * {@inheritDoc} */ @Override public String reserveJobId( @Valid final JobRequest jobRequest, @Valid final AgentClientMetadata agentClientMetadata ) { final JobRequestMetadata jobRequestMetadata = new JobRequestMetadata(null, agentClientMetadata, 0, 0, null); try { return this.persistenceService.saveJobSubmission( new JobSubmission.Builder(jobRequest, jobRequestMetadata).build() ); } catch (final IdAlreadyExistsException e) { // TODO: How to handle this? throw new GenieIdAlreadyExistsException(e); } } /** * {@inheritDoc} */ @Override public JobSpecification resolveJobSpecification( @NotBlank final String id ) throws GenieJobResolutionException, GenieJobResolutionRuntimeException { try { final JobRequest jobRequest = this.persistenceService.getJobRequest(id); final ResolvedJob resolvedJob = this.jobResolverService.resolveJob(id, jobRequest, false); this.persistenceService.saveResolvedJob(id, resolvedJob); return resolvedJob.getJobSpecification(); } catch (final NotFoundException e) { throw new GenieJobResolutionException(e); } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public JobSpecification getJobSpecification(@NotBlank final String id) { try { return this.persistenceService .getJobSpecification(id) .orElseThrow( () -> new GenieJobSpecificationNotFoundException( "No job specification exists for job with id " + id ) ); } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public JobSpecification dryRunJobSpecificationResolution( @Valid final JobRequest jobRequest ) throws GenieJobResolutionException { return this.jobResolverService.resolveJob( jobRequest.getRequestedId().orElse(UUID.randomUUID().toString()), jobRequest, false ).getJobSpecification(); } /** * {@inheritDoc} */ @Override public void claimJob(@NotBlank final String id, @Valid final AgentClientMetadata agentClientMetadata) { try { this.persistenceService.claimJob(id, agentClientMetadata); } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } } /** * {@inheritDoc} */ @Override public void updateJobStatus( @NotBlank final String id, final JobStatus currentStatus, final JobStatus newStatus, @Nullable final String newStatusMessage ) { try { this.persistenceService.updateJobStatus(id, currentStatus, newStatus, newStatusMessage); } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } } /** * {@inheritDoc} */ @Override public JobStatus getJobStatus(@NotBlank final String id) { try { return this.persistenceService.getJobStatus(id); } catch (final NotFoundException e) { throw new GenieJobNotFoundException(e); } } /** * {@inheritDoc} */ @Override public void updateJobArchiveStatus(@NotBlank final String id, final ArchiveStatus newArchiveStatus) { try { this.persistenceService.updateJobArchiveStatus(id, newArchiveStatus); } catch (NotFoundException e) { throw new GenieJobNotFoundException(e); } } }
2,583
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentFilterServiceImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector; import com.netflix.genie.web.agent.inspectors.InspectionReport; import com.netflix.genie.web.agent.services.AgentFilterService; import lombok.extern.slf4j.Slf4j; import javax.validation.Valid; import java.util.List; /** * Implementation of {@link AgentFilterService} which delegates iterates through an ordered list of * {@link AgentMetadataInspector}. Giving them the chance to accept and reject agents based on their provided * metadata. This filter accepts by default if none of the inspectors rejected. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentFilterServiceImpl implements AgentFilterService { private final List<AgentMetadataInspector> agentMetadataInspectorList; /** * Constructor. * * @param agentMetadataInspectorList the list of inspectors to consult */ public AgentFilterServiceImpl(final List<AgentMetadataInspector> agentMetadataInspectorList) { this.agentMetadataInspectorList = agentMetadataInspectorList; } /** * Inspect agent metadata and decide to accept or reject it. * This implementation iterates over the given set of {@link AgentMetadataInspector} and stops at the first one * that rejects. If none rejects, then the client is accepted. * * @param agentClientMetadata the agent client metadata * @return an inspection report */ @Override public InspectionReport inspectAgentMetadata(@Valid final AgentClientMetadata agentClientMetadata) { for (final AgentMetadataInspector agentMetadataInspector : agentMetadataInspectorList) { final InspectionReport inspectionReport = agentMetadataInspector.inspect(agentClientMetadata); final InspectionReport.Decision decision = inspectionReport.getDecision(); final String message = inspectionReport.getMessage(); log.debug( "Inspector: {} inspected: {}, decision: {} ({})", agentMetadataInspector.getClass().getSimpleName(), agentClientMetadata, decision.name(), message ); if (decision == InspectionReport.Decision.REJECT) { return InspectionReport.newRejection( "Rejected by: " + agentMetadataInspector.getClass().getSimpleName() + ": " + message ); } } return InspectionReport.newAcceptance("All inspections passed"); } }
2,584
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/AgentConnectionTrackingServiceImpl.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.agent.services.impl; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.web.agent.services.AgentConnectionTrackingService; import com.netflix.genie.web.agent.services.AgentRoutingService; import com.netflix.genie.web.properties.AgentConnectionTrackingServiceProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.scheduling.TaskScheduler; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier; /** * This service keeps track of agent connections and heartbeats. It notifies the downstream {@link AgentRoutingService} * of connected/disconnected agents while hiding details of connections, disconnections, missed heartbeats. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentConnectionTrackingServiceImpl implements AgentConnectionTrackingService, InfoContributor { private final AgentRoutingService agentRoutingService; private final TaskScheduler taskScheduler; private final HashMap<String, JobStreamsRecord> jobStreamRecordsMap = Maps.newHashMap(); private final AgentConnectionTrackingServiceProperties serviceProperties; private final Supplier<Instant> timeSupplier; /** * Constructor. * * @param agentRoutingService the agent routing service * @param taskScheduler the task scheduler * @param serviceProperties the service properties */ public AgentConnectionTrackingServiceImpl( final AgentRoutingService agentRoutingService, final TaskScheduler taskScheduler, final AgentConnectionTrackingServiceProperties serviceProperties ) { this(agentRoutingService, taskScheduler, serviceProperties, Instant::now); } @VisibleForTesting AgentConnectionTrackingServiceImpl( final AgentRoutingService agentRoutingService, final TaskScheduler taskScheduler, final AgentConnectionTrackingServiceProperties serviceProperties, final Supplier<Instant> timeSupplier ) { this.agentRoutingService = agentRoutingService; this.taskScheduler = taskScheduler; this.serviceProperties = serviceProperties; this.timeSupplier = timeSupplier; this.taskScheduler.scheduleAtFixedRate(this::cleanupTask, this.serviceProperties.getCleanupInterval()); } /** * {@inheritDoc} */ @Override public synchronized void notifyHeartbeat(final String streamId, final String claimedJobId) { boolean isNew = false; final JobStreamsRecord record; if (this.jobStreamRecordsMap.containsKey(claimedJobId)) { record = this.jobStreamRecordsMap.get(claimedJobId); } else { record = new JobStreamsRecord(claimedJobId); this.jobStreamRecordsMap.put(claimedJobId, record); isNew = true; } // Update TTL for this stream record.updateActiveStream(streamId, timeSupplier.get()); log.debug( "Received heartbeat for {} job {} using stream {}", isNew ? "new" : "existing", claimedJobId, streamId ); // If this job record is new, wake up observer if (isNew) { log.debug("Notify new agent connection for job {}", claimedJobId); this.agentRoutingService.handleClientConnected(claimedJobId); } } /** * {@inheritDoc} */ @Override public synchronized void notifyDisconnected(final String streamId, final String claimedJobId) { // Retrieve entry final JobStreamsRecord jobStreamsRecord = this.jobStreamRecordsMap.get(claimedJobId); log.debug( "Received disconnection for {} job {} using stream {}", jobStreamsRecord == null ? "unknown" : "existing", claimedJobId, streamId ); // If record exist, expunge the stream if (jobStreamsRecord != null) { jobStreamsRecord.removeActiveStream(streamId); if (!jobStreamsRecord.hasActiveStreams()) { log.debug("Job {} last stream disconnected, notifying routing service", claimedJobId); this.jobStreamRecordsMap.remove(claimedJobId); this.agentRoutingService.handleClientDisconnected(claimedJobId); } } } /** * {@inheritDoc} */ @Override public synchronized long getConnectedAgentsCount() { return this.jobStreamRecordsMap.size(); } private synchronized void cleanupTask() { final Instant cutoff = this.timeSupplier.get().minus(serviceProperties.getConnectionExpirationPeriod()); // Drop all streams that didn't heartbeat recently this.jobStreamRecordsMap.forEach( (jobId, record) -> record.expungeExpiredStreams(cutoff) ); // Remove all records that have no active streams final Set<String> removedJobIds = Sets.newHashSet(); this.jobStreamRecordsMap.entrySet().removeIf( entry -> { if (!entry.getValue().hasActiveStreams()) { removedJobIds.add(entry.getKey()); return true; } return false; } ); // Notify routing service for (final String jobId : removedJobIds) { log.debug("Job {} last stream expired, notifying routing service", jobId); this.agentRoutingService.handleClientDisconnected(jobId); } } /** * {@inheritDoc} */ @Override public void contribute(final Info.Builder builder) { final List<String> jobIds = this.getConnectedAgentsIds(); builder.withDetail("connectedAgents", jobIds); } private synchronized List<String> getConnectedAgentsIds() { return ImmutableList.copyOf(this.jobStreamRecordsMap.keySet()); } private static final class JobStreamsRecord { private final String jobId; private final Map<String, Instant> streamsLastHeartbeatMap = Maps.newHashMap(); private JobStreamsRecord(final String jobId) { this.jobId = jobId; } private void updateActiveStream(final String streamId, final Instant currentTime) { final Instant previousHeartbeat = this.streamsLastHeartbeatMap.put(streamId, currentTime); log.debug( "{} heartbeat for job {} stream {}", previousHeartbeat == null ? "Created" : "Updated", this.jobId, streamId ); } private void removeActiveStream(final String streamId) { final Instant previousHeartbeat = this.streamsLastHeartbeatMap.remove(streamId); if (previousHeartbeat != null) { log.debug("Removed job {} stream {}", this.jobId, streamId); } } private boolean hasActiveStreams() { return !this.streamsLastHeartbeatMap.isEmpty(); } private void expungeExpiredStreams(final Instant cutoff) { final boolean removed = this.streamsLastHeartbeatMap.entrySet().removeIf( entry -> entry.getValue().isBefore(cutoff) ); if (removed) { log.debug("Removed expired streams for job {}", this.jobId); } } } }
2,585
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/agent/services/impl/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Default implementations of Agent Services. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.agent.services.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,586
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/introspection/GenieWebRpcInfo.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.introspection; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import javax.validation.constraints.Max; import javax.validation.constraints.Min; /** * Container class for RPC related properties. * * @author tgianos * @since 4.0.0 */ @RequiredArgsConstructor @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class GenieWebRpcInfo { @Min(value = 1, message = "The minimum value for the RPC port is 1") @Max(value = 65_535, message = "The maximum value for the RPC port is 65,535") private final int rpcPort; }
2,587
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/introspection/GenieWebHostInfo.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.introspection; import com.netflix.genie.common.internal.util.GenieHostInfo; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; /** * Extension of {@link GenieHostInfo} which adds metadata specific to the web server. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true, callSuper = true) @ToString(doNotUseGetters = true, callSuper = true) public class GenieWebHostInfo extends GenieHostInfo { /** * Constructor. * * @param hostname The hostname of this Genie web instance */ public GenieWebHostInfo(final String hostname) { super(hostname); } }
2,588
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/introspection/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes related to the web server inspecting or knowing its own state at runtime. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.introspection; import javax.annotation.ParametersAreNonnullByDefault;
2,589
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/JobNotArchivedException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a job is completed but wasn't archived and thus output isn't available. * * @author tgianos * @since 4.0.0 */ public class JobNotArchivedException extends GenieCheckedException { /** * Constructor. */ public JobNotArchivedException() { super(); } /** * Constructor. * * @param message The detail message */ public JobNotArchivedException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public JobNotArchivedException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public JobNotArchivedException(final Throwable cause) { super(cause); } }
2,590
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/PreconditionFailedException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * Exception thrown when a precondition is not met on method invocation. * * @author tgianos * @since 4.0.0 */ public class PreconditionFailedException extends GenieCheckedException { /** * Constructor. */ public PreconditionFailedException() { super(); } /** * Constructor. * * @param message The detail message */ public PreconditionFailedException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public PreconditionFailedException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public PreconditionFailedException(final Throwable cause) { super(cause); } }
2,591
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/IdAlreadyExistsException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * Exception thrown when an resource is attempting to be saved with a unique ID that already exists in the system. * * @author tgianos * @since 4.0.0 */ public class IdAlreadyExistsException extends GenieCheckedException { /** * Constructor. */ public IdAlreadyExistsException() { super(); } /** * Constructor. * * @param message The detail message */ public IdAlreadyExistsException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public IdAlreadyExistsException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public IdAlreadyExistsException(final Throwable cause) { super(cause); } }
2,592
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/JobNotFoundException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a job is not found in the system. * * @author tgianos * @since 4.0.0 */ public class JobNotFoundException extends GenieCheckedException { /** * Constructor. */ public JobNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public JobNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public JobNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public JobNotFoundException(final Throwable cause) { super(cause); } }
2,593
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/ScriptLoadingException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a script cannot be retrieved or compiled. * * @author mprimi * @since 4.0.0 */ public class ScriptLoadingException extends GenieCheckedException { /** * Constructor. */ public ScriptLoadingException() { super(); } /** * Constructor. * * @param message The detail message */ public ScriptLoadingException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public ScriptLoadingException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public ScriptLoadingException(final Throwable cause) { super(cause); } }
2,594
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/ScriptExecutionException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a script bean encounters an error during execution. * * @author mprimi * @since 4.0.0 */ public class ScriptExecutionException extends GenieCheckedException { /** * Constructor. */ public ScriptExecutionException() { super(); } /** * Constructor. * * @param message The detail message */ public ScriptExecutionException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public ScriptExecutionException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public ScriptExecutionException(final Throwable cause) { super(cause); } }
2,595
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/AttachmentTooLargeException.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; /** * Exception thrown when the user tries to submit a job whose attachments exceed the limits. * * @author mprimi * @since 4.0.0 */ public class AttachmentTooLargeException extends SaveAttachmentException { /** * Constructor. */ public AttachmentTooLargeException() { super(); } /** * Constructor. * * @param message The detail message */ public AttachmentTooLargeException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public AttachmentTooLargeException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public AttachmentTooLargeException(final Throwable cause) { super(cause); } }
2,596
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/JobDirectoryManifestNotFoundException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a job was archived but the manifest of the archive can't be found in the archive location. * * @author tgianos * @since 4.0.0 */ public class JobDirectoryManifestNotFoundException extends GenieCheckedException { /** * Constructor. */ public JobDirectoryManifestNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public JobDirectoryManifestNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public JobDirectoryManifestNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public JobDirectoryManifestNotFoundException(final Throwable cause) { super(cause); } }
2,597
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/SaveAttachmentException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * Exception thrown when the system tries to save a user attachment to an underlying data store and it fails for * some reason. * * @author tgianos * @since 4.0.0 */ public class SaveAttachmentException extends GenieCheckedException { /** * Constructor. */ public SaveAttachmentException() { super(); } /** * Constructor. * * @param message The detail message */ public SaveAttachmentException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public SaveAttachmentException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public SaveAttachmentException(final Throwable cause) { super(cause); } }
2,598
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/ScriptNotConfiguredException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.exceptions.checked; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a script bean is not configured an thus it cannot be loaded or executed. * * @author mprimi * @since 4.0.0 */ public class ScriptNotConfiguredException extends GenieCheckedException { /** * Constructor. */ public ScriptNotConfiguredException() { super(); } /** * Constructor. * * @param message The detail message */ public ScriptNotConfiguredException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public ScriptNotConfiguredException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public ScriptNotConfiguredException(final Throwable cause) { super(cause); } }
2,599