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/exceptions
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/exceptions/checked/AgentLaunchException.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 for when the server can't launch an agent for whatever reason. * * @author tgianos * @since 4.0.0 */ public class AgentLaunchException extends GenieCheckedException { /** * Constructor. */ public AgentLaunchException() { super(); } /** * Constructor. * * @param message The error message to associate with this exception */ public AgentLaunchException(final String message) { super(message); } /** * Constructor. * * @param cause The root cause of this exception */ public AgentLaunchException(final Throwable cause) { super(cause); } /** * Constructor. * * @param message The error message to associate with this exception * @param cause The root cause of this exception */ public AgentLaunchException(final String message, final Throwable cause) { super(message, cause); } }
2,600
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/ResourceSelectionException.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; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; /** * An exception thrown when a resource selector encounters an unrecoverable error while trying to select a resource * from a collection of possible resources. * * @author tgianos * @since 4.0.0 */ public class ResourceSelectionException extends GenieCheckedException { /** * Constructor. */ public ResourceSelectionException() { super(); } /** * Constructor. * * @param message The detail message */ public ResourceSelectionException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public ResourceSelectionException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public ResourceSelectionException(final Throwable cause) { super(cause); } }
2,601
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/NotFoundException.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 resource is not found in the system. * * @author tgianos * @since 4.0.0 */ public class NotFoundException extends GenieCheckedException { /** * Constructor. */ public NotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public NotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public NotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public NotFoundException(final Throwable cause) { super(cause); } }
2,602
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/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. * */ /** * All checked exceptions specific to the web server. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.exceptions.checked; import javax.annotation.ParametersAreNonnullByDefault;
2,603
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/dtos/JobSubmission.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.dtos; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.dtos.JobRequestMetadata; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.Set; /** * The payload of all gathered information from a user request to run a job via the API. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @SuppressWarnings("FinalClass") public class JobSubmission { @NotNull @Valid private final JobRequest jobRequest; @NotNull @Valid private final JobRequestMetadata jobRequestMetadata; @NotNull private final Set<URI> attachments; private JobSubmission(final Builder builder) { this.jobRequest = builder.bJobRequest; this.jobRequestMetadata = builder.bJobRequestMetadata; this.attachments = ImmutableSet.copyOf(builder.bAttachments); } /** * Builder for {@link JobSubmission} instances. * * @author tgianos * @since 4.0.0 */ public static class Builder { private final JobRequest bJobRequest; private final JobRequestMetadata bJobRequestMetadata; private final Set<URI> bAttachments; /** * Constructor with required parameters. * * @param jobRequest The job request metadata entered by the user * @param jobRequestMetadata The metadata collected by the system about the request */ public Builder(final JobRequest jobRequest, final JobRequestMetadata jobRequestMetadata) { this.bJobRequest = jobRequest; this.bJobRequestMetadata = jobRequestMetadata; this.bAttachments = Sets.newHashSet(); } /** * Set the attachments associated with this submission if there were any. * * @param attachments The attachments {@link URI}s * @return the builder */ public Builder withAttachments(@Nullable final Set<URI> attachments) { this.setAttachments(attachments); return this; } /** * Set the attachments associated with this submission. * * @param attachments The attachments as {@link URI}s * @return the builder */ public Builder withAttachments(final URI... attachments) { this.setAttachments(Arrays.asList(attachments)); return this; } /** * Build an immutable {@link JobSubmission} instance based on the current contents of this builder. * * @return An {@link JobSubmission} instance */ public JobSubmission build() { return new JobSubmission(this); } private void setAttachments(@Nullable final Collection<URI> attachments) { this.bAttachments.clear(); if (attachments != null) { this.bAttachments.addAll(attachments); } } } }
2,604
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/dtos/ResolvedJob.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.dtos; import com.netflix.genie.common.internal.dtos.JobEnvironment; import com.netflix.genie.common.internal.dtos.JobMetadata; import com.netflix.genie.common.internal.dtos.JobSpecification; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * The payload of information representing all the concrete details the system needs to run a job. * * @author tgianos * @since 4.0.0 */ @RequiredArgsConstructor @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @SuppressWarnings("FinalClass") public class ResolvedJob { private final JobSpecification jobSpecification; private final JobEnvironment jobEnvironment; private final JobMetadata jobMetadata; }
2,605
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/dtos/ResourceSelectionResult.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.dtos; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.Optional; /** * A data class for returning the results of an attempted resource selection. * * @param <R> The resource type this selection result is for * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @SuppressWarnings("FinalClass") public class ResourceSelectionResult<R> { private final Class<?> selectorClass; private final R selectedResource; private final String selectionRationale; private ResourceSelectionResult(final Builder<R> builder) { this.selectorClass = builder.bSelectorClass; this.selectedResource = builder.bSelectedResource; this.selectionRationale = builder.bSelectionRationale; } /** * Get the selected resource if there was one. * * @return The selected resource wrapped in {@link Optional} else {@link Optional#empty()} */ public Optional<R> getSelectedResource() { return Optional.ofNullable(this.selectedResource); } /** * Return any rationale as to why this resource was selected or why no resource was selected if that was the case. * * @return Any provided rationale or {@link Optional#empty()} */ public Optional<String> getSelectionRationale() { return Optional.ofNullable(this.selectionRationale); } /** * A builder for {@link ResourceSelectionResult} instances. * * @param <R> The type of the selected resource * @author tgianos * @since 4.0.0 */ public static class Builder<R> { private final Class<?> bSelectorClass; private R bSelectedResource; private String bSelectionRationale; /** * Constructor. * * @param selectorClass The class that generated this result */ public Builder(final Class<?> selectorClass) { this.bSelectorClass = selectorClass; } /** * Set the resource that was selected by this selector if any. * * @param selectedResource The selected resource or {@literal null} * @return the builder instance */ public Builder<R> withSelectedResource(@Nullable final R selectedResource) { this.bSelectedResource = selectedResource; return this; } /** * Set the rationale for why a resource as or wasn't selected. * * @param selectionRationale The rational or {@literal null} * @return the builder instance */ public Builder<R> withSelectionRationale(@Nullable final String selectionRationale) { this.bSelectionRationale = selectionRationale; return this; } /** * Build a new immutable {@link ResourceSelectionResult} instance out of the current state of this builder. * * @return A new {@link ResourceSelectionResult} instance that is immutable */ public ResourceSelectionResult<R> build() { return new ResourceSelectionResult<>(this); } } }
2,606
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/dtos/ArchivedJobMetadata.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.dtos; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import java.net.URI; /** * A simple POJO for a compound value of related information to a job archived location and files. * * @author tgianos * @since 4.0.0 */ @Getter @AllArgsConstructor @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ArchivedJobMetadata { private final String jobId; private final DirectoryManifest manifest; private final URI archiveBaseUri; }
2,607
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/dtos/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. * */ /** * Immutable DTOs specifically used by the web server. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.dtos; import javax.annotation.ParametersAreNonnullByDefault;
2,608
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/properties/TitusAgentLauncherProperties.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.properties; import com.netflix.genie.web.agent.launchers.impl.TitusAgentLauncherImpl; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Configuration properties for the {@link TitusAgentLauncherImpl}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = TitusAgentLauncherProperties.PREFIX) @Getter @Setter @Validated public class TitusAgentLauncherProperties { /** * Properties prefix. */ public static final String PREFIX = "genie.agent.launcher.titus"; /** * An additional amount of overhead bandwidth that should be added to whatever the job originally requested. */ public static final String ADDITIONAL_BANDWIDTH_PROPERTY = PREFIX + ".additionalBandwidth"; /** * An additional number of CPUs that should be added to whatever the job originally requested. */ public static final String ADDITIONAL_CPU_PROPERTY = PREFIX + ".additionalCPU"; /** * An additional amount of disk space that should be added to whatever the job originally requested. */ public static final String ADDITIONAL_DISK_SIZE_PROPERTY = PREFIX + ".additionalDiskSize"; /** * Any additional environment variables that should be inserted into the container runtime. */ public static final String ADDITIONAL_ENVIRONMENT_PROPERTY = PREFIX + ".additional-environment"; /** * An additional number of GPUs that should be added to whatever the job originally requested. */ public static final String ADDITIONAL_GPU_PROPERTY = PREFIX + ".additionalGPU"; /** * Any additional job attributes that should be added to defaults. */ public static final String ADDITIONAL_JOB_ATTRIBUTES_PROPERTY = PREFIX + ".additional-job-attributes"; /** * An additional amount of memory that should be added to whatever the job originally requested. */ public static final String ADDITIONAL_MEMORY_PROPERTY = PREFIX + ".additionalMemory"; /** * The capacity group to launch Genie containers in Titus with. */ public static final String CAPACITY_GROUP_PROPERTY = PREFIX + ".capacityGroup"; /** * Any attributes that should be added to the request specifically for the container. */ public static final String CONTAINER_ATTRIBUTES_PROPERTY = PREFIX + ".container-attributes"; /** * Name of the property that enables {@link TitusAgentLauncherImpl}. */ public static final String ENABLE_PROPERTY = PREFIX + ".enabled"; /** * The name of the property that dictates which image to launch on Titus with. */ public static final String IMAGE_NAME_PROPERTY = PREFIX + ".imageName"; /** * The name of the property that dictates which image tag to launch on Titus with. */ public static final String IMAGE_TAG_PROPERTY = PREFIX + ".imageTag"; /** * The minimum network bandwidth to allocate to the container. */ public static final String MINIMUM_BANDWIDTH_PROPERTY = PREFIX + ".minimumBandwidth"; /** * The minimum number of CPUs any container should launch with. */ public static final String MINIMUM_CPU_PROPERTY = PREFIX + ".minimumCPU"; /** * The minimum size of the disk volume to attach to the job container. */ public static final String MINIMUM_DISK_SIZE_PROPERTY = PREFIX + ".minimumDiskSize"; /** * The minimum number of GPUs any container should launch with. */ public static final String MINIMUM_GPU_PROPERTY = PREFIX + ".minimumGPU"; /** * The minimum amount of memory a container should be allocated. */ public static final String MINIMUM_MEMORY_PROPERTY = PREFIX + ".minimumMemory"; /** * The number of retries to make on the Titus submission. */ public static final String RETRIES_PROPERTY = PREFIX + ".retries"; /** * The max duration a Titus job is allowed to run after Genie has submitted it. */ public static final String RUNTIME_LIMIT = PREFIX + ".runtimeLimit"; /** * Placeholder for job id for use in entry point expression. */ public static final String JOB_ID_PLACEHOLDER = "<JOB_ID>"; /** * Placeholder for Genie server hostname id for use in entry point expression. */ public static final String SERVER_HOST_PLACEHOLDER = "<SERVER_HOST>"; /** * Placeholder for Genie server port id for use in entry point expression. */ public static final String SERVER_PORT_PLACEHOLDER = "<SERVER_PORT>"; /** * The property containing the Agent image key to look up the corresponding image metadata within. */ public static final String AGENT_IMAGE_KEY_PROPERTY = PREFIX + ".agentImageKey"; /** * The property for titus container network mode. */ public static final String CONTAINER_NETWORK_MODE = PREFIX + ".networkMode"; /** * Whether the Titus Agent Launcher is enabled. */ private boolean enabled; /** * Titus REST endpoint. */ private URI endpoint = URI.create("https://example-titus-endpoint.tld:1234"); /** * The Titus job container entry point. * Placeholder values are substituted before submission */ private List<@NotBlank String> entryPointTemplate = Arrays.asList("/bin/genie-agent"); /** * The Titus job container command array. * Placeholder values are substituted before submission */ private List<@NotBlank String> commandTemplate = Arrays.asList( "exec", "--api-job", "--launchInJobDirectory", "--job-id", JOB_ID_PLACEHOLDER, "--server-host", SERVER_HOST_PLACEHOLDER, "--server-port", SERVER_PORT_PLACEHOLDER ); /** * The Titus job owner. */ @NotEmpty private String ownerEmail = "[email protected]"; /** * The Titus application name. */ @NotEmpty private String applicationName = "genie"; /** * The Titus capacity group. */ @NotEmpty private String capacityGroup = "default"; /** * A map of security attributes. */ @NotNull private Map<String, String> securityAttributes = new HashMap<>(); /** * A list of security groups. */ @NotNull private List<String> securityGroups = new ArrayList<>(); /** * The IAM role. */ @NotEmpty private String iAmRole = "arn:aws:iam::000000000:role/SomeProfile"; /** * The image name. */ @NotEmpty private String imageName = "image-name"; /** * The image tag. */ @NotEmpty private String imageTag = "latest"; /** * The number of retries if the job fails. */ @Min(0) private int retries; /** * The job runtime limit (also applied to the used for disruption budget). */ @DurationMin private Duration runtimeLimit = Duration.ofHours(12); /** * The Genie server hostname for the agent to connect to. */ @NotEmpty private String genieServerHost = "example.genie.tld"; /** * The Genie server port for the agent to connect to. */ @Min(0) private int genieServerPort = 9090; /** * The maximum size of the list of jobs displayed by the health indicator. */ @Min(0) private int healthIndicatorMaxSize = 100; /** * The maximum time a job is retained in the health indicator list. */ @DurationMin private Duration healthIndicatorExpiration = Duration.ofMinutes(30); /** * Additional environment variables to set. */ @NotNull private Map<String, String> additionalEnvironment = new HashMap<>(); /** * The amount of bandwidth to request in addition to the amount requested by the job. */ private DataSize additionalBandwidth = DataSize.ofBytes(0); /** * The amount of CPUs to request in addition to the amount requested by the job. */ @Min(0) private int additionalCPU = 1; /** * The amount of disk space to request in addition to the amount requested by the job. */ private DataSize additionalDiskSize = DataSize.ofGigabytes(1); /** * The amount of GPUs to request in addition to the amount requested by the job. */ @Min(0) private int additionalGPU; /** * The amount of memory to request in addition to the amount requested by the job. */ private DataSize additionalMemory = DataSize.ofGigabytes(2); /** * The minimum amount of bandwidth to request for the container. */ @NotNull private DataSize minimumBandwidth = DataSize.ofMegabytes(7); /** * The minimum amount of CPUs to request for the container. */ @Min(1) private int minimumCPU = 1; /** * The minimum amount of storage to request for the container. */ @NotNull private DataSize minimumDiskSize = DataSize.ofGigabytes(10); /** * The minimum amount of GPUs to request for the container. */ @Min(0) private int minimumGPU; /** * The minimum amount of memory to request for the container. */ @NotNull private DataSize minimumMemory = DataSize.ofGigabytes(4); /** * A map of container attributes. */ @NotNull private Map<String, String> containerAttributes = new HashMap<>(); /** * Additional job attributes. */ @NotNull private Map<String, String> additionalJobAttributes = new HashMap<>(); /** * The stack (jobGroupInfo) within the application space for Titus request. */ private String stack = ""; /** * The detail (jobGroupInfo) within the application space for Titus request. */ private String detail = ""; /** * The sequence (jobGroupInfo) within the application space for Titus request. */ private String sequence = ""; /** * The key within the images block that corresponds to the image housing the Genie agent binary. */ private String agentImageKey = "genieAgent"; }
2,609
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/properties/AgentFilterProperties.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.properties; import com.netflix.genie.web.agent.services.AgentFilterService; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import java.util.concurrent.atomic.AtomicReference; /** * Properties for the {@link AgentFilterService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentFilterProperties.PROPERTY_PREFIX) @Validated public class AgentFilterProperties implements EnvironmentAware { /** * Prefix for the properties that will be bound into this object. */ static final String PROPERTY_PREFIX = "genie.agent.filter"; /** * Property that enables the default implementation of {@link AgentFilterService}. */ public static final String VERSION_FILTER_ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private static final String MINIMUM_VERSION_PROPERTY = PROPERTY_PREFIX + ".version.minimum"; private static final String BLACKLISTED_VERSION_REGEX_PROPERTY = PROPERTY_PREFIX + ".version.blacklist"; private static final String WHITELISTED_VERSION_REGEX_PROPERTY = PROPERTY_PREFIX + ".version.whitelist"; private AtomicReference<Environment> environment = new AtomicReference<>(); /** * {@inheritDoc} */ @Override public void setEnvironment(final Environment environment) { this.environment.set(environment); } /** * Get the (dynamic) property value representing the minimum agent version allowed to connect. * * @return a version string or null if a minimum is not active */ @Nullable public String getMinimumVersion() { return getValueOrNull(MINIMUM_VERSION_PROPERTY); } /** * Get the (dynamic) property value containing a regular expression used to blacklist agent versions. * * @return a string containing a regular expression pattern, or null if one is not set */ @Nullable public String getBlacklistedVersions() { return getValueOrNull(BLACKLISTED_VERSION_REGEX_PROPERTY); } /** * Get the (dynamic) property value containing a regular expression used to whitelist agent versions. * * @return a string containing a regular expression pattern, or null if one is not set */ @Nullable public String getWhitelistedVersions() { return getValueOrNull(WHITELISTED_VERSION_REGEX_PROPERTY); } private String getValueOrNull(final String propertyKey) { final Environment env = this.environment.get(); if (env != null) { return env.getProperty(propertyKey); } return null; } }
2,610
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/properties/HeartBeatProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties related to Heart Beat gRPC Service. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = HeartBeatProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class HeartBeatProperties { /** * Prefix for all properties related to the agent heart beat service. */ public static final String PROPERTY_PREFIX = "genie.agent.heart-beat"; private Duration sendInterval = Duration.ofSeconds(5); }
2,611
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/properties/JobsProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; /** * All properties related to jobs in Genie. * * @author tgianos * @since 3.0.0 */ @Getter @Setter @Validated public class JobsProperties { @Valid private JobsForwardingProperties forwarding; @Valid private JobsLocationsProperties locations; @Valid private JobsMemoryProperties memory; @Valid private JobsUsersProperties users; @Valid private JobsActiveLimitProperties activeLimit; /** * Constructor. * * @param forwarding forwarding properties * @param locations locations properties * @param memory memory properties * @param users users properties * @param activeLimit active limit properties */ public JobsProperties( @Valid final JobsForwardingProperties forwarding, @Valid final JobsLocationsProperties locations, @Valid final JobsMemoryProperties memory, @Valid final JobsUsersProperties users, @Valid final JobsActiveLimitProperties activeLimit ) { this.forwarding = forwarding; this.locations = locations; this.memory = memory; this.users = users; this.activeLimit = activeLimit; } /** * Create a JobsProperties initialized with default values (for use in tests). * * @return a new {@link JobsProperties} instance. */ public static JobsProperties getJobsPropertiesDefaults() { return new JobsProperties( new JobsForwardingProperties(), new JobsLocationsProperties(), new JobsMemoryProperties(), new JobsUsersProperties(), new JobsActiveLimitProperties() ); } }
2,612
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/properties/AgentConfigurationProperties.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.properties; import com.netflix.genie.web.agent.services.AgentConfigurationService; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import java.time.Duration; /** * Properties for {@link AgentConfigurationService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentConfigurationProperties.PREFIX) @Getter @Setter public class AgentConfigurationProperties { /** * Properties prefix. */ static final String PREFIX = "genie.agent.configuration"; /** * The prefix that properties need to match in order to be forwarded to agents during configuration. * The prefix is stripped before forwarding. */ public static final String DYNAMIC_PROPERTIES_PREFIX = PREFIX + ".dynamic."; private Duration cacheRefreshInterval = Duration.ofMinutes(1); }
2,613
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/properties/CommandSelectorManagedScriptProperties.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.properties; import com.netflix.genie.web.scripts.CommandSelectorManagedScript; import com.netflix.genie.web.scripts.ManagedScriptBaseProperties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for {@link CommandSelectorManagedScript}. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = CommandSelectorManagedScriptProperties.PREFIX) public class CommandSelectorManagedScriptProperties extends ManagedScriptBaseProperties { /** * Prefix for this properties class. */ public static final String PREFIX = ManagedScriptBaseProperties.SCRIPTS_PREFIX + ".command-selector"; /** * Name of script source property. */ public static final String SOURCE_PROPERTY = PREFIX + ManagedScriptBaseProperties.SOURCE_PROPERTY_SUFFIX; /** * Prefix for properties passed to the script (with the prefix stripped). */ public static final String SCRIPT_PROPERTIES_PREFIX = "command-selector."; }
2,614
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/properties/ZookeeperProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties related to Zookeeper. * * @author tgianos * @since 3.1.0 */ @ConfigurationProperties(prefix = ZookeeperProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class ZookeeperProperties { /** * The property prefix for this group. */ public static final String PROPERTY_PREFIX = "genie.zookeeper"; /** * The base Zookeeper node path for Genie leadership. */ private String leaderPath = "/genie/leader/"; /** * The base Zookeeper node path for discovery. */ private String discoveryPath = "/genie/agents/"; }
2,615
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/properties/JobsLocationsProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import java.net.URI; /** * Properties for various job related locations. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = JobsLocationsProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class JobsLocationsProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.jobs.locations"; private static final String SYSTEM_TMP_DIR = System.getProperty("java.io.tmpdir", "/tmp/"); @NotNull(message = "Archives storage location is required") private URI archives = URI.create("file://" + (SYSTEM_TMP_DIR.endsWith("/") ? SYSTEM_TMP_DIR : SYSTEM_TMP_DIR + "/") + "genie/archives/"); @NotNull(message = "Default job working directory is required") private URI jobs = URI.create("file://" + (SYSTEM_TMP_DIR.endsWith("/") ? SYSTEM_TMP_DIR : SYSTEM_TMP_DIR + "/") + "genie/jobs/"); }
2,616
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/properties/TasksSchedulerPoolProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; /** * Properties related to the thread pool for the task executor within Genie. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = TasksSchedulerPoolProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class TasksSchedulerPoolProperties { /** * The property prefix for this group. */ public static final String PROPERTY_PREFIX = "genie.tasks.scheduler.pool"; /** * The number of threads desired for this system. Likely best to do one more than number of CPUs. */ @Min(1) private int size = 2; /** * The prefix for the name of the threads in this pool. */ @NotBlank(message = "A thread prefix name is required") private String threadNamePrefix = "genie-task-scheduler-"; }
2,617
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/properties/SNSNotificationsProperties.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.properties; import com.google.common.collect.Maps; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import java.util.Map; /** * Properties to configure notification delivered via SNS. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = SNSNotificationsProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class SNSNotificationsProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.notifications.sns"; /** * The property that determines if the SNS publishing is enabled. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled; private String topicARN; private Map<String, String> additionalEventKeys = Maps.newHashMap(); }
2,618
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/properties/AgentFileStreamProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties related to {@link com.netflix.genie.web.agent.services.AgentFileStreamService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentFileStreamProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class AgentFileStreamProperties { /** * Prefix for all properties related to the agent file transfer service. */ public static final String PROPERTY_PREFIX = "genie.agent.filestream"; /** * How many active transfer to allow. */ private int maxConcurrentTransfers = 100; /** * How long to wait for the first chunk of data to be received before timing out. */ private Duration unclaimedStreamStartTimeout = Duration.ofSeconds(10); /** * Time allowed to a transfer to make progress before it's marked as stalled and terminated. */ private Duration stalledTransferTimeout = Duration.ofSeconds(20); /** * How often to check on transfer in progress (and terminate the ones that did not make progress). */ private Duration stalledTransferCheckInterval = Duration.ofSeconds(5); /** * How long to wait before retrying to append a chunk of data into a stream buffer. */ private Duration writeRetryDelay = Duration.ofMillis(300); /** * How long to store a manifest before considering it stale and evicting it. */ private Duration manifestCacheExpiration = Duration.ofSeconds(30); }
2,619
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/properties/AgentLauncherSelectorScriptProperties.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.properties; import com.netflix.genie.web.scripts.ManagedScriptBaseProperties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for agent launcher selection via script. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentLauncherSelectorScriptProperties.PREFIX) public class AgentLauncherSelectorScriptProperties extends ManagedScriptBaseProperties { /** * Prefix for this properties class. */ public static final String PREFIX = ManagedScriptBaseProperties.SCRIPTS_PREFIX + ".agent-launcher-selector"; /** * Name of script source property. */ public static final String SOURCE_PROPERTY = PREFIX + ManagedScriptBaseProperties.SOURCE_PROPERTY_SUFFIX; /** * Prefix for properties passed to the script (with the prefix stripped). */ public static final String SCRIPT_PROPERTIES_PREFIX = "agent-launcher-selector."; }
2,620
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/properties/HealthProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * All properties related to health thresholds in Genie. * * @author amajumdar * @since 3.0.0 */ @ConfigurationProperties(prefix = HealthProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class HealthProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.health"; /** * Defines the threshold for the maximum CPU load percentage. Health of the system is marked OUT_OF_SERVICE if * the CPU load of a system goes beyond this threshold for <code>maxCpuLoadConsecutiveOccurrences</code> * consecutive times. * Default to 80 percentage. */ private double maxCpuLoadPercent = 80; /** * Defines the threshold of consecutive occurrences of CPU load crossing the <code>maxCpuLoadPercent</code>. * Health of the system is marked OUT_OF_SERVICE if the CPU load of a system goes beyond the threshold * <code>maxCpuLoadPercent</code> for <code>maxCpuLoadConsecutiveOccurrences</code> consecutive times. * Default to 3. */ private int maxCpuLoadConsecutiveOccurrences = 3; }
2,621
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/properties/ScriptManagerProperties.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.properties; import com.netflix.genie.web.scripts.ScriptManager; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for {@link ScriptManager}. */ @Getter @Setter @ConfigurationProperties(prefix = ScriptManagerProperties.PREFIX) public class ScriptManagerProperties { /** * Properties prefix. */ public static final String PREFIX = "genie.scripts-manager"; private long refreshInterval = 300_000L; }
2,622
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/properties/LocalAgentLauncherProperties.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.properties; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import java.time.Duration; import java.util.List; import java.util.Map; /** * Properties related to launching Agent processes locally. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = LocalAgentLauncherProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class LocalAgentLauncherProperties { /** * Prefix for all properties related to the local agent launcher. */ public static final String PROPERTY_PREFIX = "genie.agent.launcher.local"; /** * Name of the property that enables/disables the launcher. */ public static final String ENABLE_PROPERTY = PROPERTY_PREFIX + ".enabled"; /** * Placeholder for server hostname in command-line-template. */ public static final String SERVER_HOST_PLACEHOLDER = "<SERVER_HOST_PLACEHOLDER>"; /** * Placeholder for server port in command-line-template. */ public static final String SERVER_PORT_PLACEHOLDER = "<SERVER_PORT_PLACEHOLDER>"; /** * Placeholder for job id in command-line-template. */ public static final String JOB_ID_PLACEHOLDER = "<JOB_ID_PLACEHOLDER>"; /** * Placeholder for agent jar path in command-line-template. */ public static final String AGENT_JAR_PLACEHOLDER = "<AGENT_JAR_PLACEHOLDER>"; /** * Property that enables or disables the launcher. */ private boolean enabled = true; /** * The command that should be run to execute the Genie agent. Required. */ @SuppressWarnings("PMD.AvoidUsingHardCodedIP") @NotEmpty(message = "The command-line launch template cannot be empty") private List<@NotBlank String> launchCommandTemplate = Lists.newArrayList( "java", "-jar", AGENT_JAR_PLACEHOLDER, "exec", "--server-host", SERVER_HOST_PLACEHOLDER, "--server-port", SERVER_PORT_PLACEHOLDER, "--api-job", "--job-id", JOB_ID_PLACEHOLDER ); /** * The path to the agent jar. */ @NotEmpty(message = "The agent jar path cannot be empty") private String agentJarPath = "/tmp/genie-agent.jar"; /** * Additional environment variables set for the agent. */ private Map<@NotEmpty String, String> additionalEnvironment = Maps.newHashMap(); /** * Capturing the agent stdout and stderr streams to file for debugging purposes. */ private boolean processOutputCaptureEnabled; /** * Defaults to 10 GB (10,240 MB). */ @Min(value = 1, message = "The minimum value is 1MB but the value should likely be much higher") private long maxJobMemory = 10_240; /** * Default to 30 GB (30,720 MB). */ @Min(value = 1L, message = "The minimum value is 1MB but the value should likely be set much higher") private long maxTotalJobMemory = 30_720L; /** * Launch agent as the user in the job request (launches as the server user if false). */ private boolean runAsUserEnabled; /** * How long after the job information for this host is written into a local cache is it evicted. * <p> * Should be higher than {@link #getHostInfoRefreshAfter()}. */ private Duration hostInfoExpireAfter = Duration.ofMinutes(1L); /** * How long after the job information for this host is written should it be automatically refreshed from * the underlying data source. * <p> * Should be lower than {@link #getHostInfoExpireAfter()}. */ private Duration hostInfoRefreshAfter = Duration.ofSeconds(30L); /** * Genie server hostname to connect to. Only used if the command-line template references a placeholder for this * value. */ private String serverHostname = "127.0.0.1"; }
2,623
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/properties/AgentRoutingServiceProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import java.time.Duration; /** * Properties for {@link com.netflix.genie.web.agent.services.AgentRoutingService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentRoutingServiceProperties.PREFIX) @Getter @Setter public class AgentRoutingServiceProperties { /** * Properties prefix. */ static final String PREFIX = "genie.agent.routing"; private Duration refreshInterval = Duration.ofSeconds(3); }
2,624
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/properties/GRpcServerProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties related to Genie's gRPC server functionality. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = GRpcServerProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class GRpcServerProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.grpc.server"; /** * The property key to enable or disable gRPC services on the server. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled; }
2,625
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/properties/JobResolutionProperties.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.web.properties; import com.netflix.genie.common.internal.dtos.ComputeResources; import com.netflix.genie.common.internal.dtos.Image; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Properties related to the job resolution process. If loaded as a Spring bean this class with auto refresh its * contents. * * @author tgianos * @since 4.3.0 */ @Validated public class JobResolutionProperties { private static final Logger LOG = LoggerFactory.getLogger(JobResolutionProperties.class); private static final String PROPERTY_PREFIX = "genie.services.resolution"; private static final int MB_TO_MBIT = 8; private static final String DEFAULTS_PROPERTY_PREFIX = PROPERTY_PREFIX + ".defaults"; private static final String RUNTIME_DEFAULTS_PROPERTY_PREFIX = DEFAULTS_PROPERTY_PREFIX + ".runtime"; private static final Bindable<Runtime> RUNTIME_BINDABLE = Bindable.of(Runtime.class); private final Binder binder; private ComputeResources defaultComputeResources; private Map<String, Image> defaultImages; /** * Constructor. * * @param environment The spring environment */ public JobResolutionProperties(final Environment environment) { this.binder = Binder.get(environment); this.defaultComputeResources = new ComputeResources.Builder().build(); this.defaultImages = new HashMap<>(); this.refresh(); } /** * Get the default {@link ComputeResources} if any were defined. * * @return The current default {@link ComputeResources} values */ public ComputeResources getDefaultComputeResources() { return this.defaultComputeResources; } /** * Get the default mapping of images. * * @return The map of image {@literal key} to {@link Image} values */ public Map<String, Image> getDefaultImages() { return this.defaultImages; } /** * Refresh the values of the properties contained within this object. */ @Scheduled(fixedRate = 30L, timeUnit = TimeUnit.SECONDS) public void refresh() { LOG.debug("Refreshing job resolution properties"); final Runtime defaultRuntime = this.binder.bindOrCreate(RUNTIME_DEFAULTS_PROPERTY_PREFIX, RUNTIME_BINDABLE); final Resources resources = defaultRuntime.getResources(); this.defaultComputeResources = new ComputeResources.Builder() .withCpu(resources.getCpu()) .withGpu(resources.getGpu()) .withMemoryMb(resources.getMemory().toMegabytes()) .withDiskMb(resources.getDisk().toMegabytes()) .withNetworkMbps(resources.getNetwork().toMegabytes() * MB_TO_MBIT) .build(); this.defaultImages = defaultRuntime .getImages() .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> { final DefaultImage defaultImage = entry.getValue(); final Image.Builder builder = new Image.Builder(); defaultImage.getName().ifPresent(builder::withName); defaultImage.getTag().ifPresent(builder::withTag); builder.withArguments(defaultImage.getArguments()); return builder.build(); } ) ); LOG.debug( "Completed refresh of job resolution properties. New resource values = {}, new image values = {}", this.defaultComputeResources, this.defaultImages ); } /** * Container for the runtime defaults set in properties. */ public static class Runtime { private Resources resources; private final Map<String, DefaultImage> images; /** * Constructor. */ public Runtime() { this.resources = new Resources(); this.images = new HashMap<>(); } /** * Get the {@link Resources}. * * @return The resources defined by default */ public Resources getResources() { return this.resources; } /** * Set the new resources or fall back to default. * * @param resources The new resource or {@literal null} to reset to default. */ public void setResources(@Nullable final Resources resources) { this.resources = resources == null ? new Resources() : resources; } /** * The map of image key to image definitions. * * @return The images */ public Map<String, DefaultImage> getImages() { return images; } /** * Set the new default image mappings. * * @param images The new mappings or if {@literal null} empty the set of mappings */ public void setImages(@Nullable final Map<String, DefaultImage> images) { this.images.clear(); if (images != null) { this.images.putAll(images); } } } /** * Computation resource properties. */ public static class Resources { private static final int DEFAULT_CPU = 1; private static final int DEFAULT_GPU = 0; private static final DataSize DEFAULT_MEMORY = DataSize.ofMegabytes(1_500L); private static final DataSize DEFAULT_DISK = DataSize.ofGigabytes(10L); private static final DataSize DEFAULT_NETWORK = DataSize.ofMegabytes(1_250L); // 10000 mbps /** * The default number of CPUs that should be allocated to a job if no other value was requested. Min 1. */ @Min(1) private int cpu = DEFAULT_CPU; /** * The default number of GPUs that should be allocated to a job if no other value was requested. Min 0. */ @Min(0) private int gpu = DEFAULT_GPU; /** * The amount of memory that should be allocated to a job if no other value was requested. */ @NotNull private DataSize memory = DEFAULT_MEMORY; /** * The amount of disk space that should be allocated to a job if no other value was requested. */ @NotNull private DataSize disk = DEFAULT_DISK; /** * The amount of network bandwidth that should be allocated to a job if no other value was requested. Will be * converted to Mbps. */ @NotNull private DataSize network = DEFAULT_NETWORK; /** * Get the default number of CPUs. * * @return The default number of CPUs */ public int getCpu() { return this.cpu; } /** * Set the new default CPU value. * * @param cpu The cpu value or {@literal null} */ public void setCpu(@Min(1) @Nullable final Integer cpu) { this.cpu = cpu == null ? DEFAULT_CPU : cpu; } /** * Get the number of GPUs. * * @return The number of GPUs. */ public int getGpu() { return this.gpu; } /** * Set the new default amount of GPUs. * * @param gpu The new number of GPUs or {@literal null} to set back to default */ public void setGpu(@Min(0) @Nullable final Integer gpu) { this.gpu = gpu == null ? DEFAULT_GPU : gpu; } /** * Get the default amount of memory. * * @return The amount of memory as a {@link DataSize} instance */ public DataSize getMemory() { return this.memory; } /** * Set the default amount of memory for the job runtime. * * @param memory The new amount of memory or {@literal null} to reset to default */ public void setMemory(@Nullable final DataSize memory) { this.memory = memory == null ? DEFAULT_MEMORY : memory; } /** * Get the amount of disk space to allocate for the job. * * @return The disk space as {@link DataSize} instance */ public DataSize getDisk() { return this.disk; } /** * Set the new disk size. * * @param disk The new disk size or {@literal null} to set back to default */ public void setDisk(@Nullable final DataSize disk) { this.disk = disk == null ? DEFAULT_DISK : disk; } /** * Get the network bandwidth that should be allocated for the job. * * @return The network bandwidth as a {@link DataSize} instance that should be converted to something like * {@literal Mbps} */ public DataSize getNetwork() { return this.network; } /** * Set the new network bandwidth default for jobs. * * @param network The new default or if {@literal null} revert to hardcoded default */ public void setNetwork(@Nullable final DataSize network) { this.network = network == null ? DEFAULT_NETWORK : network; } } /** * Defaults for container images that will combine together to execute the Genie job. */ public static class DefaultImage { private String name; private String tag; private final List<String> arguments; /** * Constructor. */ public DefaultImage() { this.arguments = new ArrayList<>(); } /** * Get the name of the image if one was set. * * @return The name or {@link Optional#empty()} */ public Optional<String> getName() { return Optional.ofNullable(this.name); } /** * Set the new name of the image. * * @param name The name or {@literal null} */ public void setName(@Nullable final String name) { this.name = name; } /** * Get the tag for the image that should be used if one was set. * * @return The tag or {@link Optional#empty()} */ public Optional<String> getTag() { return Optional.ofNullable(this.tag); } /** * Set the new tag for the image. * * @param tag The tag or {@literal null} */ public void setTag(@Nullable final String tag) { this.tag = tag; } /** * Get the list of arguments that should be used when launching the image. * * @return The list of arguments as unmodifiable list. Attempts to modify will throw exception. */ public List<String> getArguments() { return Collections.unmodifiableList(this.arguments); } /** * Set the arguments for the image. * * @param arguments The new arguments. {@literal null} will set the arguments to an empty list. */ public void setArguments(@Nullable final List<String> arguments) { this.arguments.clear(); if (arguments != null) { this.arguments.addAll(arguments); } } } }
2,626
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/properties/UserMetricsProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties related to publishing of user metrics. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = UserMetricsProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class UserMetricsProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.tasks.user-metrics"; /** * The property that determines if the {@link com.netflix.genie.web.tasks.leader.UserMetricsTask} is enabled. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled = true; private long refreshInterval = 30_000; }
2,627
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/properties/TasksExecutorPoolProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; /** * Properties related to the thread pool for the task executor within Genie. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = TasksExecutorPoolProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class TasksExecutorPoolProperties { /** * The property prefix for this group. */ public static final String PROPERTY_PREFIX = "genie.tasks.executor.pool"; /** * The number of threads desired for this system. Likely best to do one more than number of CPUs. */ @Min(1) private int size = 2; /** * The name prefix to apply to threads from this pool. */ @NotBlank(message = "A thread prefix name is required") private String threadNamePrefix = "genie-task-executor-"; }
2,628
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/properties/HttpProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; /** * Properties related to HTTP client configuration. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = HttpProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class HttpProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.http"; @Valid private Connect connect = new Connect(); @Valid private Read read = new Read(); /** * Connection related properties for HTTP requests. * * @author tgianos * @since 4.0.0 */ @Validated @Getter @Setter public static class Connect { /** * The connection timeout time in milliseconds. */ private int timeout = 2_000; } /** * Read related properties for HTTP requests. * * @author tgianos * @since 4.0.0 */ @Validated @Getter @Setter public static class Read { /** * The read timeout time in milliseconds. */ private int timeout = 10_000; } }
2,629
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/properties/DataServiceRetryProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * All properties related to data service retry template in Genie. * * @author amajumdar * @since 3.0.0 */ @ConfigurationProperties(prefix = DataServiceRetryProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class DataServiceRetryProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.data.service.retry"; /** * Default to 5 retries. */ private int noOfRetries = 5; /** * Default to 100 ms. */ private long initialInterval = 100L; /** * Defaults to 30000 ms. */ private long maxInterval = 30000L; }
2,630
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/properties/AttachmentServiceProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.util.unit.DataSize; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; /** * Properties for the {@link com.netflix.genie.web.services.AttachmentService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AttachmentServiceProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class AttachmentServiceProperties { /** * The property prefix for job user limiting. */ public static final String PROPERTY_PREFIX = "genie.jobs.attachments"; private static final Path SYSTEM_TMP_DIR = Paths.get(System.getProperty("java.io.tmpdir", "/tmp/")); @NotNull(message = "Attachment location prefix is required") private URI locationPrefix = URI.create("file://" + SYSTEM_TMP_DIR.resolve("genie/attachments")); @NotNull(message = "Maximum attachment size is required") private DataSize maxSize = DataSize.ofMegabytes(100); @NotNull(message = "Maximum attachments total size is required") private DataSize maxTotalSize = DataSize.ofMegabytes(150); }
2,631
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/properties/JobsMemoryProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties pertaining to how much memory jobs can use on Genie. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = JobsMemoryProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class JobsMemoryProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.jobs.memory"; /** * Default to 30 GB (30,720 MB). */ private int maxSystemMemory = 30_720; /** * Default to 1.5 GB (1,536 MB). */ private long defaultJobMemory = 1_024L; /** * Defaults to 10 GB (10,240 MB). */ private int maxJobMemory = 10_240; }
2,632
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/properties/ArchiveStatusCleanupProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties related to cleaning up jobs archive status. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = ArchiveStatusCleanupProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class ArchiveStatusCleanupProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.tasks.archive-status-cleanup"; /** * Determines whether the {@link com.netflix.genie.web.tasks.leader.ArchiveStatusCleanupTask} is active. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled = true; private Duration checkInterval = Duration.ofSeconds(10); private Duration gracePeriod = Duration.ofMinutes(2); }
2,633
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/properties/AgentCleanupProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import java.time.Duration; /** * Properties related to cleaning up jobs associated to AWOL/MIA agents. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentCleanupProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class AgentCleanupProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.tasks.agent-cleanup"; /** * The property that determines if the {@link com.netflix.genie.web.tasks.leader.AgentJobCleanupTask} is enabled. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled = true; private Duration refreshInterval = Duration.ofSeconds(10); private Duration reconnectTimeLimit = Duration.ofMinutes(2); private Duration launchTimeLimit = Duration.ofMinutes(4); }
2,634
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/properties/AgentConnectionTrackingServiceProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.time.DurationMin; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; import java.time.Duration; /** * Properties for {@link com.netflix.genie.web.agent.services.AgentConnectionTrackingService}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = AgentConnectionTrackingServiceProperties.PREFIX) @Getter @Setter @Validated public class AgentConnectionTrackingServiceProperties { /** * Properties prefix. */ static final String PREFIX = "genie.agent.connection-tracking"; @NotNull @DurationMin(seconds = 1) private Duration cleanupInterval = Duration.ofSeconds(2); @NotNull @DurationMin(seconds = 1) private Duration connectionExpirationPeriod = Duration.ofSeconds(10); }
2,635
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/properties/DatabaseCleanupProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * Properties controlling the behavior of the database cleanup leadership task. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = DatabaseCleanupProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class DatabaseCleanupProperties { /** * The property prefix for Database Cleanup related tasks. */ public static final String PROPERTY_PREFIX = "genie.tasks.database-cleanup"; /** * The property key for whether this feature is enabled or not. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; /** * The cron expression for when the cleanup task should occur. */ public static final String EXPRESSION_PROPERTY = PROPERTY_PREFIX + ".expression"; /** * The batch size used to iteratively delete unused entities. */ public static final String BATCH_SIZE_PROPERTY = PROPERTY_PREFIX + ".batchSize"; /** * The property key for whether this feature is enabled or not. */ private boolean enabled; /** * The cron expression for when the cleanup task should occur. */ @NotBlank private String expression = "0 0 0 * * *"; /** * The batch size used to iteratively delete unused entities. */ @Min(1) private int batchSize = 10_000; /** * Properties related to cleaning up application records from the database. */ @NotNull private ApplicationDatabaseCleanupProperties applicationCleanup = new ApplicationDatabaseCleanupProperties(); /** * Properties related to cleaning up cluster records from the database. */ @NotNull private ClusterDatabaseCleanupProperties clusterCleanup = new ClusterDatabaseCleanupProperties(); /** * Properties related to cleaning up command records from the database. */ @NotNull private CommandDatabaseCleanupProperties commandCleanup = new CommandDatabaseCleanupProperties(); /** * Properties related to command deactivation. */ @NotNull private CommandDeactivationDatabaseCleanupProperties commandDeactivation = new CommandDeactivationDatabaseCleanupProperties(); /** * Properties related to cleaning up file records from the database. */ @NotNull private FileDatabaseCleanupProperties fileCleanup = new FileDatabaseCleanupProperties(); /** * Properties related to cleaning up job records from the database. */ @NotNull private JobDatabaseCleanupProperties jobCleanup = new JobDatabaseCleanupProperties(); /** * Properties related to cleaning up tag records from the database. */ @NotNull private TagDatabaseCleanupProperties tagCleanup = new TagDatabaseCleanupProperties(); /** * Properties related to cleaning up application records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class ApplicationDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up application records from the database. */ public static final String APPLICATION_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".application-cleanup"; /** * Skip the Applications table when performing database cleanup. */ public static final String SKIP_PROPERTY = APPLICATION_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * Skip the Applications table when performing database cleanup. */ private boolean skip; } /** * Properties related to cleaning up cluster records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class ClusterDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up cluster records from the database. */ public static final String CLUSTER_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".cluster-cleanup"; /** * Skip the Clusters table when performing database cleanup. */ public static final String SKIP_PROPERTY = CLUSTER_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * Skip the Clusters table when performing database cleanup. */ private boolean skip; } /** * Properties related to cleaning up command records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class CommandDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up command records from the database. */ public static final String COMMAND_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".command-cleanup"; /** * Skip the Commands table when performing database cleanup. */ public static final String SKIP_PROPERTY = COMMAND_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * Skip the Commands table when performing database cleanup. */ private boolean skip; } /** * Properties related to setting Commands to INACTIVE status in the database. */ @Getter @Setter @Validated public static class CommandDeactivationDatabaseCleanupProperties { /** * The prefix for all properties related to deactivating commands in the database. */ public static final String COMMAND_DEACTIVATION_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".command-deactivation"; /** * Skip deactivating commands when performing database cleanup. */ public static final String SKIP_PROPERTY = COMMAND_DEACTIVATION_PROPERTY_PREFIX + ".skip"; /** * The number of days before the current cleanup run that a command must have been created in the system to * be considered for deactivation. */ public static final String COMMAND_CREATION_THRESHOLD_PROPERTY = COMMAND_DEACTIVATION_PROPERTY_PREFIX + ".commandCreationThreshold"; /** * Skip deactivating commands when performing database cleanup. */ private boolean skip; /** * The number of days before the current cleanup run that a command must have been created in the system to * be considered for deactivation. */ @Min(1) private int commandCreationThreshold = 60; } /** * Properties related to cleaning up file records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class FileDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up file records from the database. */ public static final String FILE_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".file-cleanup"; /** * Skip the Files table when performing database cleanup. */ public static final String SKIP_PROPERTY = FILE_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * The number of days within current day that the unused files deletion will be running in batch mode. */ public static final String BATCH_DAYS_WITHIN_PROPERTY = FILE_CLEANUP_PROPERTY_PREFIX + ".batchDaysWithin"; /** * The size of the rolling window used to delete unused files, units in hours. */ public static final String ROLLING_WINDOW_HOURS_PROPERTY = FILE_CLEANUP_PROPERTY_PREFIX + ".rollingWindowHours"; /** * Skip the Files table when performing database cleanup. */ private boolean skip; /** * The number of days within current day that the unused files deletion will be running in batch mode. */ @Min(1) private int batchDaysWithin = 30; /** * The size of the rolling window used to delete unused files, units in hours. */ @Min(1) private int rollingWindowHours = 12; } /** * Properties related to cleaning up job records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class JobDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up job records from the database. */ public static final String JOB_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".job-cleanup"; /** * Skip the Jobs table when performing database cleanup. */ public static final String SKIP_PROPERTY = JOB_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * The number of days to retain jobs in the database. */ public static final String JOB_RETENTION_PROPERTY = JOB_CLEANUP_PROPERTY_PREFIX + ".retention"; /** * The number of job records to delete from the database in a single transaction. * Genie will loop and perform multiple transactions until all jobs older than the retention time are deleted. */ public static final String MAX_DELETED_PER_TRANSACTION_PROPERTY = JOB_CLEANUP_PROPERTY_PREFIX + ".maxDeletedPerTransaction"; /** * The page size used within each cleanup transaction to iterate through the job records. */ public static final String PAGE_SIZE_PROPERTY = JOB_CLEANUP_PROPERTY_PREFIX + ".pageSize"; /** * Skip the Jobs table when performing database cleanup. */ private boolean skip; /** * The number of days to retain jobs in the database. */ private int retention = 90; /** * The number of job records to delete from the database in a single transaction. * Genie will loop and perform multiple transactions until all jobs older than the retention time are deleted. */ private int maxDeletedPerTransaction = 1_000; /** * The page size used within each cleanup transaction to iterate through the job records. */ private int pageSize = 1_000; } /** * Properties related to cleaning up tag records from the database. * * @author tgianos * @since 4.0.0 */ @Getter @Setter public static class TagDatabaseCleanupProperties { /** * The prefix for all properties related to cleaning up tag records from the database. */ public static final String TAG_CLEANUP_PROPERTY_PREFIX = DatabaseCleanupProperties.PROPERTY_PREFIX + ".tag-cleanup"; /** * Skip the Tags table when performing database cleanup. */ public static final String SKIP_PROPERTY = TAG_CLEANUP_PROPERTY_PREFIX + ".skip"; /** * Skip the Tags table when performing database cleanup. */ private boolean skip; } }
2,636
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/properties/JobsUsersProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties related to users running jobs. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = JobsUsersProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class JobsUsersProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.jobs.users"; private boolean runAsUserEnabled; }
2,637
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/properties/DiskCleanupProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties controlling the behavior of the database cleanup leadership task. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = DiskCleanupProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class DiskCleanupProperties { /** * The property prefix for Disk Cleanup related tasks. */ public static final String PROPERTY_PREFIX = "genie.tasks.disk-cleanup"; /** * The property key for whether this feature is enabled or not. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled; private String expression = "0 0 0 * * *"; private int retention = 3; }
2,638
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/properties/AwsCredentialsProperties.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.properties; import com.amazonaws.regions.Regions; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; /** * Properties related to AWS credentials for Genie on top of what Spring Cloud AWS provides. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = AwsCredentialsProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class AwsCredentialsProperties { /** * The property prefix for Genie AWS Credentials. */ public static final String PROPERTY_PREFIX = "genie.aws.credentials"; @Nullable private String role; /** * Property bindings for Spring Cloud AWS region specific properties. * <p> * Spring Cloud AWS doesn't come with properties bindings for their properties. So adding this for completeness. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = SpringCloudAwsRegionProperties.PROPERTY_PREFIX) @Validated public static class SpringCloudAwsRegionProperties { /** * The property prefix for Spring Cloud AWS region properties. */ static final String PROPERTY_PREFIX = "cloud.aws.region"; @Getter @Setter private boolean auto; @Getter private Regions region = Regions.US_EAST_1; /** * Get the region. * * @return The region */ public String getStatic() { return this.region.getName(); } /** * Set the static value for the region this instance is running in. * * @param newStatic The new static region value * @throws IllegalArgumentException When {@literal newStatic} can't be parsed by * {@link Regions#fromName(String)} */ public void setStatic(final String newStatic) { this.region = Regions.fromName(newStatic); } } }
2,639
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/properties/LeadershipProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * Properties related to static leadership election configurations. * * @author tgianos * @since 4.0.0 */ @ConfigurationProperties(prefix = LeadershipProperties.PROPERTY_PREFIX) @Validated @Getter @Setter public class LeadershipProperties { /** * The property prefix for genie leadership. */ public static final String PROPERTY_PREFIX = "genie.leader"; /** * The property key for whether this feature is enabled or not. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; /** * Whether this node is the leader within the cluster or not. */ private boolean enabled; }
2,640
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/properties/JobsActiveLimitProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import java.util.concurrent.atomic.AtomicReference; /** * Properties related to number of active jobs per user. * * @author mprimi * @since 3.1.0 */ @ConfigurationProperties(prefix = JobsActiveLimitProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class JobsActiveLimitProperties implements EnvironmentAware { /** * The property prefix for job user limiting. */ public static final String PROPERTY_PREFIX = "genie.jobs.active-limit"; /** * The property key for whether this feature is enabled or not. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; /** * The property key prefix for per-user limit. */ public static final String USER_LIMIT_OVERRIDE_PROPERTY_PREFIX = PROPERTY_PREFIX + ".overrides."; /** * Default value for active user job limit enabled. */ public static final boolean DEFAULT_ENABLED = false; /** * Default value for active user job limit count. */ public static final int DEFAULT_COUNT = 100; private boolean enabled = DEFAULT_ENABLED; @Min(value = 1) private int count = DEFAULT_COUNT; private AtomicReference<Environment> environment = new AtomicReference<>(); /** * Get the maximum number of jobs a user is allowed to run concurrently. * Checks whether the user has a special limit associated, and if not it returns the global default. * * @param user the user name * @return the maximum number of jobs */ public int getUserLimit(final String user) { final Environment env = this.environment.get(); if (env != null) { return env.getProperty( USER_LIMIT_OVERRIDE_PROPERTY_PREFIX + user, Integer.class, this.count ); } return this.count; } /** * {@inheritDoc} */ @Override public void setEnvironment(final Environment environment) { this.environment.set(environment); } }
2,641
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/properties/ClusterSelectorScriptProperties.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.properties; import com.netflix.genie.web.scripts.ManagedScriptBaseProperties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for cluster selection via script. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = ClusterSelectorScriptProperties.PREFIX) public class ClusterSelectorScriptProperties extends ManagedScriptBaseProperties { /** * Prefix for this properties class. */ public static final String PREFIX = ManagedScriptBaseProperties.SCRIPTS_PREFIX + ".cluster-selector"; /** * Name of script source property. */ public static final String SOURCE_PROPERTY = PREFIX + ManagedScriptBaseProperties.SOURCE_PROPERTY_SUFFIX; /** * Prefix for properties passed to the script (with the prefix stripped). */ public static final String SCRIPT_PROPERTIES_PREFIX = "cluster-selector."; }
2,642
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/properties/RetryProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; /** * All properties related to Http retry template in Genie. * * @author amajumdar * @since 3.0.0 */ @ConfigurationProperties(prefix = RetryProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class RetryProperties { /** * The property prefix for all properties in this group. */ public static final String PROPERTY_PREFIX = "genie.retry"; /** * Total number of retries to attempt. * Default to 5 retries. */ @Min(1) private int noOfRetries = 5; /** * Default to 10000 ms. */ @Min(1L) private long initialInterval = 10_000L; /** * Defaults to 60000 ms. */ @Min(1L) @Max(Long.MAX_VALUE) private long maxInterval = 60_000L; @Valid private RetryProperties.ServiceSpecificProperties s3 = new ServiceSpecificProperties(); @Valid private RetryProperties.ServiceSpecificProperties sns = new ServiceSpecificProperties(); /** * Retry properties specific to a particular service. * * @author tgianos * @since 4.0.0 */ @Validated @Getter @Setter public static class ServiceSpecificProperties { @Min(1) private int noOfRetries = 5; } }
2,643
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/properties/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. * */ /** * This package contains classes which represent configuration properties for type binding and simpler usage. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.properties; import javax.annotation.ParametersAreNonnullByDefault;
2,644
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/properties/JobsForwardingProperties.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.properties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; /** * Properties related to job forwarding. * * @author tgianos * @since 3.0.0 */ @ConfigurationProperties(prefix = JobsForwardingProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class JobsForwardingProperties { /** * The property prefix for job forwarding. */ public static final String PROPERTY_PREFIX = "genie.jobs.forwarding"; /** * The property key for whether this feature is enabled or not. */ public static final String ENABLED_PROPERTY = PROPERTY_PREFIX + ".enabled"; private boolean enabled; @NotEmpty(message = "A scheme is required for forwarding") private String scheme = "http"; @Min(value = 1, message = "Port can't be less than one for forwarding") private int port = 8080; }
2,645
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/properties
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/properties/converters/URIPropertyConverter.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.properties.converters; import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; import org.springframework.core.convert.converter.Converter; import java.net.URI; /** * A converter between a String and a {@link URI} to enforce well formatted schema representations of resources. * * @author tgianos * @since 4.0.0 */ @ConfigurationPropertiesBinding public class URIPropertyConverter implements Converter<String, URI> { /** * {@inheritDoc} */ @Override public URI convert(final String source) { final URI uri = URI.create(source); // Make sure we have an absolute URI if (!uri.isAbsolute()) { throw new IllegalArgumentException("The supplied URI (" + source + ") is not absolute"); } return uri; } }
2,646
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/properties
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/properties/converters/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * A package which contains implementations of {@link org.springframework.core.convert.converter.Converter} to convert * between String representations of properties and more complex objects that can be used more effectively * programmatically without spreading such conversion all over the code. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.properties.converters; import javax.annotation.ParametersAreNonnullByDefault;
2,647
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/scripts/ResourceSelectorScriptResult.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.scripts; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.Optional; /** * Class to represent a generic response from a script which selects a resource from a set of resources. * * @param <R> The type of resource that was selected * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @JsonDeserialize(builder = ResourceSelectorScriptResult.Builder.class) @SuppressWarnings("FinalClass") public class ResourceSelectorScriptResult<R> { private final R resource; private final String rationale; private ResourceSelectorScriptResult(final Builder<R> builder) { this.resource = builder.bResource; this.rationale = builder.bRationale; } /** * Get the selected resource if there was one. * * @return The resource wrapped in an {@link Optional} or {@link Optional#empty()} */ public Optional<R> getResource() { return Optional.ofNullable(this.resource); } /** * Get the rationale for the selection decision. * * @return The rationale wrapped in an {@link Optional} or {@link Optional#empty()} */ public Optional<String> getRationale() { return Optional.ofNullable(this.rationale); } /** * A builder for these the results to prevent scripts from having to redo everything based on constructors if * we change parameters. * * @param <R> The type of resource that was selected * @author tgianos * @since 4.0.0 */ public static class Builder<R> { private R bResource; private String bRationale; /** * Set the resource that was selected if any. * * @param resource The resource that was selected or {@literal null} * @return The builder instance */ public Builder<R> withResource(@Nullable final R resource) { this.bResource = resource; return this; } /** * Set the rationale for the selection or lack thereof. * * @param rationale The rationale or {@literal null} if there was none * @return The builder instance */ public Builder<R> withRationale(@Nullable final String rationale) { this.bRationale = rationale; return this; } /** * Build a new instance of a {@link ResourceSelectorScriptResult} based on the contents of this builder. * * @return A new instance of {@link ResourceSelectorScriptResult} */ public ResourceSelectorScriptResult<R> build() { return new ResourceSelectorScriptResult<>(this); } } }
2,648
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/scripts/AgentLauncherSelectorManagedScript.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.scripts; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.agent.launchers.AgentLauncher; import com.netflix.genie.web.exceptions.checked.ResourceSelectionException; import com.netflix.genie.web.properties.AgentLauncherSelectorScriptProperties; import com.netflix.genie.web.selectors.AgentLauncherSelectionContext; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * Extension of {@link ResourceSelectorScript} that delegates selection of a job's agent launcher when more than one * choice is available. See also: {@link com.netflix.genie.web.selectors.AgentLauncherSelector}. * * @author mprimi * @since 4.0.0 */ @Slf4j public class AgentLauncherSelectorManagedScript extends ResourceSelectorScript<AgentLauncher, AgentLauncherSelectionContext> { static final String AGENT_LAUNCHERS_BINDING = "agentLaunchersParameter"; /** * Constructor. * * @param scriptManager script manager * @param properties script manager properties * @param registry meter registry * @param propertyMapCache dynamic properties map cache */ public AgentLauncherSelectorManagedScript( final ScriptManager scriptManager, final AgentLauncherSelectorScriptProperties properties, final MeterRegistry registry, final PropertiesMapCache propertyMapCache ) { super(scriptManager, properties, registry, propertyMapCache); } /** * {@inheritDoc} */ @Override public ResourceSelectorScriptResult<AgentLauncher> selectResource( final AgentLauncherSelectionContext context ) throws ResourceSelectionException { log.debug( "Called to attempt to select agent launcher from {} for job {}", context.getAgentLaunchers(), context.getJobId() ); return super.selectResource(context); } /** * {@inheritDoc} */ @Override protected void addParametersForScript( final Map<String, Object> parameters, final AgentLauncherSelectionContext context ) { super.addParametersForScript(parameters, context); // TODO: Remove once internal scripts migrate to use context directly parameters.put(AGENT_LAUNCHERS_BINDING, context.getAgentLaunchers()); } }
2,649
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/scripts/GroovyScriptUtils.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.scripts; import com.google.common.collect.ImmutableMap; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.web.selectors.AgentLauncherSelectionContext; import com.netflix.genie.web.selectors.ClusterSelectionContext; import com.netflix.genie.web.selectors.CommandSelectionContext; import groovy.lang.Binding; import java.util.Map; import java.util.Set; /** * Utility functions that can be used within Groovy scripts executed from Genie. * * @author tgianos * @since 4.0.0 */ public final class GroovyScriptUtils { private static final Map<String, String> EMPTY_PROPERTIES_MAP = ImmutableMap.of(); private GroovyScriptUtils() { } /** * Given the {@link Binding} that a script has attempt to extract the command selection context. * * @param binding The {@link Binding} for the script * @return The {@link CommandSelectionContext} instance * @throws IllegalArgumentException If there is no context parameter for the script or it is not a * {@link CommandSelectionContext} */ public static CommandSelectionContext getCommandSelectionContext( final Binding binding ) throws IllegalArgumentException { return getObjectVariable(binding, ResourceSelectorScript.CONTEXT_BINDING, CommandSelectionContext.class); } /** * Given the {@link Binding} that a script has attempt to extract the cluster selection context. * * @param binding The {@link Binding} for the script * @return The {@link ClusterSelectionContext} instance * @throws IllegalArgumentException If there is no context parameter for the script or it is not a * {@link ClusterSelectionContext} */ public static ClusterSelectionContext getClusterSelectionContext( final Binding binding ) throws IllegalArgumentException { return getObjectVariable(binding, ResourceSelectorScript.CONTEXT_BINDING, ClusterSelectionContext.class); } /** * Given the {@link Binding} that a script has attempt to extract the cluster selection context. * * @param binding The {@link Binding} for the script * @return The {@link ClusterSelectionContext} instance * @throws IllegalArgumentException If there is no context parameter for the script or it is not a * {@link ClusterSelectionContext} */ public static AgentLauncherSelectionContext getAgentLauncherSelectionContext( final Binding binding ) throws IllegalArgumentException { return getObjectVariable(binding, ResourceSelectorScript.CONTEXT_BINDING, AgentLauncherSelectionContext.class); } /** * Given the {@link Binding} that a script has attempt to extract the properties map. * * @param binding The {@link Binding} for the script * @return The map of properties */ @SuppressWarnings("unchecked") // Due to cast of Map to Map<String, String> public static Map<String, String> getProperties( final Binding binding ) { try { if (binding.hasVariable(ResourceSelectorScript.PROPERTIES_MAP_BINDING)) { return (Map<String, String>) binding.getVariable(ResourceSelectorScript.PROPERTIES_MAP_BINDING); } } catch (ClassCastException e) { // Value bound is not Map<String, String> -- should never happen } // Properties not bound -- should never happen return EMPTY_PROPERTIES_MAP; } /** * Given the {@link Binding} that a script has attempt to extract the clusters parameter. * * @param binding The {@link Binding} of the script * @return The set of {@link Cluster}'s * @throws IllegalArgumentException If there is no clusters parameter, it isn't a set, is empty or doesn't contain * all {@link Cluster} instances * @deprecated Use {@link #getClusterSelectionContext(Binding)} or {@link #getCommandSelectionContext(Binding)} * instead */ @Deprecated public static Set<Cluster> getClusters(final Binding binding) throws IllegalArgumentException { return getSetVariable(binding, ClusterSelectorManagedScript.CLUSTERS_BINDING, Cluster.class); } /** * Given the {@link Binding} that a script has attempt to extract the commands parameter. * * @param binding The {@link Binding} of the script * @return The set of {@link Command}'s * @throws IllegalArgumentException If there is no commands parameter, it isn't a set, is empty or doesn't contain * all {@link Command} instances * @deprecated Use {@link #getClusterSelectionContext(Binding)} or {@link #getCommandSelectionContext(Binding)} * instead */ @Deprecated public static Set<Command> getCommands(final Binding binding) throws IllegalArgumentException { return getSetVariable(binding, CommandSelectorManagedScript.COMMANDS_BINDING, Command.class); } @SuppressWarnings("unchecked") private static <R> R getObjectVariable( final Binding binding, final String variableName, final Class<R> expectedType ) { if (!binding.hasVariable(variableName) || !(binding.getVariable(variableName).getClass().isAssignableFrom(expectedType))) { throw new IllegalArgumentException(variableName + " argument not instance of " + expectedType.getName()); } return (R) binding.getVariable(variableName); } @SuppressWarnings("unchecked") private static <R> Set<R> getSetVariable( final Binding binding, final String bindingName, final Class<R> expectedType ) { if (!binding.hasVariable(bindingName) || !(binding.getVariable(bindingName) instanceof Set<?>)) { throw new IllegalArgumentException( "Expected " + bindingName + " to be instance of Set<" + expectedType.getName() + ">" ); } final Set<?> set = (Set<?>) binding.getVariable(bindingName); if (set.isEmpty() || !set.stream().allMatch(expectedType::isInstance)) { throw new IllegalArgumentException( "Expected " + bindingName + " to be non-empty set of " + expectedType.getName() ); } return (Set<R>) set; } }
2,650
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/scripts/ManagedScriptBaseProperties.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.scripts; import lombok.Getter; import lombok.Setter; import org.springframework.validation.annotation.Validated; import javax.annotation.Nullable; import java.net.URI; import java.time.Duration; /** * Base abstract properties for individual script classes to extend. * * @author mprimi * @since 4.0.0 */ @Getter @Setter @Validated public abstract class ManagedScriptBaseProperties { protected static final String SCRIPTS_PREFIX = "genie.scripts"; protected static final String SOURCE_PROPERTY_SUFFIX = ".source"; @Nullable private URI source; private long timeout = 5_000L; private boolean autoLoadEnabled = true; private Duration propertiesRefreshInterval = Duration.ofMinutes(5); }
2,651
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/scripts/ResourceSelectorScript.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.scripts; import com.google.common.collect.Maps; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.exceptions.checked.ResourceSelectionException; import com.netflix.genie.web.exceptions.checked.ScriptExecutionException; import com.netflix.genie.web.exceptions.checked.ScriptNotConfiguredException; import com.netflix.genie.web.selectors.ResourceSelectionContext; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * Interface for defining the contract between the selection of a resource from a set of resources for a given * job request. * * @param <R> The type of resource this script is selecting from * @param <C> The context for resource selection which must extend {@link ResourceSelectionContext} * @author tgianos * @since 4.0.0 */ @Slf4j public class ResourceSelectorScript<R, C extends ResourceSelectionContext<R>> extends ManagedScript { static final String CONTEXT_BINDING = "contextParameter"; static final String PROPERTIES_MAP_BINDING = "propertiesMap"; private final PropertiesMapCache propertiesCache; /** * Constructor. * * @param scriptManager The {@link ScriptManager} instance to use * @param properties The {@link ManagedScriptBaseProperties} instance to use * @param registry The {@link MeterRegistry} instance to use * @param propertyMapCache The {@link PropertiesMapCache} instance to use */ protected ResourceSelectorScript( final ScriptManager scriptManager, final ManagedScriptBaseProperties properties, final MeterRegistry registry, final PropertiesMapCache propertyMapCache ) { super(scriptManager, properties, registry); this.propertiesCache = propertyMapCache; } /** * Given the {@link JobRequest} and an associated set of {@literal resources} which matched the request criteria * invoke the configured script to see if a preferred resource is selected based on the current logic. * * @param context The {@link ResourceSelectionContext} instance containing information about the context for this * selection * @return A {@link ResourceSelectorScriptResult} instance * @throws ResourceSelectionException If an unexpected error occurs during selection */ public ResourceSelectorScriptResult<R> selectResource(final C context) throws ResourceSelectionException { try { final Map<String, Object> parameters = Maps.newHashMap(); parameters.put(PROPERTIES_MAP_BINDING, this.propertiesCache.get()); this.addParametersForScript(parameters, context); final Object evaluationResult = this.evaluateScript(parameters); if (!(evaluationResult instanceof ResourceSelectorScriptResult)) { throw new ResourceSelectionException( "Selector evaluation returned invalid type: " + evaluationResult.getClass().getName() + " expected " + ResourceSelectorScriptResult.class.getName() ); } @SuppressWarnings("unchecked") final ResourceSelectorScriptResult<R> result = (ResourceSelectorScriptResult<R>) evaluationResult; // Validate that the selected resource is actually in the original set if (result.getResource().isPresent() && !context.getResources().contains(result.getResource().get())) { throw new ResourceSelectionException(result.getResource().get() + " is not in original set"); } return result; } catch ( final ScriptExecutionException | ScriptNotConfiguredException | RuntimeException e ) { throw new ResourceSelectionException(e); } } /** * Add any implementation specific parameters to the map of parameters to send to the script. * * @param parameters The existing set of parameters for implementations to add to * @param context The selection context */ protected void addParametersForScript(final Map<String, Object> parameters, final C context) { parameters.put(CONTEXT_BINDING, context); } }
2,652
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/scripts/ScriptManager.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.scripts; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.web.exceptions.checked.ScriptExecutionException; import com.netflix.genie.web.exceptions.checked.ScriptLoadingException; import com.netflix.genie.web.exceptions.checked.ScriptNotConfiguredException; import com.netflix.genie.web.properties.ScriptManagerProperties; import com.netflix.genie.web.util.MetricsConstants; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.scheduling.TaskScheduler; import javax.annotation.concurrent.ThreadSafe; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Utility to load, reload and execute scripts (in whichever format/language supported by {@link ScriptEngine}) via URI * (e.g., local file, classpath, URL). * <p> * N.B.: Scripts must be explicitly registered by calling {@link #manageScript(URI)} in order to be evaluated. * <p> * N.B.: If a compilation or access error is encountered while reloading a previously compiled script, the latest * compiled version is retained, until it can be replaced with a newer one. * * @author mprimi * @since 4.0.0 */ @Slf4j @ThreadSafe public class ScriptManager { private static final String SCRIPT_LOAD_TIMER_NAME = "genie.scripts.load.timer"; private static final String SCRIPT_EVALUATE_TIMER_NAME = "genie.scripts.evaluate.timer"; private final ConcurrentMap<URI, AtomicReference<CompiledScript>> scriptsMap = Maps.newConcurrentMap(); private final ScriptManagerProperties properties; private final TaskScheduler taskScheduler; private final ExecutorService executorService; private final ScriptEngineManager scriptEngineManager; private final ResourceLoader resourceLoader; private final MeterRegistry meterRegistry; /** * Constructor. * * @param properties properties * @param taskScheduler task scheduler * @param executorService executor service * @param scriptEngineManager script engine manager * @param resourceLoader resource loader * @param meterRegistry meter registry */ public ScriptManager( final ScriptManagerProperties properties, final TaskScheduler taskScheduler, final ExecutorService executorService, final ScriptEngineManager scriptEngineManager, final ResourceLoader resourceLoader, final MeterRegistry meterRegistry ) { this.properties = properties; this.taskScheduler = taskScheduler; this.executorService = executorService; this.scriptEngineManager = scriptEngineManager; this.resourceLoader = resourceLoader; this.meterRegistry = meterRegistry; } /** * Start managing the given script, loading it ASAP (asynchronously) and refreshing it periodically. * Because the execution of this task is asynchronous, this method returns immediately and does not surface any * loading errors encountered. * * @param scriptUri the script to load and manage */ public void manageScript(final URI scriptUri) { final AtomicBoolean newKey = new AtomicBoolean(false); final AtomicReference<CompiledScript> compiledScriptReference = this.scriptsMap.computeIfAbsent( scriptUri, (key) -> { newKey.set(true); return new AtomicReference<>(); } ); if (newKey.get()) { this.taskScheduler.scheduleAtFixedRate( new LoadScriptTask( scriptUri, compiledScriptReference, this.scriptEngineManager, this.resourceLoader, this.meterRegistry ), Instant.now(), Duration.ofMillis(this.properties.getRefreshInterval()) ); log.debug("Scheduled periodic refresh task for script: {}", scriptUri); } } /** * Evaluate a given script. * * @param scriptUri the script URI * @param bindings the input parameter bindings * @param timeout the timeout in milliseconds * @return the result of the evaluation * @throws ScriptNotConfiguredException if the script is not loaded (due to invalid URI or compilation errors). * @throws ScriptExecutionException if the script evaluation produces an error */ protected Object evaluateScript( final URI scriptUri, final Bindings bindings, final long timeout ) throws ScriptNotConfiguredException, ScriptExecutionException { final Set<Tag> tags = Sets.newHashSet(); tags.add(Tag.of(MetricsConstants.TagKeys.SCRIPT_URI, scriptUri.toString())); final long start = System.nanoTime(); final CompiledScript compiledScript; try { compiledScript = this.getCompiledScript(scriptUri); } catch (ScriptNotConfiguredException e) { final long durationNano = System.nanoTime() - start; MetricsUtils.addFailureTagsWithException(tags, e); this.meterRegistry.timer( SCRIPT_EVALUATE_TIMER_NAME, tags ).record(durationNano, TimeUnit.NANOSECONDS); throw e; } final ScriptContext scriptContext = new SimpleScriptContext(); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); final Future<Object> taskFuture = this.executorService.submit(() -> compiledScript.eval(scriptContext)); try { final Object evaluationResult = taskFuture.get(timeout, TimeUnit.MILLISECONDS); MetricsUtils.addSuccessTags(tags); return evaluationResult; } catch (TimeoutException | InterruptedException | ExecutionException e) { // On timeout, stop evaluation. In other cases doesn't hurt taskFuture.cancel(true); MetricsUtils.addFailureTagsWithException(tags, e); throw new ScriptExecutionException( "Script evaluation failed: " + scriptUri + ": " + e.getClass().getSimpleName() + ": " + e.getMessage(), e ); } finally { final long durationNano = System.nanoTime() - start; this.meterRegistry.timer( SCRIPT_EVALUATE_TIMER_NAME, tags ).record(durationNano, TimeUnit.NANOSECONDS); } } private CompiledScript getCompiledScript(final URI scriptUri) throws ScriptNotConfiguredException { final AtomicReference<CompiledScript> compiledScriptReference = this.scriptsMap.get(scriptUri); if (compiledScriptReference == null) { throw new ScriptNotConfiguredException("Unknown script: " + scriptUri); } final CompiledScript compiledScript = compiledScriptReference.get(); if (compiledScript == null) { throw new ScriptNotConfiguredException("Script not loaded/compiled: " + scriptUri); } return compiledScript; } boolean isLoaded(final URI scriptUri) { try { getCompiledScript(scriptUri); return true; } catch (ScriptNotConfiguredException e) { return false; } } @Slf4j private static class LoadScriptTask implements Runnable { private final URI scriptUri; private final AtomicReference<CompiledScript> compiledScriptReference; private final ScriptEngineManager scriptEngineManager; private final ResourceLoader resourceLoader; private final MeterRegistry registry; LoadScriptTask( final URI scriptUri, final AtomicReference<CompiledScript> compiledScriptReference, final ScriptEngineManager scriptEngineManager, final ResourceLoader resourceLoader, final MeterRegistry registry ) { this.scriptUri = scriptUri; this.compiledScriptReference = compiledScriptReference; this.scriptEngineManager = scriptEngineManager; this.resourceLoader = resourceLoader; this.registry = registry; } /** * Attempt to load and compile the given script. If successful, stores the resulting {@link CompiledScript} into * the provided reference. * Also records metrics. */ @Override public void run() { final Set<Tag> tags = Sets.newHashSet(); tags.add(Tag.of(MetricsConstants.TagKeys.SCRIPT_URI, this.scriptUri.toString())); final long start = System.nanoTime(); try { final CompiledScript compiledScript = this.loadScript(); this.compiledScriptReference.set(compiledScript); MetricsUtils.addSuccessTags(tags); } catch (ScriptLoadingException e) { log.error("Failed to load script: " + scriptUri, e); MetricsUtils.addFailureTagsWithException(tags, e); } catch (Exception e) { log.error("Error loading script: " + scriptUri, e); MetricsUtils.addFailureTagsWithException(tags, e); } finally { final long durationNano = System.nanoTime() - start; this.registry.timer( SCRIPT_LOAD_TIMER_NAME, tags ).record(durationNano, TimeUnit.NANOSECONDS); } } private CompiledScript loadScript() throws ScriptLoadingException { final String scriptUriString = this.scriptUri.toString(); // Determine the script type by looking at its filename extension (i.e. .js, .groovy, ...) final String scriptExtension = StringUtils.substringAfterLast(this.scriptUri.getPath(), "."); if (StringUtils.isBlank(scriptExtension)) { throw new ScriptLoadingException("Failed to determine file extension: " + scriptUriString); } final Resource scriptResource = this.resourceLoader.getResource(scriptUriString); if (!scriptResource.exists()) { throw new ScriptLoadingException("Script not found: " + scriptUriString); } final ScriptEngine engine = this.scriptEngineManager.getEngineByExtension(scriptExtension); if (engine == null) { throw new ScriptLoadingException( "Script engine for file extension: " + scriptExtension + " not available"); } if (!(engine instanceof Compilable)) { // We want a compilable engine so we can cache the script throw new ScriptLoadingException( "Script engine for file extension: " + scriptExtension + " is not " + Compilable.class.getName() ); } final Compilable compilable = (Compilable) engine; final InputStream scriptInputStream; try { scriptInputStream = scriptResource.getInputStream(); } catch (IOException e) { throw new ScriptLoadingException("Failed to read script", e); } final InputStreamReader reader = new InputStreamReader(scriptInputStream, StandardCharsets.UTF_8); final CompiledScript compiledScript; try { compiledScript = compilable.compile(reader); } catch (final ScriptException e) { throw new ScriptLoadingException("Failed to compile script: " + scriptUriString, e); } log.debug("Successfully compiled: " + scriptUriString); return compiledScript; } } }
2,653
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/scripts/ClusterSelectorManagedScript.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.scripts; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.exceptions.checked.ResourceSelectionException; import com.netflix.genie.web.properties.ClusterSelectorScriptProperties; import com.netflix.genie.web.selectors.ClusterSelectionContext; import com.netflix.genie.web.selectors.ClusterSelector; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * Extension of {@link ResourceSelectorScript} that delegates selection of a job's cluster when more than one choice is * available. See also: {@link ClusterSelector}. * <p> * The contract between the script and the Java code is that the script will be supplied global variables * {@code clusters} and {@code jobRequest} which will be a {@code Set} of {@link Cluster} instances * matching the cluster criteria and the job request that kicked off this evaluation respectively. The code expects the * script to return a {@link ResourceSelectorScriptResult} instance. * * @author mprimi * @since 4.0.0 */ @Slf4j public class ClusterSelectorManagedScript extends ResourceSelectorScript<Cluster, ClusterSelectionContext> { static final String CLUSTERS_BINDING = "clustersParameter"; /** * Constructor. * * @param scriptManager script manager * @param properties script manager properties * @param registry meter registry * @param propertyMapCache dynamic properties map cache */ public ClusterSelectorManagedScript( final ScriptManager scriptManager, final ClusterSelectorScriptProperties properties, final MeterRegistry registry, final PropertiesMapCache propertyMapCache ) { super(scriptManager, properties, registry, propertyMapCache); } /** * {@inheritDoc} */ @Override public ResourceSelectorScriptResult<Cluster> selectResource( final ClusterSelectionContext context ) throws ResourceSelectionException { log.debug( "Called to attempt to select a cluster from {} for job {}", context.getClusters(), context.getJobId() ); return super.selectResource(context); } /** * {@inheritDoc} */ @Override protected void addParametersForScript( final Map<String, Object> parameters, final ClusterSelectionContext context ) { super.addParametersForScript(parameters, context); // TODO: Remove once internal scripts migrate to use context directly parameters.put(CLUSTERS_BINDING, context.getClusters()); } }
2,654
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/scripts/CommandSelectorManagedScript.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.scripts; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.common.internal.util.PropertiesMapCache; import com.netflix.genie.web.exceptions.checked.ResourceSelectionException; import com.netflix.genie.web.properties.CommandSelectorManagedScriptProperties; import com.netflix.genie.web.selectors.CommandSelectionContext; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import java.util.Map; /** * An extension of {@link ResourceSelectorScript} which from a set of commands and the original job request will * attempt to determine the best command to use for execution. * * @author tgianos * @since 4.0.0 */ @Slf4j public class CommandSelectorManagedScript extends ResourceSelectorScript<Command, CommandSelectionContext> { static final String COMMANDS_BINDING = "commandsParameter"; /** * Constructor. * * @param scriptManager The {@link ScriptManager} instance to use * @param properties The {@link CommandSelectorManagedScriptProperties} instance to use * @param registry The {@link MeterRegistry} instance to use * @param propertyMapCache The {@link PropertiesMapCache} instance to use */ public CommandSelectorManagedScript( final ScriptManager scriptManager, final CommandSelectorManagedScriptProperties properties, final MeterRegistry registry, final PropertiesMapCache propertyMapCache ) { super(scriptManager, properties, registry, propertyMapCache); } /** * {@inheritDoc} */ @Override public ResourceSelectorScriptResult<Command> selectResource( final CommandSelectionContext context ) throws ResourceSelectionException { log.debug( "Called to attempt to select a command from {} for job {}", context.getResources(), context.getJobId() ); return super.selectResource(context); } /** * {@inheritDoc} */ @Override protected void addParametersForScript( final Map<String, Object> parameters, final CommandSelectionContext context ) { super.addParametersForScript(parameters, context); // TODO: Remove once internal scripts migrate to use context directly parameters.put(COMMANDS_BINDING, context.getResources()); } }
2,655
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/scripts/ManagedScript.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.scripts; import com.google.common.annotations.VisibleForTesting; import com.netflix.genie.web.exceptions.checked.ScriptExecutionException; import com.netflix.genie.web.exceptions.checked.ScriptNotConfiguredException; import io.micrometer.core.instrument.MeterRegistry; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import javax.script.Bindings; import javax.script.SimpleBindings; import java.net.URI; import java.util.Map; /** * Abstract script class for components that rely on an external script to be loaded and invoked at runtime. * This class makes use of {@link ScriptManager} to execute. * * @author mprimi * @since 4.0.0 */ @Slf4j public abstract class ManagedScript { private final ScriptManager scriptManager; @Getter private final ManagedScriptBaseProperties properties; private final MeterRegistry registry; protected ManagedScript( final ScriptManager scriptManager, final ManagedScriptBaseProperties properties, final MeterRegistry registry ) { this.scriptManager = scriptManager; this.properties = properties; this.registry = registry; } /** * Request the script to be warm and ready for evaluation. * This is a best-effort attempt with no guarantee of success. Furthermore loading may happen asynchronously. */ public void warmUp() { final URI scriptUri = this.properties.getSource(); if (this.properties.isAutoLoadEnabled() && scriptUri != null) { this.scriptManager.manageScript(scriptUri); } } protected Object evaluateScript( final Map<String, Object> scriptParameters ) throws ScriptExecutionException, ScriptNotConfiguredException { final URI scriptUri = this.properties.getSource(); if (scriptUri == null) { throw new ScriptNotConfiguredException("Script source URI not set"); } // NOTE: Avoid the constructor that directly takes the map as it uses it directly as the underlying // implementation and if it's immutable it could cause unexpected side effects not expected by // some implementation. final Bindings bindings = new SimpleBindings(); bindings.putAll(scriptParameters); return this.scriptManager.evaluateScript(scriptUri, bindings, this.properties.getTimeout()); } @VisibleForTesting boolean isReadyToEvaluate() { final URI scriptUri = this.properties.getSource(); return scriptUri != null && this.scriptManager.isLoaded(scriptUri); } }
2,656
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/scripts/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Package for script loaded at runtime to provide custom extensions and behavior. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.scripts; import javax.annotation.ParametersAreNonnullByDefault;
2,657
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/events/GenieEventBusImpl.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.events; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.SimpleApplicationEventMulticaster; import org.springframework.core.ResolvableType; import javax.annotation.Nullable; import java.util.function.Predicate; /** * An event bus implementation for the Genie application to use. * * @author tgianos * @since 3.1.2 */ @Slf4j public class GenieEventBusImpl implements GenieEventBus, ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware { private final SimpleApplicationEventMulticaster syncMulticaster; private final SimpleApplicationEventMulticaster asyncMulticaster; /** * Constructor. * * @param syncEventMulticaster The synchronous task multicaster to use * @param asyncEventMulticaster The asynchronous task multicaster to use */ public GenieEventBusImpl( @NonNull final SimpleApplicationEventMulticaster syncEventMulticaster, @NonNull final SimpleApplicationEventMulticaster asyncEventMulticaster ) { this.syncMulticaster = syncEventMulticaster; this.asyncMulticaster = asyncEventMulticaster; } /** * {@inheritDoc} */ @Override public void publishSynchronousEvent(@NonNull final ApplicationEvent event) { // TODO: Metric here? log.debug("Publishing synchronous event {}", event); this.syncMulticaster.multicastEvent(event); } /** * {@inheritDoc} */ @Override public void publishAsynchronousEvent(@NonNull final ApplicationEvent event) { // TODO: Metric here? log.debug("Publishing asynchronous event {}", event); this.asyncMulticaster.multicastEvent(event); } /** * {@inheritDoc} */ @Override public void addApplicationListener(final ApplicationListener<?> listener) { log.debug("Adding application listener {}", listener); this.syncMulticaster.addApplicationListener(listener); this.asyncMulticaster.addApplicationListener(listener); } /** * {@inheritDoc} */ @Override public void addApplicationListenerBean(final String listenerBeanName) { log.debug("Adding application listener bean with name {}", listenerBeanName); this.syncMulticaster.addApplicationListenerBean(listenerBeanName); this.asyncMulticaster.addApplicationListenerBean(listenerBeanName); } /** * {@inheritDoc} */ @Override public void removeApplicationListener(final ApplicationListener<?> listener) { log.debug("Removing application listener {}", listener); this.syncMulticaster.removeApplicationListener(listener); this.asyncMulticaster.removeApplicationListener(listener); } /** * {@inheritDoc} */ @Override public void removeApplicationListenerBean(final String listenerBeanName) { log.debug("Removing application listener bean with name {}", listenerBeanName); this.syncMulticaster.removeApplicationListenerBean(listenerBeanName); this.asyncMulticaster.removeApplicationListenerBean(listenerBeanName); } /** * {@inheritDoc} */ @Override public void removeApplicationListeners(final Predicate<ApplicationListener<?>> predicate) { log.debug("Removing application listeners matching predicate {}", predicate); this.syncMulticaster.removeApplicationListeners(predicate); this.asyncMulticaster.removeApplicationListeners(predicate); } /** * {@inheritDoc} */ @Override public void removeApplicationListenerBeans(final Predicate<String> predicate) { log.debug("Removing application listener beans matching predicate {}", predicate); this.syncMulticaster.removeApplicationListenerBeans(predicate); this.asyncMulticaster.removeApplicationListenerBeans(predicate); } /** * {@inheritDoc} */ @Override public void removeAllListeners() { log.debug("Removing all application listeners"); this.syncMulticaster.removeAllListeners(); this.asyncMulticaster.removeAllListeners(); } /** * {@inheritDoc} */ @Override public void multicastEvent(final ApplicationEvent event) { // TODO: Metric here? log.debug("Multi-casting event {}", event); this.asyncMulticaster.multicastEvent(event); } /** * {@inheritDoc} */ @Override public void multicastEvent(final ApplicationEvent event, @Nullable final ResolvableType eventType) { // TODO: Metric here? log.debug("Multi-casting event {} of type {}", event, eventType); this.asyncMulticaster.multicastEvent(event, eventType); } /** * {@inheritDoc} */ @Override public void setBeanClassLoader(final ClassLoader classLoader) { this.syncMulticaster.setBeanClassLoader(classLoader); this.asyncMulticaster.setBeanClassLoader(classLoader); } /** * {@inheritDoc} */ @Override public void setBeanFactory(final BeanFactory beanFactory) { this.syncMulticaster.setBeanFactory(beanFactory); this.asyncMulticaster.setBeanFactory(beanFactory); } }
2,658
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/events/GenieEventBus.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.events; import lombok.NonNull; import org.springframework.context.ApplicationEvent; /** * Genie Event Bus interface. * * @author tgianos * @since 3.1.2 */ public interface GenieEventBus { /** * Publish an event in the same thread as the calling thread. * * @param event The event to publish */ void publishSynchronousEvent(@NonNull ApplicationEvent event); /** * Publish an event in a different thread than the calling thread. * * @param event The event to publish */ void publishAsynchronousEvent(@NonNull ApplicationEvent event); }
2,659
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/events/JobStateChangeEvent.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.events; import com.netflix.genie.common.internal.dtos.JobStatus; import lombok.Getter; import lombok.ToString; import org.springframework.context.ApplicationEvent; import javax.annotation.Nullable; /** * Event representing a job status change. * * @author mprimi * @since 4.0.0 */ @Getter @ToString public class JobStateChangeEvent extends ApplicationEvent { private final String jobId; private final JobStatus previousStatus; private final JobStatus newStatus; /** * Constructor. * * @param jobId the job id * @param previousStatus the previous status, or null if the job was just created * @param newStatus the status the job just transitioned to * @param source the event source */ public JobStateChangeEvent( final String jobId, @Nullable final JobStatus previousStatus, final JobStatus newStatus, final Object source ) { super(source); this.jobId = jobId; this.previousStatus = previousStatus; this.newStatus = newStatus; } }
2,660
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/events/JobFinishedSNSPublisher.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.events; import com.amazonaws.services.sns.AmazonSNS; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.common.internal.dtos.FinishedJob; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException; 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.properties.SNSNotificationsProperties; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import java.util.HashMap; import java.util.stream.Collectors; /** * Publishes Amazon SNS notifications with detailed information about each completed job. * * @author mprimi * @since 4.0.0 */ @Slf4j public class JobFinishedSNSPublisher extends AbstractSNSPublisher implements ApplicationListener<JobStateChangeEvent> { private static final char COLON = ':'; private static final String JOB_ID_KEY_NAME = "jobId"; private static final String JOB_VERSION_KEY_NAME = "jobVersion"; private static final String JOB_NAME_KEY_NAME = "jobName"; private static final String JOB_USER_KEY_NAME = "jobUser"; private static final String JOB_DESCRIPTION_KEY_NAME = "jobDescription"; private static final String JOB_METADATA_KEY_NAME = "jobMetadata"; private static final String JOB_TAGS_KEY_NAME = "jobTags"; private static final String JOB_CREATED_TIMESTAMP_KEY_NAME = "jobCreatedTimestamp"; private static final String JOB_CREATED_ISO_TIMESTAMP_KEY_NAME = "jobCreatedIsoTimestamp"; private static final String JOB_STATUS_KEY_NAME = "jobStatus"; private static final String JOB_COMMAND_CRITERION_KEY_NAME = "jobCommandCriterion"; private static final String JOB_CLUSTER_CRITERIA_KEY_NAME = "jobClusterCriteria"; private static final String JOB_STARTED_TIMESTAMP_KEY_NAME = "jobStartedTimestamp"; private static final String JOB_STARTED_ISO_TIMESTAMP_KEY_NAME = "jobStartedIsoTimestamp"; private static final String JOB_GROUPING_KEY_NAME = "jobGrouping"; private static final String JOB_FINISHED_TIMESTAMP_KEY_NAME = "jobFinishedTimestamp"; private static final String JOB_FINISHED_ISO_TIMESTAMP_KEY_NAME = "jobFinishedIsoTimestamp"; private static final String JOB_AGENT_VERSION_KEY_NAME = "jobAgentVersion"; private static final String JOB_GROUPING_INSTANCE_KEY_NAME = "jobGroupingInstance"; private static final String JOB_STATUS_MESSAGE_KEY_NAME = "jobStatusMessage"; private static final String JOB_API_CLIENT_HOSTNAME_KEY_NAME = "jobApiClientHostname"; private static final String JOB_REQUESTED_MEMORY_KEY_NAME = "jobRequestedMemory"; private static final String JOB_AGENT_HOSTNAME_KEY_NAME = "jobAgentHostname"; private static final String JOB_API_CLIENT_USER_AGENT_KEY_NAME = "jobApiClientUserAgent"; private static final String JOB_EXIT_CODE_KEY_NAME = "jobExitCode"; private static final String JOB_NUM_ATTACHMENTS_KEY_NAME = "jobNumAttachments"; private static final String JOB_ARCHIVE_LOCATION_KEY_NAME = "jobArchiveLocation"; private static final String JOB_USED_MEMORY_KEY_NAME = "jobUsedMemory"; private static final String JOB_ARGUMENTS_KEY_NAME = "jobArguments"; private static final String COMMAND_ID_KEY_NAME = "commandId"; private static final String COMMAND_NAME_KEY_NAME = "commandName"; private static final String COMMAND_VERSION_KEY_NAME = "commandVersion"; private static final String COMMAND_DESCRIPTION_KEY_NAME = "commandDescription"; private static final String COMMAND_CREATED_TIMESTAMP_KEY_NAME = "commandCreatedTimestamp"; private static final String COMMAND_CREATED_ISO_TIMESTAMP_KEY_NAME = "commandCreatedIsoTimestamp"; private static final String COMMAND_UPDATED_TIMESTAMP_KEY_NAME = "commandUpdatedTimestamp"; private static final String COMMAND_UPDATED_ISO_TIMESTAMP_KEY_NAME = "commandUpdatedIsoTimestamp"; private static final String COMMAND_EXECUTABLE_KEY_NAME = "commandExecutable"; private static final String CLUSTER_ID_KEY_NAME = "clusterId"; private static final String CLUSTER_NAME_KEY_NAME = "clusterName"; private static final String CLUSTER_VERSION_KEY_NAME = "clusterVersion"; private static final String CLUSTER_DESCRIPTION_KEY_NAME = "clusterDescription"; private static final String CLUSTER_CREATED_TIMESTAMP_KEY_NAME = "clusterCreatedTimestamp"; private static final String CLUSTER_CREATED_ISO_TIMESTAMP_KEY_NAME = "clusterCreatedIsoTimestamp"; private static final String CLUSTER_UPDATED_TIMESTAMP_KEY_NAME = "clusterUpdatedTimestamp"; private static final String CLUSTER_UPDATED_ISO_TIMESTAMP_KEY_NAME = "clusterUpdatedIsoTimestamp"; private static final String APPLICATIONS_KEY_NAME = "applications"; private final PersistenceService persistenceService; /** * Constructor. * * @param snsClient Amazon SNS client * @param properties configuration properties * @param dataServices the {@link DataServices} instance to use * @param registry metrics registry * @param mapper object mapper */ public JobFinishedSNSPublisher( final AmazonSNS snsClient, final SNSNotificationsProperties properties, final DataServices dataServices, final MeterRegistry registry, final ObjectMapper mapper ) { super(properties, registry, snsClient, mapper); this.persistenceService = dataServices.getPersistenceService(); } /** * {@inheritDoc} */ @Override public void onApplicationEvent(final JobStateChangeEvent event) { if (!this.properties.isEnabled()) { // Publishing is disabled return; } final JobStatus jobStatus = event.getNewStatus(); if (!jobStatus.isFinished()) { // Job still in progress. return; } final String jobId = event.getJobId(); final FinishedJob job; try { job = persistenceService.getFinishedJob(jobId); } catch (final NotFoundException | GenieInvalidStatusException e) { log.error("Failed to retrieve finished job: {}", jobId, e); return; } log.debug("Publishing SNS notification for completed job {}", jobId); final HashMap<String, Object> eventDetailsMap = Maps.newHashMap(); eventDetailsMap.put(JOB_ID_KEY_NAME, jobId); eventDetailsMap.put(JOB_NAME_KEY_NAME, job.getName()); eventDetailsMap.put(JOB_USER_KEY_NAME, job.getUser()); eventDetailsMap.put(JOB_VERSION_KEY_NAME, job.getVersion()); eventDetailsMap.put(JOB_DESCRIPTION_KEY_NAME, job.getDescription().orElse(null)); eventDetailsMap.put(JOB_METADATA_KEY_NAME, job.getMetadata().orElse(null)); eventDetailsMap.put(JOB_TAGS_KEY_NAME, job.getTags()); eventDetailsMap.put(JOB_CREATED_TIMESTAMP_KEY_NAME, job.getCreated().toEpochMilli()); eventDetailsMap.put(JOB_CREATED_ISO_TIMESTAMP_KEY_NAME, job.getCreated()); eventDetailsMap.put(JOB_STATUS_KEY_NAME, job.getStatus()); eventDetailsMap.put(JOB_COMMAND_CRITERION_KEY_NAME, job.getCommandCriterion()); eventDetailsMap.put(JOB_CLUSTER_CRITERIA_KEY_NAME, job.getClusterCriteria()); eventDetailsMap.put( JOB_STARTED_TIMESTAMP_KEY_NAME, job.getStarted().isPresent() ? job.getStarted().get().toEpochMilli() : null ); eventDetailsMap.put(JOB_STARTED_ISO_TIMESTAMP_KEY_NAME, job.getStarted().orElse(null)); eventDetailsMap.put( JOB_FINISHED_TIMESTAMP_KEY_NAME, job.getFinished().isPresent() ? job.getFinished().get().toEpochMilli() : null ); eventDetailsMap.put(JOB_FINISHED_ISO_TIMESTAMP_KEY_NAME, job.getFinished().orElse(null)); eventDetailsMap.put(JOB_GROUPING_KEY_NAME, job.getGrouping().orElse(null)); eventDetailsMap.put(JOB_GROUPING_INSTANCE_KEY_NAME, job.getGroupingInstance().orElse(null)); eventDetailsMap.put(JOB_STATUS_MESSAGE_KEY_NAME, job.getStatusMessage().orElse(null)); eventDetailsMap.put(JOB_REQUESTED_MEMORY_KEY_NAME, job.getRequestedMemory().orElse(null)); eventDetailsMap.put(JOB_API_CLIENT_HOSTNAME_KEY_NAME, job.getRequestApiClientHostname().orElse(null)); eventDetailsMap.put(JOB_API_CLIENT_USER_AGENT_KEY_NAME, job.getRequestApiClientUserAgent().orElse(null)); eventDetailsMap.put(JOB_AGENT_HOSTNAME_KEY_NAME, job.getRequestAgentClientHostname().orElse(null)); eventDetailsMap.put(JOB_AGENT_VERSION_KEY_NAME, job.getRequestAgentClientVersion().orElse(null)); eventDetailsMap.put(JOB_NUM_ATTACHMENTS_KEY_NAME, job.getNumAttachments().orElse(null)); eventDetailsMap.put(JOB_EXIT_CODE_KEY_NAME, job.getExitCode().orElse(null)); eventDetailsMap.put(JOB_ARCHIVE_LOCATION_KEY_NAME, job.getArchiveLocation().orElse(null)); eventDetailsMap.put(JOB_USED_MEMORY_KEY_NAME, job.getMemoryUsed().orElse(null)); eventDetailsMap.put(JOB_ARGUMENTS_KEY_NAME, job.getCommandArgs()); if (job.getCommand().isPresent()) { final Command command = job.getCommand().get(); eventDetailsMap.put(COMMAND_ID_KEY_NAME, command.getId()); eventDetailsMap.put(COMMAND_NAME_KEY_NAME, command.getMetadata().getName()); eventDetailsMap.put(COMMAND_VERSION_KEY_NAME, command.getMetadata().getVersion()); eventDetailsMap.put(COMMAND_DESCRIPTION_KEY_NAME, command.getMetadata().getDescription().orElse(null)); eventDetailsMap.put(COMMAND_CREATED_TIMESTAMP_KEY_NAME, command.getCreated().toEpochMilli()); eventDetailsMap.put(COMMAND_CREATED_ISO_TIMESTAMP_KEY_NAME, command.getCreated()); eventDetailsMap.put(COMMAND_UPDATED_TIMESTAMP_KEY_NAME, command.getUpdated().toEpochMilli()); eventDetailsMap.put(COMMAND_UPDATED_ISO_TIMESTAMP_KEY_NAME, command.getUpdated()); eventDetailsMap.put(COMMAND_EXECUTABLE_KEY_NAME, command.getExecutable()); } else { eventDetailsMap.put(COMMAND_ID_KEY_NAME, null); eventDetailsMap.put(COMMAND_NAME_KEY_NAME, null); eventDetailsMap.put(COMMAND_VERSION_KEY_NAME, null); eventDetailsMap.put(COMMAND_DESCRIPTION_KEY_NAME, null); eventDetailsMap.put(COMMAND_CREATED_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(COMMAND_CREATED_ISO_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(COMMAND_UPDATED_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(COMMAND_UPDATED_ISO_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(COMMAND_EXECUTABLE_KEY_NAME, null); } if (job.getCluster().isPresent()) { final Cluster cluster = job.getCluster().get(); eventDetailsMap.put(CLUSTER_ID_KEY_NAME, cluster.getId()); eventDetailsMap.put(CLUSTER_NAME_KEY_NAME, cluster.getMetadata().getName()); eventDetailsMap.put(CLUSTER_VERSION_KEY_NAME, cluster.getMetadata().getVersion()); eventDetailsMap.put(CLUSTER_DESCRIPTION_KEY_NAME, cluster.getMetadata().getDescription().orElse(null)); eventDetailsMap.put(CLUSTER_CREATED_TIMESTAMP_KEY_NAME, cluster.getCreated().toEpochMilli()); eventDetailsMap.put(CLUSTER_CREATED_ISO_TIMESTAMP_KEY_NAME, cluster.getCreated()); eventDetailsMap.put(CLUSTER_UPDATED_TIMESTAMP_KEY_NAME, cluster.getUpdated().toEpochMilli()); eventDetailsMap.put(CLUSTER_UPDATED_ISO_TIMESTAMP_KEY_NAME, cluster.getUpdated()); } else { eventDetailsMap.put(CLUSTER_ID_KEY_NAME, null); eventDetailsMap.put(CLUSTER_NAME_KEY_NAME, null); eventDetailsMap.put(CLUSTER_VERSION_KEY_NAME, null); eventDetailsMap.put(CLUSTER_DESCRIPTION_KEY_NAME, null); eventDetailsMap.put(CLUSTER_CREATED_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(CLUSTER_CREATED_ISO_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(CLUSTER_UPDATED_TIMESTAMP_KEY_NAME, null); eventDetailsMap.put(CLUSTER_UPDATED_ISO_TIMESTAMP_KEY_NAME, null); } eventDetailsMap.put( APPLICATIONS_KEY_NAME, job.getApplications().stream().map( application -> application.getId() + COLON + application.getMetadata().getVersion() ).collect(Collectors.toList()) ); this.publishEvent(EventType.JOB_FINISHED, eventDetailsMap); } }
2,661
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/events/AbstractSNSPublisher.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.events; import com.amazonaws.services.sns.AmazonSNS; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.genie.web.properties.SNSNotificationsProperties; import com.netflix.genie.web.util.MetricsUtils; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Abstract SNS publisher that adds fields common to all payloads, records metrics, etc. * * @author mprimi * @since 4.0.0 */ @Slf4j abstract class AbstractSNSPublisher { private static final String PUBLISH_METRIC_COUNTER_NAME_FORMAT = "genie.notifications.sns.publish.counter"; private static final String EVENT_TYPE_METRIC_TAG_NAME = "type"; private static final String EVENT_TYPE_KEY_NAME = "type"; private static final String EVENT_ID_KEY_NAME = "id"; private static final String EVENT_TIMESTAMP_KEY_NAME = "timestamp"; private static final String EVENT_ISO_TIMESTAMP_KEY_NAME = "isoTimestamp"; private static final String EVENT_DETAILS_KEY_NAME = "details"; protected final SNSNotificationsProperties properties; protected final MeterRegistry registry; private final AmazonSNS snsClient; private final ObjectMapper mapper; /** * Constructor. * * @param properties SNS properties * @param registry metrics registry * @param snsClient SNS client * @param mapper JSON object mapper */ AbstractSNSPublisher( final SNSNotificationsProperties properties, final MeterRegistry registry, final AmazonSNS snsClient, final ObjectMapper mapper ) { this.properties = properties; this.registry = registry; this.snsClient = snsClient; this.mapper = mapper; } protected void publishEvent(final EventType eventType, final HashMap<String, Object> eventDetailsMap) { final String topic = this.properties.getTopicARN(); if (StringUtils.isBlank(topic)) { // Likely a misconfiguration. Emit a warning. log.warn("SNS Notifications enabled, but no topic specified"); return; } final Map<String, Object> eventMap = Maps.newHashMap(); // Add static keys defined in configuration eventMap.putAll(this.properties.getAdditionalEventKeys()); // Add event type, timestamp, event id eventMap.put(EVENT_TYPE_KEY_NAME, eventType.name()); eventMap.put(EVENT_ID_KEY_NAME, UUID.randomUUID().toString()); final Instant timestamp = Instant.now(); eventMap.put(EVENT_TIMESTAMP_KEY_NAME, timestamp.toEpochMilli()); eventMap.put(EVENT_ISO_TIMESTAMP_KEY_NAME, timestamp); // Add event details eventMap.put(EVENT_DETAILS_KEY_NAME, eventDetailsMap); final Set<Tag> metricTags = Sets.newHashSet(eventType.getTypeTag()); try { // Serialize message final String serializedMessage = this.mapper.writeValueAsString(eventMap); // Send message this.snsClient.publish(topic, serializedMessage); log.debug("Published SNS notification (type: {})", eventType.name()); metricTags.addAll(MetricsUtils.newSuccessTagsSet()); } catch (JsonProcessingException | RuntimeException e) { metricTags.addAll(MetricsUtils.newFailureTagsSetForException(e)); log.error("Failed to publish SNS notification", e); } finally { this.registry.counter( PUBLISH_METRIC_COUNTER_NAME_FORMAT, metricTags ).increment(); } } /** * Types of event. */ @Getter(AccessLevel.PROTECTED) protected enum EventType { JOB_STATUS_CHANGE, JOB_FINISHED; private final Tag typeTag = Tag.of(EVENT_TYPE_METRIC_TAG_NAME, this.name()); } }
2,662
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/events/JobNotificationMetricPublisher.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.events; import com.google.common.collect.Sets; import com.netflix.genie.web.util.MetricsConstants; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; /** * Listens to job status changes and publishes metrics. * * @author mprimi * @since 4.0.0 */ @Slf4j public class JobNotificationMetricPublisher implements ApplicationListener<JobStateChangeEvent> { private static final String STATE_TRANSITION_METRIC_NAME = "genie.jobs.notifications.state-transition.counter"; private static final String FINAL_STATE_METRIC_NAME = "genie.jobs.notifications.final-state.counter"; private final MeterRegistry registry; /** * Constructor. * * @param registry metrics registry */ public JobNotificationMetricPublisher(final MeterRegistry registry) { this.registry = registry; } /** * {@inheritDoc} */ @Override public void onApplicationEvent(final JobStateChangeEvent event) { final String fromStateString = event.getPreviousStatus() == null ? "null" : event.getPreviousStatus().name(); final String toStateString = event.getNewStatus().name(); final boolean isFinalState = event.getNewStatus().isFinished(); log.debug( "Job '{}' changed state from {} to {} {}", event.getJobId(), fromStateString, toStateString, isFinalState ? "(final state)" : "" ); // Increment counter for this particular from/to transition this.registry.counter( STATE_TRANSITION_METRIC_NAME, Sets.newHashSet( Tag.of(MetricsConstants.TagKeys.FROM_STATE, fromStateString), Tag.of(MetricsConstants.TagKeys.TO_STATE, toStateString) ) ).increment(); // Increment counter for final state if (isFinalState) { this.registry.counter( FINAL_STATE_METRIC_NAME, MetricsConstants.TagKeys.TO_STATE, toStateString ).increment(); } } }
2,663
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/events/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. * */ /** * Contains all the classes which extend {@link org.springframework.context.ApplicationEvent} for customized events * within Genie. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.events; import javax.annotation.ParametersAreNonnullByDefault;
2,664
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/events/JobStateChangeSNSPublisher.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.events; import com.amazonaws.services.sns.AmazonSNS; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.web.properties.SNSNotificationsProperties; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import java.util.HashMap; /** * Publishes Amazon SNS notifications for fine-grained job state changes. * * @author mprimi * @since 4.0.0 */ @Slf4j public class JobStateChangeSNSPublisher extends AbstractSNSPublisher implements ApplicationListener<JobStateChangeEvent> { private static final String JOB_ID_KEY_NAME = "jobId"; private static final String FROM_STATE_KEY_NAME = "fromState"; private static final String TO_STATE_KEY_NAME = "toState"; /** * Constructor. * * @param snsClient Amazon SNS client * @param properties configuration properties * @param registry metrics registry * @param mapper object mapper */ public JobStateChangeSNSPublisher( final AmazonSNS snsClient, final SNSNotificationsProperties properties, final MeterRegistry registry, final ObjectMapper mapper ) { super(properties, registry, snsClient, mapper); } /** * {@inheritDoc} */ @Override public void onApplicationEvent(final JobStateChangeEvent event) { if (!this.properties.isEnabled()) { // Publishing is disabled return; } final String jobId = event.getJobId(); final JobStatus fromState = event.getPreviousStatus(); final JobStatus toState = event.getNewStatus(); final HashMap<String, Object> eventDetailsMap = Maps.newHashMap(); eventDetailsMap.put(JOB_ID_KEY_NAME, jobId); eventDetailsMap.put(FROM_STATE_KEY_NAME, fromState != null ? fromState.name() : "null"); eventDetailsMap.put(TO_STATE_KEY_NAME, toState.name()); this.publishEvent(EventType.JOB_STATUS_CHANGE, eventDetailsMap); } }
2,665
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/observers/PersistedJobStatusObserver.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.data.observers; import com.netflix.genie.common.internal.dtos.JobStatus; import javax.annotation.Nullable; /** * Interface for an observer that gets notified of job 'status' change after the latter is persisted. * This observer is invoked as callback during data/persistence methods. * It should NOT spend significant time processing. * * @author mprimi * @since 4.0.0 */ public interface PersistedJobStatusObserver { /** * Handle a notification of job status change after the latter was successfully committed to persistent storage. * * @param jobId the job unique id * @param previousStatus the previous job status, or null if this job was just created and persisted * @param currentStatus the job status that was just persisted. Guaranteed to be different than the previous. */ void notify(String jobId, @Nullable JobStatus previousStatus, JobStatus currentStatus); }
2,666
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/observers/PersistedJobStatusObserverImpl.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.data.observers; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.web.events.GenieEventBus; import com.netflix.genie.web.events.JobStateChangeEvent; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; /** * Observer of persisted entities modifications that publishes events on the event bus to be consumed asynchronously by * interested consumers. * * @author mprimi * @since 4.0.0 */ @Slf4j public class PersistedJobStatusObserverImpl implements PersistedJobStatusObserver { private final GenieEventBus genieEventBus; /** * Constructor. * * @param genieEventBus the genie event bus */ public PersistedJobStatusObserverImpl(final GenieEventBus genieEventBus) { this.genieEventBus = genieEventBus; } /** * {@inheritDoc} */ @Override public void notify(final String jobId, @Nullable final JobStatus previousStatus, final JobStatus currentStatus) { final JobStateChangeEvent event = new JobStateChangeEvent(jobId, previousStatus, currentStatus, this); log.debug("Publishing event: {}", event); this.genieEventBus.publishAsynchronousEvent(event); log.info("Job {} status changed from: {} to: {}", jobId, previousStatus, currentStatus); } }
2,667
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/observers/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. * */ /** * Entity observer classes that get notified about transformations applied to entities. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.observers; import javax.annotation.ParametersAreNonnullByDefault;
2,668
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/DataServices.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.data.services; import lombok.AllArgsConstructor; import lombok.Getter; /** * Container class for encapsulating all the various data related services in Genie to ease dependency patterns. * * @author tgianos * @since 4.0.0 */ @AllArgsConstructor @Getter public class DataServices { private final PersistenceService persistenceService; }
2,669
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/PersistenceService.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.data.services; import com.fasterxml.jackson.databind.JsonNode; 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.UserResourcesSummary; import com.netflix.genie.common.dto.search.JobSearchResult; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.Application; import com.netflix.genie.common.internal.dtos.ApplicationRequest; import com.netflix.genie.common.internal.dtos.ApplicationStatus; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.dtos.ClusterRequest; import com.netflix.genie.common.internal.dtos.ClusterStatus; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.common.internal.dtos.CommandRequest; import com.netflix.genie.common.internal.dtos.CommandStatus; import com.netflix.genie.common.internal.dtos.CommonResource; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.common.internal.dtos.FinishedJob; 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.unchecked.GenieInvalidStatusException; import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobAlreadyClaimedException; import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.JobInfoAggregate; 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.exceptions.checked.PreconditionFailedException; import com.netflix.genie.web.services.AttachmentService; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.validation.annotation.Validated; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; /** * Service API for all Genie persistence related operations. * * @author tgianos * @since 4.0.0 */ @Validated public interface PersistenceService { //region Application APIs /** * Save a new application. * * @param applicationRequest The {@link ApplicationRequest} containing the metadata of the application to create * @return The unique id of the application that was created * @throws IdAlreadyExistsException If the ID is already used by another application */ String saveApplication(@Valid ApplicationRequest applicationRequest) throws IdAlreadyExistsException; /** * Get the application metadata for given id. * * @param id unique id for application configuration to get. Not null/empty. * @return The {@link Application} * @throws NotFoundException if no application with {@literal id} exists */ Application getApplication(@NotBlank String id) throws NotFoundException; /** * Find applications which match the given filter criteria. * * @param name Name of the application. Can be null or empty. * @param user The user who created the application. Can be null/empty * @param statuses The statuses of the applications to find. Can be null. * @param tags Tags allocated to this application * @param type The type of the application to find * @param page The page requested for the search results * @return The page of found applications */ Page<Application> findApplications( @Nullable String name, @Nullable String user, @Nullable Set<ApplicationStatus> statuses, @Nullable Set<String> tags, @Nullable String type, Pageable page ); /** * Update an {@link Application}. * * @param id The id of the application to update * @param updateApp Information to update for the application configuration with * @throws NotFoundException If no {@link Application} with {@literal id} exists * @throws PreconditionFailedException If {@literal id} and {@literal updateApp} id don't match */ void updateApplication( @NotBlank String id, @Valid Application updateApp ) throws NotFoundException, PreconditionFailedException; /** * Delete all applications from the system. * * @throws PreconditionFailedException When any {@link Application} is still associated with a command */ void deleteAllApplications() throws PreconditionFailedException; /** * Delete an {@link Application} from the system. * * @param id unique id of the application to delete * @throws PreconditionFailedException When the {@link Application} is still used by any command */ void deleteApplication(@NotBlank String id) throws PreconditionFailedException; /** * Get all the commands the application with given id is associated with. * * @param id The id of the application to get the commands for. * @param statuses The desired status(es) to filter the associated commands for * @return The commands the application is used by * @throws NotFoundException If no {@link Application} with {@literal id} exists */ Set<Command> getCommandsForApplication( @NotBlank String id, @Nullable Set<CommandStatus> statuses ) throws NotFoundException; /** * Delete any unused applications that were created before the given time. * Unused means they aren't linked to any other resources in the Genie system like jobs or commands and therefore * referential integrity is maintained. * * @param createdThreshold The instant in time that any application had to be created before (exclusive) to be * considered for deletion. Presents ability to filter out newly created applications if * desired. * @param batchSize The maximum number of applications to delete in a single transaction * @return The number of successfully deleted applications */ long deleteUnusedApplications(@NotNull Instant createdThreshold, @Min(1) int batchSize); //endregion //region Cluster APIs /** * Save a {@link Cluster}. * * @param clusterRequest The cluster information to save * @return The id of the saved cluster * @throws IdAlreadyExistsException If a {@link Cluster} with the given {@literal id} already exists */ String saveCluster(@Valid ClusterRequest clusterRequest) throws IdAlreadyExistsException; /** * Get the {@link Cluster} identified by the given {@literal id}. * * @param id unique id of the {@link Cluster} to get * @return The {@link Cluster} * @throws NotFoundException If no {@link Cluster} with {@literal id} exists */ Cluster getCluster(@NotBlank String id) throws NotFoundException; /** * Find and {@link Cluster}s that match the given parameters. Null or empty parameters are ignored. * * @param name cluster name * @param statuses {@link ClusterStatus} that clusters must be in to be matched * @param tags tags attached to this cluster * @param minUpdateTime min time when cluster was updated * @param maxUpdateTime max time when cluster was updated * @param page The page to get * @return All the clusters matching the criteria */ Page<Cluster> findClusters( @Nullable String name, @Nullable Set<ClusterStatus> statuses, @Nullable Set<String> tags, @Nullable Instant minUpdateTime, @Nullable Instant maxUpdateTime, Pageable page ); /** * Update a {@link Cluster} with the given information. * * @param id The id of the cluster to update * @param updateCluster The information to update the cluster with * @throws NotFoundException If no {@link Cluster} with {@literal id} exists * @throws PreconditionFailedException If the {@literal id} doesn't match the {@literal updateCluster} id */ void updateCluster( @NotBlank String id, @Valid Cluster updateCluster ) throws NotFoundException, PreconditionFailedException; /** * Delete all clusters from database. * * @throws PreconditionFailedException If the cluster is still associated with any job */ void deleteAllClusters() throws PreconditionFailedException; /** * Delete a {@link Cluster} by id. * * @param id unique id of the cluster to delete * @throws PreconditionFailedException If the cluster is still associated with any job */ void deleteCluster(@NotBlank String id) throws PreconditionFailedException; /** * Delete all clusters that are in one of the given states, aren't attached to any jobs and were created before * the given time. * * @param deleteStatuses The set of {@link ClusterStatus} a cluster must be in to be considered for * deletion. * @param clusterCreatedThreshold The instant in time before which a cluster must have been created to be * considered for deletion. Exclusive. * @param batchSize The maximum number of clusters to delete in a single transaction * @return The number of clusters deleted */ long deleteUnusedClusters( Set<ClusterStatus> deleteStatuses, @NotNull Instant clusterCreatedThreshold, @Min(1) int batchSize ); /** * Find all the {@link Cluster}'s that match the given {@link Criterion}. * * @param criterion The {@link Criterion} supplied that each cluster needs to completely match to be returned * @param addDefaultStatus {@literal true} if the a default status should be added to the supplied * {@link Criterion} if the supplied criterion doesn't already have a status * @return All the {@link Cluster}'s which matched the {@link Criterion} */ Set<Cluster> findClustersMatchingCriterion(@Valid Criterion criterion, boolean addDefaultStatus); /** * Find all the {@link Cluster}'s that match any of the given {@link Criterion}. * * @param criteria The set of {@link Criterion} supplied that a cluster needs to completely match at least * one of to be returned * @param addDefaultStatus {@literal true} if the a default status should be added to the supplied * {@link Criterion} if the supplied criterion doesn't already have a status * @return All the {@link Cluster}'s which matched the {@link Criterion} */ Set<Cluster> findClustersMatchingAnyCriterion(@NotEmpty Set<@Valid Criterion> criteria, boolean addDefaultStatus); //endregion //region Command APIs /** * Save a {@link Command} in the system based on the given {@link CommandRequest}. * * @param commandRequest encapsulates the command configuration information to create * @return The id of the command that was saved * @throws IdAlreadyExistsException If there was a conflict on the unique id for the command */ String saveCommand(@Valid CommandRequest commandRequest) throws IdAlreadyExistsException; /** * Get the metadata for the {@link Command} identified by the id. * * @param id unique id for command to get. Not null/empty. * @return The command * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ Command getCommand(@NotBlank String id) throws NotFoundException; /** * Find commands matching the given filter criteria. * * @param name Name of command config * @param user The name of the user who created the configuration * @param statuses The status of the commands to get. Can be null. * @param tags tags allocated to this command * @param page The page of results to get * @return All the commands matching the specified criteria */ Page<Command> findCommands( @Nullable String name, @Nullable String user, @Nullable Set<CommandStatus> statuses, @Nullable Set<String> tags, Pageable page ); /** * Update a {@link Command}. * * @param id The id of the command configuration to update. Not null or empty. * @param updateCommand contains the information to update the command with * @throws NotFoundException If no {@link Command} exists with the given {@literal id} * @throws PreconditionFailedException When the {@literal id} doesn't match the id of {@literal updateCommand} */ void updateCommand( @NotBlank String id, @Valid Command updateCommand ) throws NotFoundException, PreconditionFailedException; /** * Delete all commands from the system. * * @throws PreconditionFailedException If any constraint is violated trying to delete a command */ void deleteAllCommands() throws PreconditionFailedException; /** * Delete a {@link Command} from system. * * @param id unique if of the command to delete * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ void deleteCommand(@NotBlank String id) throws NotFoundException; /** * Add applications for the command. * * @param id The id of the command to add the application file to. Not null/empty/blank. * @param applicationIds The ids of the applications to add. Not null. * @throws NotFoundException If no {@link Command} exists with the given {@literal id} or one of the * applications doesn't exist * @throws PreconditionFailedException If an application with one of the ids is already associated with the command */ void addApplicationsForCommand( @NotBlank String id, @NotEmpty List<@NotBlank String> applicationIds ) throws NotFoundException, PreconditionFailedException; /** * Set the applications for the command. * * @param id The id of the command to add the application file to. Not null/empty/blank. * @param applicationIds The ids of the applications to set. Not null. * @throws NotFoundException If no {@link Command} exists with the given {@literal id} or one of the * applications doesn't exist * @throws PreconditionFailedException If there are duplicate application ids in the list */ void setApplicationsForCommand( @NotBlank String id, @NotNull List<@NotBlank String> applicationIds ) throws NotFoundException, PreconditionFailedException; /** * Get the applications for a given command. * * @param id The id of the command to get the application for. Not null/empty/blank. * @return The applications or exception if none exist. * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ List<Application> getApplicationsForCommand(String id) throws NotFoundException; /** * Remove all the applications from the command. * * @param id The id of the command to remove the application from. Not null/empty/blank. * @throws NotFoundException If no {@link Command} exists with the given {@literal id} * @throws PreconditionFailedException If applications are unable to be removed */ void removeApplicationsForCommand(@NotBlank String id) throws NotFoundException, PreconditionFailedException; /** * Remove the application from the command. * * @param id The id of the command to remove the application from. Not null/empty/blank. * @param appId The id of the application to remove. Not null/empty/blank * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ void removeApplicationForCommand(@NotBlank String id, @NotBlank String appId) throws NotFoundException; /** * Get all the clusters the command with given id is associated with. * * @param id The id of the command to get the clusters for. * @param statuses The status of the clusters returned * @return The clusters the command is available on. * @throws NotFoundException If no {@link Command} exists with the given {@literal id} */ Set<Cluster> getClustersForCommand( @NotBlank String id, @Nullable Set<ClusterStatus> statuses ) throws NotFoundException; /** * For the given command {@literal id} return the Cluster {@link Criterion} in priority order that is currently * associated with this command if any. * * @param id The id of the command to get the criteria for * @return The cluster criteria in priority order * @throws NotFoundException If no command with {@literal id} exists */ List<Criterion> getClusterCriteriaForCommand(String id) throws NotFoundException; /** * Add a new {@link Criterion} to the existing list of cluster criteria for the command identified by {@literal id}. * This new criterion will be the lowest priority criterion. * * @param id The id of the command to add to * @param criterion The new {@link Criterion} to add * @throws NotFoundException If no command with {@literal id} exists */ void addClusterCriterionForCommand(String id, @Valid Criterion criterion) throws NotFoundException; /** * Add a new {@link Criterion} to the existing list of cluster criteria for the command identified by {@literal id}. * The {@literal priority} is the place in the list this new criterion should be placed. A value of {@literal 0} * indicates it should be placed at the front of the list with the highest possible priority. {@literal 1} would be * second in the list etc. If {@literal priority} is {@literal >} the current size of the cluster criteria list * this new criterion will be placed at the end as the lowest priority item. * * @param id The id of the command to add to * @param criterion The new {@link Criterion} to add * @param priority The place in the existing cluster criteria list this new criterion should be placed. Min 0. * @throws NotFoundException If no command with {@literal id} exists */ void addClusterCriterionForCommand( String id, @Valid Criterion criterion, @Min(0) int priority ) throws NotFoundException; /** * For the command identified by {@literal id} reset the entire list of cluster criteria to match the contents of * {@literal clusterCriteria}. * * @param id The id of the command to set the cluster criteria for * @param clusterCriteria The priority list of {@link Criterion} to set * @throws NotFoundException If no command with {@literal id} exists */ void setClusterCriteriaForCommand(String id, List<@Valid Criterion> clusterCriteria) throws NotFoundException; /** * Remove the {@link Criterion} with the given {@literal priority} from the current list of cluster criteria * associated with the command identified by {@literal id}. A value of {@literal 0} for {@literal priority} * will result in the first element in the list being removed, {@literal 1} the second element and so on. * * @param id The id of the command to remove the criterion from * @param priority The priority of the criterion to remove * @throws NotFoundException If no command with {@literal id} exists */ void removeClusterCriterionForCommand(String id, @Min(0) int priority) throws NotFoundException; /** * Remove all the {@link Criterion} currently associated with the command identified by {@literal id}. * * @param id The id of the command to remove the criteria from * @throws NotFoundException If no command with {@literal id} exists */ void removeAllClusterCriteriaForCommand(String id) throws NotFoundException; /** * Find all the {@link Command}'s that match the given {@link Criterion}. * * @param criterion The {@link Criterion} supplied that each command needs to completely match to be returned * @param addDefaultStatus {@literal true} if a default status should be added to the supplied criterion if a * status isn't already present * @return All the {@link Command}'s which matched the {@link Criterion} */ Set<Command> findCommandsMatchingCriterion(@Valid Criterion criterion, boolean addDefaultStatus); /** * Update the status of a command to the {@literal desiredStatus} if its status is in {@literal currentStatuses}, * it was created before {@literal commandCreatedThreshold} and it hasn't been used in any job. * * @param desiredStatus The new status the matching commands should have * @param commandCreatedThreshold The instant in time which a command must have been created before to be * considered for update. Exclusive * @param currentStatuses The set of current statuses a command must have to be considered for update * @param batchSize The maximum number of commands to update in a single transaction * @return The number of commands whose statuses were updated to {@literal desiredStatus} */ int updateStatusForUnusedCommands( CommandStatus desiredStatus, Instant commandCreatedThreshold, Set<CommandStatus> currentStatuses, int batchSize ); /** * Bulk delete commands from the database where their status is in {@literal deleteStatuses} they were created * before {@literal commandCreatedThreshold} and they aren't attached to any jobs still in the database. * * @param deleteStatuses The set of statuses a command must be in in order to be considered for deletion * @param commandCreatedThreshold The instant in time a command must have been created before to be considered for * deletion. Exclusive. * @param batchSize The maximum number of commands to delete in a single transaction * @return The number of commands that were deleted */ long deleteUnusedCommands( Set<CommandStatus> deleteStatuses, @NotNull Instant commandCreatedThreshold, @Min(1) int batchSize ); //endregion //region Job APIs //region V3 Job APIs /** * Get job information for given job id. * * @param id id of job to look up * @return the job * @throws GenieException if there is an error */ Job getJob(@NotBlank String id) throws GenieException; /** * Get job execution for given job id. * * @param id id of job execution to look up * @return the job * @throws GenieException if there is an error */ JobExecution getJobExecution(@NotBlank String id) throws GenieException; /** * Get the metadata about a job. * * @param id The id of the job to get metadata for * @return The metadata for a job * @throws GenieException If any error occurs */ JobMetadata getJobMetadata(@NotBlank String id) throws GenieException; /** * Find jobs which match the given filter criteria. * * @param id id for job * @param name name of job * @param user user who submitted job * @param statuses statuses of job * @param tags tags for the job * @param clusterName name of cluster for job * @param clusterId id of cluster for job * @param commandName name of the command run in the job * @param commandId id of the command run in 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 job grouping to search for * @param groupingInstance The job grouping instance to search for * @param page Page information of job to get * @return Metadata information on jobs which match the criteria */ @SuppressWarnings("checkstyle:parameternumber") Page<JobSearchResult> findJobs( @Nullable String id, @Nullable String name, @Nullable String user, @Nullable Set<com.netflix.genie.common.dto.JobStatus> statuses, @Nullable Set<String> tags, @Nullable String clusterName, @Nullable String clusterId, @Nullable String commandName, @Nullable String commandId, @Nullable Instant minStarted, @Nullable Instant maxStarted, @Nullable Instant minFinished, @Nullable Instant maxFinished, @Nullable String grouping, @Nullable String groupingInstance, @NotNull Pageable page ); //endregion //region V4 Job APIs /** * This method will delete a chunk of jobs whose creation time is earlier than the given date. * * @param creationThreshold The instant in time before which all jobs should be deleted * @param excludeStatuses The set of statuses that should be excluded from deletion if a job is in one of these * statuses * @param batchSize The maximum number of jobs that should be deleted per query * @return the number of deleted jobs */ long deleteJobsCreatedBefore( @NotNull Instant creationThreshold, @NotNull Set<JobStatus> excludeStatuses, @Min(1) int batchSize ); /** * Save the given job submission information in the underlying data store. * <p> * The job record will be created with initial state of {@link JobStatus#RESERVED} meaning that the unique id * returned by this API has been reserved within Genie and no other job can use it. If * {@link JobSubmission} contains some attachments these attachments will be persisted to a * configured storage system (i.e. local disk, S3, etc) and added to the set of dependencies for the job. * The underlying attachment storage system must be accessible by the agent process configured by the system. For * example if the server is set up to write attachments to local disk but the agent is not running locally but * instead on the remote system it will not be able to access those attachments (as dependencies) and fail. * See {@link AttachmentService} for more information. * * @param jobSubmission All the information the system has gathered regarding the job submission from the user * either via the API or via the agent CLI * @return The unique id of the job within the Genie ecosystem * @throws IdAlreadyExistsException If the id the user requested already exists in the system for another job */ @Nonnull String saveJobSubmission(@Valid JobSubmission jobSubmission) throws IdAlreadyExistsException; /** * Get the original request for a job. * * @param id The unique id of the job to get * @return The job request if one was found * @throws NotFoundException If no job with {@code id} exists */ JobRequest getJobRequest(@NotBlank String id) throws NotFoundException; /** * Save the given resolved details for a job. Sets the job status to {@link JobStatus#RESOLVED}. * * @param id The id of the job * @param resolvedJob The resolved information for the job * @throws NotFoundException When the job identified by {@code id} can't be found and the * specification can't be saved or one of the resolved cluster, command * or applications not longer exist in the system. */ void saveResolvedJob(@NotBlank String id, @Valid ResolvedJob resolvedJob) throws NotFoundException; /** * Get the saved job specification for the given job. If the job hasn't had a job specification resolved an empty * {@link Optional} will be returned. * * @param id The id of the job * @return The {@link JobSpecification} if one is present else an empty {@link Optional} * @throws NotFoundException If no job with {@code id} exists */ Optional<JobSpecification> getJobSpecification(@NotBlank String id) throws NotFoundException; /** * 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 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 NotFoundException 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 JobStatus#RESOLVED} */ void claimJob( @NotBlank String id, @Valid AgentClientMetadata agentClientMetadata ) throws NotFoundException, GenieJobAlreadyClaimedException, GenieInvalidStatusException; /** * 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. If the {@literal currentStatus} is different from what the source of truth thinks this * function will skip the update and just return the current source of truth value. * * @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 * @return The job status in the source of truth * @throws NotFoundException if no job with the given {@code id} exists */ JobStatus updateJobStatus( @NotBlank String id, @NotNull JobStatus currentStatus, @NotNull JobStatus newStatus, @Nullable String newStatusMessage ) throws NotFoundException; /** * Update the status and status message of the job. * * @param id The id of the job to update the status for. * @param archiveStatus The updated archive status for the job. * @throws NotFoundException If no job with the given {@code id} exists */ void updateJobArchiveStatus( @NotBlank(message = "No job id entered. Unable to update.") String id, @NotNull(message = "Status cannot be null.") ArchiveStatus archiveStatus ) throws NotFoundException; /** * Get the status for a job with the given {@code id}. * * @param id The id of the job to get status for * @return The job status * @throws NotFoundException If no job with the given {@code id} exists */ JobStatus getJobStatus(@NotBlank String id) throws NotFoundException; /** * Get the archive status for a job with the given {@code id}. * * @param id The id of the job to get status for * @return The job archive status * @throws NotFoundException If no job with the given {@code id} exists */ ArchiveStatus getJobArchiveStatus(@NotBlank String id) throws NotFoundException; /** * Get the location a job directory was archived to if at all. * * @param id The id of the job to get the location for * @return The archive location or {@link Optional#empty()} * @throws NotFoundException When there is no job with id {@code id} */ Optional<String> getJobArchiveLocation(@NotBlank String id) throws NotFoundException; /** * Get a DTO representing a finished job. * * @param id The id of the job to retrieve * @return the finished job * @throws NotFoundException if no job with the given {@code id} exists * @throws GenieInvalidStatusException if the current status of the job is not final */ FinishedJob getFinishedJob(@NotBlank String id) throws NotFoundException, GenieInvalidStatusException; /** * Get whether the job with the given ID was submitted via the REST API or other mechanism. * * @param id The id of the job. Not blank. * @return {@literal true} if the job was submitted via the API. {@literal false} otherwise * @throws NotFoundException If no job with {@literal id} exists */ boolean isApiJob(@NotBlank String id) throws NotFoundException; /** * Get the cluster the job used or is using. * * @param id The id of the job to get the cluster for * @return The {@link Cluster} * @throws NotFoundException If either the job or the cluster is not found */ Cluster getJobCluster(@NotBlank String id) throws NotFoundException; /** * Get the command the job used or is using. * * @param id The id of the job to get the command for * @return The {@link Command} * @throws NotFoundException If either the job or the command is not found */ Command getJobCommand(@NotBlank String id) throws NotFoundException; /** * Get the applications the job used or is currently using. * * @param id The id of the job to get the applications for * @return The {@link Application}s * @throws NotFoundException If either the job or the applications were not found */ List<Application> getJobApplications(@NotBlank String id) throws NotFoundException; /** * Get the count of 'active' jobs for a given user across all instances. * * @param user The user name * @return the number of active jobs for a given user */ long getActiveJobCountForUser(@NotBlank String user); /** * Get a map of summaries of resources usage for each user with at least one active job. * * @param statuses The set of {@link JobStatus} a job must be in to be considered in this request * @param api Whether the job was submitted via the api ({@literal true}) or the agent cli ({@literal false}) * @return a map of user resources summaries, keyed on user name */ Map<String, UserResourcesSummary> getUserResourcesSummaries(Set<JobStatus> statuses, boolean api); /** * Get the amount of memory currently used on the given host by Genie jobs in any of the following states. * <p> * {@link JobStatus#CLAIMED} * {@link JobStatus#INIT} * {@link JobStatus#RUNNING} * * @param hostname The hostname to get the memory for * @return The amount of memory being used in MB by all jobs */ long getUsedMemoryOnHost(@NotBlank String hostname); /** * Get the set of active jobs. * * @return The set of job ids which currently have a status which is considered active */ Set<String> getActiveJobs(); /** * Get the set of jobs in that have not reached CLAIMED state. * * @return The set of job ids for jobs which are active but haven't been claimed */ Set<String> getUnclaimedJobs(); /** * Get all the aggregate metadata information about jobs running on a given hostname. * * @param hostname The hostname the agent is running the job on * @return A {@link JobInfoAggregate} containing the metadata information */ JobInfoAggregate getHostJobInformation(@NotBlank String hostname); /** * Get the set of jobs (agent only) whose state is in {@code statuses} and archive status is in * {@code archiveStatuses} and last updated before {@code updated}. * * @param statuses the set of job statuses * @param archiveStatuses the set of job archive statuses * @param updated the threshold of last update * @return a set of job ids */ Set<String> getJobsWithStatusAndArchiveStatusUpdatedBefore( @NotEmpty Set<JobStatus> statuses, @NotEmpty Set<ArchiveStatus> archiveStatuses, @NotNull Instant updated ); /** * Update the requested launcher extension field for this job. * * @param id The id of the job to update the laucher extension for. * @param launcherExtension The updated requested launcher extension JSON blob. * @throws NotFoundException If no job with the given {@code id} exists */ void updateRequestedLauncherExt( @NotBlank(message = "No job id entered. Unable to update.") String id, @NotNull(message = "Status cannot be null.") JsonNode launcherExtension ) throws NotFoundException; /** * Get the command the job used or is using. * * @param id The id of the job to get the command for * @return The {@link JsonNode} passed to the launcher at launch, or a * {@link com.fasterxml.jackson.databind.node.NullNode} if none was saved * @throws NotFoundException If no job with the given {@code id} exists */ JsonNode getRequestedLauncherExt(@NotBlank String id) throws NotFoundException; /** * Update the launcher extension field for this job. * * @param id The id of the job to update the launcher extension for. * @param launcherExtension The updated launcher extension JSON blob. * @throws NotFoundException If no job with the given {@code id} exists */ void updateLauncherExt( @NotBlank(message = "No job id entered. Unable to update.") String id, @NotNull(message = "Status cannot be null.") JsonNode launcherExtension ) throws NotFoundException; /** * Get the job requested launcher extension. * * @param id The id of the job to get the command for * @return The {@link JsonNode} emitted by the launcher at launch * @throws NotFoundException If no job with the given {@code id} exists */ JsonNode getLauncherExt(@NotBlank String id) throws NotFoundException; //endregion //endregion //region General CommonResource APIs /** * Add configuration files to the existing set for a resource. * * @param <R> The resource type that the configs should be associated with * @param id The id of the resource to add the configuration file to. Not null/empty/blank. * @param configs The configuration files to add. Max file length is 1024 characters. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void addConfigsToResource( @NotBlank String id, Set<@Size(max = 1024) String> configs, Class<R> resourceClass ) throws NotFoundException; /** * Get the set of configuration files associated with the resource with the given id. * * @param <R> The resource type that the configs are associated with * @param id The id of the resource to get the configuration files for. Not null/empty/blank. * @param resourceClass The class of the resource * @return The set of configuration files as paths * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> Set<String> getConfigsForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Update the set of configuration files associated with the resource with the given id. * * @param <R> The resource type that the configs should be associated with * @param id The id of the resource to update the configuration files for. Not null/empty/blank. * @param configs The configuration files to replace existing configurations with. Not null/empty. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void updateConfigsForResource( @NotBlank String id, Set<@Size(max = 1024) String> configs, Class<R> resourceClass ) throws NotFoundException; /** * Remove all configuration files from the resource. * * @param <R> The resource type that the configs should be associated with * @param id The id of the resource to remove the configuration file from. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeAllConfigsForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Remove a configuration file from the given resource. * * @param <R> The resource type that the configs should be associated with * @param id The id of the resource to remove the configuration file from. Not null/empty/blank. * @param config The configuration file to remove. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeConfigForResource( @NotBlank String id, @NotBlank String config, Class<R> resourceClass ) throws NotFoundException; /** * Add dependency files to the existing set for a resource. * * @param <R> The resource type that the dependencies should be associated with * @param id The id of the resource to add the dependency file to. Not null/empty/blank. * @param dependencies The dependency files to add. Max file length is 1024 characters. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void addDependenciesToResource( @NotBlank String id, Set<@Size(max = 1024) String> dependencies, Class<R> resourceClass ) throws NotFoundException; /** * Get the set of dependency files associated with the resource with the given id. * * @param <R> The resource type that the dependencies are associated with * @param id The id of the resource to get the dependency files for. Not null/empty/blank. * @param resourceClass The class of the resource * @return The set of dependency files as paths * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> Set<String> getDependenciesForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Update the set of dependency files associated with the resource with the given id. * * @param <R> The resource type that the dependencies should be associated with * @param id The id of the resource to update the dependency files for. Not null/empty/blank. * @param dependencies The dependency files to replace existing dependencys with. Not null/empty. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void updateDependenciesForResource( @NotBlank String id, Set<@Size(max = 1024) String> dependencies, Class<R> resourceClass ) throws NotFoundException; /** * Remove all dependency files from the resource. * * @param <R> The resource type that the dependencies should be associated with * @param id The id of the resource to remove the dependency file from. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeAllDependenciesForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Remove a dependency file from the given resource. * * @param <R> The resource type that the dependencies should be associated with * @param id The id of the resource to remove the dependency file from. Not null/empty/blank. * @param dependency The dependency file to remove. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeDependencyForResource( @NotBlank String id, @NotBlank String dependency, Class<R> resourceClass ) throws NotFoundException; /** * Add tags to the existing set for a resource. * * @param <R> The resource type that the tags should be associated with * @param id The id of the resource to add the tags to. Not null/empty/blank. * @param tags The tags to add. Max file length is 255 characters. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void addTagsToResource( @NotBlank String id, Set<@Size(max = 255) String> tags, Class<R> resourceClass ) throws NotFoundException; /** * Get the set of tags associated with the resource with the given id. * * @param <R> The resource type that the tags are associated with * @param id The id of the resource to get the tags for. Not null/empty/blank. * @param resourceClass The class of the resource * @return The set of tags * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> Set<String> getTagsForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Update the set of tags associated with the resource with the given id. * * @param <R> The resource type that the tags should be associated with * @param id The id of the resource to update the tags for. Not null/empty/blank. * @param tags The tags to replace existing tags with. Not null/empty. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void updateTagsForResource( @NotBlank String id, Set<@Size(max = 255) String> tags, Class<R> resourceClass ) throws NotFoundException; /** * Remove all tags from the resource. * * @param <R> The resource type that the tags should be associated with * @param id The id of the resource to remove the tags from. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeAllTagsForResource( @NotBlank String id, Class<R> resourceClass ) throws NotFoundException; /** * Remove a tag from the given resource. * * @param <R> The resource type that the tag should be associated with * @param id The id of the resource to remove the tag from. Not null/empty/blank. * @param tag The tag to remove. Not null/empty/blank. * @param resourceClass The class of the resource * @throws NotFoundException If no resource of type {@link R} with {@literal id} exists */ <R extends CommonResource> void removeTagForResource( @NotBlank String id, @NotBlank String tag, Class<R> resourceClass ) throws NotFoundException; //endregion //region Tag APIs /** * Delete all tags from the database that aren't referenced which were created before the supplied created * threshold. * * @param createdThreshold The instant in time where tags created before this time that aren't referenced * will be deleted. Inclusive * @param batchSize The maximum number of tags to delete in a single transaction * @return The number of tags deleted */ long deleteUnusedTags(@NotNull Instant createdThreshold, @Min(1) int batchSize); //endregion //region File APIs /** * Delete all files from the database that aren't referenced which were created before the supplied created * threshold. * * @param createdThresholdLowerBound The instant in time when files created after this time that aren't referenced * will be selected. Inclusive. * @param createdThresholdUpperBound The instant in time when files created before this time that aren't referenced * will be selected. Inclusive. * @param batchSize The maximum number of files to delete in a single transaction * @return The number of files deleted */ long deleteUnusedFiles(@NotNull Instant createdThresholdLowerBound, @NotNull Instant createdThresholdUpperBound, @Min(1) int batchSize); //endregion }
2,670
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/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. * */ /** * Service definitions specific to the data tier of Genie web. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services; import javax.annotation.ParametersAreNonnullByDefault;
2,671
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/package-info.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implementations of data services. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,672
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/JpaPersistenceServiceImpl.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.data.services.impl.jpa; import brave.SpanCustomizer; import brave.Tracer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.netflix.genie.common.dto.Job; import com.netflix.genie.common.dto.JobExecution; import com.netflix.genie.common.dto.UserResourcesSummary; 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.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentConfigRequest; import com.netflix.genie.common.internal.dtos.Application; import com.netflix.genie.common.internal.dtos.ApplicationMetadata; import com.netflix.genie.common.internal.dtos.ApplicationRequest; import com.netflix.genie.common.internal.dtos.ApplicationStatus; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.dtos.ClusterMetadata; import com.netflix.genie.common.internal.dtos.ClusterRequest; import com.netflix.genie.common.internal.dtos.ClusterStatus; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.common.internal.dtos.CommandMetadata; import com.netflix.genie.common.internal.dtos.CommandRequest; import com.netflix.genie.common.internal.dtos.CommandStatus; import com.netflix.genie.common.internal.dtos.CommonMetadata; import com.netflix.genie.common.internal.dtos.CommonResource; import com.netflix.genie.common.internal.dtos.ComputeResources; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.common.internal.dtos.ExecutionEnvironment; import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria; import com.netflix.genie.common.internal.dtos.FinishedJob; import com.netflix.genie.common.internal.dtos.Image; import com.netflix.genie.common.internal.dtos.JobEnvironment; import com.netflix.genie.common.internal.dtos.JobEnvironmentRequest; import com.netflix.genie.common.internal.dtos.JobMetadata; 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.dtos.converters.DtoConverters; import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException; 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.GenieRuntimeException; import com.netflix.genie.common.internal.tracing.TracingConstants; import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter; import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents; import com.netflix.genie.web.data.services.PersistenceService; import com.netflix.genie.web.data.services.impl.jpa.converters.EntityV3DtoConverters; import com.netflix.genie.web.data.services.impl.jpa.converters.EntityV4DtoConverters; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.BaseEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.CriterionEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.UniqueIdEntity; import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.JobInfoAggregate; import com.netflix.genie.web.data.services.impl.jpa.queries.predicates.ApplicationPredicates; import com.netflix.genie.web.data.services.impl.jpa.queries.predicates.ClusterPredicates; import com.netflix.genie.web.data.services.impl.jpa.queries.predicates.CommandPredicates; import com.netflix.genie.web.data.services.impl.jpa.queries.predicates.JobPredicates; import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobExecutionProjection; import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobMetadataProjection; import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.FinishedJobProjection; import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaApplicationRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaBaseRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaClusterRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCommandRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaCriterionRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaFileRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaJobRepository; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaRepositories; import com.netflix.genie.web.data.services.impl.jpa.repositories.JpaTagRepository; import 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.exceptions.checked.PreconditionFailedException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.dao.DataIntegrityViolationException; 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.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Order; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Implementation of {@link PersistenceService} using JPA. * * @author tgianos * @since 4.0.0 */ @Transactional( // TODO: Double check the docs on this as default is runtime exception and error... may want to incorporate them rollbackFor = { GenieException.class, GenieCheckedException.class, GenieRuntimeException.class, ConstraintViolationException.class } ) @Slf4j public class JpaPersistenceServiceImpl implements PersistenceService { /** * The set of active statuses as their names. */ @VisibleForTesting static final Set<String> ACTIVE_STATUS_SET = JobStatus .getActiveStatuses() .stream() .map(Enum::name) .collect(Collectors.toSet()); /** * The set containing statuses that come before CLAIMED. */ @VisibleForTesting static final Set<String> UNCLAIMED_STATUS_SET = JobStatus .getStatusesBeforeClaimed() .stream() .map(Enum::name) .collect(Collectors.toSet()); /** * The set of job statuses which are considered to be using memory on a Genie node. */ @VisibleForTesting static final Set<String> USING_MEMORY_JOB_SET = Stream .of(JobStatus.CLAIMED, JobStatus.INIT, JobStatus.RUNNING) .map(Enum::name) .collect(Collectors.toSet()); private static final String LOAD_GRAPH_HINT = "javax.persistence.loadgraph"; private static final int MAX_STATUS_MESSAGE_LENGTH = 255; private final EntityManager entityManager; private final JpaApplicationRepository applicationRepository; private final JpaClusterRepository clusterRepository; private final JpaCommandRepository commandRepository; private final JpaCriterionRepository criterionRepository; private final JpaFileRepository fileRepository; private final JpaJobRepository jobRepository; private final JpaTagRepository tagRepository; private final Tracer tracer; private final BraveTagAdapter tagAdapter; /** * Constructor. * * @param entityManager The {@link EntityManager} to use * @param jpaRepositories All the repositories in the Genie application * @param tracingComponents All the Brave related tracing components needed to add metadata to Spans */ public JpaPersistenceServiceImpl( final EntityManager entityManager, final JpaRepositories jpaRepositories, final BraveTracingComponents tracingComponents ) { this.entityManager = entityManager; this.applicationRepository = jpaRepositories.getApplicationRepository(); this.clusterRepository = jpaRepositories.getClusterRepository(); this.commandRepository = jpaRepositories.getCommandRepository(); this.criterionRepository = jpaRepositories.getCriterionRepository(); this.fileRepository = jpaRepositories.getFileRepository(); this.jobRepository = jpaRepositories.getJobRepository(); this.tagRepository = jpaRepositories.getTagRepository(); this.tracer = tracingComponents.getTracer(); this.tagAdapter = tracingComponents.getTagAdapter(); } //region Application APIs /** * {@inheritDoc} */ @Override public String saveApplication(@Valid final ApplicationRequest applicationRequest) throws IdAlreadyExistsException { log.debug("[saveApplication] Called to save {}", applicationRequest); final ApplicationEntity entity = new ApplicationEntity(); this.setUniqueId(entity, applicationRequest.getRequestedId().orElse(null)); this.updateApplicationEntity(entity, applicationRequest.getResources(), applicationRequest.getMetadata()); try { return this.applicationRepository.save(entity).getUniqueId(); } catch (final DataIntegrityViolationException e) { throw new IdAlreadyExistsException( "An application with id " + entity.getUniqueId() + " already exists", e ); } } /** * {@inheritDoc} */ @Override public Application getApplication(@NotBlank final String id) throws NotFoundException { log.debug("[getApplication] Called for {}", id); return EntityV4DtoConverters.toV4ApplicationDto( this.applicationRepository .getApplicationDto(id) .orElseThrow(() -> new NotFoundException("No application with id " + id + " exists")) ); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public Page<Application> findApplications( @Nullable final String name, @Nullable final String user, @Nullable final Set<ApplicationStatus> statuses, @Nullable final Set<String> tags, @Nullable final String type, final Pageable page ) { /* * NOTE: This is implemented this way for a reason: * 1. To solve the JPA N+1 problem: https://vladmihalcea.com/n-plus-1-query-problem/ * 2. To address this: https://vladmihalcea.com/fix-hibernate-hhh000104-entity-fetch-pagination-warning-message/ * This reduces the number of queries from potentially 100's to 3 */ log.debug( "[findApplications] Called with name = {}, user = {}, statuses = {}, tags = {}, type = {}", name, user, statuses, tags, type ); final Set<String> statusStrings = statuses != null ? statuses.stream().map(Enum::name).collect(Collectors.toSet()) : null; // TODO: Still more optimization that can be done here to not load these entities // Figure out how to use just strings in the predicate final Set<TagEntity> tagEntities = tags == null ? null : this.tagRepository.findByTagIn(tags); if (tagEntities != null && tagEntities.size() != tags.size()) { // short circuit for no results as at least one of the expected tags doesn't exist return new PageImpl<>(new ArrayList<>(0)); } final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class); final Root<ApplicationEntity> countQueryRoot = countQuery.from(ApplicationEntity.class); final Subquery<Long> countIdSubQuery = countQuery.subquery(Long.class); final Root<ApplicationEntity> countIdSubQueryRoot = countIdSubQuery.from(ApplicationEntity.class); countIdSubQuery.select(countIdSubQueryRoot.get(ApplicationEntity_.id)); countIdSubQuery.where( ApplicationPredicates.find( countIdSubQueryRoot, countIdSubQuery, criteriaBuilder, name, user, statusStrings, tagEntities, type ) ); countQuery.select(criteriaBuilder.count(countQueryRoot)); countQuery.where(countQueryRoot.get(ApplicationEntity_.id).in(countIdSubQuery)); final Long totalCount = this.entityManager.createQuery(countQuery).getSingleResult(); if (totalCount == null || totalCount == 0) { // short circuit for no results return new PageImpl<>(new ArrayList<>(0)); } final CriteriaQuery<Long> idQuery = criteriaBuilder.createQuery(Long.class); final Root<ApplicationEntity> idQueryRoot = idQuery.from(ApplicationEntity.class); idQuery.select(idQueryRoot.get(ApplicationEntity_.id)); idQuery.where( // NOTE: The problem with trying to reuse the predicate above even though they seem the same is they have // different query objects. If there is a join added by the predicate function it won't be on the // right object as these criteria queries are basically builders ApplicationPredicates.find( idQueryRoot, idQuery, criteriaBuilder, name, user, statusStrings, tagEntities, type ) ); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining( order -> { if (order.isAscending()) { orders.add(criteriaBuilder.asc(idQueryRoot.get(order.getProperty()))); } else { orders.add(criteriaBuilder.desc(idQueryRoot.get(order.getProperty()))); } } ); idQuery.orderBy(orders); final List<Long> applicationIds = this.entityManager .createQuery(idQuery) .setFirstResult(((Long) page.getOffset()).intValue()) .setMaxResults(page.getPageSize()) .getResultList(); final CriteriaQuery<ApplicationEntity> contentQuery = criteriaBuilder.createQuery(ApplicationEntity.class); final Root<ApplicationEntity> contentQueryRoot = contentQuery.from(ApplicationEntity.class); contentQuery.select(contentQueryRoot); contentQuery.where(contentQueryRoot.get(ApplicationEntity_.id).in(applicationIds)); // Need to make the same order by or results won't be accurate contentQuery.orderBy(orders); final List<Application> applications = this.entityManager .createQuery(contentQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(ApplicationEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4ApplicationDto) .collect(Collectors.toList()); return new PageImpl<>(applications, page, totalCount); } /** * {@inheritDoc} */ @Override public void updateApplication( @NotBlank final String id, @Valid final Application updateApp ) throws NotFoundException, PreconditionFailedException { log.debug("[updateApplication] Called to update application {} with {}", id, updateApp); if (!updateApp.getId().equals(id)) { throw new PreconditionFailedException("Application id " + id + " inconsistent with id passed in."); } this.updateApplicationEntity( this.applicationRepository .getApplicationDto(id) .orElseThrow(() -> new NotFoundException("No application with id " + id + " exists")), updateApp.getResources(), updateApp.getMetadata() ); } /** * {@inheritDoc} */ @Override public void deleteAllApplications() throws PreconditionFailedException { log.debug("[deleteAllApplications] Called"); for (final ApplicationEntity entity : this.applicationRepository.findAll()) { this.deleteApplicationEntity(entity); } } /** * {@inheritDoc} */ @Override public void deleteApplication(@NotBlank final String id) throws PreconditionFailedException { log.debug("[deleteApplication] Called for {}", id); final Optional<ApplicationEntity> entity = this.applicationRepository.getApplicationAndCommands(id); if (entity.isEmpty()) { // There's nothing to do as the caller wants to delete something that doesn't exist. return; } this.deleteApplicationEntity(entity.get()); } /** * {@inheritDoc} */ @Override public Set<Command> getCommandsForApplication( @NotBlank final String id, @Nullable final Set<CommandStatus> statuses ) throws NotFoundException { log.debug("[getCommandsForApplication] Called for application {} filtered by statuses {}", id, statuses); return this.applicationRepository .getApplicationAndCommandsDto(id) .orElseThrow(() -> new NotFoundException("No application with id " + id + " exists")) .getCommands() .stream() .filter( commandEntity -> statuses == null || statuses.contains(DtoConverters.toV4CommandStatus(commandEntity.getStatus())) ) .map(EntityV4DtoConverters::toV4CommandDto) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteUnusedApplications(final Instant createdThreshold, final int batchSize) { log.info("Attempting to delete unused applications created before {}", createdThreshold); return this.applicationRepository.deleteByIdIn( this.applicationRepository.findUnusedApplications(createdThreshold, batchSize) ); } //endregion //region Cluster APIs /** * {@inheritDoc} */ @Override public String saveCluster(@Valid final ClusterRequest clusterRequest) throws IdAlreadyExistsException { log.debug("[saveCluster] Called to save {}", clusterRequest); final ClusterEntity entity = new ClusterEntity(); this.setUniqueId(entity, clusterRequest.getRequestedId().orElse(null)); this.updateClusterEntity(entity, clusterRequest.getResources(), clusterRequest.getMetadata()); try { return this.clusterRepository.save(entity).getUniqueId(); } catch (final DataIntegrityViolationException e) { throw new IdAlreadyExistsException("A cluster with id " + entity.getUniqueId() + " already exists", e); } } /** * {@inheritDoc} */ @Override public Cluster getCluster(@NotBlank final String id) throws NotFoundException { log.debug("[getCluster] Called for {}", id); return EntityV4DtoConverters.toV4ClusterDto( this.clusterRepository .getClusterDto(id) .orElseThrow(() -> new NotFoundException("No cluster with id " + id + " exists")) ); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public Page<Cluster> findClusters( @Nullable final String name, @Nullable final Set<ClusterStatus> statuses, @Nullable final Set<String> tags, @Nullable final Instant minUpdateTime, @Nullable final Instant maxUpdateTime, final Pageable page ) { /* * NOTE: This is implemented this way for a reason: * 1. To solve the JPA N+1 problem: https://vladmihalcea.com/n-plus-1-query-problem/ * 2. To address this: https://vladmihalcea.com/fix-hibernate-hhh000104-entity-fetch-pagination-warning-message/ * This reduces the number of queries from potentially 100's to 3 */ log.debug( "[findClusters] Called with name = {}, statuses = {}, tags = {}, minUpdateTime = {}, maxUpdateTime = {}", name, statuses, tags, minUpdateTime, maxUpdateTime ); final Set<String> statusStrings = statuses != null ? statuses.stream().map(Enum::name).collect(Collectors.toSet()) : null; // TODO: Still more optimization that can be done here to not load these entities // Figure out how to use just strings in the predicate final Set<TagEntity> tagEntities = tags == null ? null : this.tagRepository.findByTagIn(tags); if (tagEntities != null && tagEntities.size() != tags.size()) { // short circuit for no results as at least one of the expected tags doesn't exist return new PageImpl<>(new ArrayList<>(0)); } final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class); final Root<ClusterEntity> countQueryRoot = countQuery.from(ClusterEntity.class); final Subquery<Long> countIdSubQuery = countQuery.subquery(Long.class); final Root<ClusterEntity> countIdSubQueryRoot = countIdSubQuery.from(ClusterEntity.class); countIdSubQuery.select(countIdSubQueryRoot.get(ClusterEntity_.id)); countIdSubQuery.where( ClusterPredicates.find( countIdSubQueryRoot, countIdSubQuery, criteriaBuilder, name, statusStrings, tagEntities, minUpdateTime, maxUpdateTime ) ); countQuery.select(criteriaBuilder.count(countQueryRoot)); countQuery.where(countQueryRoot.get(ClusterEntity_.id).in(countIdSubQuery)); final Long totalCount = this.entityManager.createQuery(countQuery).getSingleResult(); if (totalCount == null || totalCount == 0) { // short circuit for no results return new PageImpl<>(new ArrayList<>(0)); } final CriteriaQuery<Long> idQuery = criteriaBuilder.createQuery(Long.class); final Root<ClusterEntity> idQueryRoot = idQuery.from(ClusterEntity.class); idQuery.select(idQueryRoot.get(ClusterEntity_.id)); idQuery.where( // NOTE: The problem with trying to reuse the predicate above even though they seem the same is they have // different query objects. If there is a join added by the predicate function it won't be on the // right object as these criteria queries are basically builders ClusterPredicates.find( idQueryRoot, idQuery, criteriaBuilder, name, statusStrings, tagEntities, minUpdateTime, maxUpdateTime ) ); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining( order -> { if (order.isAscending()) { orders.add(criteriaBuilder.asc(idQueryRoot.get(order.getProperty()))); } else { orders.add(criteriaBuilder.desc(idQueryRoot.get(order.getProperty()))); } } ); idQuery.orderBy(orders); final List<Long> clusterIds = this.entityManager .createQuery(idQuery) .setFirstResult(((Long) page.getOffset()).intValue()) .setMaxResults(page.getPageSize()) .getResultList(); final CriteriaQuery<ClusterEntity> contentQuery = criteriaBuilder.createQuery(ClusterEntity.class); final Root<ClusterEntity> contentQueryRoot = contentQuery.from(ClusterEntity.class); contentQuery.select(contentQueryRoot); contentQuery.where(contentQueryRoot.get(ClusterEntity_.id).in(clusterIds)); // Need to make the same order by or results won't be accurate contentQuery.orderBy(orders); final List<Cluster> clusters = this.entityManager .createQuery(contentQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(ClusterEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4ClusterDto) .collect(Collectors.toList()); return new PageImpl<>(clusters, page, totalCount); } /** * {@inheritDoc} */ @Override public void updateCluster( @NotBlank final String id, @Valid final Cluster updateCluster ) throws NotFoundException, PreconditionFailedException { log.debug("[updateCluster] Called to update cluster {} with {}", id, updateCluster); if (!updateCluster.getId().equals(id)) { throw new PreconditionFailedException("Application id " + id + " inconsistent with id passed in."); } this.updateClusterEntity( this.clusterRepository .getClusterDto(id) .orElseThrow(() -> new NotFoundException("No cluster with id " + id + " exists")), updateCluster.getResources(), updateCluster.getMetadata() ); } /** * {@inheritDoc} */ @Override public void deleteAllClusters() throws PreconditionFailedException { log.debug("[deleteAllClusters] Called"); for (final ClusterEntity entity : this.clusterRepository.findAll()) { this.deleteClusterEntity(entity); } } /** * {@inheritDoc} */ @Override public void deleteCluster(@NotBlank final String id) throws PreconditionFailedException { log.debug("[deleteCluster] Called for {}", id); final Optional<ClusterEntity> entity = this.clusterRepository.findByUniqueId(id); if (entity.isEmpty()) { // There's nothing to do as the caller wants to delete something that doesn't exist. return; } this.deleteClusterEntity(entity.get()); } /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteUnusedClusters( final Set<ClusterStatus> deleteStatuses, final Instant clusterCreatedThreshold, final int batchSize ) { log.info( "[deleteUnusedClusters] Deleting with statuses {} that were created before {}", deleteStatuses, clusterCreatedThreshold ); return this.clusterRepository.deleteByIdIn( this.clusterRepository.findUnusedClusters( deleteStatuses.stream().map(Enum::name).collect(Collectors.toSet()), clusterCreatedThreshold, batchSize ) ); } /** * {@inheritDoc} */ @Override public Set<Cluster> findClustersMatchingCriterion( @Valid final Criterion criterion, final boolean addDefaultStatus ) { final Criterion finalCriterion; if (addDefaultStatus && criterion.getStatus().isEmpty()) { finalCriterion = new Criterion(criterion, ClusterStatus.UP.name()); } else { finalCriterion = criterion; } log.debug("[findClustersMatchingCriterion] Called to find clusters matching {}", finalCriterion); final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<ClusterEntity> criteriaQuery = criteriaBuilder.createQuery(ClusterEntity.class); final Root<ClusterEntity> queryRoot = criteriaQuery.from(ClusterEntity.class); criteriaQuery.where( ClusterPredicates.findClustersMatchingCriterion(queryRoot, criteriaQuery, criteriaBuilder, finalCriterion) ); return this.entityManager.createQuery(criteriaQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(ClusterEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4ClusterDto) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override public Set<Cluster> findClustersMatchingAnyCriterion( @NotEmpty final Set<@Valid Criterion> criteria, final boolean addDefaultStatus ) { final Set<Criterion> finalCriteria; if (addDefaultStatus) { final String defaultStatus = ClusterStatus.UP.name(); final ImmutableSet.Builder<Criterion> criteriaBuilder = ImmutableSet.builder(); for (final Criterion criterion : criteria) { if (criterion.getStatus().isPresent()) { criteriaBuilder.add(criterion); } else { criteriaBuilder.add(new Criterion(criterion, defaultStatus)); } } finalCriteria = criteriaBuilder.build(); } else { finalCriteria = criteria; } log.debug("[findClustersMatchingAnyCriterion] Called to find clusters matching any of {}", finalCriteria); final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<ClusterEntity> criteriaQuery = criteriaBuilder.createQuery(ClusterEntity.class); final Root<ClusterEntity> queryRoot = criteriaQuery.from(ClusterEntity.class); criteriaQuery.where( ClusterPredicates.findClustersMatchingAnyCriterion(queryRoot, criteriaQuery, criteriaBuilder, finalCriteria) ); return this.entityManager.createQuery(criteriaQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(ClusterEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4ClusterDto) .collect(Collectors.toSet()); } //endregion //region Command APIs /** * {@inheritDoc} */ @Override public String saveCommand(@Valid final CommandRequest commandRequest) throws IdAlreadyExistsException { log.debug("[saveCommand] Called to save {}", commandRequest); final CommandEntity entity = new CommandEntity(); this.setUniqueId(entity, commandRequest.getRequestedId().orElse(null)); this.updateCommandEntity( entity, commandRequest.getResources(), commandRequest.getMetadata(), commandRequest.getExecutable(), commandRequest.getComputeResources().orElse(null), commandRequest.getClusterCriteria(), commandRequest.getImages() ); try { return this.commandRepository.save(entity).getUniqueId(); } catch (final DataIntegrityViolationException e) { throw new IdAlreadyExistsException( "A command with id " + entity.getUniqueId() + " already exists", e ); } } /** * {@inheritDoc} */ @Override public Command getCommand(@NotBlank final String id) throws NotFoundException { log.debug("[getCommand] Called for {}", id); return EntityV4DtoConverters.toV4CommandDto( this.commandRepository .getCommandDto(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) ); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public Page<Command> findCommands( @Nullable final String name, @Nullable final String user, @Nullable final Set<CommandStatus> statuses, @Nullable final Set<String> tags, final Pageable page ) { /* * NOTE: This is implemented this way for a reason: * 1. To solve the JPA N+1 problem: https://vladmihalcea.com/n-plus-1-query-problem/ * 2. To address this: https://vladmihalcea.com/fix-hibernate-hhh000104-entity-fetch-pagination-warning-message/ * This reduces the number of queries from potentially 100's to 3 */ log.debug( "[findCommands] Called with name = {}, user = {}, statuses = {}, tags = {}", name, user, statuses, tags ); final Set<String> statusStrings = statuses != null ? statuses.stream().map(Enum::name).collect(Collectors.toSet()) : null; // TODO: Still more optimization that can be done here to not load these entities // Figure out how to use just strings in the predicate final Set<TagEntity> tagEntities = tags == null ? null : this.tagRepository.findByTagIn(tags); if (tagEntities != null && tagEntities.size() != tags.size()) { // short circuit for no results as at least one of the expected tags doesn't exist return new PageImpl<>(new ArrayList<>(0)); } final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class); final Root<CommandEntity> countQueryRoot = countQuery.from(CommandEntity.class); final Subquery<Long> countIdSubQuery = countQuery.subquery(Long.class); final Root<CommandEntity> countIdSubQueryRoot = countIdSubQuery.from(CommandEntity.class); countIdSubQuery.select(countIdSubQueryRoot.get(CommandEntity_.id)); countIdSubQuery.where( CommandPredicates.find( countIdSubQueryRoot, countIdSubQuery, criteriaBuilder, name, user, statusStrings, tagEntities ) ); countQuery.select(criteriaBuilder.count(countQueryRoot)); countQuery.where(countQueryRoot.get(CommandEntity_.id).in(countIdSubQuery)); final Long totalCount = this.entityManager.createQuery(countQuery).getSingleResult(); if (totalCount == null || totalCount == 0) { // short circuit for no results return new PageImpl<>(new ArrayList<>(0)); } final CriteriaQuery<Long> idQuery = criteriaBuilder.createQuery(Long.class); final Root<CommandEntity> idQueryRoot = idQuery.from(CommandEntity.class); idQuery.select(idQueryRoot.get(CommandEntity_.id)); idQuery.where( // NOTE: The problem with trying to reuse the predicate above even though they seem the same is they have // different query objects. If there is a join added by the predicate function it won't be on the // right object as these criteria queries are basically builders CommandPredicates.find( idQueryRoot, idQuery, criteriaBuilder, name, user, statusStrings, tagEntities ) ); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining( order -> { if (order.isAscending()) { orders.add(criteriaBuilder.asc(idQueryRoot.get(order.getProperty()))); } else { orders.add(criteriaBuilder.desc(idQueryRoot.get(order.getProperty()))); } } ); idQuery.orderBy(orders); final List<Long> commandIds = this.entityManager .createQuery(idQuery) .setFirstResult(((Long) page.getOffset()).intValue()) .setMaxResults(page.getPageSize()) .getResultList(); final CriteriaQuery<CommandEntity> contentQuery = criteriaBuilder.createQuery(CommandEntity.class); final Root<CommandEntity> contentQueryRoot = contentQuery.from(CommandEntity.class); contentQuery.select(contentQueryRoot); contentQuery.where(contentQueryRoot.get(CommandEntity_.id).in(commandIds)); // Need to make the same order by or results won't be accurate contentQuery.orderBy(orders); final List<Command> commands = this.entityManager .createQuery(contentQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(CommandEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4CommandDto) .collect(Collectors.toList()); return new PageImpl<>(commands, page, totalCount); } /** * {@inheritDoc} */ @Override public void updateCommand( @NotBlank final String id, @Valid final Command updateCommand ) throws NotFoundException, PreconditionFailedException { log.debug("[updateCommand] Called to update command {} with {}", id, updateCommand); if (!updateCommand.getId().equals(id)) { throw new PreconditionFailedException("Command id " + id + " inconsistent with id passed in."); } this.updateCommandEntity( this.commandRepository .getCommandDto(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")), updateCommand.getResources(), updateCommand.getMetadata(), updateCommand.getExecutable(), updateCommand.getComputeResources(), updateCommand.getClusterCriteria(), updateCommand.getImages() ); } /** * {@inheritDoc} */ @Override public void deleteAllCommands() throws PreconditionFailedException { log.debug("[deleteAllCommands] Called"); this.commandRepository.findAll().forEach(this::deleteCommandEntity); } /** * {@inheritDoc} */ @Override public void deleteCommand(@NotBlank final String id) throws NotFoundException { log.debug("[deleteCommand] Called to delete command with id {}", id); this.deleteCommandEntity( this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) ); } /** * {@inheritDoc} */ @Override public void addApplicationsForCommand( @NotBlank final String id, @NotEmpty final List<@NotBlank String> applicationIds ) throws NotFoundException, PreconditionFailedException { log.debug("[addApplicationsForCommand] Called to add {} to {}", applicationIds, id); final CommandEntity commandEntity = this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); for (final String applicationId : applicationIds) { commandEntity.addApplication( this.applicationRepository .getApplicationAndCommands(applicationId) .orElseThrow(() -> new NotFoundException("No application with id " + applicationId + " exists")) ); } } /** * {@inheritDoc} */ @Override public void setApplicationsForCommand( @NotBlank final String id, @NotNull final List<@NotBlank String> applicationIds ) throws NotFoundException, PreconditionFailedException { log.debug("[setApplicationsForCommand] Called to set {} for {}", applicationIds, id); if (Sets.newHashSet(applicationIds).size() != applicationIds.size()) { throw new PreconditionFailedException("Duplicate application id in " + applicationIds); } final CommandEntity commandEntity = this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); final List<ApplicationEntity> applicationEntities = Lists.newArrayList(); for (final String applicationId : applicationIds) { applicationEntities.add( this.applicationRepository .getApplicationAndCommands(applicationId) .orElseThrow(() -> new NotFoundException("No application with id " + applicationId + " exists")) ); } commandEntity.setApplications(applicationEntities); } /** * {@inheritDoc} */ @Override public List<Application> getApplicationsForCommand(final String id) throws NotFoundException { log.debug("[getApplicationsForCommand] Called for {}", id); return this.commandRepository .getCommandAndApplicationsDto(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .getApplications() .stream() .map(EntityV4DtoConverters::toV4ApplicationDto) .collect(Collectors.toList()); } /** * {@inheritDoc} */ @Override public void removeApplicationsForCommand( @NotBlank final String id ) throws NotFoundException, PreconditionFailedException { log.debug("[removeApplicationsForCommand] Called to for {}", id); this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .setApplications(null); } /** * {@inheritDoc} */ @Override public void removeApplicationForCommand( @NotBlank final String id, @NotBlank final String appId ) throws NotFoundException { log.debug("[removeApplicationForCommand] Called to for {} from {}", appId, id); this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .removeApplication( this.applicationRepository .getApplicationAndCommands(appId) .orElseThrow(() -> new NotFoundException("No application with id " + appId + " exists")) ); } /** * {@inheritDoc} */ @Override public Set<Cluster> getClustersForCommand( @NotBlank final String id, @Nullable final Set<ClusterStatus> statuses ) throws NotFoundException { log.debug("[getClustersForCommand] Called for {} with statuses {}", id, statuses); final List<Criterion> clusterCriteria = this.getClusterCriteriaForCommand(id); return this .findClustersMatchingAnyCriterion(Sets.newHashSet(clusterCriteria), false) .stream() .filter(cluster -> statuses == null || statuses.contains(cluster.getMetadata().getStatus())) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override public List<Criterion> getClusterCriteriaForCommand(final String id) throws NotFoundException { log.debug("[getClusterCriteriaForCommand] Called to get cluster criteria for command {}", id); return this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .getClusterCriteria() .stream() .map(EntityV4DtoConverters::toCriterionDto) .collect(Collectors.toList()); } /** * {@inheritDoc} */ @Override public void addClusterCriterionForCommand( final String id, @Valid final Criterion criterion ) throws NotFoundException { log.debug("[addClusterCriterionForCommand] Called to add cluster criteria {} for command {}", criterion, id); this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .addClusterCriterion(this.toCriterionEntity(criterion)); } /** * {@inheritDoc} */ @Override public void addClusterCriterionForCommand( final String id, @Valid final Criterion criterion, @Min(0) final int priority ) throws NotFoundException { log.debug( "[addClusterCriterionForCommand] Called to add cluster criteria {} for command {} at priority {}", criterion, id, priority ); this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) .addClusterCriterion(this.toCriterionEntity(criterion), priority); } /** * {@inheritDoc} */ @Override public void setClusterCriteriaForCommand( final String id, final List<@Valid Criterion> clusterCriteria ) throws NotFoundException { log.debug( "[setClusterCriteriaForCommand] Called to set cluster criteria {} for command {}", clusterCriteria, id ); final CommandEntity commandEntity = this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); this.updateClusterCriteria(commandEntity, clusterCriteria); } /** * {@inheritDoc} */ @Override public void removeClusterCriterionForCommand(final String id, @Min(0) final int priority) throws NotFoundException { log.debug( "[removeClusterCriterionForCommand] Called to remove cluster criterion with priority {} from command {}", priority, id ); final CommandEntity commandEntity = this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); if (priority >= commandEntity.getClusterCriteria().size()) { throw new NotFoundException( "No criterion with priority " + priority + " exists for command " + id + ". Unable to remove." ); } try { final CriterionEntity criterionEntity = commandEntity.removeClusterCriterion(priority); log.debug("Successfully removed cluster criterion {} from command {}", criterionEntity, id); // Ensure this dangling criterion is deleted from the database this.criterionRepository.delete(criterionEntity); } catch (final IllegalArgumentException e) { log.error("Failed to remove cluster criterion with priority {} from command {}", priority, id, e); } } /** * {@inheritDoc} */ @Override public void removeAllClusterCriteriaForCommand(final String id) throws NotFoundException { log.debug("[removeAllClusterCriteriaForCommand] Called to remove all cluster criteria from command {}", id); this.deleteAllClusterCriteria( this.commandRepository .getCommandAndClusterCriteria(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")) ); } /** * {@inheritDoc} */ @Override public Set<Command> findCommandsMatchingCriterion( @Valid final Criterion criterion, final boolean addDefaultStatus ) { final Criterion finalCriterion; if (addDefaultStatus && criterion.getStatus().isEmpty()) { finalCriterion = new Criterion(criterion, CommandStatus.ACTIVE.name()); } else { finalCriterion = criterion; } log.debug("[findCommandsMatchingCriterion] Called to find commands matching {}", finalCriterion); final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<CommandEntity> criteriaQuery = criteriaBuilder.createQuery(CommandEntity.class); final Root<CommandEntity> queryRoot = criteriaQuery.from(CommandEntity.class); criteriaQuery.where( CommandPredicates.findCommandsMatchingCriterion(queryRoot, criteriaQuery, criteriaBuilder, finalCriterion) ); return this.entityManager.createQuery(criteriaQuery) .setHint(LOAD_GRAPH_HINT, this.entityManager.getEntityGraph(CommandEntity.DTO_ENTITY_GRAPH)) .getResultStream() .map(EntityV4DtoConverters::toV4CommandDto) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public int updateStatusForUnusedCommands( final CommandStatus desiredStatus, final Instant commandCreatedThreshold, final Set<CommandStatus> currentStatuses, final int batchSize ) { log.info( "Attempting to update at most {} commands with statuses {} " + "which were created before {} and haven't been used in jobs to new status {}", batchSize, currentStatuses, commandCreatedThreshold, desiredStatus ); final int updateCount = this.commandRepository.setStatusWhereIdIn( desiredStatus.name(), this.commandRepository.findUnusedCommandsByStatusesCreatedBefore( currentStatuses.stream().map(Enum::name).collect(Collectors.toSet()), commandCreatedThreshold, batchSize ) ); log.info( "Updated {} commands with statuses {} " + "which were created before {} and haven't been used in any jobs to new status {}", updateCount, currentStatuses, commandCreatedThreshold, desiredStatus ); return updateCount; } /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteUnusedCommands( final Set<CommandStatus> deleteStatuses, final Instant commandCreatedThreshold, final int batchSize ) { log.info( "Deleting commands with statuses {} that were created before {}", deleteStatuses, commandCreatedThreshold ); return this.commandRepository.deleteByIdIn( this.commandRepository.findUnusedCommandsByStatusesCreatedBefore( deleteStatuses.stream().map(Enum::name).collect(Collectors.toSet()), commandCreatedThreshold, batchSize ) ); } //endregion //region Job APIs //region V3 Job APIs /** * {@inheritDoc} */ @Override public Job getJob(@NotBlank final String id) throws GenieException { log.debug("[getJob] Called with id {}", id); return EntityV3DtoConverters.toJobDto( this.jobRepository .getV3Job(id) .orElseThrow(() -> new GenieNotFoundException("No job with id " + id)) ); } /** * {@inheritDoc} */ @Override public JobExecution getJobExecution(@NotBlank final String id) throws GenieException { log.debug("[getJobExecution] Called with id {}", id); return EntityV3DtoConverters.toJobExecutionDto( this.jobRepository .findByUniqueId(id, JobExecutionProjection.class) .orElseThrow(() -> new GenieNotFoundException("No job with id " + id)) ); } /** * {@inheritDoc} */ @Override public com.netflix.genie.common.dto.JobMetadata getJobMetadata(@NotBlank final String id) throws GenieException { log.debug("[getJobMetadata] Called with id {}", id); return EntityV3DtoConverters.toJobMetadataDto( this.jobRepository .findByUniqueId(id, JobMetadataProjection.class) .orElseThrow(() -> new GenieNotFoundException("No job found for id " + id)) ); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) @SuppressWarnings("checkstyle:parameternumber") public Page<JobSearchResult> findJobs( @Nullable final String id, @Nullable final String name, @Nullable final String user, @Nullable final Set<com.netflix.genie.common.dto.JobStatus> statuses, @Nullable final Set<String> tags, @Nullable final String clusterName, @Nullable final String clusterId, @Nullable final String commandName, @Nullable final String commandId, @Nullable final Instant minStarted, @Nullable final Instant maxStarted, @Nullable final Instant minFinished, @Nullable final Instant maxFinished, @Nullable final String grouping, @Nullable final String groupingInstance, @NotNull final Pageable page ) { log.debug("[findJobs] Called"); ClusterEntity clusterEntity = null; if (clusterId != null) { final Optional<ClusterEntity> optionalClusterEntity = this.getEntityOrNullForFindJobs(this.clusterRepository, clusterId, clusterName); if (optionalClusterEntity.isPresent()) { clusterEntity = optionalClusterEntity.get(); } else { // Won't find anything matching the query return new PageImpl<>(Lists.newArrayList(), page, 0); } } CommandEntity commandEntity = null; if (commandId != null) { final Optional<CommandEntity> optionalCommandEntity = this.getEntityOrNullForFindJobs(this.commandRepository, commandId, commandName); if (optionalCommandEntity.isPresent()) { commandEntity = optionalCommandEntity.get(); } else { // Won't find anything matching the query return new PageImpl<>(Lists.newArrayList(), page, 0); } } final Set<String> statusStrings = statuses != null ? statuses.stream().map(Enum::name).collect(Collectors.toSet()) : null; final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); final Root<JobEntity> root = countQuery.from(JobEntity.class); countQuery .select(cb.count(root)) .where( JobPredicates .getFindPredicate( root, cb, id, name, user, statusStrings, tags, clusterName, clusterEntity, commandName, commandEntity, minStarted, maxStarted, minFinished, maxFinished, grouping, groupingInstance ) ); final long totalCount = this.entityManager.createQuery(countQuery).getSingleResult(); if (totalCount == 0) { // short circuit for no results return new PageImpl<>(new ArrayList<>(0)); } final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class); final Root<JobEntity> contentQueryRoot = contentQuery.from(JobEntity.class); contentQuery.multiselect( contentQueryRoot.get(JobEntity_.uniqueId), contentQueryRoot.get(JobEntity_.name), contentQueryRoot.get(JobEntity_.user), contentQueryRoot.get(JobEntity_.status), contentQueryRoot.get(JobEntity_.started), contentQueryRoot.get(JobEntity_.finished), contentQueryRoot.get(JobEntity_.clusterName), contentQueryRoot.get(JobEntity_.commandName) ); contentQuery.where( JobPredicates .getFindPredicate( contentQueryRoot, cb, id, name, user, statusStrings, tags, clusterName, clusterEntity, commandName, commandEntity, minStarted, maxStarted, minFinished, maxFinished, grouping, groupingInstance ) ); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining( order -> { if (order.isAscending()) { orders.add(cb.asc(root.get(order.getProperty()))); } else { orders.add(cb.desc(root.get(order.getProperty()))); } } ); contentQuery.orderBy(orders); final List<JobSearchResult> results = this.entityManager .createQuery(contentQuery) .setFirstResult(((Long) page.getOffset()).intValue()) .setMaxResults(page.getPageSize()) .getResultList(); return new PageImpl<>(results, page, totalCount); } //endregion //region V4 Job APIs /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteJobsCreatedBefore( @NotNull final Instant creationThreshold, @NotNull final Set<JobStatus> excludeStatuses, @Min(1) final int batchSize ) { final String excludeStatusesString = excludeStatuses.toString(); final String creationThresholdString = creationThreshold.toString(); log.info( "[deleteJobsCreatedBefore] Attempting to delete at most {} jobs created before {} that do not have any of " + "these statuses {}", batchSize, creationThresholdString, excludeStatusesString ); final Set<String> ignoredStatusStrings = excludeStatuses.stream().map(Enum::name).collect(Collectors.toSet()); final long numJobsDeleted = this.jobRepository.deleteByIdIn( this.jobRepository.findJobsCreatedBefore( creationThreshold, ignoredStatusStrings, batchSize ) ); log.info( "[deleteJobsCreatedBefore] Deleted {} jobs created before {} that did not have any of these statuses {}", numJobsDeleted, creationThresholdString, excludeStatusesString ); return numJobsDeleted; } /** * {@inheritDoc} */ @Override @Nonnull public String saveJobSubmission(@Valid final JobSubmission jobSubmission) throws IdAlreadyExistsException { log.debug("[saveJobSubmission] Attempting to save job submission {}", jobSubmission); // TODO: Metrics final JobEntity jobEntity = new JobEntity(); jobEntity.setStatus(JobStatus.RESERVED.name()); final JobRequest jobRequest = jobSubmission.getJobRequest(); final JobRequestMetadata jobRequestMetadata = jobSubmission.getJobRequestMetadata(); // Create the unique id if one doesn't already exist this.setUniqueId(jobEntity, jobRequest.getRequestedId().orElse(null)); jobEntity.setCommandArgs(jobRequest.getCommandArgs()); this.setJobMetadataFields( jobEntity, jobRequest.getMetadata(), jobRequest.getResources().getSetupFile().orElse(null) ); this.setJobExecutionEnvironmentFields(jobEntity, jobRequest.getResources(), jobSubmission.getAttachments()); this.setExecutionResourceCriteriaFields(jobEntity, jobRequest.getCriteria()); this.setRequestedJobEnvironmentFields(jobEntity, jobRequest.getRequestedJobEnvironment()); this.setRequestedAgentConfigFields(jobEntity, jobRequest.getRequestedAgentConfig()); this.setRequestMetadataFields(jobEntity, jobRequestMetadata); // Set archive status jobEntity.setArchiveStatus( jobRequest.getRequestedAgentConfig().isArchivingDisabled() ? ArchiveStatus.DISABLED.name() : ArchiveStatus.PENDING.name() ); // Persist. Catch exception if the ID is reused try { final String id = this.jobRepository.save(jobEntity).getUniqueId(); log.debug( "[saveJobSubmission] Saved job submission {} under job id {}", jobSubmission, id ); final SpanCustomizer spanCustomizer = this.addJobIdTag(id); // This is a new job so add flag representing that fact this.tagAdapter.tag(spanCustomizer, TracingConstants.NEW_JOB_TAG, TracingConstants.TRUE_VALUE); return id; } catch (final DataIntegrityViolationException e) { throw new IdAlreadyExistsException( "A job with id " + jobEntity.getUniqueId() + " already exists. Unable to reserve id.", e ); } } /** * {@inheritDoc} */ @Override public JobRequest getJobRequest(@NotBlank final String id) throws NotFoundException { log.debug("[getJobRequest] Requested for id {}", id); return this.jobRepository .getV4JobRequest(id) .map(EntityV4DtoConverters::toV4JobRequestDto) .orElseThrow(() -> new NotFoundException("No job ith id " + id + " exists")); } /** * {@inheritDoc} */ @Override public void saveResolvedJob( @NotBlank final String id, @Valid final ResolvedJob resolvedJob ) throws NotFoundException { log.debug("[saveResolvedJob] Requested to save resolved information {} for job with id {}", resolvedJob, id); final JobEntity entity = this.getJobEntity(id); try { if (entity.isResolved()) { log.error("[saveResolvedJob] Job {} was already resolved", id); // This job has already been resolved there's nothing further to save return; } // Make sure if the job is resolvable otherwise don't do anything if (!DtoConverters.toV4JobStatus(entity.getStatus()).isResolvable()) { log.error( "[saveResolvedJob] Job {} is already in a non-resolvable state {}. Needs to be one of {}. Won't " + "save resolved info", id, entity.getStatus(), JobStatus.getResolvableStatuses() ); return; } final JobSpecification jobSpecification = resolvedJob.getJobSpecification(); this.setExecutionResources( entity, jobSpecification.getCluster().getId(), jobSpecification.getCommand().getId(), jobSpecification .getApplications() .stream() .map(JobSpecification.ExecutionResource::getId) .collect(Collectors.toList()) ); entity.setEnvironmentVariables(jobSpecification.getEnvironmentVariables()); entity.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); jobSpecification.getArchiveLocation().ifPresent(entity::setArchiveLocation); jobSpecification.getTimeout().ifPresent(entity::setTimeoutUsed); final JobEnvironment jobEnvironment = resolvedJob.getJobEnvironment(); this.updateComputeResources( jobEnvironment.getComputeResources(), entity::setCpuUsed, entity::setGpuUsed, entity::setMemoryUsed, entity::setDiskMbUsed, entity::setNetworkMbpsUsed ); this.updateImages( jobEnvironment.getImages(), entity::setImagesUsed ); entity.setResolved(true); entity.setStatus(JobStatus.RESOLVED.name()); log.debug("[saveResolvedJob] Saved resolved information {} for job with id {}", resolvedJob, id); } catch (final NotFoundException e) { log.error( "[saveResolvedJob] Unable to save resolved job information {} for job {} due to {}", resolvedJob, id, e.getMessage(), e ); throw e; } } /** * {@inheritDoc} */ @Override public Optional<JobSpecification> getJobSpecification(@NotBlank final String id) throws NotFoundException { log.debug("[getJobSpecification] Requested to get job specification for job {}", id); final JobSpecificationProjection projection = this.jobRepository .getJobSpecification(id) .orElseThrow( () -> new NotFoundException("No job ith id " + id + " exists. Unable to get job specification.") ); return projection.isResolved() ? Optional.of(EntityV4DtoConverters.toJobSpecificationDto(projection)) : Optional.empty(); } /** * {@inheritDoc} */ // TODO: The AOP aspects are firing on a lot of these APIs for retries and we may not want them to given a lot of // these are un-recoverable. May want to revisit what is in the aspect. @Override public void claimJob( @NotBlank final String id, @Valid final AgentClientMetadata agentClientMetadata ) throws NotFoundException, GenieJobAlreadyClaimedException, GenieInvalidStatusException { log.debug("[claimJob] Agent with metadata {} requesting to claim job with id {}", agentClientMetadata, id); final JobEntity jobEntity = this.getJobEntity(id); if (jobEntity.isClaimed()) { throw new GenieJobAlreadyClaimedException("Job with id " + id + " is already claimed. Unable to claim."); } final JobStatus currentStatus = DtoConverters.toV4JobStatus(jobEntity.getStatus()); // The job must be in one of the claimable states in order to be claimed // TODO: Perhaps could use jobEntity.isResolved here also but wouldn't check the case that the job was in a // terminal state like killed or invalid in which case we shouldn't claim it anyway as the agent would // continue running if (!currentStatus.isClaimable()) { throw new GenieInvalidStatusException( "Job " + id + " is in status " + currentStatus + " and can't be claimed. Needs to be one of " + JobStatus.getClaimableStatuses() ); } // Good to claim jobEntity.setClaimed(true); jobEntity.setStatus(JobStatus.CLAIMED.name()); // TODO: It might be nice to set the status message as well to something like "Job claimed by XYZ..." // we could do this in other places too like after reservation, resolving, etc // TODO: Should these be required? We're reusing the DTO here but perhaps the expectation at this point // is that the agent will always send back certain metadata agentClientMetadata.getHostname().ifPresent(jobEntity::setAgentHostname); agentClientMetadata.getVersion().ifPresent(jobEntity::setAgentVersion); agentClientMetadata.getPid().ifPresent(jobEntity::setAgentPid); log.debug("[claimJob] Claimed job {} for agent with metadata {}", id, agentClientMetadata); } /** * {@inheritDoc} */ @Override public JobStatus updateJobStatus( @NotBlank final String id, @NotNull final JobStatus currentStatus, @NotNull final JobStatus newStatus, @Nullable final String newStatusMessage ) throws NotFoundException { log.debug( "[updateJobStatus] Requested to change the status of job {} from {} to {} with message {}", id, currentStatus, newStatus, newStatusMessage ); if (currentStatus == newStatus) { log.debug( "[updateJobStatus] Requested new status for {} is same as current status: {}. Skipping update.", id, currentStatus ); return newStatus; } final JobEntity jobEntity = this.getJobEntity(id); final JobStatus actualCurrentStatus = DtoConverters.toV4JobStatus(jobEntity.getStatus()); if (actualCurrentStatus != currentStatus) { log.warn( "[updateJobStatus] Job {} actual status {} differs from expected status {}. Skipping update.", id, actualCurrentStatus, currentStatus ); return actualCurrentStatus; } // TODO: Should we prevent updating status for statuses already covered by "reserveJobId" and // "saveResolvedJob"? // Only change the status if the entity isn't already in a terminal state if (actualCurrentStatus.isActive()) { jobEntity.setStatus(newStatus.name()); jobEntity.setStatusMsg(StringUtils.truncate(newStatusMessage, MAX_STATUS_MESSAGE_LENGTH)); if (newStatus.equals(JobStatus.RUNNING)) { // Status being changed to running so set start date. jobEntity.setStarted(Instant.now()); } else if (jobEntity.getStarted().isPresent() && newStatus.isFinished()) { // Since start date is set the job was running previously and now has finished // with status killed, failed or succeeded. So we set the job finish time. jobEntity.setFinished(Instant.now()); } log.debug( "[updateJobStatus] Changed the status of job {} from {} to {} with message {}", id, currentStatus, newStatus, newStatusMessage ); return newStatus; } else { log.warn( "[updateJobStatus] Job status for {} is already terminal state {}. Skipping update.", id, actualCurrentStatus ); return actualCurrentStatus; } } /** * {@inheritDoc} */ @Override public void updateJobArchiveStatus( @NotBlank(message = "No job id entered. Unable to update.") final String id, @NotNull(message = "Status cannot be null.") final ArchiveStatus archiveStatus ) throws NotFoundException { log.debug( "[updateJobArchiveStatus] Requested to change the archive status of job {} to {}", id, archiveStatus ); this.jobRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No job exists for the id specified")) .setArchiveStatus(archiveStatus.name()); log.debug( "[updateJobArchiveStatus] Changed the archive status of job {} to {}", id, archiveStatus ); } /** * {@inheritDoc} */ @Override public JobStatus getJobStatus(@NotBlank final String id) throws NotFoundException { return DtoConverters.toV4JobStatus( this.jobRepository .getJobStatus(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists. Unable to get status.")) ); } /** * {@inheritDoc} */ @Override public ArchiveStatus getJobArchiveStatus(@NotBlank final String id) throws NotFoundException { try { return ArchiveStatus.valueOf( this.jobRepository .getArchiveStatus(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")) ); } catch (IllegalArgumentException e) { return ArchiveStatus.UNKNOWN; } } /** * {@inheritDoc} */ @Override public Optional<String> getJobArchiveLocation(@NotBlank final String id) throws NotFoundException { final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<String> query = criteriaBuilder.createQuery(String.class); final Root<JobEntity> root = query.from(JobEntity.class); query.select(root.get(JobEntity_.archiveLocation)); query.where(criteriaBuilder.equal(root.get(JobEntity_.uniqueId), id)); try { return Optional.ofNullable( this.entityManager .createQuery(query) .getSingleResult() ); } catch (final NoResultException e) { throw new NotFoundException("No job with id " + id + " exits.", e); } } /** * {@inheritDoc} */ @Override public FinishedJob getFinishedJob(@NotBlank final String id) throws NotFoundException, GenieInvalidStatusException { // TODO return this.jobRepository.findByUniqueId(id, FinishedJobProjection.class) .map(EntityV4DtoConverters::toFinishedJobDto) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists.")); } /** * {@inheritDoc} */ @Override public boolean isApiJob(@NotBlank final String id) throws NotFoundException { return this.jobRepository .isAPI(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")); } /** * {@inheritDoc} */ @Override public Cluster getJobCluster(@NotBlank final String id) throws NotFoundException { log.debug("[getJobCluster] Called for job {}", id); return EntityV4DtoConverters.toV4ClusterDto( this.jobRepository.getJobCluster(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")) .getCluster() .orElseThrow(() -> new NotFoundException("Job " + id + " has no associated cluster")) ); } /** * {@inheritDoc} */ @Override public Command getJobCommand(@NotBlank final String id) throws NotFoundException { log.debug("[getJobCommand] Called for job {}", id); return EntityV4DtoConverters.toV4CommandDto( this.jobRepository.getJobCommand(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")) .getCommand() .orElseThrow(() -> new NotFoundException("Job " + id + " has no associated command")) ); } /** * {@inheritDoc} */ @Override public List<Application> getJobApplications(@NotBlank final String id) throws NotFoundException { log.debug("[getJobApplications] Called for job {}", id); return this.jobRepository.getJobApplications(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")) .getApplications() .stream() .map(EntityV4DtoConverters::toV4ApplicationDto) .collect(Collectors.toList()); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public long getActiveJobCountForUser(@NotBlank final String user) { log.debug("[getActiveJobCountForUser] Called for jobs with user {}", user); final Long count = this.jobRepository.countJobsByUserAndStatusIn(user, ACTIVE_STATUS_SET); if (count == null || count < 0) { throw new GenieRuntimeException("Count query for user " + user + "produced an unexpected result: " + count); } return count; } /** * {@inheritDoc} */ @Override @Transactional(readOnly = true) public Map<String, UserResourcesSummary> getUserResourcesSummaries( final Set<JobStatus> statuses, final boolean api ) { log.debug("[getUserResourcesSummaries] Called for statuses {} and api {}", statuses, api); return this.jobRepository .getUserJobResourcesAggregates( statuses.stream().map(JobStatus::name).collect(Collectors.toSet()), api ) .stream() .map(EntityV3DtoConverters::toUserResourceSummaryDto) .collect(Collectors.toMap(UserResourcesSummary::getUser, userResourcesSummary -> userResourcesSummary)); } /** * {@inheritDoc} */ @Override public long getUsedMemoryOnHost(@NotBlank final String hostname) { log.debug("[getUsedMemoryOnHost] Called for hostname {}", hostname); return this.jobRepository.getTotalMemoryUsedOnHost(hostname, USING_MEMORY_JOB_SET); } /** * {@inheritDoc} */ @Override public Set<String> getActiveJobs() { log.debug("[getActiveJobs] Called"); return this.jobRepository.getJobIdsWithStatusIn(ACTIVE_STATUS_SET); } /** * {@inheritDoc} */ @Override public Set<String> getUnclaimedJobs() { log.debug("[getUnclaimedJobs] Called"); return this.jobRepository.getJobIdsWithStatusIn(UNCLAIMED_STATUS_SET); } /** * {@inheritDoc} */ @Override public JobInfoAggregate getHostJobInformation(@NotBlank final String hostname) { log.debug("[getHostJobInformation] Called for hostname {}", hostname); return this.jobRepository.getHostJobInfo(hostname, ACTIVE_STATUS_SET, USING_MEMORY_JOB_SET); } /** * {@inheritDoc} */ @Override public Set<String> getJobsWithStatusAndArchiveStatusUpdatedBefore( @NotEmpty final Set<JobStatus> statuses, @NotEmpty final Set<ArchiveStatus> archiveStatuses, @NotNull final Instant updated ) { log.debug( "[getJobsWithStatusAndArchiveStatusUpdatedBefore] Called with statuses {}, archiveStatuses {}, updated {}", statuses, archiveStatuses, updated ); return this.jobRepository.getJobsWithStatusAndArchiveStatusUpdatedBefore( statuses.stream().map(JobStatus::name).collect(Collectors.toSet()), archiveStatuses.stream().map(ArchiveStatus::name).collect(Collectors.toSet()), updated ); } /** * {@inheritDoc} */ @Override public void updateRequestedLauncherExt( @NotBlank(message = "No job id entered. Unable to update.") final String id, @NotNull(message = "Status cannot be null.") final JsonNode launcherExtension ) throws NotFoundException { log.debug("[updateRequestedLauncherExt] Requested to update launcher requested ext of job {}", id); this.jobRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No job exists for the id specified")) .setRequestedLauncherExt(launcherExtension); log.debug("[updateRequestedLauncherExt] Updated launcher requested ext of job {}", id); } /** * {@inheritDoc} */ @Override public JsonNode getRequestedLauncherExt(@NotBlank final String id) throws NotFoundException { log.debug("[getRequestedLauncherExt] Requested for job {}", id); return this.jobRepository.getRequestedLauncherExt(id).orElse(NullNode.getInstance()); } /** * {@inheritDoc} */ @Override public void updateLauncherExt( @NotBlank(message = "No job id entered. Unable to update.") final String id, @NotNull(message = "Status cannot be null.") final JsonNode launcherExtension ) throws NotFoundException { log.debug("[updateLauncherExt] Requested to update launcher ext of job {}", id); this.jobRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No job exists for the id specified")) .setLauncherExt(launcherExtension); log.debug("[updateLauncherExt] Updated launcher ext of job {}", id); } /** * {@inheritDoc} */ @Override public JsonNode getLauncherExt(@NotBlank final String id) throws NotFoundException { log.debug("[getLauncherExt] Requested for job {}", id); return this.jobRepository.getLauncherExt(id).orElse(NullNode.getInstance()); } //endregion //endregion //region General CommonResource APIs /** * {@inheritDoc} */ @Override public <R extends CommonResource> void addConfigsToResource( @NotBlank final String id, final Set<@Size(max = 1024) String> configs, final Class<R> resourceClass ) throws NotFoundException { this.getResourceConfigEntities(id, resourceClass).addAll(this.createOrGetFileEntities(configs)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> Set<String> getConfigsForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { return this.getResourceConfigEntities(id, resourceClass) .stream() .map(FileEntity::getFile) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void updateConfigsForResource( @NotBlank final String id, final Set<@Size(max = 1024) String> configs, final Class<R> resourceClass ) throws NotFoundException { final Set<FileEntity> configEntities = this.getResourceConfigEntities(id, resourceClass); configEntities.clear(); configEntities.addAll(this.createOrGetFileEntities(configs)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeAllConfigsForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { final Set<FileEntity> configEntities = this.getResourceConfigEntities(id, resourceClass); configEntities.clear(); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeConfigForResource( @NotBlank final String id, @NotBlank final String config, final Class<R> resourceClass ) throws NotFoundException { this.getResourceConfigEntities(id, resourceClass).removeIf(entity -> config.equals(entity.getFile())); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void addDependenciesToResource( @NotBlank final String id, final Set<@Size(max = 1024) String> dependencies, final Class<R> resourceClass ) throws NotFoundException { this.getResourceDependenciesEntities(id, resourceClass).addAll(this.createOrGetFileEntities(dependencies)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> Set<String> getDependenciesForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { return this.getResourceDependenciesEntities(id, resourceClass) .stream() .map(FileEntity::getFile) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void updateDependenciesForResource( @NotBlank final String id, final Set<@Size(max = 1024) String> dependencies, final Class<R> resourceClass ) throws NotFoundException { final Set<FileEntity> dependencyEntities = this.getResourceDependenciesEntities(id, resourceClass); dependencyEntities.clear(); dependencyEntities.addAll(this.createOrGetFileEntities(dependencies)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeAllDependenciesForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { final Set<FileEntity> dependencyEntities = this.getResourceDependenciesEntities(id, resourceClass); dependencyEntities.clear(); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeDependencyForResource( @NotBlank final String id, @NotBlank final String dependency, final Class<R> resourceClass ) throws NotFoundException { this.getResourceDependenciesEntities(id, resourceClass).removeIf(entity -> dependency.equals(entity.getFile())); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void addTagsToResource( @NotBlank final String id, final Set<@Size(max = 255) String> tags, final Class<R> resourceClass ) throws NotFoundException { this.getResourceTagEntities(id, resourceClass).addAll(this.createOrGetTagEntities(tags)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> Set<String> getTagsForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { return this.getResourceTagEntities(id, resourceClass) .stream() .map(TagEntity::getTag) .collect(Collectors.toSet()); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void updateTagsForResource( @NotBlank final String id, final Set<@Size(max = 255) String> tags, final Class<R> resourceClass ) throws NotFoundException { final Set<TagEntity> tagEntities = this.getResourceTagEntities(id, resourceClass); tagEntities.clear(); tagEntities.addAll(this.createOrGetTagEntities(tags)); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeAllTagsForResource( @NotBlank final String id, final Class<R> resourceClass ) throws NotFoundException { final Set<TagEntity> tagEntities = this.getResourceTagEntities(id, resourceClass); tagEntities.clear(); } /** * {@inheritDoc} */ @Override public <R extends CommonResource> void removeTagForResource( @NotBlank final String id, @NotBlank final String tag, final Class<R> resourceClass ) throws NotFoundException { this.getResourceTagEntities(id, resourceClass).removeIf(entity -> tag.equals(entity.getTag())); } //endregion //region Tag APIs /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteUnusedTags(@NotNull final Instant createdThreshold, @Min(1) final int batchSize) { log.info("[deleteUnusedTags] Called to delete unused tags created before {}", createdThreshold); return this.tagRepository.deleteByIdIn( this.tagRepository .findUnusedTags(createdThreshold, batchSize) .stream() .map(Number::longValue) .collect(Collectors.toSet()) ); } //endregion //region File APIs /** * {@inheritDoc} */ @Override @Transactional(isolation = Isolation.READ_COMMITTED) public long deleteUnusedFiles(@NotNull final Instant createdThresholdLowerBound, @NotNull final Instant createdThresholdUpperBound, @Min(1) final int batchSize) { log.debug( "[deleteUnusedFiles] Called to delete unused files created between {} and {}", createdThresholdLowerBound, createdThresholdUpperBound ); return this.fileRepository.deleteByIdIn( this.fileRepository .findUnusedFiles(createdThresholdLowerBound, createdThresholdUpperBound, batchSize) .stream() .map(Number::longValue) .collect(Collectors.toSet()) ); } //endregion //region Helper Methods private ApplicationEntity getApplicationEntity(final String id) throws NotFoundException { return this.applicationRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No application with id " + id + " exists")); } private ClusterEntity getClusterEntity(final String id) throws NotFoundException { return this.clusterRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No cluster with id " + id + " exists")); } private CommandEntity getCommandEntity(final String id) throws NotFoundException { return this.commandRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); } private JobEntity getJobEntity(final String id) throws NotFoundException { return this.jobRepository .findByUniqueId(id) .orElseThrow(() -> new NotFoundException("No job with id " + id + " exists")); } private FileEntity createOrGetFileEntity(final String file) { return this.createOrGetSharedEntity( file, this.fileRepository::findByFile, FileEntity::new, this.fileRepository::saveAndFlush ); } private Set<FileEntity> createOrGetFileEntities(final Set<String> files) { return files.stream().map(this::createOrGetFileEntity).collect(Collectors.toSet()); } private TagEntity createOrGetTagEntity(final String tag) { return this.createOrGetSharedEntity( tag, this.tagRepository::findByTag, TagEntity::new, this.tagRepository::saveAndFlush ); } private Set<TagEntity> createOrGetTagEntities(final Set<String> tags) { return tags.stream().map(this::createOrGetTagEntity).collect(Collectors.toSet()); } private <E> E createOrGetSharedEntity( final String value, final Function<String, Optional<E>> find, final Function<String, E> entityCreation, final Function<E, E> saveAndFlush ) { final Optional<E> existingEntity = find.apply(value); if (existingEntity.isPresent()) { return existingEntity.get(); } try { return saveAndFlush.apply(entityCreation.apply(value)); } catch (final DataIntegrityViolationException e) { // If this isn't found now there's really nothing we can do so throw runtime return find .apply(value) .orElseThrow( () -> new GenieRuntimeException(value + " entity creation failed but still can't find record", e) ); } } private <R extends CommonResource> Set<FileEntity> getResourceConfigEntities( final String id, final Class<R> resourceClass ) throws NotFoundException { if (resourceClass.equals(Application.class)) { return this.getApplicationEntity(id).getConfigs(); } else if (resourceClass.equals(Cluster.class)) { return this.getClusterEntity(id).getConfigs(); } else if (resourceClass.equals(Command.class)) { return this.getCommandEntity(id).getConfigs(); } else { throw new IllegalArgumentException("Unsupported type: " + resourceClass); } } private <R extends CommonResource> Set<FileEntity> getResourceDependenciesEntities( final String id, final Class<R> resourceClass ) throws NotFoundException { if (resourceClass.equals(Application.class)) { return this.getApplicationEntity(id).getDependencies(); } else if (resourceClass.equals(Cluster.class)) { return this.getClusterEntity(id).getDependencies(); } else if (resourceClass.equals(Command.class)) { return this.getCommandEntity(id).getDependencies(); } else { throw new IllegalArgumentException("Unsupported type: " + resourceClass); } } private <R extends CommonResource> Set<TagEntity> getResourceTagEntities( final String id, final Class<R> resourceClass ) throws NotFoundException { if (resourceClass.equals(Application.class)) { return this.getApplicationEntity(id).getTags(); } else if (resourceClass.equals(Cluster.class)) { return this.getClusterEntity(id).getTags(); } else if (resourceClass.equals(Command.class)) { return this.getCommandEntity(id).getTags(); } else { throw new IllegalArgumentException("Unsupported type: " + resourceClass); } } private <E extends UniqueIdEntity> void setUniqueId(final E entity, @Nullable final String requestedId) { if (requestedId != null) { entity.setUniqueId(requestedId); entity.setRequestedId(true); } else { entity.setUniqueId(UUID.randomUUID().toString()); entity.setRequestedId(false); } } private void setEntityResources( final ExecutionEnvironment resources, final Consumer<Set<FileEntity>> configsConsumer, final Consumer<Set<FileEntity>> dependenciesConsumer ) { // Save all the unowned entities first to avoid unintended flushes configsConsumer.accept(this.createOrGetFileEntities(resources.getConfigs())); dependenciesConsumer.accept(this.createOrGetFileEntities(resources.getDependencies())); } private void setEntityTags(final Set<String> tags, final Consumer<Set<TagEntity>> tagsConsumer) { tagsConsumer.accept(this.createOrGetTagEntities(tags)); } private void updateApplicationEntity( final ApplicationEntity entity, final ExecutionEnvironment resources, final ApplicationMetadata metadata ) { entity.setStatus(metadata.getStatus().name()); entity.setType(metadata.getType().orElse(null)); this.setEntityResources(resources, entity::setConfigs, entity::setDependencies); this.setEntityTags(metadata.getTags(), entity::setTags); this.setBaseEntityMetadata(entity, metadata, resources.getSetupFile().orElse(null)); } private void updateClusterEntity( final ClusterEntity entity, final ExecutionEnvironment resources, final ClusterMetadata metadata ) { entity.setStatus(metadata.getStatus().name()); this.setEntityResources(resources, entity::setConfigs, entity::setDependencies); this.setEntityTags(metadata.getTags(), entity::setTags); this.setBaseEntityMetadata(entity, metadata, resources.getSetupFile().orElse(null)); } // Compiler keeps complaining about `executable` being marked nullable, it isn't @SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE") private void updateCommandEntity( final CommandEntity entity, final ExecutionEnvironment resources, final CommandMetadata metadata, final List<String> executable, @Nullable final ComputeResources computeResources, final List<Criterion> clusterCriteria, @Nullable final Map<String, Image> images ) { this.setEntityResources(resources, entity::setConfigs, entity::setDependencies); this.setEntityTags(metadata.getTags(), entity::setTags); this.setBaseEntityMetadata(entity, metadata, resources.getSetupFile().orElse(null)); entity.setStatus(metadata.getStatus().name()); entity.setExecutable(executable); this.updateComputeResources( computeResources, entity::setCpu, entity::setGpu, entity::setMemory, entity::setDiskMb, entity::setNetworkMbps ); this.updateImages(images, entity::setImages); this.updateClusterCriteria(entity, clusterCriteria); } private void setBaseEntityMetadata( final BaseEntity entity, final CommonMetadata metadata, @Nullable final String setupFile ) { // NOTE: These are all called in case someone has changed it to set something to null. DO NOT use ifPresent entity.setName(metadata.getName()); entity.setUser(metadata.getUser()); entity.setVersion(metadata.getVersion()); entity.setDescription(metadata.getDescription().orElse(null)); entity.setMetadata(metadata.getMetadata().orElse(null)); entity.setSetupFile(setupFile == null ? null : this.createOrGetFileEntity(setupFile)); } private void deleteApplicationEntity(final ApplicationEntity entity) throws PreconditionFailedException { final Set<CommandEntity> commandEntities = entity.getCommands(); if (!commandEntities.isEmpty()) { throw new PreconditionFailedException( "Unable to delete application with id " + entity.getUniqueId() + " as it is still used by the following commands: " + commandEntities.stream().map(CommandEntity::getUniqueId).collect(Collectors.joining()) ); } this.applicationRepository.delete(entity); } private void deleteClusterEntity(final ClusterEntity entity) { this.clusterRepository.delete(entity); } private void deleteCommandEntity(final CommandEntity entity) { //Remove the command from the associated Application references final List<ApplicationEntity> originalApps = entity.getApplications(); if (originalApps != null) { final List<ApplicationEntity> applicationEntities = Lists.newArrayList(originalApps); applicationEntities.forEach(entity::removeApplication); } this.commandRepository.delete(entity); } private void deleteAllClusterCriteria(final CommandEntity commandEntity) { final List<CriterionEntity> persistedEntities = commandEntity.getClusterCriteria(); final List<CriterionEntity> entitiesToDelete = Lists.newArrayList(persistedEntities); persistedEntities.clear(); // Ensure Criterion aren't left dangling this.criterionRepository.deleteAll(entitiesToDelete); } private CriterionEntity toCriterionEntity(final Criterion criterion) { final CriterionEntity criterionEntity = new CriterionEntity(); criterion.getId().ifPresent(criterionEntity::setUniqueId); criterion.getName().ifPresent(criterionEntity::setName); criterion.getVersion().ifPresent(criterionEntity::setVersion); criterion.getStatus().ifPresent(criterionEntity::setStatus); criterionEntity.setTags(this.createOrGetTagEntities(criterion.getTags())); return criterionEntity; } private void updateClusterCriteria(final CommandEntity commandEntity, final List<Criterion> clusterCriteria) { // First remove all the old criteria this.deleteAllClusterCriteria(commandEntity); // Set the new criteria commandEntity.setClusterCriteria( clusterCriteria .stream() .map(this::toCriterionEntity) .collect(Collectors.toList()) ); } private void setJobMetadataFields( final JobEntity jobEntity, final JobMetadata jobMetadata, @Nullable final String setupFile ) { this.setBaseEntityMetadata(jobEntity, jobMetadata, setupFile); this.setEntityTags(jobMetadata.getTags(), jobEntity::setTags); jobMetadata.getEmail().ifPresent(jobEntity::setEmail); jobMetadata.getGroup().ifPresent(jobEntity::setGenieUserGroup); jobMetadata.getGrouping().ifPresent(jobEntity::setGrouping); jobMetadata.getGroupingInstance().ifPresent(jobEntity::setGroupingInstance); } private void setJobExecutionEnvironmentFields( final JobEntity jobEntity, final ExecutionEnvironment executionEnvironment, @Nullable final Set<URI> savedAttachments ) { jobEntity.setConfigs(this.createOrGetFileEntities(executionEnvironment.getConfigs())); final Set<FileEntity> dependencies = this.createOrGetFileEntities(executionEnvironment.getDependencies()); if (savedAttachments != null) { dependencies.addAll( this.createOrGetFileEntities(savedAttachments.stream().map(URI::toString).collect(Collectors.toSet())) ); } jobEntity.setDependencies(dependencies); } private void setExecutionResourceCriteriaFields( final JobEntity jobEntity, final ExecutionResourceCriteria criteria ) { final List<Criterion> clusterCriteria = criteria.getClusterCriteria(); final List<CriterionEntity> clusterCriteriaEntities = Lists.newArrayListWithExpectedSize(clusterCriteria.size()); for (final Criterion clusterCriterion : clusterCriteria) { clusterCriteriaEntities.add(this.toCriterionEntity(clusterCriterion)); } jobEntity.setClusterCriteria(clusterCriteriaEntities); jobEntity.setCommandCriterion(this.toCriterionEntity(criteria.getCommandCriterion())); jobEntity.setRequestedApplications(criteria.getApplicationIds()); } private void setRequestedJobEnvironmentFields( final JobEntity jobEntity, final JobEnvironmentRequest requestedJobEnvironment ) { jobEntity.setRequestedEnvironmentVariables(requestedJobEnvironment.getRequestedEnvironmentVariables()); this.updateComputeResources( requestedJobEnvironment.getRequestedComputeResources(), jobEntity::setRequestedCpu, jobEntity::setRequestedGpu, jobEntity::setRequestedMemory, jobEntity::setRequestedDiskMb, jobEntity::setRequestedNetworkMbps ); requestedJobEnvironment.getExt().ifPresent(jobEntity::setRequestedAgentEnvironmentExt); this.updateImages(requestedJobEnvironment.getRequestedImages(), jobEntity::setRequestedImages); } private void setRequestedAgentConfigFields( final JobEntity jobEntity, final AgentConfigRequest requestedAgentConfig ) { jobEntity.setInteractive(requestedAgentConfig.isInteractive()); jobEntity.setArchivingDisabled(requestedAgentConfig.isArchivingDisabled()); requestedAgentConfig .getRequestedJobDirectoryLocation() .ifPresent(location -> jobEntity.setRequestedJobDirectoryLocation(location.getAbsolutePath())); requestedAgentConfig.getTimeoutRequested().ifPresent(jobEntity::setRequestedTimeout); requestedAgentConfig.getExt().ifPresent(jobEntity::setRequestedAgentConfigExt); } private void setRequestMetadataFields( final JobEntity jobEntity, final JobRequestMetadata jobRequestMetadata ) { jobEntity.setApi(jobRequestMetadata.isApi()); jobEntity.setNumAttachments(jobRequestMetadata.getNumAttachments()); jobEntity.setTotalSizeOfAttachments(jobRequestMetadata.getTotalSizeOfAttachments()); jobRequestMetadata.getApiClientMetadata().ifPresent( apiClientMetadata -> { apiClientMetadata.getHostname().ifPresent(jobEntity::setRequestApiClientHostname); apiClientMetadata.getUserAgent().ifPresent(jobEntity::setRequestApiClientUserAgent); } ); jobRequestMetadata.getAgentClientMetadata().ifPresent( agentClientMetadata -> { agentClientMetadata.getHostname().ifPresent(jobEntity::setRequestAgentClientHostname); agentClientMetadata.getVersion().ifPresent(jobEntity::setRequestAgentClientVersion); agentClientMetadata.getPid().ifPresent(jobEntity::setRequestAgentClientPid); } ); } private void setExecutionResources( final JobEntity job, final String clusterId, final String commandId, final List<String> applicationIds ) throws NotFoundException { final ClusterEntity cluster = this.getClusterEntity(clusterId); final CommandEntity command = this.getCommandEntity(commandId); final List<ApplicationEntity> applications = Lists.newArrayList(); for (final String applicationId : applicationIds) { applications.add(this.getApplicationEntity(applicationId)); } job.setCluster(cluster); job.setCommand(command); job.setApplications(applications); } private <E extends BaseEntity> Optional<E> getEntityOrNullForFindJobs( final JpaBaseRepository<E> repository, final String id, @Nullable final String name ) { // User is requesting jobs using a given entity. If it doesn't exist short circuit the search final Optional<E> optionalEntity = repository.findByUniqueId(id); if (optionalEntity.isPresent()) { final E entity = optionalEntity.get(); // If the name doesn't match user input request we can also short circuit search if (name != null && !entity.getName().equals(name)) { // Won't find anything matching the query return Optional.empty(); } } return optionalEntity; } private SpanCustomizer addJobIdTag(final String jobId) { final SpanCustomizer spanCustomizer = this.tracer.currentSpanCustomizer(); this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_ID_TAG, jobId); return spanCustomizer; } private void updateComputeResources( @Nullable final ComputeResources computeResources, final Consumer<Integer> cpuSetter, final Consumer<Integer> gpuSetter, final Consumer<Long> memorySetter, final Consumer<Long> diskMbSetter, final Consumer<Long> networkMbpsSetter ) { // If nothing was passed in assume it means the user desired everything to be null or missing if (computeResources == null) { cpuSetter.accept(null); gpuSetter.accept(null); memorySetter.accept(null); diskMbSetter.accept(null); networkMbpsSetter.accept(null); } else { // NOTE: These are all called in case someone has changed it to set something to null. DO NOT use ifPresent cpuSetter.accept(computeResources.getCpu().orElse(null)); gpuSetter.accept(computeResources.getGpu().orElse(null)); memorySetter.accept(computeResources.getMemoryMb().orElse(null)); diskMbSetter.accept(computeResources.getDiskMb().orElse(null)); networkMbpsSetter.accept(computeResources.getNetworkMbps().orElse(null)); } } private void updateImages( @Nullable final Map<String, Image> images, final Consumer<JsonNode> imagesSetter ) { if (images == null) { imagesSetter.accept(null); } else { imagesSetter.accept(GenieObjectMapper.getMapper().valueToTree(images)); } } //endregion }
2,673
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/package-info.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Implementations of data services with JPA as the underlying technology. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services.impl.jpa; import javax.annotation.ParametersAreNonnullByDefault;
2,674
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/package-info.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Classes related to performing quires on a relational database for Genie. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services.impl.jpa.queries; import javax.annotation.ParametersAreNonnullByDefault;
2,675
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/ApplicationPredicates.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.data.services.impl.jpa.queries.predicates; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * {@link Predicate} generation helpers for querying {@link ApplicationEntity}. * * @author tgianos */ public final class ApplicationPredicates { /** * Private constructor for utility class. */ private ApplicationPredicates() { } /** * Get a {@link Predicate} using the specified parameters. * * @param root The {@link Root} (from) for this query * @param cq The {@link CriteriaQuery} instance this predicate is for * @param cb The {@link CriteriaBuilder} for the query * @param name The name of the application * @param user The name of the user who created the application * @param statuses The status of the application * @param tags The set of tags to search with * @param type The type of applications to fine * @return A specification object used for querying */ public static Predicate find( final Root<ApplicationEntity> root, final AbstractQuery<?> cq, final CriteriaBuilder cb, @Nullable final String name, @Nullable final String user, @Nullable final Set<String> statuses, @Nullable final Set<TagEntity> tags, @Nullable final String type ) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(name)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(ApplicationEntity_.name), name) ); } if (StringUtils.isNotBlank(user)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(ApplicationEntity_.user), user) ); } if (statuses != null && !statuses.isEmpty()) { predicates.add( cb.or( statuses .stream() .map(status -> cb.equal(root.get(ApplicationEntity_.status), status)) .toArray(Predicate[]::new) ) ); } if (tags != null && !tags.isEmpty()) { final Join<ApplicationEntity, TagEntity> tagEntityJoin = root.join(ApplicationEntity_.tags); predicates.add(tagEntityJoin.in(tags)); cq.groupBy(root.get(ApplicationEntity_.id)); cq.having(cb.equal(cb.count(root.get(ApplicationEntity_.id)), tags.size())); } if (StringUtils.isNotBlank(type)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(ApplicationEntity_.type), type) ); } return cb.and(predicates.toArray(new Predicate[0])); } }
2,676
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/JobPredicates.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.data.services.impl.jpa.queries.predicates; import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity_; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * {@link Predicate} helpers for querying {@link JobEntity}. * * @author tgianos */ public final class JobPredicates { /** * Protected constructor for utility class. */ private JobPredicates() { } /** * Generate a criteria query predicate for a where clause based on the given parameters. * * @param root The root to use * @param cb The criteria builder to use * @param id The job id * @param name The job name * @param user The user who created the job * @param statuses The job statuses * @param tags The tags for the jobs to find * @param clusterName The cluster name * @param cluster The cluster the job should have been run on * @param commandName The command name * @param command The command the job should have been run with * @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 job grouping to search for * @param groupingInstance The job grouping instance to search for * @return The specification */ @SuppressWarnings("checkstyle:parameternumber") public static Predicate getFindPredicate( final Root<JobEntity> root, final CriteriaBuilder cb, @Nullable final String id, @Nullable final String name, @Nullable final String user, @Nullable final Set<String> statuses, @Nullable final Set<String> tags, @Nullable final String clusterName, @Nullable final ClusterEntity cluster, @Nullable final String commandName, @Nullable final CommandEntity command, @Nullable final Instant minStarted, @Nullable final Instant maxStarted, @Nullable final Instant minFinished, @Nullable final Instant maxFinished, @Nullable final String grouping, @Nullable final String groupingInstance ) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(id)) { predicates.add(PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.uniqueId), id)); } if (StringUtils.isNotBlank(name)) { predicates.add(PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name)); } if (StringUtils.isNotBlank(user)) { predicates.add(PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user)); } if (statuses != null && !statuses.isEmpty()) { predicates.add( cb.or( statuses .stream() .map(status -> cb.equal(root.get(JobEntity_.status), status)).toArray(Predicate[]::new) ) ); } if (tags != null && !tags.isEmpty()) { predicates.add(cb.like(root.get(JobEntity_.tagSearchString), PredicateUtils.getTagLikeString(tags))); } if (cluster != null) { predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster)); } if (StringUtils.isNotBlank(clusterName)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName), clusterName) ); } if (command != null) { predicates.add(cb.equal(root.get(JobEntity_.command), command)); } if (StringUtils.isNotBlank(commandName)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName), commandName) ); } if (minStarted != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted)); } if (maxStarted != null) { predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted)); } if (minFinished != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished)); } if (maxFinished != null) { predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished)); } if (grouping != null) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.grouping), grouping) ); } if (groupingInstance != null) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate( cb, root.get(JobEntity_.groupingInstance), groupingInstance ) ); } return cb.and(predicates.toArray(new Predicate[0])); } }
2,677
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/ClusterPredicates.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.data.services.impl.jpa.queries.predicates; import com.google.common.collect.Lists; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import org.apache.commons.lang3.StringUtils; import org.springframework.data.jpa.domain.Specification; import javax.annotation.Nullable; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * {@link Predicate} generation helpers for querying {@link ClusterEntity}. * * @author tgianos */ public final class ClusterPredicates { /** * Private constructor for utility class. */ private ClusterPredicates() { } /** * Generate a {@link Predicate} given the parameters. * * @param root The {@link Root} of the query * @param cq The {@link CriteriaQuery} * @param cb The {@link CriteriaBuilder} * @param name The name of the cluster to find * @param statuses The statuses of the clusters to find * @param tags The tags of the clusters to find * @param minUpdateTime The minimum updated time of the clusters to find * @param maxUpdateTime The maximum updated time of the clusters to find * @return The {@link Predicate} representing these parameters */ public static Predicate find( final Root<ClusterEntity> root, final AbstractQuery<?> cq, final CriteriaBuilder cb, @Nullable final String name, @Nullable final Set<String> statuses, @Nullable final Set<TagEntity> tags, @Nullable final Instant minUpdateTime, @Nullable final Instant maxUpdateTime ) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(name)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(ClusterEntity_.name), name) ); } if (minUpdateTime != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(ClusterEntity_.updated), minUpdateTime)); } if (maxUpdateTime != null) { predicates.add(cb.lessThan(root.get(ClusterEntity_.updated), maxUpdateTime)); } if (tags != null && !tags.isEmpty()) { final Join<ClusterEntity, TagEntity> tagEntityJoin = root.join(ClusterEntity_.tags); predicates.add(tagEntityJoin.in(tags)); cq.groupBy(root.get(ClusterEntity_.id)); cq.having(cb.equal(cb.count(root.get(ClusterEntity_.id)), tags.size())); } if (statuses != null && !statuses.isEmpty()) { //Could optimize this as we know size could use native array predicates.add( cb.or( statuses .stream() .map(status -> cb.equal(root.get(ClusterEntity_.status), status)) .toArray(Predicate[]::new) ) ); } return cb.and(predicates.toArray(new Predicate[0])); } /** * Get the {@link Predicate} for the query which will find the clusters which match the given criterion. * * @param root The {@link Root} of the query * @param cq The {@link CriteriaQuery} * @param cb The {@link CriteriaBuilder} * @param criterion The {@link Criterion} to match clusters against * @return A {@link Predicate} for this query */ public static Predicate findClustersMatchingCriterion( final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb, final Criterion criterion ) { final Subquery<Long> criterionSubquery = cq.subquery(Long.class); final Root<ClusterEntity> criterionSubqueryRoot = criterionSubquery.from(ClusterEntity.class); criterionSubquery.select(criterionSubqueryRoot.get(ClusterEntity_.id)); criterionSubquery.where( PredicateUtils.createCriterionPredicate( criterionSubqueryRoot, criterionSubquery, cb, ClusterEntity_.uniqueId, ClusterEntity_.name, ClusterEntity_.version, ClusterEntity_.status, () -> criterionSubqueryRoot.join(ClusterEntity_.tags, JoinType.INNER), ClusterEntity_.id, criterion ) ); return root.get(ClusterEntity_.id).in(criterionSubquery); } /** * Get the specification for the query which will find the clusters which match any of the given criterion. * * @param root The {@link Root} of the query * @param cq The {@link CriteriaQuery} * @param cb The {@link CriteriaBuilder} * @param criteria The set of {@link Criterion} to match clusters against * @return A {@link Specification} for this query */ public static Predicate findClustersMatchingAnyCriterion( final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb, final Set<Criterion> criteria ) { final List<Predicate> predicates = Lists.newArrayList(); for (final Criterion criterion : criteria) { predicates.add(findClustersMatchingCriterion(root, cq, cb, criterion)); } return cb.or(predicates.toArray(new Predicate[0])); } }
2,678
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/PredicateUtils.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.data.services.impl.jpa.queries.predicates; import com.google.common.collect.Lists; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.web.data.services.impl.jpa.entities.BaseEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.IdEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.UniqueIdEntity; import org.apache.commons.lang3.StringUtils; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Join; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.SingularAttribute; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Set; import java.util.function.Supplier; /** * Utility methods for the JPA {@link Predicate} generation. * * @author tgianos * @since 3.0.0 */ public final class PredicateUtils { static final String PERCENT = "%"; static final String TAG_DELIMITER = "|"; private PredicateUtils() { } /** * Convert a set of TagEntities to the '|' delimited tag search string. * * @param tags The tags to convert * @return The tag search string in case insensitive order. e.g. |tag1||tag2||tag3| */ public static String createTagSearchString(final Set<TagEntity> tags) { // Tag search string length max is currently 1024 which will be caught by hibernate validator if this // exceeds that length return TAG_DELIMITER + tags .stream() .map(TagEntity::getTag) .sorted(String.CASE_INSENSITIVE_ORDER) .reduce((one, two) -> one + TAG_DELIMITER + TAG_DELIMITER + two) .orElse("") + TAG_DELIMITER; } /** * Create either an equals or like predicate based on the presence of the '%' character in the search value. * * @param cb The criteria builder to use for predicate creation * @param expression The expression of the field the predicate is acting on * @param value The value to compare the field to * @return A LIKE predicate if the value contains a '%' otherwise an EQUAL predicate */ static Predicate getStringLikeOrEqualPredicate( @NotNull final CriteriaBuilder cb, @NotNull final Expression<String> expression, @NotNull final String value ) { if (StringUtils.contains(value, PERCENT)) { return cb.like(expression, value); } else { return cb.equal(expression, value); } } /** * Get the sorted like statement for tags used in specification queries. * * @param tags The tags to use. Not null. * @return The tags sorted while ignoring case delimited with percent symbol. */ static String getTagLikeString(@NotNull final Set<String> tags) { final StringBuilder builder = new StringBuilder(); tags.stream() .filter(StringUtils::isNotBlank) .sorted(String.CASE_INSENSITIVE_ORDER) .forEach( tag -> builder .append(PERCENT) .append(TAG_DELIMITER) .append(tag) .append(TAG_DELIMITER) ); return builder.append(PERCENT).toString(); } static <E extends BaseEntity> Predicate createCriterionPredicate( final Root<E> root, final AbstractQuery<?> cq, final CriteriaBuilder cb, final SingularAttribute<UniqueIdEntity, String> uniqueIdAttribute, final SingularAttribute<BaseEntity, String> nameAttribute, final SingularAttribute<BaseEntity, String> versionAttribute, final SingularAttribute<BaseEntity, String> statusAttribute, final Supplier<Join<E, TagEntity>> tagJoinSupplier, final SingularAttribute<IdEntity, Long> idAttribute, final Criterion criterion ) { final List<Predicate> predicates = Lists.newArrayList(); criterion.getId().ifPresent(id -> predicates.add(cb.equal(root.get(uniqueIdAttribute), id))); criterion.getName().ifPresent(name -> predicates.add(cb.equal(root.get(nameAttribute), name))); criterion.getVersion().ifPresent(version -> predicates.add(cb.equal(root.get(versionAttribute), version))); criterion.getStatus().ifPresent(status -> predicates.add(cb.equal(root.get(statusAttribute), status))); final Set<String> tags = criterion.getTags(); if (!tags.isEmpty()) { final Join<E, TagEntity> tagJoin = tagJoinSupplier.get(); predicates.add(tagJoin.get(TagEntity_.tag).in(tags)); cq.groupBy(root.get(idAttribute)); cq.having( cb.equal( cb.count(root.get(idAttribute)), tags.size() ) ); } return cb.and(predicates.toArray(new Predicate[0])); } }
2,679
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/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. * */ /** * Package containing specification classes for use with JPA queries through Spring. * * @author tgianos * @since 3.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services.impl.jpa.queries.predicates; import javax.annotation.ParametersAreNonnullByDefault;
2,680
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/predicates/CommandPredicates.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.data.services.impl.jpa.queries.predicates; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity_; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.persistence.criteria.AbstractQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * {@link Predicate} generation helpers for querying {@link CommandEntity}. * * @author tgianos */ public final class CommandPredicates { /** * Private constructor for utility class. */ private CommandPredicates() { } /** * Get a predicate using the specified parameters. * * @param root The {@link Root} (from) for this query * @param cq The {@link CriteriaQuery} instance this predicate is for * @param cb The {@link CriteriaBuilder} for the query * @param name The name of the command * @param user The name of the user who created the command * @param statuses The status of the command * @param tags The set of tags to search the command for * @return A {@link Predicate} object used for querying */ public static Predicate find( final Root<CommandEntity> root, final AbstractQuery<?> cq, final CriteriaBuilder cb, @Nullable final String name, @Nullable final String user, @Nullable final Set<String> statuses, @Nullable final Set<TagEntity> tags ) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(name)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(CommandEntity_.name), name) ); } if (StringUtils.isNotBlank(user)) { predicates.add( PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(CommandEntity_.user), user) ); } if (statuses != null && !statuses.isEmpty()) { predicates.add( cb.or( statuses .stream() .map(status -> cb.equal(root.get(CommandEntity_.status), status)) .toArray(Predicate[]::new) ) ); } if (tags != null && !tags.isEmpty()) { final Join<CommandEntity, TagEntity> tagEntityJoin = root.join(CommandEntity_.tags); predicates.add(tagEntityJoin.in(tags)); cq.groupBy(root.get(CommandEntity_.id)); cq.having(cb.equal(cb.count(root.get(CommandEntity_.id)), tags.size())); } return cb.and(predicates.toArray(new Predicate[0])); } /** * Get the specification for the query which will find the commands which match the given criterion. * * @param root The {@link Root} (from) for the query * @param cq The {@link CriteriaQuery} instance * @param cb The {@link CriteriaBuilder} instance * @param criterion The {@link Criterion} to match commands against * @return A {@link Predicate} for this query */ public static Predicate findCommandsMatchingCriterion( final Root<CommandEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb, final Criterion criterion ) { final Subquery<Long> criterionSubquery = cq.subquery(Long.class); final Root<CommandEntity> criterionSubqueryRoot = criterionSubquery.from(CommandEntity.class); criterionSubquery.select(criterionSubqueryRoot.get(CommandEntity_.id)); criterionSubquery.where( cb.and( PredicateUtils.createCriterionPredicate( criterionSubqueryRoot, criterionSubquery, cb, CommandEntity_.uniqueId, CommandEntity_.name, CommandEntity_.version, CommandEntity_.status, () -> criterionSubqueryRoot.join(CommandEntity_.tags, JoinType.INNER), CommandEntity_.id, criterion ), cb.isNotEmpty(criterionSubqueryRoot.get(CommandEntity_.clusterCriteria)) ) ); return root.get(CommandEntity_.id).in(criterionSubquery); } }
2,681
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/aggregates/JobInfoAggregate.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.data.services.impl.jpa.queries.aggregates; /** * An object to return aggregate data selected with regards to memory usage on a given Genie host. * * @author tgianos * @since 4.0.0 */ public interface JobInfoAggregate { /** * Get the total amount of memory (in MB) that was allocated by jobs on this host. * * @return The total memory allocated */ long getTotalMemoryAllocated(); /** * Get the total amount of memory (in MB) that is actively in use by jobs on this host. * * @return The total memory used */ long getTotalMemoryUsed(); /** * Get the number of jobs in any of the active states on this host. * * @return The number of active jobs */ long getNumberOfActiveJobs(); }
2,682
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/aggregates/UserJobResourcesAggregate.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.data.services.impl.jpa.queries.aggregates; /** * An aggregate of running jobs and memory used for a given user. * * @author mprimi * @since 4.0.0 */ public interface UserJobResourcesAggregate { /** * Get the user name. * * @return the user name */ String getUser(); /** * Get the number of running jobs for the user. * * @return count of jobs */ Long getRunningJobsCount(); /** * Get the total amount of memory used by all running jobs for the user. * * @return amount of memory (in megabytes) */ Long getUsedMemory(); }
2,683
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/aggregates/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. * */ /** * A package containing aggregates interfaces for Spring Data JPA. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.web.data.services.impl.jpa.queries.aggregates; import javax.annotation.ParametersAreNonnullByDefault;
2,684
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/UniqueIdProjection.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.data.services.impl.jpa.queries.projections; /** * Projection for getting the Unique Id of a resource. * * @author tgianos * @since 4.0.0 */ public interface UniqueIdProjection extends AuditProjection { /** * Get the unique identifier for this entity. * * @return The globally unique identifier of this entity */ String getUniqueId(); }
2,685
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobCommonFieldsProjection.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.data.services.impl.jpa.queries.projections; import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity; import java.util.List; import java.util.Optional; import java.util.Set; /** * Projection for common fields between pre 3.3.0 JobRequest and Job entities. * * @author tgianos * @since 3.3.0 */ public interface JobCommonFieldsProjection extends BaseProjection { /** * Get the command arguments for this job. * * @return The command arguments */ List<String> getCommandArgs(); /** * Get the tags for the job. * * @return Any tags that were sent in when job was originally requested */ Set<TagEntity> getTags(); /** * Get the grouping this job is a part of. e.g. scheduler job name for job run many times * * @return The grouping */ Optional<String> getGrouping(); /** * Get the instance identifier of a grouping. e.g. the run id of a given scheduled job * * @return The grouping instance */ Optional<String> getGroupingInstance(); }
2,686
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/StatusProjection.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.data.services.impl.jpa.queries.projections; /** * Projection for returning only the status of a given resource. * * @author tgianos * @since 3.3.0 */ public interface StatusProjection { /** * Get the current status of this resource. * * @return The status. */ String getStatus(); }
2,687
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/AgentHostnameProjection.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.data.services.impl.jpa.queries.projections; import java.util.Optional; /** * Projection for job hosts. * * @author tgianos * @since 3.3.0 */ public interface AgentHostnameProjection { /** * Get the host name where the agent ran or is running the job. * * @return The host name where the job agent is running or was run wrapped in an {@link Optional} */ Optional<String> getAgentHostname(); }
2,688
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobSearchProjection.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.data.services.impl.jpa.queries.projections; import java.time.Instant; import java.util.Optional; /** * Projection to return only the fields desired for a job with search results. * * @author tgianos * @since 3.3.0 */ public interface JobSearchProjection extends StatusProjection { /** * Get the unique identifier of the job. * * @return The unique identifier */ String getUniqueId(); /** * Get the name of the job. * * @return The name of the job */ String getName(); /** * Get the user who ran or is running the job. * * @return the user */ String getUser(); /** * Get the time the job started if it has started. * * @return The time the job started */ Optional<Instant> getStarted(); /** * Get the time the job finished if it has finished. * * @return The time the job finished */ Optional<Instant> getFinished(); /** * Get the name of the cluster that is running or did run this job. * * @return The cluster name or empty Optional if it hasn't been set */ Optional<String> getClusterName(); /** * Get the name of the command that is executing this job. * * @return The command name or empty Optional if one wasn't set yet */ Optional<String> getCommandName(); }
2,689
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobApplicationsProjection.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.data.services.impl.jpa.queries.projections; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity; import java.util.List; /** * Projection to return just the applications associated with a given job. * * @author tgianos * @since 3.3.0 */ public interface JobApplicationsProjection { /** * Get the applications associated with a job. * * @return The applications associated with a job in desired setup order */ List<ApplicationEntity> getApplications(); }
2,690
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobProjection.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.data.services.impl.jpa.queries.projections; import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity; import java.time.Instant; import java.util.List; import java.util.Optional; /** * Projection for the fields originally available in pre-3.3.0 JobEntity classes. * * @author tgianos * @since 3.3.0 */ public interface JobProjection extends JobCommonFieldsProjection, StatusProjection, JobArchiveLocationProjection { /** * Get the current status message of the job. * * @return The status message */ Optional<String> getStatusMsg(); /** * Get when the job was started. * * @return The start date */ Optional<Instant> getStarted(); /** * Get when the job was finished. * * @return The finish date */ Optional<Instant> getFinished(); /** * Get the name of the cluster that is running or did run this job. * * @return The cluster name or empty Optional if it hasn't been set */ Optional<String> getClusterName(); /** * Get the name of the command that is executing this job. * * @return The command name or empty Optional if one wasn't set yet */ Optional<String> getCommandName(); /** * Get the applications used to run this job. * * @return The applications */ List<ApplicationEntity> getApplications(); }
2,691
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobArchiveLocationProjection.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.data.services.impl.jpa.queries.projections; import java.util.Optional; /** * A projection which only returns the archive location for a job. * * @author tgianos * @since 4.0.0 */ public interface JobArchiveLocationProjection { /** * Get the location where the job was archived. * * @return The archive location */ Optional<String> getArchiveLocation(); }
2,692
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobCommandProjection.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.data.services.impl.jpa.queries.projections; import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity; import java.util.Optional; /** * Projection to return just the command for a given job. * * @author tgianos * @since 3.3.0 */ public interface JobCommandProjection { /** * Get the command that ran or is currently running a given job. * * @return The command entity */ Optional<CommandEntity> getCommand(); }
2,693
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/IdProjection.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.data.services.impl.jpa.queries.projections; /** * A projection just for returning the id field of a given entity. * * @author tgianos * @since 3.1.0 */ public interface IdProjection { /** * Get the id from the projection. * * @return The id */ long getId(); }
2,694
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/BaseProjection.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.data.services.impl.jpa.queries.projections; import com.fasterxml.jackson.databind.JsonNode; import java.util.Optional; /** * Projection for the common fields. * * @author tgianos * @since 3.3.0 */ public interface BaseProjection extends UniqueIdProjection { /** * Get the version. * * @return The version of the resource (job, app, etc) */ String getVersion(); /** * Get the user who created the resource. * * @return The user who created the resource */ String getUser(); /** * Get the name of the resource. * * @return The name of the resource */ String getName(); /** * Get the status of this resource as a String. * * @return The status */ String getStatus(); /** * Get the description of this resource. * * @return The description which could be null so it's wrapped in Optional */ Optional<String> getDescription(); /** * Get the metadata of this entity which is unstructured JSON. * * @return Optional of the metadata json node */ Optional<JsonNode> getMetadata(); }
2,695
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobExecutionProjection.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.data.services.impl.jpa.queries.projections; import com.fasterxml.jackson.databind.JsonNode; import java.time.Instant; import java.util.Optional; /** * Projection with the data present in a Genie JobExecutionEntity from pre-3.3.0. * * @author tgianos * @since 3.3.0 */ public interface JobExecutionProjection extends AuditProjection, AgentHostnameProjection { /** * Get when the job was started. * * @return The start date */ Optional<Instant> getStarted(); /** * Get the unique identifier of this job execution. * * @return The unique id */ String getUniqueId(); /** * Get the process id of the job. * * @return the process id */ Optional<Integer> getProcessId(); /** * Get the exit code from the process that ran the job. * * @return The exit code or -1 if the job hasn't finished yet */ Optional<Integer> getExitCode(); /** * Get the number of CPU's used by the job. * * @return The number of CPU's used or {@link Optional#empty()} */ Optional<Integer> getCpuUsed(); /** * Get the number of GPUs used by the job. * * @return The number of GPUs used or {@link Optional#empty()} */ Optional<Integer> getGpuUsed(); /** * Get the amount of memory (in MB) that this job is/was run with. * * @return The memory as an optional as it could be null */ Optional<Long> getMemoryUsed(); /** * Get the amount of disk space used for a job. * * @return The amount of disk space in MB or {@link Optional#empty()} */ Optional<Long> getDiskMbUsed(); /** * Get network bandwidth used for a job if any. * * @return The network bandwidth in mbps or {@link Optional#empty()} */ Optional<Long> getNetworkMbpsUsed(); /** * Get the final resolved timeout duration (in seconds) if there was one for this job. * * @return The timeout value wrapped in an {@link Optional} */ Optional<Integer> getTimeoutUsed(); /** * Get the archive status for this job. * * @return An Optional wrapping the string representation of the archive status, if is present. */ Optional<String> getArchiveStatus(); /** * Get the launcher metadata for this job. * * @return An Optional wrapping the JSON representation of the launcher metadata, if present. */ Optional<JsonNode> getLauncherExt(); /** * Get the set of image configuration used for this job. * * @return The images used or {@link Optional#empty()} */ Optional<JsonNode> getImagesUsed(); }
2,696
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobApiProjection.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.data.services.impl.jpa.queries.projections; /** * A projection which allows the system to pull back whether the job was submitted via the REST API or other mechanism. * * @author tgianos * @since 4.0.0 */ public interface JobApiProjection { /** * Return whether or not this job was submitted via the API or other (e.g. Agent CLI) mechanism. * * @return {@literal true} if the job was submitted via an API call. {@literal false} otherwise. */ boolean isApi(); }
2,697
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/SetupFileProjection.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.data.services.impl.jpa.queries.projections; import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity; import java.util.Optional; /** * Projection for returning the setup file of a given entity. * * @author tgianos * @since 3.3.0 */ public interface SetupFileProjection { /** * Get the setup file for this resource. * * @return The setup file */ Optional<FileEntity> getSetupFile(); }
2,698
0
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries
Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/AuditProjection.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.data.services.impl.jpa.queries.projections; import java.time.Instant; /** * Returns all the base entity attributes. * * @author tgianos * @since 3.3.0 */ public interface AuditProjection extends IdProjection { /** * Get when this entity was created. * * @return The created timestamp */ Instant getCreated(); /** * Get when this entity was updated. * * @return The updated timestamp */ Instant getUpdated(); }
2,699