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/data/services/impl/jpa/queries | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/JobClusterProjection.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.ClusterEntity;
import java.util.Optional;
/**
* Projection to return just the cluster for a given job.
*
* @author tgianos
* @since 3.3.0
*/
public interface JobClusterProjection {
/**
* Get the cluster that ran or is currently running a given job.
*
* @return The cluster entity
*/
Optional<ClusterEntity> getCluster();
}
| 2,700 |
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/JobMetadataProjection.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 of the jobs table which produces only the fields that were present in the pre-3.3.0
* JobMetadata table before it was merged into one large jobs table.
*
* @author tgianos
* @since 3.3.0
*/
public interface JobMetadataProjection extends AuditProjection {
/**
* Get the unique identifier of this job execution.
*
* @return The unique id
*/
String getUniqueId();
/**
* Get the request api client hostname.
*
* @return {@link Optional} of the client host
*/
Optional<String> getRequestApiClientHostname();
/**
* Get the user agent.
*
* @return Optional of the user agent
*/
Optional<String> getRequestApiClientUserAgent();
/**
* Get the number of attachments.
*
* @return The number of attachments as an optional
*/
Optional<Integer> getNumAttachments();
/**
* Get the total size of the attachments.
*
* @return The total size of attachments as an optional
*/
Optional<Long> getTotalSizeOfAttachments();
/**
* Get the size of standard out for this job.
*
* @return The size (in bytes) of this jobs standard out file as Optional
*/
Optional<Long> getStdOutSize();
/**
* Get the size of standard error for this job.
*
* @return The size (in bytes) of this jobs standard error file as Optional
*/
Optional<Long> getStdErrSize();
}
| 2,701 |
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/package-info.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.
*
*/
/**
* A package containing projection interfaces for Spring Data JPA.
*
* @author tgianos
* @since 3.1.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.queries.projections;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,702 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/v4/FinishedJobProjection.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.v4;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
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.CriterionEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.BaseProjection;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Projection for a job entity that reached a terminal status.
*
* @author mprimi
* @since 4.0.0
*/
public interface FinishedJobProjection extends BaseProjection {
/**
* 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();
/**
* 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 metadata of this entity which is unstructured JSON.
*
* @return Optional of the metadata json node
*/
Optional<JsonNode> getMetadata();
/**
* Get the command arguments the user supplied for this job.
*
* @return The command arguments
*/
List<String> getCommandArgs();
/**
* Get the memory requested to run this job with.
*
* @return The amount of memory the user requested for this job in MB as an Optional
*/
Optional<Long> getRequestedMemory();
/**
* Get the request api client hostname.
*
* @return {@link Optional} of the client host
*/
Optional<String> getRequestApiClientHostname();
/**
* Get the user agent.
*
* @return {@link Optional} of the user agent
*/
Optional<String> getRequestApiClientUserAgent();
/**
* Get the number of attachments.
*
* @return The number of attachments as an {@link Optional}
*/
Optional<Integer> getNumAttachments();
/**
* Get the hostname of the agent that requested this job be run if there was one.
*
* @return The hostname wrapped in an {@link Optional}
*/
Optional<String> getRequestAgentClientHostname();
/**
* Get the version of the agent that requested this job be run if there was one.
*
* @return The version wrapped in an {@link Optional}
*/
Optional<String> getRequestAgentClientVersion();
/**
* 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 location where the job was archived.
*
* @return The archive location
*/
Optional<String> getArchiveLocation();
/**
* Get the amount of memory (in MB) that this job is/was run with.
*
* @return The memory as an {@link Optional} as it could be null
*/
Optional<Long> getMemoryUsed();
/**
* Get all the cluster criteria.
*
* @return The criteria in priority order
*/
List<CriterionEntity> getClusterCriteria();
/**
* Get the command criterion for this job.
*
* @return The command criterion for this job
*/
CriterionEntity getCommandCriterion();
/**
* Get the applications used to run this job.
*
* @return The applications
*/
List<ApplicationEntity> getApplications();
/**
* Get the cluster that ran or is currently running a given job.
*
* @return The cluster entity
*/
Optional<ClusterEntity> getCluster();
/**
* Get the command that ran or is currently running a given job.
*
* @return The command entity
*/
Optional<CommandEntity> getCommand();
}
| 2,703 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/v4/ExecutionResourceProjection.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.v4;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity;
import java.util.Optional;
import java.util.Set;
/**
* A projection for fields from an entity which are needed for an
* {@link JobSpecification.ExecutionResource}.
*
* @author tgianos
* @since 4.0.0
*/
public interface ExecutionResourceProjection {
/**
* Get the unique identifier for this entity.
*
* @return The globally unique identifier of this entity
*/
String getUniqueId();
/**
* Get all the configuration files for this entity.
*
* @return The set of configs
*/
Set<FileEntity> getConfigs();
/**
* Get all the dependency files for this entity.
*
* @return The set of dependencies
*/
Set<FileEntity> getDependencies();
/**
* Get the setup file for this entity.
*
* @return The setup file
*/
Optional<FileEntity> getSetupFile();
}
| 2,704 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/v4/JobRequestProjection.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.v4;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.common.internal.dtos.JobRequest;
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.TagEntity;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Projection of just the fields needed for a V4 {@link JobRequest}.
*
* @author tgianos
* @since 4.0.0
*/
// TODO: Clean this up as things get more finalized to break out fields into reusable super interfaces
public interface JobRequestProjection {
/**
* Get the unique identifier for this entity.
*
* @return The globally unique identifier of this entity
*/
String getUniqueId();
/**
* Get whether the unique identifier of this request was requested by the user or not.
*
* @return True if it was requested by the user
*/
// TODO: As we move more to V4 as default move this to more shared location
boolean isRequestedId();
/**
* Get the name of the resource.
*
* @return The name of the resource
*/
String getName();
/**
* Get the user who created the resource.
*
* @return The user who created the resource
*/
String getUser();
/**
* Get the version.
*
* @return The version of the resource (job, app, etc)
*/
String getVersion();
/**
* 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();
/**
* Get the command arguments the user supplied 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();
/**
* Get all the environment variables that were requested be added to the Job Runtime environment by the user.
*
* @return The requested environment variables
*/
Map<String, String> getRequestedEnvironmentVariables();
/**
* Get the requested directory on disk where the Genie job working directory should be placed if a user asked to
* override the default.
*
* @return The requested job directory location wrapped in an {@link Optional}
*/
Optional<String> getRequestedJobDirectoryLocation();
/**
* Get the extension configuration of a job agent environment.
*
* @return The extension configuration if it exists wrapped in an {@link Optional}
*/
Optional<JsonNode> getRequestedAgentEnvironmentExt();
/**
* Get the extension configuration of a job agent configuration.
*
* @return The extension configuration if it exists wrapped in an {@link Optional}
*/
Optional<JsonNode> getRequestedAgentConfigExt();
/**
* Get whether the job was an interactive job or not when launched.
*
* @return true if the job was interactive
*/
boolean isInteractive();
/**
* Get the setup file for this resource.
*
* @return The setup file
*/
Optional<FileEntity> getSetupFile();
/**
* Get the user group for this job.
*
* @return the user group
*/
Optional<String> getGenieUserGroup();
/**
* Get all the cluster criteria.
*
* @return The criteria in priority order
*/
List<CriterionEntity> getClusterCriteria();
/**
* Get the command criterion for this job.
*
* @return The command criterion for this job
*/
CriterionEntity getCommandCriterion();
/**
* Get all the dependency files for this job.
*
* @return The set of dependencies
*/
Set<FileEntity> getDependencies();
/**
* Get all the configuration files for this job.
*
* @return The set of configs
*/
Set<FileEntity> getConfigs();
/**
* Get whether log archiving was requested to be disabled for this job or not.
*
* @return true if log archival was disabled
*/
boolean isArchivingDisabled();
/**
* Get the email of the user associated with this job if they desire an email notification at completion
* of the job.
*
* @return The email
*/
Optional<String> getEmail();
/**
* Get the number of CPU's requested to run this job.
*
* @return The number of CPU's as an Optional
*/
Optional<Integer> getRequestedCpu();
/**
* Get the number of GPUs requested by the job.
*
* @return The number of GPUs requested or {@link Optional#empty()}
*/
Optional<Integer> getRequestedGpu();
/**
* Get the memory requested to run this job with.
*
* @return The amount of memory the user requested for this job in MB as an Optional
*/
Optional<Long> getRequestedMemory();
/**
* Get the requested disk space for the job if any.
*
* @return The requested amount of disk space in MB or {@link Optional#empty()}
*/
Optional<Long> getRequestedDiskMb();
/**
* Get the requested network mbps for the job if any.
*
* @return The requested network bandwidth in mbps or {@link Optional#empty()}
*/
Optional<Long> getRequestedNetworkMbps();
/**
* Get the timeout (in seconds) requested by the user for this job.
*
* @return The number of seconds before a timeout as an Optional
*/
Optional<Integer> getRequestedTimeout();
/**
* Get any applications requested by their id.
*
* @return The applications
*/
List<String> getRequestedApplications();
/**
* Get the requested container image configurations if there were any.
*
* @return The requested images or {@link Optional#empty()}
*/
Optional<JsonNode> getRequestedImages();
}
| 2,705 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/v4/JobSpecificationProjection.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.v4;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
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.FileEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobArchiveLocationProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.UniqueIdProjection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Projection of the database fields which make up the required elements of a job specification.
*
* @author tgianos
* @since 4.0.0
*/
public interface JobSpecificationProjection extends UniqueIdProjection, JobArchiveLocationProjection {
/**
* Get all the configuration files for this job.
*
* @return The set of configs
*/
Set<FileEntity> getConfigs();
/**
* Get all the dependency files for this job.
*
* @return The set of dependencies
*/
Set<FileEntity> getDependencies();
/**
* Get the setup file for this resource.
*
* @return The setup file
*/
Optional<FileEntity> getSetupFile();
/**
* Get the job directory location the agent should use.
*
* @return The job directory location if its been set wrapped in an {@link Optional}
*/
Optional<String> getJobDirectoryLocation();
/**
* Get the command arguments the user supplied for this job.
*
* @return The command arguments
*/
List<String> getCommandArgs();
// TODO: Figure out how to use nested projections for linked entities. It'll work but the fact
// JobEntity implements these interfaces conflicts with the non-projection
/**
* Get the cluster that ran or is currently running a given job.
*
* @return The cluster entity
*/
Optional<ClusterEntity> getCluster();
/**
* Get the command that ran or is currently running a given job.
*
* @return The command entity
*/
Optional<CommandEntity> getCommand();
/**
* Get the applications used to run this job.
*
* @return The applications
*/
List<ApplicationEntity> getApplications();
/**
* Get whether the job was an interactive job or not when launched.
*
* @return true if the job was interactive
*/
boolean isInteractive();
/**
* Get the final set of environment variables sent from the server to the agent for the job.
*
* @return The environment variables
*/
Map<String, String> getEnvironmentVariables();
/**
* Get whether the job specification has been resolved yet or not.
*
* @return True if the job specification has been resolved
*/
boolean isResolved();
/**
* 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();
}
| 2,706 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/data/services/impl/jpa/queries/projections/v4/package-info.java | /*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Projections for V4 data types.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,707 |
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/converters/EntityV4DtoConverters.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.converters;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableList;
import com.netflix.genie.common.external.util.GenieObjectMapper;
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.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterMetadata;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.CommandMetadata;
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.JobEnvironmentRequest;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import com.netflix.genie.common.internal.dtos.converters.DtoConverters;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieClusterNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieCommandNotFoundException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
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.CriterionEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
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.JobRequestProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Utility methods for converting from DTO to entities and vice versa.
*
* @author tgianos
* @since 4.0.0
*/
public final class EntityV4DtoConverters {
private static final Logger LOG = LoggerFactory.getLogger(EntityV4DtoConverters.class);
private static final TypeReference<Map<String, Image>> IMAGES_TYPE_REFERENCE = new TypeReference<>() {
};
private static final ObjectNode EMPTY_JSON = GenieObjectMapper.getMapper().createObjectNode();
private EntityV4DtoConverters() {
}
/**
* Convert an application entity to a DTO for external exposure.
*
* @param applicationEntity The entity to convert
* @return The immutable DTO representation of the entity data
* @throws IllegalArgumentException On invalid field
*/
public static Application toV4ApplicationDto(
final ApplicationEntity applicationEntity
) throws IllegalArgumentException {
final ApplicationMetadata.Builder metadataBuilder = new ApplicationMetadata.Builder(
applicationEntity.getName(),
applicationEntity.getUser(),
applicationEntity.getVersion(),
DtoConverters.toV4ApplicationStatus(applicationEntity.getStatus())
)
.withTags(applicationEntity.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet()));
applicationEntity.getType().ifPresent(metadataBuilder::withType);
applicationEntity.getDescription().ifPresent(metadataBuilder::withDescription);
applicationEntity.getMetadata().ifPresent(metadataBuilder::withMetadata);
return new Application(
applicationEntity.getUniqueId(),
applicationEntity.getCreated(),
applicationEntity.getUpdated(),
toExecutionEnvironment(
applicationEntity.getConfigs(),
applicationEntity.getDependencies(),
applicationEntity.getSetupFile().orElse(null)
),
metadataBuilder.build()
);
}
/**
* Convert a cluster entity to a DTO for external exposure.
*
* @param clusterEntity The entity to convert
* @return The immutable DTO representation of the entity data
* @throws IllegalArgumentException On any invalid field value
*/
public static Cluster toV4ClusterDto(final ClusterEntity clusterEntity) throws IllegalArgumentException {
final ClusterMetadata.Builder metadataBuilder = new ClusterMetadata.Builder(
clusterEntity.getName(),
clusterEntity.getUser(),
clusterEntity.getVersion(),
DtoConverters.toV4ClusterStatus(clusterEntity.getStatus())
)
.withTags(clusterEntity.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet()));
clusterEntity.getDescription().ifPresent(metadataBuilder::withDescription);
clusterEntity.getMetadata().ifPresent(metadataBuilder::withMetadata);
return new Cluster(
clusterEntity.getUniqueId(),
clusterEntity.getCreated(),
clusterEntity.getUpdated(),
toExecutionEnvironment(
clusterEntity.getConfigs(),
clusterEntity.getDependencies(),
clusterEntity.getSetupFile().orElse(null)
),
metadataBuilder.build()
);
}
/**
* Convert a command entity to a DTO for external exposure.
*
* @param commandEntity The entity to convert
* @return The immutable DTO representation of the entity data
* @throws IllegalArgumentException On any invalid field value
*/
public static Command toV4CommandDto(final CommandEntity commandEntity) throws IllegalArgumentException {
final CommandMetadata.Builder metadataBuilder = new CommandMetadata.Builder(
commandEntity.getName(),
commandEntity.getUser(),
commandEntity.getVersion(),
DtoConverters.toV4CommandStatus(commandEntity.getStatus())
)
.withTags(commandEntity.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet()));
commandEntity.getDescription().ifPresent(metadataBuilder::withDescription);
commandEntity.getMetadata().ifPresent(metadataBuilder::withMetadata);
return new Command(
commandEntity.getUniqueId(),
commandEntity.getCreated(),
commandEntity.getUpdated(),
toExecutionEnvironment(
commandEntity.getConfigs(),
commandEntity.getDependencies(),
commandEntity.getSetupFile().orElse(null)
),
metadataBuilder.build(),
commandEntity.getExecutable(),
commandEntity
.getClusterCriteria()
.stream()
.map(EntityV4DtoConverters::toCriterionDto)
.collect(Collectors.toList()),
toComputeResources(
commandEntity::getCpu,
commandEntity::getGpu,
commandEntity::getMemory,
commandEntity::getDiskMb,
commandEntity::getNetworkMbps
),
toImages(commandEntity::getImages)
);
}
/**
* Convert a job request entity to a DTO.
*
* @param jobRequestProjection The projection of the {@link JobRequestProjection} to convert
* @return The original job request DTO
* @throws GenieRuntimeException When criterion can't be properly converted
*/
public static JobRequest toV4JobRequestDto(final JobRequestProjection jobRequestProjection) {
final String requestedId = jobRequestProjection.isRequestedId() ? jobRequestProjection.getUniqueId() : null;
// Rebuild the job metadata
final JobMetadata.Builder jobMetadataBuilder = new JobMetadata.Builder(
jobRequestProjection.getName(),
jobRequestProjection.getUser(),
jobRequestProjection.getVersion()
);
jobRequestProjection.getGenieUserGroup().ifPresent(jobMetadataBuilder::withGroup);
jobRequestProjection.getEmail().ifPresent(jobMetadataBuilder::withEmail);
jobRequestProjection.getGrouping().ifPresent(jobMetadataBuilder::withGrouping);
jobRequestProjection.getGroupingInstance().ifPresent(jobMetadataBuilder::withGroupingInstance);
jobRequestProjection.getDescription().ifPresent(jobMetadataBuilder::withDescription);
jobMetadataBuilder.withTags(
jobRequestProjection.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet())
);
jobRequestProjection.getMetadata().ifPresent(jobMetadataBuilder::withMetadata);
// Rebuild the execution resource criteria
final ImmutableList.Builder<Criterion> clusterCriteria = ImmutableList.builder();
for (final CriterionEntity criterionEntity : jobRequestProjection.getClusterCriteria()) {
clusterCriteria.add(toCriterionDto(criterionEntity));
}
final Criterion commandCriterion = toCriterionDto(jobRequestProjection.getCommandCriterion());
final ExecutionResourceCriteria executionResourceCriteria = new ExecutionResourceCriteria(
clusterCriteria.build(),
commandCriterion,
jobRequestProjection.getRequestedApplications()
);
// Rebuild the job resources
final ExecutionEnvironment jobResources = toExecutionEnvironment(
jobRequestProjection.getConfigs(),
jobRequestProjection.getDependencies(),
jobRequestProjection.getSetupFile().orElse(null)
);
// Rebuild the Agent Config Request
final AgentConfigRequest.Builder agentConfigRequestBuilder = new AgentConfigRequest.Builder();
jobRequestProjection.getRequestedAgentConfigExt().ifPresent(agentConfigRequestBuilder::withExt);
jobRequestProjection
.getRequestedJobDirectoryLocation()
.ifPresent(agentConfigRequestBuilder::withRequestedJobDirectoryLocation);
agentConfigRequestBuilder.withInteractive(jobRequestProjection.isInteractive());
agentConfigRequestBuilder.withArchivingDisabled(jobRequestProjection.isArchivingDisabled());
jobRequestProjection.getRequestedTimeout().ifPresent(agentConfigRequestBuilder::withTimeoutRequested);
// Rebuild the Agent Environment Request
final JobEnvironmentRequest.Builder jobEnvironmentRequestBuilder = new JobEnvironmentRequest.Builder();
jobRequestProjection.getRequestedAgentEnvironmentExt().ifPresent(jobEnvironmentRequestBuilder::withExt);
jobEnvironmentRequestBuilder
.withRequestedEnvironmentVariables(jobRequestProjection.getRequestedEnvironmentVariables());
jobEnvironmentRequestBuilder.withRequestedComputeResources(
toComputeResources(
jobRequestProjection::getRequestedCpu,
jobRequestProjection::getRequestedGpu,
jobRequestProjection::getRequestedMemory,
jobRequestProjection::getRequestedDiskMb,
jobRequestProjection::getRequestedNetworkMbps
)
);
jobEnvironmentRequestBuilder.withRequestedImages(toImages(jobRequestProjection::getRequestedImages));
return new JobRequest(
requestedId,
jobResources,
jobRequestProjection.getCommandArgs(),
jobMetadataBuilder.build(),
executionResourceCriteria,
jobEnvironmentRequestBuilder.build(),
agentConfigRequestBuilder.build()
);
}
/**
* Convert a given {@link CriterionEntity} to the equivalent {@link Criterion} DTO representation.
*
* @param criterionEntity The entity to convert
* @return The DTO representation
*/
public static Criterion toCriterionDto(final CriterionEntity criterionEntity) {
final Criterion.Builder builder = new Criterion.Builder();
criterionEntity.getUniqueId().ifPresent(builder::withId);
criterionEntity.getName().ifPresent(builder::withName);
criterionEntity.getVersion().ifPresent(builder::withVersion);
criterionEntity.getStatus().ifPresent(builder::withStatus);
builder.withTags(criterionEntity.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet()));
// Since these entities have been stored successfully they were validated before and shouldn't contain errors
// we can't recover from error anyway in a good way here. Hence re-wrapping checked exception in runtime
try {
return builder.build();
} catch (final IllegalArgumentException iae) {
LOG.error("Creating a Criterion DTO from a Criterion entity threw exception", iae);
// TODO: For now this is a generic GenieRuntimeException. If we would like more advanced logic at the
// edges (REST API, RPC API) based on type of exceptions we should subclass GenieRuntimeException
throw new GenieRuntimeException(iae);
}
}
/**
* Convert a given {@link FinishedJobProjection} to the equivalent {@link FinishedJob} DTO representation.
*
* @param finishedJobProjection the entity projection
* @return the DTO representation
* @throws IllegalArgumentException On any invalid field
*/
public static FinishedJob toFinishedJobDto(
final FinishedJobProjection finishedJobProjection
) throws IllegalArgumentException {
final FinishedJob.Builder builder = new FinishedJob.Builder(
finishedJobProjection.getUniqueId(),
finishedJobProjection.getName(),
finishedJobProjection.getUser(),
finishedJobProjection.getVersion(),
finishedJobProjection.getCreated(),
DtoConverters.toV4JobStatus(finishedJobProjection.getStatus()),
finishedJobProjection.getCommandArgs(),
toCriterionDto(finishedJobProjection.getCommandCriterion()),
finishedJobProjection.getClusterCriteria()
.stream()
.map(EntityV4DtoConverters::toCriterionDto)
.collect(Collectors.toList())
);
finishedJobProjection.getStarted().ifPresent(builder::withStarted);
finishedJobProjection.getFinished().ifPresent(builder::withFinished);
finishedJobProjection.getDescription().ifPresent(builder::withDescription);
finishedJobProjection.getGrouping().ifPresent(builder::withGrouping);
finishedJobProjection.getGroupingInstance().ifPresent(builder::withGroupingInstance);
finishedJobProjection.getStatusMsg().ifPresent(builder::withStatusMessage);
finishedJobProjection.getRequestedMemory().ifPresent(builder::withRequestedMemory);
finishedJobProjection.getRequestApiClientHostname().ifPresent(builder::withRequestApiClientHostname);
finishedJobProjection.getRequestApiClientUserAgent().ifPresent(builder::withRequestApiClientUserAgent);
finishedJobProjection.getRequestAgentClientHostname().ifPresent(builder::withRequestAgentClientHostname);
finishedJobProjection.getRequestAgentClientVersion().ifPresent(builder::withRequestAgentClientVersion);
finishedJobProjection.getNumAttachments().ifPresent(builder::withNumAttachments);
finishedJobProjection.getExitCode().ifPresent(builder::withExitCode);
finishedJobProjection.getArchiveLocation().ifPresent(builder::withArchiveLocation);
finishedJobProjection.getMemoryUsed().ifPresent(builder::withMemoryUsed);
builder.withTags(
finishedJobProjection.getTags()
.stream()
.map(TagEntity::getTag)
.collect(Collectors.toSet())
);
finishedJobProjection.getMetadata().ifPresent(builder::withMetadata);
finishedJobProjection.getCommand().ifPresent(
commandEntity ->
builder.withCommand(toV4CommandDto(commandEntity))
);
finishedJobProjection.getCluster().ifPresent(
clusterEntity ->
builder.withCluster(toV4ClusterDto(clusterEntity))
);
builder.withApplications(
finishedJobProjection.getApplications()
.stream()
.map(EntityV4DtoConverters::toV4ApplicationDto)
.collect(Collectors.toList())
);
return builder.build();
}
/**
* Convert the values contained in the {@link JobSpecificationProjection} to an immutable {@link JobSpecification}
* DTO.
*
* @param jobSpecificationProjection The entity values to convert
* @return An immutable Job Specification instance
* @throws GenieClusterNotFoundException When the cluster isn't found in the database which it should be at this
* point given the input to the db was valid at the time of persistence
* @throws GenieCommandNotFoundException When the command isn't found in the database which it should be at this
* point given the input to the db was valid at the time of persistence
* @throws GenieRuntimeException All input should be valid at this point so if we can't create a job spec
* dto something has become corrupted in the db
*/
public static JobSpecification toJobSpecificationDto(final JobSpecificationProjection jobSpecificationProjection) {
final String id = jobSpecificationProjection.getUniqueId();
// Check error conditions up front
final ClusterEntity clusterEntity = jobSpecificationProjection
.getCluster()
.orElseThrow(
() -> new GenieClusterNotFoundException("No cluster found for job " + id + ". Was expected to exist.")
);
final CommandEntity commandEntity = jobSpecificationProjection
.getCommand()
.orElseThrow(
() -> new GenieCommandNotFoundException("No command found for job " + id + ". Was expected to exist.")
);
final File jobDirectoryLocation = jobSpecificationProjection
.getJobDirectoryLocation()
.map(File::new)
.orElseThrow(
() -> new GenieRuntimeException(
"No job directory location available for job " + id + ". Was expected to exist"
)
);
final String archiveLocation = jobSpecificationProjection.getArchiveLocation().orElse(null);
final JobSpecification.ExecutionResource job = toExecutionResource(
id,
jobSpecificationProjection.getConfigs(),
jobSpecificationProjection.getDependencies(),
jobSpecificationProjection.getSetupFile().orElse(null)
);
final JobSpecification.ExecutionResource cluster = toExecutionResource(
clusterEntity.getUniqueId(),
clusterEntity.getConfigs(),
clusterEntity.getDependencies(),
clusterEntity.getSetupFile().orElse(null)
);
final JobSpecification.ExecutionResource command = toExecutionResource(
commandEntity.getUniqueId(),
commandEntity.getConfigs(),
commandEntity.getDependencies(),
commandEntity.getSetupFile().orElse(null)
);
final List<JobSpecification.ExecutionResource> applications = jobSpecificationProjection
.getApplications()
.stream()
.map(
applicationEntity -> toExecutionResource(
applicationEntity.getUniqueId(),
applicationEntity.getConfigs(),
applicationEntity.getDependencies(),
applicationEntity.getSetupFile().orElse(null)
)
)
.collect(Collectors.toList());
return new JobSpecification(
commandEntity.getExecutable(),
jobSpecificationProjection.getCommandArgs(),
job,
cluster,
command,
applications,
jobSpecificationProjection.getEnvironmentVariables(),
jobSpecificationProjection.isInteractive(),
jobDirectoryLocation,
archiveLocation,
jobSpecificationProjection.getTimeoutUsed().orElse(null)
);
}
private static JobSpecification.ExecutionResource toExecutionResource(
final String id,
final Set<FileEntity> configs,
final Set<FileEntity> dependencies,
@Nullable final FileEntity setupFile
) {
return new JobSpecification.ExecutionResource(id, toExecutionEnvironment(configs, dependencies, setupFile));
}
private static ExecutionEnvironment toExecutionEnvironment(
final Set<FileEntity> configs,
final Set<FileEntity> dependencies,
@Nullable final FileEntity setupFile
) {
return new ExecutionEnvironment(
configs.stream().map(FileEntity::getFile).collect(Collectors.toSet()),
dependencies.stream().map(FileEntity::getFile).collect(Collectors.toSet()),
setupFile != null ? setupFile.getFile() : null
);
}
private static ComputeResources toComputeResources(
final Supplier<Optional<Integer>> cpuGetter,
final Supplier<Optional<Integer>> gpuGetter,
final Supplier<Optional<Long>> memoryGetter,
final Supplier<Optional<Long>> diskMbGetter,
final Supplier<Optional<Long>> networkMbpsGetter
) {
return new ComputeResources
.Builder()
.withCpu(cpuGetter.get().orElse(null))
.withGpu(gpuGetter.get().orElse(null))
.withMemoryMb(memoryGetter.get().orElse(null))
.withDiskMb(diskMbGetter.get().orElse(null))
.withNetworkMbps(networkMbpsGetter.get().orElse(null))
.build();
}
private static Map<String, Image> toImages(final Supplier<Optional<JsonNode>> imagesGetter) {
return GenieObjectMapper
.getMapper()
.convertValue(imagesGetter.get().orElse(EMPTY_JSON), IMAGES_TYPE_REFERENCE);
}
}
| 2,708 |
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/converters/EntityV3DtoConverters.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.converters;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.netflix.genie.common.dto.ArchiveStatus;
import com.netflix.genie.common.dto.ContainerImage;
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.Runtime;
import com.netflix.genie.common.dto.RuntimeResources;
import com.netflix.genie.common.dto.UserResourcesSummary;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.Image;
import com.netflix.genie.common.internal.dtos.converters.DtoConverters;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.UserJobResourcesAggregate;
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.JobProjection;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Converters between entities and V3 DTOs.
*
* @author tgianos
* @since 3.3.0
*/
@Slf4j
public final class EntityV3DtoConverters {
private static final TypeReference<Map<String, Image>> IMAGES_TYPE_REFERENCE = new TypeReference<>() {
};
private static final ObjectNode EMPTY_JSON = GenieObjectMapper.getMapper().createObjectNode();
private EntityV3DtoConverters() {
}
/**
* Convert the data in this job projection into a job DTO for external exposure.
*
* @param jobProjection The data from the database
* @return The job DTO representation
*/
public static Job toJobDto(final JobProjection jobProjection) {
final Job.Builder builder = new Job.Builder(
jobProjection.getName(),
jobProjection.getUser(),
jobProjection.getVersion()
)
.withId(jobProjection.getUniqueId())
.withCreated(jobProjection.getCreated())
.withUpdated(jobProjection.getUpdated())
.withTags(jobProjection.getTags().stream().map(TagEntity::getTag).collect(Collectors.toSet()))
.withStatus(DtoConverters.toV3JobStatus(DtoConverters.toV4JobStatus(jobProjection.getStatus())))
.withCommandArgs(jobProjection.getCommandArgs());
jobProjection.getDescription().ifPresent(builder::withDescription);
jobProjection.getStatusMsg().ifPresent(builder::withStatusMsg);
jobProjection.getStarted().ifPresent(builder::withStarted);
jobProjection.getFinished().ifPresent(builder::withFinished);
jobProjection.getArchiveLocation().ifPresent(builder::withArchiveLocation);
jobProjection.getClusterName().ifPresent(builder::withClusterName);
jobProjection.getCommandName().ifPresent(builder::withCommandName);
jobProjection.getGrouping().ifPresent(builder::withGrouping);
jobProjection.getGroupingInstance().ifPresent(builder::withGroupingInstance);
jobProjection.getMetadata().ifPresent(builder::withMetadata);
return builder.build();
}
/**
* Convert job execution database data into a DTO.
*
* @param jobExecutionProjection The database data
* @return {@link JobExecution} instance
*/
public static JobExecution toJobExecutionDto(final JobExecutionProjection jobExecutionProjection) {
final JobExecution.Builder builder = new JobExecution
.Builder(jobExecutionProjection.getAgentHostname().orElse(UUID.randomUUID().toString()))
.withId(jobExecutionProjection.getUniqueId())
.withCreated(jobExecutionProjection.getCreated())
.withUpdated(jobExecutionProjection.getUpdated());
jobExecutionProjection.getProcessId().ifPresent(builder::withProcessId);
// Calculate the timeout as it used to be represented pre-timeoutUsed
if (jobExecutionProjection.getStarted().isPresent() && jobExecutionProjection.getTimeoutUsed().isPresent()) {
final Instant started = jobExecutionProjection.getStarted().get();
builder.withTimeout(started.plusSeconds(jobExecutionProjection.getTimeoutUsed().get()));
}
jobExecutionProjection.getExitCode().ifPresent(builder::withExitCode);
final RuntimeResources.Builder resourcesBuilder = new RuntimeResources.Builder();
jobExecutionProjection.getCpuUsed().ifPresent(resourcesBuilder::withCpu);
jobExecutionProjection.getGpuUsed().ifPresent(resourcesBuilder::withGpu);
jobExecutionProjection.getMemoryUsed().ifPresent(resourcesBuilder::withMemoryMb);
jobExecutionProjection.getDiskMbUsed().ifPresent(resourcesBuilder::withDiskMb);
jobExecutionProjection.getNetworkMbpsUsed().ifPresent(resourcesBuilder::withNetworkMbps);
final Map<String, ContainerImage> images = GenieObjectMapper
.getMapper()
.convertValue(jobExecutionProjection.getImagesUsed().orElse(EMPTY_JSON), IMAGES_TYPE_REFERENCE)
.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
entry -> DtoConverters.toV3ContainerImage(entry.getValue())
)
);
builder.withRuntime(new Runtime.Builder().withResources(resourcesBuilder.build()).withImages(images).build());
try {
builder.withArchiveStatus(
ArchiveStatus.valueOf(
jobExecutionProjection.getArchiveStatus().orElseThrow(IllegalArgumentException::new)
)
);
} catch (IllegalArgumentException e) {
// If NULL or set to an invalid enum value
builder.withArchiveStatus(ArchiveStatus.UNKNOWN);
}
jobExecutionProjection.getLauncherExt().ifPresent(builder::withLauncherExt);
return builder.build();
}
/**
* Convert job metadata information to a DTO.
*
* @param jobMetadataProjection The database information
* @return A {@link JobMetadata} instance
*/
public static JobMetadata toJobMetadataDto(final JobMetadataProjection jobMetadataProjection) {
final JobMetadata.Builder builder = new JobMetadata.Builder()
.withId(jobMetadataProjection.getUniqueId())
.withCreated(jobMetadataProjection.getCreated())
.withUpdated(jobMetadataProjection.getUpdated());
jobMetadataProjection.getRequestApiClientHostname().ifPresent(builder::withClientHost);
jobMetadataProjection.getRequestApiClientUserAgent().ifPresent(builder::withUserAgent);
jobMetadataProjection.getNumAttachments().ifPresent(builder::withNumAttachments);
jobMetadataProjection.getTotalSizeOfAttachments().ifPresent(builder::withTotalSizeOfAttachments);
jobMetadataProjection.getStdErrSize().ifPresent(builder::withStdErrSize);
jobMetadataProjection.getStdOutSize().ifPresent(builder::withStdOutSize);
return builder.build();
}
/**
* Convert a user resources summary to a DTO.
*
* @param userJobResourcesAggregate The database data to convert
* @return A {@link UserResourcesSummary} instance
*/
public static UserResourcesSummary toUserResourceSummaryDto(
final UserJobResourcesAggregate userJobResourcesAggregate
) {
final String user = userJobResourcesAggregate.getUser();
final Long jobCount = userJobResourcesAggregate.getRunningJobsCount();
final Long memory = userJobResourcesAggregate.getUsedMemory();
return new UserResourcesSummary(
user == null ? "NULL" : user,
jobCount == null ? 0 : jobCount,
memory == null ? 0 : memory
);
}
}
| 2,709 |
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/converters/IntegerToLongConverter.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.converters;
import javax.annotation.Nullable;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* An {@link AttributeConverter} to convert {@link Integer} objects into {@link Long} for storage and vice versa.
*
* @author ltian
* @since 4.3.0
*/
@Converter
public class IntegerToLongConverter implements AttributeConverter<Long, Integer> {
/**
* {@inheritDoc}
*/
@Override
@Nullable
public Integer convertToDatabaseColumn(@Nullable final Long attribute) {
if (attribute == null) {
return null;
}
return attribute.intValue();
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public Long convertToEntityAttribute(@Nullable final Integer dbData) {
if (dbData == null) {
return null;
}
return Long.valueOf(dbData);
}
}
| 2,710 |
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/converters/JsonAttributeConverter.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.converters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException;
import javax.annotation.Nullable;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* An {@link AttributeConverter} to convert {@link JsonNode} objects into their String representations for storage
* and vice versa.
*
* @author tgianos
* @since 4.0.0
*/
@Converter
public class JsonAttributeConverter implements AttributeConverter<JsonNode, String> {
/**
* {@inheritDoc}
*/
@Override
@Nullable
public String convertToDatabaseColumn(@Nullable final JsonNode attribute) {
if (attribute == null) {
return null;
}
try {
return GenieObjectMapper.getMapper().writeValueAsString(attribute);
} catch (final JsonProcessingException e) {
throw new GenieRuntimeException("Unable to convert JsonNode to a JSON string for storing in database", e);
}
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public JsonNode convertToEntityAttribute(@Nullable final String dbData) {
if (dbData == null) {
return null;
}
try {
return GenieObjectMapper.getMapper().readTree(dbData);
} catch (final JsonProcessingException e) {
throw new GenieRuntimeException("Unable to convert: (" + dbData + ") to JsonNode", e);
}
}
}
| 2,711 |
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/converters/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.
*
*/
/**
* Converters between entities and various DTOs.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.converters;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,712 |
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/utils/H2Utils.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.utils;
import org.apache.commons.lang3.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Utilities for working with H2 database. In particular can write stored functions here that are pre-compiled.
*
* @author tgianos
* @since 4.0.0
*/
public final class H2Utils {
static final String V3_COMMAND_EXECUTABLE_QUERY = "SELECT `id`, `executable` FROM `commands`;";
static final String V4_COMMAND_ARGUMENT_SQL = "INSERT INTO `command_executable_arguments` VALUES(?,?,?);";
static final int V3_COMMAND_ID_INDEX = 1;
static final int V3_COMMAND_EXECUTABLE_INDEX = 2;
static final int V4_COMMAND_ID_INDEX = 1;
static final int V4_COMMAND_ARGUMENT_INDEX = 2;
static final int V4_COMMAND_ARGUMENT_ORDER_INDEX = 3;
private H2Utils() {
}
/**
* Split the existing command executable on any whitespace characters and insert them into the
* {@code command_executable_arguments} table in order.
* <p>
* See: {@code src/main/resources/db/migration/h2/V4_0_0__Genie_4.sql} for usage
*
* @param con The database connection to use
* @throws Exception On Error
*/
public static void splitV3CommandExecutableForV4(final Connection con) throws Exception {
try (
PreparedStatement commandsQuery = con.prepareStatement(V3_COMMAND_EXECUTABLE_QUERY);
PreparedStatement insertCommandArgument = con.prepareStatement(V4_COMMAND_ARGUMENT_SQL);
ResultSet rs = commandsQuery.executeQuery()
) {
while (rs.next()) {
final long commandId = rs.getLong(V3_COMMAND_ID_INDEX);
final String executable = rs.getString(V3_COMMAND_EXECUTABLE_INDEX);
final String[] arguments = StringUtils.splitByWholeSeparator(executable, null);
if (arguments.length > 0) {
insertCommandArgument.setLong(V4_COMMAND_ID_INDEX, commandId);
for (int i = 0; i < arguments.length; i++) {
insertCommandArgument.setString(V4_COMMAND_ARGUMENT_INDEX, arguments[i]);
insertCommandArgument.setInt(V4_COMMAND_ARGUMENT_ORDER_INDEX, i);
insertCommandArgument.executeUpdate();
}
}
}
}
}
}
| 2,713 |
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/utils/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.
*
*/
/**
* Utilities for working with JPA or the Genie databases in general.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.utils;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,714 |
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/repositories/JpaCriterionRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.CriterionEntity;
/**
* A repository for {@link CriterionEntity}.
*
* @author tgianos
* @since 4.0.0
*/
public interface JpaCriterionRepository extends JpaIdRepository<CriterionEntity> {
}
| 2,715 |
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/repositories/JpaJobRepository.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.repositories;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.common.dto.JobStatus;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity;
import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.JobInfoAggregate;
import com.netflix.genie.web.data.services.impl.jpa.queries.aggregates.UserJobResourcesAggregate;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobApplicationsProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobClusterProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobCommandProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobRequestProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Job repository.
*
* @author tgianos
*/
public interface JpaJobRepository extends JpaBaseRepository<JobEntity> {
/**
* The query used to find batches of jobs before a certain time.
*/
String FIND_OLD_JOBS_QUERY =
"SELECT id"
+ " FROM jobs"
+ " WHERE created < :createdThreshold AND status NOT IN (:excludedStatuses)"
+ " LIMIT :batchSize"; // JPQL doesn't support limit so this needs to be native query
// TODO: Make interfaces generic but be aware of https://jira.spring.io/browse/DATAJPA-1185
/**
* Given the hostname that agents are running on return the total memory their jobs are currently using.
*
* @param agentHostname The agent hostname
* @param statuses The job statuses to filter by e.g. {@link JobStatus#getActiveStatuses()}
* @return The total memory used in MB
*/
@Query(
"SELECT COALESCE(SUM(j.memoryUsed), 0)"
+ " FROM JobEntity j"
+ " WHERE j.agentHostname = :agentHostname AND j.status IN (:statuses)"
)
long getTotalMemoryUsedOnHost(
@Param("agentHostname") String agentHostname,
@Param("statuses") Set<String> statuses
);
/**
* In a single query get aggregate information for the amount of memory used and count of active jobs on a given
* host.
*
* @param agentHostname The hostname where the agent is running the job
* @param activeStatuses The set of statuses to use in order to consider a job "active"
* @param usedStatuses The set of statuses to use in order to consider a job to actively be using memory
* @return A {@link JobInfoAggregate} instance with the requested information
*/
@Query(
value = "SELECT"
+ " ("
+ "SELECT COALESCE(SUM(j.memory_used), 0)"
+ " FROM jobs j"
+ " WHERE j.agent_hostname = :agentHostname and j.status IN (:activeStatuses)"
+ ") as totalMemoryAllocated,"
+ " ("
+ "SELECT COALESCE(SUM(j.memory_used), 0)"
+ " FROM jobs j"
+ " WHERE j.agent_hostname = :agentHostname and j.status IN (:usedStatuses)"
+ ") as totalMemoryUsed,"
+ " ("
+ "SELECT COUNT(*)"
+ " FROM jobs j"
+ " WHERE j.agent_hostname = :agentHostname and j.status IN (:activeStatuses)"
+ ") as numberOfActiveJobs",
nativeQuery = true // Native due to JPQL not allowing select queries without a from clause
)
JobInfoAggregate getHostJobInfo(
@Param("agentHostname") String agentHostname,
@Param("activeStatuses") Set<String> activeStatuses,
@Param("usedStatuses") Set<String> usedStatuses
);
/**
* Count all jobs that belong to a given user and are in any of the given states.
*
* @param user the user name
* @param statuses the set of statuses
* @return the count of jobs matching the search criteria
*/
Long countJobsByUserAndStatusIn(@NotBlank String user, @NotEmpty Set<String> statuses);
/**
* Find a batch of jobs that were created before the given time.
*
* @param createdThreshold The time before which the jobs were submitted. Exclusive
* @param excludeStatuses The set of statuses which should be excluded from the results
* @param limit The maximum number of jobs to to find
* @return The number of deleted jobs
*/
@Query(value = FIND_OLD_JOBS_QUERY, nativeQuery = true)
Set<Long> findJobsCreatedBefore(
@Param("createdThreshold") Instant createdThreshold,
@Param("excludedStatuses") Set<String> excludeStatuses,
@Param("batchSize") int limit
);
/**
* Returns resources usage for each user that has a running job.
* Only jobs running on Genie servers are considered (i.e. no Agent jobs)
*
* @param statuses The set of statuses a job has to be in to be considered
* @param api Whether the job was submitted through the api ({@literal true}) or agent cli ({@literal false})
* @return The user resource aggregates
*/
@Query(
"SELECT j.user AS user, COUNT(j) as runningJobsCount, COALESCE(SUM(j.memoryUsed), 0) as usedMemory"
+ " FROM JobEntity j"
+ " WHERE j.status IN (:statuses) AND j.api = :isApi"
+ " GROUP BY j.user"
)
Set<UserJobResourcesAggregate> getUserJobResourcesAggregates(
@Param("statuses") Set<String> statuses,
@Param("isApi") boolean api
);
/**
* Find agent jobs in the given set of states.
*
* @param statuses the job statuses filter
* @return a set of job projections
*/
@Query("SELECT j.uniqueId FROM JobEntity j WHERE j.status IN (:statuses)")
Set<String> getJobIdsWithStatusIn(@Param("statuses") @NotEmpty Set<String> statuses);
/**
* Find agent jobs in the given set of job and archive states that were marked finished before a given threshold.
*
* @param statuses the job statuses filter
* @param archiveStatuses the job archive statuses filter
* @param updateThreshold select jobs last updated before this threshold
* @return a set of job ids
*/
@Query(
"SELECT j.uniqueId"
+ " FROM JobEntity j"
+ " WHERE j.status IN (:statuses)"
+ " AND j.archiveStatus IN (:archiveStatuses)"
+ " AND j.updated < :updatedThreshold"
)
Set<String> getJobsWithStatusAndArchiveStatusUpdatedBefore(
@Param("statuses") @NotEmpty Set<String> statuses,
@Param("archiveStatuses") @NotEmpty Set<String> archiveStatuses,
@Param("updatedThreshold") Instant updateThreshold
);
/**
* Get only the status of a job.
*
* @param id The id of the job to get the status for
* @return The job status string or {@link Optional#empty()} if no job with the given id exists
*/
@Query("SELECT j.status FROM JobEntity j WHERE j.uniqueId = :id")
Optional<String> getJobStatus(@Param("id") String id);
/**
* Return whether the job was submitted via the API or the Agent CLI.
*
* @param id The unique id of the job
* @return {@literal true} if the job was submitted via the API. {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j.api FROM JobEntity j WHERE j.uniqueId = :id")
Optional<Boolean> isAPI(@Param("id") String id);
/**
* Get only the hostname of a job.
*
* @param id The id of the job to get the hostname for
* @return The job hostname or {@link Optional#empty()} if no job with the given id exists
*/
@Query("SELECT j.agentHostname FROM JobEntity j WHERE j.uniqueId = :id")
Optional<String> getJobHostname(@Param("id") String id);
/**
* Get only the archive status of a job.
*
* @param id The id of the job to get the archive status for
* @return The job archive status or {@link Optional#empty()} if no job with the given id exists
*/
@Query("SELECT COALESCE(j.archiveStatus, 'UNKNOWN') FROM JobEntity j WHERE j.uniqueId = :id")
Optional<String> getArchiveStatus(@Param("id") String id);
/**
* Get only the requested launcher ext of a job.
*
* @param id The id of the job
* @return The requested launcher ext JSON node {@link Optional#empty()} if no job with the given id exists
*/
@Query("SELECT j.requestedLauncherExt FROM JobEntity j WHERE j.uniqueId = :id")
Optional<JsonNode> getRequestedLauncherExt(@Param("id") String id);
/**
* Get only the launcher ext of a job.
*
* @param id The id of the job
* @return The launcher ext JSON node {@link Optional#empty()} if no job with the given id exists
*/
@Query("SELECT j.launcherExt FROM JobEntity j WHERE j.uniqueId = :id")
Optional<JsonNode> getLauncherExt(@Param("id") String id);
/**
* Get the data needed to create a V3 Job DTO.
*
* @param id The unique id of the job
* @return The {@link JobProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.V3_JOB_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobProjection> getV3Job(@Param("id") String id);
/**
* Get the data needed to create a V4 Job Request DTO.
*
* @param id The unique id of the job
* @return The {@link JobRequestProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.V4_JOB_REQUEST_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobRequestProjection> getV4JobRequest(@Param("id") String id);
/**
* Get the data needed to create a V4 Job Specification DTO.
*
* @param id The unique id of the job
* @return The {@link JobSpecificationProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.V4_JOB_SPECIFICATION_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobSpecificationProjection> getJobSpecification(@Param("id") String id);
/**
* Get the applications for a job.
*
* @param id The unique id of the job
* @return The {@link JobApplicationsProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.JOB_APPLICATIONS_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobApplicationsProjection> getJobApplications(@Param("id") String id);
/**
* Get the cluster for a job.
*
* @param id The unique id of the job
* @return The {@link JobClusterProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.JOB_CLUSTER_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobClusterProjection> getJobCluster(@Param("id") String id);
/**
* Get the command for a job.
*
* @param id The unique id of the job
* @return The {@link JobCommandProjection} data or {@link Optional#empty()} if the job doesn't exist
*/
@Query("SELECT j FROM JobEntity j WHERE j.uniqueId = :id")
@EntityGraph(value = JobEntity.JOB_COMMAND_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<JobCommandProjection> getJobCommand(@Param("id") String id);
}
| 2,716 |
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/repositories/JpaApplicationRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.ApplicationEntity;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Application repository.
*
* @author tgianos
*/
public interface JpaApplicationRepository extends JpaBaseRepository<ApplicationEntity> {
/**
* Find any application records where they are not linked to any jobs and it's not linked to any commands and was
* created before the given time.
*/
String FIND_UNUSED_APPLICATIONS_QUERY =
"SELECT id"
+ " FROM applications"
+ " WHERE created < :createdThreshold"
+ " AND id NOT IN (SELECT DISTINCT(application_id) FROM commands_applications)"
+ " AND id NOT IN (SELECT DISTINCT(application_id) FROM jobs_applications)"
+ " LIMIT :limit";
/**
* Delete any application records where it's not linked to any jobs and it's not linked to any commands and was
* created before the given time.
*
* @param createdThreshold The instant in time before which records should be considered for deletion. Exclusive.
* @param limit Maximum number of IDs to return
* @return The ids of the applications that are unused
*/
@Query(value = FIND_UNUSED_APPLICATIONS_QUERY, nativeQuery = true)
Set<Long> findUnusedApplications(
@Param("createdThreshold") Instant createdThreshold,
@Param("limit") int limit
);
/**
* Get the {@link ApplicationEntity} but eagerly fetch all relational information needed to construct a DTO.
*
* @param id The unique identifier of the application to get
* @return An {@link ApplicationEntity} with dto data loaded or {@link Optional#empty()} if no application with the
* given id exists
*/
@Query("SELECT a FROM ApplicationEntity a WHERE a.uniqueId = :id")
@EntityGraph(value = ApplicationEntity.DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<ApplicationEntity> getApplicationDto(@Param("id") String id);
/**
* Get the {@link ApplicationEntity} but eagerly fetch all command base information as well.
*
* @param id The unique identifier of the application to get
* @return An {@link ApplicationEntity} with command data loaded or {@link Optional#empty()} if no application with
* the given id exists
*/
@Query("SELECT a FROM ApplicationEntity a WHERE a.uniqueId = :id")
@EntityGraph(value = ApplicationEntity.COMMANDS_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<ApplicationEntity> getApplicationAndCommands(@Param("id") String id);
/**
* Get the {@link ApplicationEntity} but eagerly fetch all command DTO information as well.
*
* @param id The unique identifier of the application to get
* @return An {@link ApplicationEntity} with command data loaded or {@link Optional#empty()} if no application with
* the given id exists
*/
@Query("SELECT a FROM ApplicationEntity a WHERE a.uniqueId = :id")
@EntityGraph(value = ApplicationEntity.COMMANDS_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<ApplicationEntity> getApplicationAndCommandsDto(@Param("id") String id);
}
| 2,717 |
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/repositories/JpaCommandRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.CommandEntity;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Command repository.
*
* @author tgianos
*/
public interface JpaCommandRepository extends JpaBaseRepository<CommandEntity> {
/**
* The query used to find commands that are in a certain status, not used in jobs and created some time ago.
*/
String FIND_UNUSED_COMMANDS_IN_STATUS_CREATED_BEFORE_QUERY =
"SELECT id"
+ " FROM commands"
+ " WHERE status IN (:statuses)"
+ " AND created < :commandCreatedThreshold"
+ " AND id NOT IN ("
+ "SELECT DISTINCT(command_id)"
+ " FROM jobs"
+ " WHERE command_id IS NOT NULL"
+ ")"
+ " LIMIT :limit";
/**
* Bulk set the status of commands which match the given inputs.
*
* @param desiredStatus The new status the matching commands should have
* @param commandIds The ids which should be updated
* @return The number of commands that were updated by the query
*/
@Query(value = "UPDATE CommandEntity c SET c.status = :desiredStatus WHERE c.id IN (:commandIds)")
@Modifying
int setStatusWhereIdIn(
@Param("desiredStatus") String desiredStatus,
@Param("commandIds") Set<Long> commandIds
);
/**
* Find commands from the database where their status is in {@literal statuses} and they were created
* before {@literal commandCreatedThreshold} and they aren't attached to any jobs still in the database.
*
* @param statuses The set of statuses a command must be in for it to be considered unused
* @param commandCreatedThreshold The instant in time a command must have been created before to be considered
* unused. Exclusive.
* @param limit Maximum number of IDs to return
* @return The ids of the commands that are considered unused
*/
@Query(value = FIND_UNUSED_COMMANDS_IN_STATUS_CREATED_BEFORE_QUERY, nativeQuery = true)
Set<Long> findUnusedCommandsByStatusesCreatedBefore(
@Param("statuses") Set<String> statuses,
@Param("commandCreatedThreshold") Instant commandCreatedThreshold,
@Param("limit") int limit
);
/**
* Find the command with the given id but also eagerly load that commands applications.
*
* @param id The id of the command to get
* @return The {@link CommandEntity} with its applications data loaded or {@link Optional#empty()} if there is no
* command with the given id
*/
@Query("SELECT c FROM CommandEntity c WHERE c.uniqueId = :id")
@EntityGraph(value = CommandEntity.APPLICATIONS_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<CommandEntity> getCommandAndApplications(@Param("id") String id);
/**
* Find the command with the given id but also eagerly load that commands applications full dto contents.
*
* @param id The id of the command to get
* @return The {@link CommandEntity} with its applications data loaded or {@link Optional#empty()} if there is no
* command with the given id
*/
@Query("SELECT c FROM CommandEntity c WHERE c.uniqueId = :id")
@EntityGraph(value = CommandEntity.APPLICATIONS_DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<CommandEntity> getCommandAndApplicationsDto(@Param("id") String id);
/**
* Find the command with the given id but also eagerly load that commands cluster criteria.
*
* @param id The id of the command to get
* @return The {@link CommandEntity} with its criteria data loaded or {@link Optional#empty()} if there is no
* command with the given id
*/
@Query("SELECT c FROM CommandEntity c WHERE c.uniqueId = :id")
@EntityGraph(value = CommandEntity.CLUSTER_CRITERIA_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<CommandEntity> getCommandAndClusterCriteria(@Param("id") String id);
/**
* Find the command with the given id but also eagerly load all data needed for a command DTO.
*
* @param id The id of the command to get
* @return The {@link CommandEntity} all DTO data loaded or {@link Optional#empty()} if there is no
* command with the given id
*/
@Query("SELECT c FROM CommandEntity c WHERE c.uniqueId = :id")
@EntityGraph(value = CommandEntity.DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<CommandEntity> getCommandDto(@Param("id") String id);
}
| 2,718 |
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/repositories/JpaTagRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.TagEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Repository for tags.
*
* @author tgianos
* @since 3.3.0
*/
public interface JpaTagRepository extends JpaIdRepository<TagEntity> {
/**
* This is the query used to find the ids of tags that aren't referenced by any of the other tables.
*/
String SELECT_FOR_UPDATE_UNUSED_TAGS_SQL =
"SELECT id "
+ "FROM tags "
+ "WHERE id NOT IN (SELECT DISTINCT(tag_id) FROM applications_tags) "
+ "AND id NOT IN (SELECT DISTINCT(tag_id) FROM clusters_tags) "
+ "AND id NOT IN (SELECT DISTINCT(tag_id) FROM commands_tags) "
+ "AND id NOT IN (SELECT DISTINCT(tag_id) FROM criteria_tags) "
+ "AND id NOT IN (SELECT DISTINCT(tag_id) FROM jobs_tags) "
+ "AND created <= :createdThreshold "
+ "LIMIT :limit "
+ "FOR UPDATE;";
/**
* Find a tag by its unique tag value.
*
* @param tag The tag value to search for
* @return An Optional of a TagEntity
*/
Optional<TagEntity> findByTag(String tag);
/**
* Find out whether a tag entity with the given tag value exists.
*
* @param tag The tag value to check for
* @return True if the tag exists
*/
boolean existsByTag(String tag);
/**
* Find tag entities where the tag value is in the given set of tags.
*
* @param tags The tags to find entities for
* @return The tag entities
*/
Set<TagEntity> findByTagIn(Set<String> tags);
/**
* Find 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 returned. Inclusive
* @param limit Maximum number of IDs to return
* @return The number of tags deleted
*/
@Query(value = SELECT_FOR_UPDATE_UNUSED_TAGS_SQL, nativeQuery = true)
Set<Number> findUnusedTags(
@Param("createdThreshold") Instant createdThreshold,
@Param("limit") int limit
);
/**
* Delete all tags from the database whose ids are in the supplied set.
*
* @param ids The ids of the tags to delete
* @return The number of tags deleted
*/
@Modifying
Long deleteByIdIn(Set<Long> ids);
}
| 2,719 |
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/repositories/JpaRepositories.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.repositories;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Container class for encapsulating all the various JPA Repositories in Genie to ease dependency patterns.
*
* @author tgianos
* @since 4.0.0
*/
@AllArgsConstructor
@Getter
public class JpaRepositories {
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;
}
| 2,720 |
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/repositories/JpaIdRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.IdEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
/**
* A base repository for all Genie JPA repositories to inherit from to save boilerplate.
*
* @param <E> The entity type which must extend IdEntity
* @author tgianos
* @since 3.3.0
*/
@NoRepositoryBean
interface JpaIdRepository<E extends IdEntity> extends JpaRepository<E, Long>, JpaSpecificationExecutor<E> {
}
| 2,721 |
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/repositories/JpaBaseRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.BaseEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.NoRepositoryBean;
import java.util.Optional;
import java.util.Set;
/**
* A common repository for inheritance of common methods for Entities extending BaseEntity.
*
* @param <E> The entity class to act on which must extend BaseEntity
* @author tgianos
* @since 3.3.0
*/
@NoRepositoryBean
public interface JpaBaseRepository<E extends BaseEntity> extends JpaIdRepository<E> {
/**
* Find an entity by its unique id.
*
* @param uniqueId The unique id to find an entity for
* @return The entity found or empty Optional
*/
Optional<E> findByUniqueId(String uniqueId);
// TODO: Make interfaces generic but be aware of https://jira.spring.io/browse/DATAJPA-1185
/**
* Find an entity by its unique id.
*
* @param <T> The class type which is a projection of E
* @param uniqueId The unique id to find an entity for
* @param type The entity or projection type to return
* @return The entity found or empty Optional
*/
<T> Optional<T> findByUniqueId(String uniqueId, Class<T> type);
/**
* Find out whether an entity with the given unique id exists.
*
* @param uniqueId The unique id to check for existence
* @return True if an entity with the unique id exists
*/
boolean existsByUniqueId(String uniqueId);
/**
* Delete all entities whose ids are contained in the given set of ids.
*
* @param ids The ids of the entities to delete
* @return The number of deleted entities
*/
@Modifying
Long deleteByIdIn(Set<Long> ids);
}
| 2,722 |
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/repositories/JpaFileRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.FileEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Repository for file references.
*
* @author tgianos
* @since 3.3.0
*/
public interface JpaFileRepository extends JpaIdRepository<FileEntity> {
/**
* The query used to select any dangling file references.
*/
String SELECT_FOR_UPDATE_UNUSED_FILES_SQL =
"SELECT id "
+ "FROM files "
+ "WHERE id NOT IN (SELECT DISTINCT(setup_file) FROM applications WHERE setup_file IS NOT NULL) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM applications_configs) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM applications_dependencies) "
+ "AND id NOT IN (SELECT DISTINCT(setup_file) FROM clusters WHERE setup_file IS NOT NULL) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM clusters_configs) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM clusters_dependencies) "
+ "AND id NOT IN (SELECT DISTINCT(setup_file) FROM commands WHERE setup_file IS NOT NULL) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM commands_configs) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM commands_dependencies) "
+ "AND id NOT IN (SELECT DISTINCT(setup_file) FROM jobs WHERE setup_file IS NOT NULL) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM jobs_configs) "
+ "AND id NOT IN (SELECT DISTINCT(file_id) FROM jobs_dependencies) "
+ "AND created <= :createdThresholdUpperBound "
+ "AND created >= :createdThresholdLowerBound "
+ "LIMIT :limit "
+ "FOR UPDATE;";
/**
* Find a file by its unique file value.
*
* @param file The file value to search for
* @return An Optional of a FileEntity
*/
Optional<FileEntity> findByFile(String file);
/**
* Find out whether a file entity with the given file value exists.
*
* @param file The file value to check for
* @return True if the file exists
*/
boolean existsByFile(String file);
/**
* Find file entities where the file value is in the given set of files.
*
* @param files The files to find entities for
* @return The file entities
*/
Set<FileEntity> findByFileIn(Set<String> files);
/**
* Find the ids of 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 limit The maximum number of file ids to retrieve
* @return The ids of the files which should be deleted
*/
@Query(value = SELECT_FOR_UPDATE_UNUSED_FILES_SQL, nativeQuery = true)
Set<Number> findUnusedFiles(
@Param("createdThresholdLowerBound") Instant createdThresholdLowerBound,
@Param("createdThresholdUpperBound") Instant createdThresholdUpperBound,
@Param("limit") int limit
);
/**
* Delete all files from the database that are in the current set of ids.
*
* @param ids The unique ids of the files to delete
* @return The number of files deleted
*/
@Modifying
Long deleteByIdIn(Set<Long> ids);
}
| 2,723 |
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/repositories/JpaClusterRepository.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.repositories;
import com.netflix.genie.web.data.services.impl.jpa.entities.ClusterEntity;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
/**
* Cluster repository.
*
* @author tgianos
*/
public interface JpaClusterRepository extends JpaBaseRepository<ClusterEntity> {
/**
* The SQL to find all clusters that aren't attached to any jobs still in the database and were created before
* a certain point in time.
*/
String FIND_UNUSED_CLUSTERS_SQL =
"SELECT id"
+ " FROM clusters"
+ " WHERE status IN (:unusedStatuses)"
+ " AND created < :clusterCreatedThreshold"
+ " AND id NOT IN (SELECT DISTINCT(cluster_id) FROM jobs WHERE cluster_id IS NOT NULL)"
+ " LIMIT :limit";
/**
* Find all the clusters that aren't attached to any jobs in the database, were created before the given time
* and have one of the given statuses.
*
* @param unusedStatuses The set of statuses a cluster must have to be considered unused
* @param clusterCreatedThreshold The instant in time which a cluster must have been created before to be considered
* unused. Exclusive.
* @param limit Maximum number of IDs to return
* @return The ids of the clusters that are considered unused
*/
@Query(value = FIND_UNUSED_CLUSTERS_SQL, nativeQuery = true)
// TODO: Could use different lock mode
Set<Long> findUnusedClusters(
@Param("unusedStatuses") Set<String> unusedStatuses,
@Param("clusterCreatedThreshold") Instant clusterCreatedThreshold,
@Param("limit") int limit
);
/**
* Find the cluster with the given id but also eagerly load all data needed for a cluster DTO.
*
* @param id The id of the command to get
* @return The {@link ClusterEntity} with all DTO data loaded or {@link Optional#empty()} if there is no
* cluster with the given id
*/
@Query("SELECT c FROM ClusterEntity c WHERE c.uniqueId = :id")
@EntityGraph(value = ClusterEntity.DTO_ENTITY_GRAPH, type = EntityGraph.EntityGraphType.LOAD)
Optional<ClusterEntity> getClusterDto(@Param("id") String id);
}
| 2,724 |
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/repositories/package-info.java | /*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes used for accessing data with JPA.
*
* @author tgianos
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.repositories;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,725 |
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/listeners/JobEntityListener.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.listeners;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.dtos.converters.DtoConverters;
import com.netflix.genie.web.data.observers.PersistedJobStatusObserver;
import com.netflix.genie.web.data.services.impl.jpa.entities.JobEntity;
import lombok.extern.slf4j.Slf4j;
import javax.persistence.PostLoad;
import javax.persistence.PostUpdate;
import java.util.Optional;
/**
* Listener for Job JPA entity ({@link JobEntity}).
* Currently tracks persistent changes to the status of a job and notifies an observer.
* Could be extended to do proxy more persist changes.
* <p>
* N.B. Spring configuration.
* - This class does not appear in any AutoConfiguration as bean.
* It is referenced as {@link java.util.EventListener} by {@link JobEntity}.
* EntityManager creates it even if a bean of the same type exists already.
* - The constructor parameter {@code persistedJobStatusObserver} is marked {@code Nullable} so that an instance can be
* created even if no bean of that type is configured.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class JobEntityListener {
private final PersistedJobStatusObserver persistedJobStatusObserver;
/**
* Constructor.
*
* @param persistedJobStatusObserver the observer to notify of persisted job status changes
*/
public JobEntityListener(final PersistedJobStatusObserver persistedJobStatusObserver) {
this.persistedJobStatusObserver = persistedJobStatusObserver;
}
/**
* Persistence callback invoked after a job entity has been committed/flushed into persistent storage.
* If the persisted status of the job is different from the last one notified, then a notification is emitted.
*
* @param jobEntity the job that was just persisted
*/
@PostUpdate
public void jobUpdate(final JobEntity jobEntity) {
final JobStatus currentState;
try {
currentState = DtoConverters.toV4JobStatus(jobEntity.getStatus());
} catch (final IllegalArgumentException e) {
log.error("Unable to convert current status {} to a valid JobStatus", jobEntity.getStatus(), e);
return;
}
final JobStatus previouslyNotifiedState;
final Optional<String> pnsOptional = jobEntity.getNotifiedJobStatus();
if (pnsOptional.isPresent()) {
try {
previouslyNotifiedState = DtoConverters.toV4JobStatus(pnsOptional.get());
} catch (final IllegalArgumentException e) {
log.error(
"Unable to convert previously notified status {} to a valid JobStatus",
jobEntity.getStatus(),
e
);
return;
}
} else {
previouslyNotifiedState = null;
}
final String jobId = jobEntity.getUniqueId();
if (currentState != previouslyNotifiedState) {
log.debug(
"Detected state change for job: {} from: {} to: {}",
jobId,
previouslyNotifiedState,
currentState
);
// Notify observer
this.persistedJobStatusObserver.notify(jobId, previouslyNotifiedState, currentState);
// Save this as the latest published state
jobEntity.setNotifiedJobStatus(currentState.name());
}
}
/**
* Persistence callback invoked after a job entity is loaded or refreshed.
* The job status loaded from persistent storage is also the last state that was notified.
*
* @param jobEntity the job that was just loaded
*/
@PostLoad
public void jobLoad(final JobEntity jobEntity) {
// The persisted status is also the most recently notified state.
jobEntity.setNotifiedJobStatus(jobEntity.getStatus());
}
}
| 2,726 |
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/listeners/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 listeners classes that listen to changes applied in persistent storage.
*
* @author tgianos
* @since 3.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.listeners;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,727 |
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/entities/CriterionEntity.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.entities;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* Entity for criteria records.
*
* @author tgianos
* @since 3.3.0
*/
@NoArgsConstructor
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "criteria")
public class CriterionEntity extends IdEntity {
@Basic
@Column(name = "unique_id", updatable = false)
@Size(max = 255, message = "The id part of the criterion can't be longer than 255 characters")
private String uniqueId;
@Basic
@Column(name = "name", updatable = false)
@Size(max = 255, message = "The name part of the criterion can't be longer than 255 characters")
private String name;
@Basic
@Column(name = "version", updatable = false)
@Size(max = 255, message = "The version part of the criterion can't be longer than 255 characters")
private String version;
@Basic
@Column(name = "status", updatable = false)
@Size(max = 255, message = "The status part of the criterion can't be longer than 255 characters")
private String status;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "criteria_tags",
joinColumns = {
@JoinColumn(name = "criterion_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<TagEntity> tags = new HashSet<>();
/**
* Constructor.
*
* @param uniqueId The unique id of the resource this criterion is or was trying to match
* @param name The name of the resource this criterion is or was trying to match
* @param version The version of the resource this criterion is or was trying to match
* @param status The status of the resource this criterion is or was trying to match
* @param tags The tags on the resource this criterion is or was trying to match
*/
public CriterionEntity(
@Nullable final String uniqueId,
@Nullable final String name,
@Nullable final String version,
@Nullable final String status,
@Nullable final Set<TagEntity> tags
) {
super();
this.uniqueId = uniqueId;
this.name = name;
this.version = version;
this.status = status;
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* Get the unique id this criterion was using if there was one.
*
* @return The unique id wrapped in an {@link Optional}
*/
public Optional<String> getUniqueId() {
return Optional.ofNullable(this.uniqueId);
}
/**
* Set the unique id this criterion used.
*
* @param uniqueId The unique id to set
*/
public void setUniqueId(@Nullable final String uniqueId) {
this.uniqueId = uniqueId;
}
/**
* Get the name this criterion was using if there was one.
*
* @return The name wrapped in an {@link Optional}
*/
public Optional<String> getName() {
return Optional.ofNullable(this.name);
}
/**
* Set the name this criterion used.
*
* @param name The name to set
*/
public void setName(@Nullable final String name) {
this.name = name;
}
/**
* Get the version this criterion was using if there was one.
*
* @return The version wrapped in an {@link Optional}
*/
public Optional<String> getVersion() {
return Optional.ofNullable(this.version);
}
/**
* Set the version this criterion used.
*
* @param version The version to set
*/
public void setVersion(@Nullable final String version) {
this.version = version;
}
/**
* Get the status this criterion was using if there was one.
*
* @return The status wrapped in an {@link Optional}
*/
public Optional<String> getStatus() {
return Optional.ofNullable(this.status);
}
/**
* Set the status this criterion used.
*
* @param status The version to set
*/
public void setStatus(@Nullable final String status) {
this.status = status;
}
/**
* Set all the tags associated to this criterion.
*
* @param tags The criterion tags to set
*/
public void setTags(@Nullable final Set<TagEntity> tags) {
this.tags.clear();
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,728 |
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/entities/JobEntity.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.entities;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.web.data.services.impl.jpa.converters.IntegerToLongConverter;
import com.netflix.genie.web.data.services.impl.jpa.converters.JsonAttributeConverter;
import com.netflix.genie.web.data.services.impl.jpa.listeners.JobEntityListener;
import com.netflix.genie.web.data.services.impl.jpa.queries.predicates.PredicateUtils;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobApiProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobApplicationsProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobArchiveLocationProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobClusterProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobCommandProjection;
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.JobProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.JobSearchProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.StatusProjection;
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.JobRequestProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.v4.JobSpecificationProjection;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MapKeyColumn;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.OrderColumn;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* A row in the jobs table.
*
* @author amsharma
* @author tgianos
*/
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@EntityListeners(
{
// Can't decouple through interface or abstract class or configuration, only concrete classes work.
JobEntityListener.class
}
)
@Table(name = "jobs")
// Note: We're using hibernate by default it ignores fetch graphs and just loads basic fields anyway without
// bytecode enhancement. For now just use this to load relationships and not worry too much about optimizing
// column projection on large entity fetches
// See:
// https://www.baeldung.com/jpa-entity-graph#creating-entity-graph-2
// https://stackoverflow.com/questions/37054082/hibernate-ignores-fetchgraph
@NamedEntityGraphs(
{
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.V3_JOB_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("metadata"),
@NamedAttributeNode("commandArgs"),
@NamedAttributeNode("tags"),
@NamedAttributeNode("imagesUsed"),
// In actually looking at code this isn't used
// @NamedAttributeNode("applications")
}
),
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.V4_JOB_REQUEST_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("metadata"),
@NamedAttributeNode("commandArgs"),
@NamedAttributeNode("tags"),
@NamedAttributeNode("requestedEnvironmentVariables"),
@NamedAttributeNode("requestedAgentEnvironmentExt"),
@NamedAttributeNode("requestedAgentConfigExt"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode(
value = "clusterCriteria",
subgraph = "criterion-sub-graph"
),
@NamedAttributeNode(
value = "commandCriterion",
subgraph = "criterion-sub-graph"
),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("requestedApplications"),
@NamedAttributeNode("requestedLauncherExt"),
@NamedAttributeNode("requestedImages"),
},
subgraphs = {
@NamedSubgraph(
name = "criterion-sub-graph",
attributeNodes = {
@NamedAttributeNode("tags")
}
),
}
),
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.V4_JOB_SPECIFICATION_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("configs"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("commandArgs"),
@NamedAttributeNode(
value = "cluster",
subgraph = "resource-sub-graph"
),
@NamedAttributeNode(
value = "command",
subgraph = "command-sub-graph"
),
@NamedAttributeNode(
value = "applications",
subgraph = "resource-sub-graph"
),
},
subgraphs = {
@NamedSubgraph(
name = "resource-sub-graph",
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies")
}
),
@NamedSubgraph(
name = "command-sub-graph",
attributeNodes = {
@NamedAttributeNode("executable"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies")
}
),
}
),
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.JOB_APPLICATIONS_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "applications",
subgraph = "application-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "application-sub-graph",
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags")
}
)
}
),
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.JOB_CLUSTER_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "cluster",
subgraph = "cluster-sub-graph"
),
},
subgraphs = {
@NamedSubgraph(
name = "cluster-sub-graph",
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags"),
}
),
}
),
// Intended to be used as a LOAD graph
@NamedEntityGraph(
name = JobEntity.JOB_COMMAND_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "command",
subgraph = "command-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "command-sub-graph",
attributeNodes = {
@NamedAttributeNode("executable"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags"),
@NamedAttributeNode(
value = "clusterCriteria",
subgraph = "criteria-sub-graph"
)
}
),
@NamedSubgraph(
name = "criteria-sub-graph",
attributeNodes = {
@NamedAttributeNode("tags")
}
)
}
)
}
)
public class JobEntity extends BaseEntity implements
FinishedJobProjection,
JobProjection,
JobMetadataProjection,
JobExecutionProjection,
JobApplicationsProjection,
JobClusterProjection,
JobCommandProjection,
JobSearchProjection,
JobRequestProjection,
JobSpecificationProjection,
JobArchiveLocationProjection,
JobApiProjection,
StatusProjection {
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed
* for a V3 Job DTO.
*/
public static final String V3_JOB_DTO_ENTITY_GRAPH = "Job.v3.dto.job";
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed
* for a V4 Job Request DTO.
*/
public static final String V4_JOB_REQUEST_DTO_ENTITY_GRAPH = "Job.v4.dto.request";
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed
* for a V4 Job Specification DTO.
*/
public static final String V4_JOB_SPECIFICATION_DTO_ENTITY_GRAPH = "Job.v4.dto.specification";
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed to get the
* applications for a job.
*/
public static final String JOB_APPLICATIONS_DTO_ENTITY_GRAPH = "Job.applications";
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed to get the
* cluster for a job.
*/
public static final String JOB_CLUSTER_DTO_ENTITY_GRAPH = "Job.cluster";
/**
* The name of the {@link javax.persistence.EntityGraph} which will load all the data needed to get the
* command for a job.
*/
public static final String JOB_COMMAND_DTO_ENTITY_GRAPH = "Job.command";
private static final long serialVersionUID = 2849367731657512224L;
// TODO: Drop this column once search implemented via better mechanism
@Basic
@Column(name = "tags", length = 1024, updatable = false)
@Size(max = 1024, message = "Max length in database is 1024 characters")
@Getter(AccessLevel.PACKAGE)
@Setter(AccessLevel.NONE)
private String tagSearchString;
@Basic
@Column(name = "genie_user_group", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String genieUserGroup;
@Basic(optional = false)
@Column(name = "archiving_disabled", nullable = false, updatable = false)
private boolean archivingDisabled;
@Basic
@Column(name = "email", updatable = false)
@Email
@Size(max = 255, message = "Max length in database is 255 characters")
private String email;
@Basic
@Column(name = "requested_cpu", updatable = false)
@Min(value = 1, message = "Can't have less than 1 CPU")
private Integer requestedCpu;
@Basic
@Column(name = "cpu_used")
@Min(value = 1, message = "Can't have less than 1 CPU")
private Integer cpuUsed;
@Basic
@Column(name = "requested_gpu", updatable = false)
@Min(value = 0, message = "Can't have less than 0 GPU")
private Integer requestedGpu;
@Basic
@Column(name = "gpu_used")
@Min(value = 0, message = "Can't have less than 0 GPU")
private Integer gpuUsed;
@Column(name = "requested_memory", updatable = false)
// Memory that stored in DB has data type of Integer and unit type of MB. If the requestedMemory retrieved from db
// is 2048, it means 2048 MB, NOT 2048 Bytes.
@Convert(converter = IntegerToLongConverter.class)
@Min(value = 1, message = "Can't have less than 1 MB of memory allocated")
private Long requestedMemory;
@Column(name = "memory_used")
// Memory that stored in DB has data type of Integer and unit type of MB. If the memoryUsed retrieved from db
// is 2048, it means 2048 MB, NOT 2048 Bytes.
@Convert(converter = IntegerToLongConverter.class)
@Min(value = 1, message = "Can't have less than 1 MB of memory allocated")
private Long memoryUsed;
@Basic
@Column(name = "requested_disk_mb", updatable = false)
@Min(value = 1, message = "Can't have less than 1 MB of disk space")
private Long requestedDiskMb;
@Basic
@Column(name = "disk_mb_used")
@Min(value = 1, message = "Can't have less than 1 MB of disk space")
private Long diskMbUsed;
@Basic
@Column(name = "requested_network_mbps", updatable = false)
@Min(value = 1, message = "Can't have less than 1 MBPS of network")
private Long requestedNetworkMbps;
@Basic
@Column(name = "network_mbps_used")
@Min(value = 1, message = "Can't have less than 1 MBPS of network")
private Long networkMbpsUsed;
@Basic
@Column(name = "requested_timeout", updatable = false)
@Min(value = 1)
private Integer requestedTimeout;
@Basic
@Column(name = "timeout_used")
@Min(value = 1)
private Integer timeoutUsed;
@Basic
@Column(name = "grouping", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String grouping;
@Basic
@Column(name = "grouping_instance", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String groupingInstance;
@Basic
@Column(name = "request_api_client_hostname", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String requestApiClientHostname;
@Basic
@Column(name = "request_api_client_user_agent", length = 1024, updatable = false)
@Size(max = 1024, message = "Max length in database is 1024 characters")
private String requestApiClientUserAgent;
@Basic
@Column(name = "request_agent_client_hostname", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String requestAgentClientHostname;
@Basic
@Column(name = "request_agent_client_version", updatable = false)
@Size(max = 255, message = "Max length in database is 255 characters")
private String requestAgentClientVersion;
@Basic
@Column(name = "request_agent_client_pid", updatable = false)
@Min(value = 0, message = "Agent Client Pid can't be less than zero")
private Integer requestAgentClientPid;
@Basic
@Column(name = "num_attachments", updatable = false)
@Min(value = 0, message = "Can't have less than zero attachments")
private Integer numAttachments;
@Basic
@Column(name = "total_size_of_attachments", updatable = false)
@Min(value = 0, message = "Can't have less than zero bytes total attachment size")
private Long totalSizeOfAttachments;
@Basic
@Column(name = "std_out_size")
@Min(value = 0, message = "Can't have less than zero bytes for std out size")
private Long stdOutSize;
@Basic
@Column(name = "std_err_size")
@Min(value = 0, message = "Can't have less than zero bytes for std err size")
private Long stdErrSize;
@Basic
@Column(name = "cluster_name")
@Size(max = 255, message = "Max length in database is 255 characters")
private String clusterName;
@Basic
@Column(name = "command_name")
@Size(max = 255, message = "Max length in database is 255 characters")
private String commandName;
@Basic
@Column(name = "status_msg")
@Size(max = 255, message = "Max length in database is 255 characters")
private String statusMsg;
@Basic
@Column(name = "started")
private Instant started;
@Basic
@Column(name = "finished")
private Instant finished;
@Basic
@Column(name = "agent_hostname")
@Size(max = 255, message = "An agent hostname can be no longer than 255 characters")
private String agentHostname;
@Basic
@Column(name = "agent_version")
@Size(max = 255, message = "An agent version can be no longer than 255 characters")
private String agentVersion;
@Basic
@Column(name = "agent_pid")
@Min(0)
private Integer agentPid;
@Basic
@Column(name = "process_id")
private Integer processId;
@Basic
@Column(name = "exit_code")
private Integer exitCode;
@Basic
@Column(name = "archive_location", length = 1024)
@Size(max = 1024, message = "Max length in database is 1024 characters")
private String archiveLocation;
@Basic(optional = false)
@Column(name = "interactive", nullable = false, updatable = false)
private boolean interactive;
@Basic(optional = false)
@Column(name = "resolved", nullable = false)
private boolean resolved;
@Basic(optional = false)
@Column(name = "claimed", nullable = false)
private boolean claimed;
@Basic
@Column(name = "requested_job_directory_location", length = 1024, updatable = false)
private String requestedJobDirectoryLocation;
@Basic
@Column(name = "job_directory_location", length = 1024)
private String jobDirectoryLocation;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "requested_agent_config_ext", updatable = false, columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode requestedAgentConfigExt;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "requested_agent_environment_ext", updatable = false, columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode requestedAgentEnvironmentExt;
@Basic(optional = false)
@Column(name = "api", nullable = false)
private boolean api = true;
@Basic
@Column(name = "archive_status", length = 20)
private String archiveStatus;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "requested_images", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode requestedImages;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "images_used", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode imagesUsed;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "requested_launcher_ext", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode requestedLauncherExt;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "launcher_ext", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode launcherExt;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cluster_id")
@ToString.Exclude
private ClusterEntity cluster;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "command_id")
@ToString.Exclude
private CommandEntity command;
@ElementCollection
@CollectionTable(
name = "job_command_arguments",
joinColumns = {
@JoinColumn(name = "job_id", nullable = false, updatable = false)
}
)
@Column(name = "argument", length = 10_000, nullable = false, updatable = false)
@OrderColumn(name = "argument_order", nullable = false, updatable = false)
@ToString.Exclude
private List<@NotBlank @Size(max = 10_000) String> commandArgs = new ArrayList<>();
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(
name = "job_requested_environment_variables",
joinColumns = {
@JoinColumn(name = "job_id", nullable = false, updatable = false)
}
)
@MapKeyColumn(name = "name", updatable = false)
@Column(name = "value", length = 1024, nullable = false, updatable = false)
@ToString.Exclude
private Map<@NotBlank @Size(max = 255) String, @NotNull @Size(max = 1024) String>
requestedEnvironmentVariables = new HashMap<>();
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(
name = "job_environment_variables",
joinColumns = {
@JoinColumn(name = "job_id", nullable = false)
}
)
@MapKeyColumn(name = "name")
@Column(name = "value", length = 1024, nullable = false)
@ToString.Exclude
private Map<@NotBlank @Size(max = 255) String, @NotNull @Size(max = 1024) String>
environmentVariables = new HashMap<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "jobs_applications",
joinColumns = {
@JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false)
}
)
@OrderColumn(name = "application_order", nullable = false, updatable = false)
@ToString.Exclude
private List<ApplicationEntity> applications = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(
name = "jobs_cluster_criteria",
joinColumns = {
@JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "criterion_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@OrderColumn(name = "priority_order", nullable = false, updatable = false)
@ToString.Exclude
private List<CriterionEntity> clusterCriteria = new ArrayList<>();
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "command_criterion", nullable = false, updatable = false)
@ToString.Exclude
private CriterionEntity commandCriterion;
@ElementCollection
@CollectionTable(
name = "job_requested_applications",
joinColumns = {
@JoinColumn(name = "job_id", nullable = false, updatable = false)
}
)
@Column(name = "application_id", nullable = false, updatable = false)
@OrderColumn(name = "application_order", nullable = false, updatable = false)
@ToString.Exclude
private List<String> requestedApplications = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "jobs_configs",
joinColumns = {
@JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> configs = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "jobs_dependencies",
joinColumns = {
@JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> dependencies = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "jobs_tags",
joinColumns = {
@JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<TagEntity> tags = new HashSet<>();
@Transient
@ToString.Exclude
private String notifiedJobStatus;
/**
* Default Constructor.
*/
public JobEntity() {
super();
}
/**
* Before a job is created, create the job search string.
*/
@PrePersist
void onCreateJob() {
if (!this.tags.isEmpty()) {
// Tag search string length max is currently 1024 which will be caught by hibernate validator if this
// exceeds that length
this.tagSearchString = PredicateUtils.createTagSearchString(this.tags);
}
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getGenieUserGroup() {
return Optional.ofNullable(this.genieUserGroup);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getEmail() {
return Optional.ofNullable(this.email);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getRequestedCpu() {
return Optional.ofNullable(this.requestedCpu);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getRequestedTimeout() {
return Optional.ofNullable(this.requestedTimeout);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getCpuUsed() {
return Optional.ofNullable(this.cpuUsed);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getGpuUsed() {
return Optional.ofNullable(this.gpuUsed);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getDiskMbUsed() {
return Optional.ofNullable(this.diskMbUsed);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getNetworkMbpsUsed() {
return Optional.ofNullable(this.networkMbpsUsed);
}
/**
* Set the command criterion.
*
* @param commandCriterion The criterion. Null clears reference.
*/
public void setCommandCriterion(@Nullable final CriterionEntity commandCriterion) {
this.commandCriterion = commandCriterion;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getGrouping() {
return Optional.ofNullable(this.grouping);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getGroupingInstance() {
return Optional.ofNullable(this.groupingInstance);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getStatusMsg() {
return Optional.ofNullable(this.statusMsg);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Instant> getStarted() {
return Optional.ofNullable(this.started);
}
/**
* Set the start time for the job.
*
* @param started The started time.
*/
public void setStarted(@Nullable final Instant started) {
this.started = started;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Instant> getFinished() {
return Optional.ofNullable(this.finished);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getRequestedMemory() {
return Optional.ofNullable(this.requestedMemory);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getRequestApiClientHostname() {
return Optional.ofNullable(this.requestApiClientHostname);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getRequestApiClientUserAgent() {
return Optional.ofNullable(this.requestApiClientUserAgent);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getNumAttachments() {
return Optional.ofNullable(this.numAttachments);
}
/**
* Get the hostname of the agent that requested this job be run if there was one.
*
* @return The hostname wrapped in an {@link Optional}
*/
public Optional<String> getRequestAgentClientHostname() {
return Optional.ofNullable(this.requestAgentClientHostname);
}
/**
* Get the version of the agent that requested this job be run if there was one.
*
* @return The version wrapped in an {@link Optional}
*/
public Optional<String> getRequestAgentClientVersion() {
return Optional.ofNullable(this.requestAgentClientVersion);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getExitCode() {
return Optional.ofNullable(this.exitCode);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getArchiveLocation() {
return Optional.ofNullable(this.archiveLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getMemoryUsed() {
return Optional.ofNullable(this.memoryUsed);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<ClusterEntity> getCluster() {
return Optional.ofNullable(this.cluster);
}
/**
* Set the cluster this job ran on.
*
* @param cluster The cluster this job ran on
*/
public void setCluster(@Nullable final ClusterEntity cluster) {
if (this.cluster != null) {
this.clusterName = null;
}
this.cluster = cluster;
if (this.cluster != null) {
this.clusterName = cluster.getName();
}
}
/**
* {@inheritDoc}
*/
@Override
public Optional<CommandEntity> getCommand() {
return Optional.ofNullable(this.command);
}
/**
* Set the command used to run this job.
*
* @param command The command
*/
public void setCommand(@Nullable final CommandEntity command) {
if (this.command != null) {
this.commandName = null;
}
this.command = command;
if (this.command != null) {
this.commandName = command.getName();
}
}
/**
* Set the finishTime for the job.
*
* @param finished The finished time.
*/
public void setFinished(@Nullable final Instant finished) {
this.finished = finished;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getTotalSizeOfAttachments() {
return Optional.ofNullable(this.totalSizeOfAttachments);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getStdOutSize() {
return Optional.ofNullable(this.stdOutSize);
}
/**
* Set the total size in bytes of the std out file for this job.
*
* @param stdOutSize The size. Null empty's database field
*/
public void setStdOutSize(@Nullable final Long stdOutSize) {
this.stdOutSize = stdOutSize;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getStdErrSize() {
return Optional.ofNullable(this.stdErrSize);
}
/**
* Set the total size in bytes of the std err file for this job.
*
* @param stdErrSize The size. Null empty's database field
*/
public void setStdErrSize(@Nullable final Long stdErrSize) {
this.stdErrSize = stdErrSize;
}
/**
* Get the PID of the agent that requested this job be run if there was one.
*
* @return The PID wrapped in an {@link Optional}
*/
public Optional<Integer> getRequestAgentClientPid() {
return Optional.ofNullable(this.requestAgentClientPid);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getClusterName() {
return Optional.ofNullable(this.clusterName);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getCommandName() {
return Optional.ofNullable(this.commandName);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getAgentHostname() {
return Optional.ofNullable(this.agentHostname);
}
/**
* Get the version of the agent that claimed this job.
*
* @return The version wrapped in an {@link Optional} in case it wasn't set yet in which case it will be
* {@link Optional#empty()}
*/
public Optional<String> getAgentVersion() {
return Optional.ofNullable(this.agentVersion);
}
/**
* Get the pid of the agent that claimed this job.
*
* @return The pid wrapped in an {@link Optional} in case it wasn't set yet in which case it will be
* {@link Optional#empty()}
*/
public Optional<Integer> getAgentPid() {
return Optional.ofNullable(this.agentPid);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getProcessId() {
return Optional.ofNullable(this.processId);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getTimeoutUsed() {
return Optional.ofNullable(this.timeoutUsed);
}
/**
* Set the final resolved timeout duration for this job.
*
* @param timeoutUsed The timeout value (in seconds) after which this job should be killed by the system
*/
public void setTimeoutUsed(@Nullable final Integer timeoutUsed) {
this.timeoutUsed = timeoutUsed;
}
/**
* Get the archive status for the job if there is one.
*
* @return The archive status or {@link Optional#empty()} if there is none
*/
public Optional<String> getArchiveStatus() {
return Optional.ofNullable(this.archiveStatus);
}
/**
* Set the archive status for this job.
*
* @param archiveStatus The new archive status
*/
public void setArchiveStatus(@Nullable final String archiveStatus) {
this.archiveStatus = archiveStatus;
}
/**
* Get any metadata associated with this job pertaining to the launcher that launched it.
*
* @return The metadata or {@link Optional#empty()} if there isn't any
*/
public Optional<JsonNode> getLauncherExt() {
return Optional.ofNullable(this.launcherExt);
}
/**
* Set any metadata pertaining to the launcher that launched this job.
*
* @param launcherExt The metadata
*/
public void setLauncherExt(@Nullable final JsonNode launcherExt) {
this.launcherExt = launcherExt;
}
/**
* Set the command arguments to use with this job.
*
* @param commandArgs The command arguments to use
*/
public void setCommandArgs(@Nullable final List<String> commandArgs) {
this.commandArgs.clear();
if (commandArgs != null) {
this.commandArgs.addAll(commandArgs);
}
}
/**
* Set all the files associated as configuration files for this job.
*
* @param configs The configuration files to set
*/
public void setConfigs(@Nullable final Set<FileEntity> configs) {
this.configs.clear();
if (configs != null) {
this.configs.addAll(configs);
}
}
/**
* Set all the files associated as dependency files for this job.
*
* @param dependencies The dependency files to set
*/
public void setDependencies(@Nullable final Set<FileEntity> dependencies) {
this.dependencies.clear();
if (dependencies != null) {
this.dependencies.addAll(dependencies);
}
}
/**
* Set all the tags associated to this job.
*
* @param tags The tags to set
*/
public void setTags(@Nullable final Set<TagEntity> tags) {
this.tags.clear();
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* Set the requested environment variables.
*
* @param requestedEnvironmentVariables The environment variables the user requested be added to the job runtime
*/
public void setRequestedEnvironmentVariables(@Nullable final Map<String, String> requestedEnvironmentVariables) {
this.requestedEnvironmentVariables.clear();
if (requestedEnvironmentVariables != null) {
this.requestedEnvironmentVariables.putAll(requestedEnvironmentVariables);
}
}
/**
* Set the environment variables for the job.
*
* @param environmentVariables The final set of environment variables that were set in the job runtime
*/
public void setEnvironmentVariables(@Nullable final Map<String, String> environmentVariables) {
this.environmentVariables.clear();
if (environmentVariables != null) {
this.environmentVariables.putAll(environmentVariables);
}
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getRequestedJobDirectoryLocation() {
return Optional.ofNullable(this.requestedJobDirectoryLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<JsonNode> getRequestedAgentEnvironmentExt() {
return Optional.ofNullable(this.requestedAgentEnvironmentExt);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<JsonNode> getRequestedAgentConfigExt() {
return Optional.ofNullable(this.requestedAgentConfigExt);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Integer> getRequestedGpu() {
return Optional.ofNullable(this.requestedGpu);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getRequestedDiskMb() {
return Optional.ofNullable(this.requestedDiskMb);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Long> getRequestedNetworkMbps() {
return Optional.ofNullable(this.requestedNetworkMbps);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<JsonNode> getRequestedImages() {
return Optional.ofNullable(this.requestedImages);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getJobDirectoryLocation() {
return Optional.ofNullable(this.jobDirectoryLocation);
}
/**
* {@inheritDoc}
*/
@Override
public Optional<JsonNode> getImagesUsed() {
return Optional.ofNullable(this.imagesUsed);
}
/**
* Set the applications used to run this job.
*
* @param applications The applications
*/
public void setApplications(@Nullable final List<ApplicationEntity> applications) {
this.applications.clear();
if (applications != null) {
this.applications.addAll(applications);
}
}
/**
* Set the cluster criteria set for this job.
*
* @param clusterCriteria The cluster criteria in priority order
*/
public void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria) {
this.clusterCriteria.clear();
if (clusterCriteria != null) {
this.clusterCriteria.addAll(clusterCriteria);
}
}
/**
* Get the previously notified job status if there was one.
*
* @return The previously notified job status wrapped in an {@link Optional} or {@link Optional#empty()}
*/
public Optional<String> getNotifiedJobStatus() {
return Optional.ofNullable(this.notifiedJobStatus);
}
/**
* Get any metadata the user provided with respect to the launcher.
*
* @return The metadata or {@link Optional#empty()} if there isn't any
*/
public Optional<JsonNode> getRequestedLauncherExt() {
return Optional.ofNullable(this.requestedLauncherExt);
}
/**
* Set any metadata pertaining to the launcher that was provided by the user.
*
* @param requestedLauncherExt The metadata
*/
public void setRequestedLauncherExt(@Nullable final JsonNode requestedLauncherExt) {
this.requestedLauncherExt = requestedLauncherExt;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,729 |
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/entities/BaseEntity.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.entities;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.web.data.services.impl.jpa.converters.JsonAttributeConverter;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.BaseProjection;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.SetupFileProjection;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Optional;
/**
* The base for all Genie top level entities. e.g. Applications, Jobs, etc.
*
* @author amsharma
* @author tgianos
* @since 2.0.0
*/
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@MappedSuperclass
public class BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection {
private static final long serialVersionUID = -5040659007494311180L;
@Basic(optional = false)
@Column(name = "version", nullable = false)
@NotBlank(message = "Version is missing and is required.")
@Size(max = 255, message = "Max length in database is 255 characters")
private String version;
@Basic(optional = false)
@Column(name = "genie_user", nullable = false)
@NotBlank(message = "User name is missing and is required.")
@Size(max = 255, message = "Max length in database is 255 characters")
private String user;
@Basic(optional = false)
@Column(name = "name", nullable = false)
@NotBlank(message = "Name is missing and is required.")
@Size(max = 255, message = "Max length in database is 255 characters")
private String name;
@Basic(optional = false)
@Column(name = "status", nullable = false, length = 20)
private String status;
@Basic
@Column(name = "description", length = 1000)
@Size(max = 1000, message = "Max length in database is 1000 characters")
private String description;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "metadata", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode metadata;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "setup_file")
@ToString.Exclude
private FileEntity setupFile;
/**
* Default constructor.
*/
BaseEntity() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getDescription() {
return Optional.ofNullable(this.description);
}
/**
* Set the description of this entity.
*
* @param description The description
*/
public void setDescription(@Nullable final String description) {
this.description = description;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<JsonNode> getMetadata() {
return Optional.ofNullable(this.metadata);
}
/**
* Set the JSON metadata of this entity.
*
* @param metadata The metadata of this entity
*/
public void setMetadata(@Nullable final JsonNode metadata) {
this.metadata = metadata;
}
/**
* {@inheritDoc}
*/
@Override
public Optional<FileEntity> getSetupFile() {
return Optional.ofNullable(this.setupFile);
}
/**
* Set the setup file for this entity.
*
* @param setupFile The setup file. Null clears reference in the database
*/
public void setSetupFile(@Nullable final FileEntity setupFile) {
this.setupFile = setupFile;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,730 |
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/entities/ApplicationEntity.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.entities;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.Table;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* Representation of the state of an Application.
*
* @author amsharma
* @author tgianos
* @since 2.0.0
*/
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "applications")
@NamedEntityGraphs(
{
@NamedEntityGraph(
name = ApplicationEntity.COMMANDS_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("commands")
}
),
@NamedEntityGraph(
name = ApplicationEntity.COMMANDS_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "commands",
subgraph = "command-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "command-sub-graph",
attributeNodes = {
@NamedAttributeNode("executable"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags"),
@NamedAttributeNode(
value = "clusterCriteria",
subgraph = "criteria-sub-graph"
)
}
),
@NamedSubgraph(
name = "criteria-sub-graph",
attributeNodes = {
@NamedAttributeNode("tags")
}
)
}
),
@NamedEntityGraph(
name = ApplicationEntity.DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags")
}
)
}
)
public class ApplicationEntity extends BaseEntity {
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load everything needed to access
* an applications commands base fields.
*/
public static final String COMMANDS_ENTITY_GRAPH = "Application.commands";
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load everything needed to access
* an applications commands and create the command DTOs.
*/
public static final String COMMANDS_DTO_ENTITY_GRAPH = "Application.commands.dto";
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load everything needed to construct an
* Application DTO.
*/
public static final String DTO_ENTITY_GRAPH = "Application.dto";
private static final long serialVersionUID = -8780722054561507963L;
@Basic
@Column(name = "type")
private String type;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "applications_configs",
joinColumns = {
@JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> configs = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "applications_dependencies",
joinColumns = {
@JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
private Set<FileEntity> dependencies = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "applications_tags",
joinColumns = {
@JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<TagEntity> tags = new HashSet<>();
@ManyToMany(mappedBy = "applications", fetch = FetchType.LAZY)
@ToString.Exclude
private Set<CommandEntity> commands = new HashSet<>();
/**
* Default constructor.
*/
public ApplicationEntity() {
super();
}
/**
* Get the type of this application.
*
* @return The type as an Optional in case it's null
*/
public Optional<String> getType() {
return Optional.ofNullable(this.type);
}
/**
* Set all the files associated as configuration files for this application.
*
* @param configs The configuration files to set
*/
public void setConfigs(@Nullable final Set<FileEntity> configs) {
this.configs.clear();
if (configs != null) {
this.configs.addAll(configs);
}
}
/**
* Set all the files associated as dependency files for this application.
*
* @param dependencies The dependency files to set
*/
public void setDependencies(@Nullable final Set<FileEntity> dependencies) {
this.dependencies.clear();
if (dependencies != null) {
this.dependencies.addAll(dependencies);
}
}
/**
* Set all the tags associated to this application.
*
* @param tags The dependency tags to set
*/
public void setTags(@Nullable final Set<TagEntity> tags) {
this.tags.clear();
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* Set all the commands associated with this application.
*
* @param commands The commands to set.
*/
void setCommands(@Nullable final Set<CommandEntity> commands) {
this.commands.clear();
if (commands != null) {
this.commands.addAll(commands);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,731 |
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/entities/IdEntity.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.entities;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.IdProjection;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.Getter;
import lombok.ToString;
import org.hibernate.Hibernate;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.util.Objects;
/**
* Base class which only provides an ID. For use cases when we don't care about audit fields like
* created, updated, entity version etc.
*
* @author tgianos
* @since 3.3.0
*/
@Getter
@ToString(
doNotUseGetters = true
)
@MappedSuperclass
public class IdEntity implements IdProjection, Serializable {
private static final long serialVersionUID = 7526472297322776147L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private long id;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings({"BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS"})
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
return false;
}
final IdEntity idEntity = (IdEntity) o;
return Objects.equals(this.id, idEntity.id);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return getClass().hashCode();
}
}
| 2,732 |
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/entities/AuditEntity.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.entities;
import com.netflix.genie.web.data.services.impl.jpa.queries.projections.AuditProjection;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.ToString;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;
import java.time.Instant;
/**
* Abstract class to support basic columns for all entities for genie.
*
* @author tgianos
*/
@Getter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@MappedSuperclass
public class AuditEntity extends IdEntity implements AuditProjection {
@Basic(optional = false)
@Column(name = "created", nullable = false, updatable = false)
private Instant created = Instant.now();
@Basic(optional = false)
@Column(name = "updated", nullable = false)
private Instant updated = Instant.now();
@Version
@Column(name = "entity_version", nullable = false)
@Getter(AccessLevel.NONE)
@ToString.Exclude
private Integer entityVersion;
/**
* Updates the created and updated timestamps to be creation time.
*/
@PrePersist
protected void onCreateBaseEntity() {
final Instant now = Instant.now();
this.updated = now;
this.created = now;
}
/**
* On any update to the entity will update the update time.
*/
@PreUpdate
protected void onUpdateBaseEntity() {
this.updated = Instant.now();
}
/**
* Get when this entity was created.
*
* @return The created timestamps
*/
public Instant getCreated() {
return this.created;
}
/**
* Get the time this entity was updated.
*
* @return The updated timestamp
*/
public Instant getUpdated() {
return this.updated;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,733 |
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/entities/TagEntity.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.entities;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* Entity representing a Tag.
*
* @author tgianos
* @since 3.3.0
*/
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(
callSuper = false,
doNotUseGetters = true
)
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "tags")
public class TagEntity extends AuditEntity {
@Basic(optional = false)
@Column(name = "tag", nullable = false, unique = true, updatable = false)
@NotBlank(message = "Must have a tag value associated with this entity")
@Size(max = 255, message = "Max length of a tag is 255 characters")
private String tag;
/**
* Constructor.
*
* @param tag The tag to use
*/
public TagEntity(final String tag) {
super();
this.tag = tag;
}
}
| 2,734 |
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/entities/FileEntity.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.entities;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* File Entity.
*
* @author tgianos
* @since 3.3.0
*/
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(
callSuper = false,
doNotUseGetters = true
)
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "files")
public class FileEntity extends AuditEntity {
@Basic(optional = false)
@Column(name = "file", nullable = false, unique = true, updatable = false)
@NotBlank(message = "Must have a file location associated with this entity")
@Size(max = 1024, message = "Max length of a file is 1024 characters")
private String file;
/**
* Constructor.
*
* @param file The file to reference
*/
public FileEntity(final String file) {
super();
this.file = file;
}
}
| 2,735 |
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/entities/ClusterEntity.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.entities;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.Table;
import java.util.HashSet;
import java.util.Set;
/**
* Representation of the state of the Cluster object.
*
* @author amsharma
* @author tgianos
* @since 2.0.0
*/
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "clusters")
@NamedEntityGraphs(
{
@NamedEntityGraph(
name = ClusterEntity.DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags")
}
)
}
)
public class ClusterEntity extends BaseEntity {
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load everything needed to construct a
* Cluster DTO.
*/
public static final String DTO_ENTITY_GRAPH = "Cluster.dto";
private static final long serialVersionUID = -5674870110962005872L;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "clusters_configs",
joinColumns = {
@JoinColumn(name = "cluster_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> configs = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "clusters_dependencies",
joinColumns = {
@JoinColumn(name = "cluster_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> dependencies = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "clusters_tags",
joinColumns = {
@JoinColumn(name = "cluster_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<TagEntity> tags = new HashSet<>();
/**
* Default Constructor.
*/
public ClusterEntity() {
super();
}
/**
* Set all the files associated as configuration files for this cluster.
*
* @param configs The configuration files to set
*/
public void setConfigs(@Nullable final Set<FileEntity> configs) {
this.configs.clear();
if (configs != null) {
this.configs.addAll(configs);
}
}
/**
* Set all the files associated as dependency files for this cluster.
*
* @param dependencies The dependency files to set
*/
public void setDependencies(@Nullable final Set<FileEntity> dependencies) {
this.dependencies.clear();
if (dependencies != null) {
this.dependencies.addAll(dependencies);
}
}
/**
* Set all the tags associated to this cluster.
*
* @param tags The dependency tags to set
*/
public void setTags(@Nullable final Set<TagEntity> tags) {
this.tags.clear();
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,736 |
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/entities/UniqueIdEntity.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.entities;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
import java.util.UUID;
/**
* An extendable entity class for tables which have a UniqueId field.
*
* @author tgianos
* @since 4.0.0
*/
@MappedSuperclass
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
public class UniqueIdEntity extends AuditEntity {
@Basic(optional = false)
@Column(name = "unique_id", nullable = false, unique = true, updatable = false)
@NotBlank(message = "A unique identifier is missing and is required.")
@Size(max = 255, message = "Max length in database is 255 characters")
private String uniqueId = UUID.randomUUID().toString();
@Basic(optional = false)
@Column(name = "requested_id", nullable = false, updatable = false)
private boolean requestedId;
/**
* {@inheritDoc}
*/
@SuppressFBWarnings({"BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS"})
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
return false;
}
final UniqueIdEntity that = (UniqueIdEntity) o;
return Objects.equals(this.uniqueId, that.uniqueId);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return this.uniqueId.hashCode();
}
}
| 2,737 |
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/entities/CommandEntity.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.entities;
import com.fasterxml.jackson.databind.JsonNode;
import com.netflix.genie.web.data.services.impl.jpa.converters.IntegerToLongConverter;
import com.netflix.genie.web.data.services.impl.jpa.converters.JsonAttributeConverter;
import com.netflix.genie.web.exceptions.checked.PreconditionFailedException;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.annotation.Nullable;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.NamedSubgraph;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
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.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Representation of the state of the Command Object.
*
* @author amsharma
* @author tgianos
*/
@Getter
@Setter
@ToString(
callSuper = true,
doNotUseGetters = true
)
@Entity
@Table(name = "commands")
@NamedEntityGraphs(
{
@NamedEntityGraph(
name = CommandEntity.APPLICATIONS_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "applications",
subgraph = "application-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "application-sub-graph",
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags")
}
)
}
),
@NamedEntityGraph(
name = CommandEntity.APPLICATIONS_DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "applications",
subgraph = "application-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "application-sub-graph",
attributeNodes = {
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags")
}
)
}
),
@NamedEntityGraph(
name = CommandEntity.CLUSTER_CRITERIA_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode(
value = "clusterCriteria",
subgraph = "criteria-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "criteria-sub-graph",
attributeNodes = {
@NamedAttributeNode("tags")
}
)
}
),
@NamedEntityGraph(
name = CommandEntity.DTO_ENTITY_GRAPH,
attributeNodes = {
@NamedAttributeNode("executable"),
@NamedAttributeNode("launcherExt"),
@NamedAttributeNode("setupFile"),
@NamedAttributeNode("configs"),
@NamedAttributeNode("dependencies"),
@NamedAttributeNode("tags"),
@NamedAttributeNode("images"),
@NamedAttributeNode(
value = "clusterCriteria",
subgraph = "criteria-sub-graph"
)
},
subgraphs = {
@NamedSubgraph(
name = "criteria-sub-graph",
attributeNodes = {
@NamedAttributeNode("tags")
}
)
}
)
}
)
public class CommandEntity extends BaseEntity {
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load the command base fields and
* its associated applications base fields.
*/
public static final String APPLICATIONS_ENTITY_GRAPH = "Command.applications";
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load the command base fields and
* its associated applications dto fields.
*/
public static final String APPLICATIONS_DTO_ENTITY_GRAPH = "Command.applications.dto";
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load the command base fields and
* its associated cluster criteria.
*/
public static final String CLUSTER_CRITERIA_ENTITY_GRAPH = "Command.clusterCriteria";
/**
* The name of the {@link javax.persistence.EntityGraph} which will eagerly load everything needed to construct a
* Command DTO.
*/
public static final String DTO_ENTITY_GRAPH = "Command.DTO";
private static final long serialVersionUID = -8058995173025433517L;
private static final int HIGHEST_CRITERION_PRIORITY = 0;
@ElementCollection
@CollectionTable(
name = "command_executable_arguments",
joinColumns = {
@JoinColumn(name = "command_id", nullable = false)
}
)
@Column(name = "argument", length = 1024, nullable = false)
@OrderColumn(name = "argument_order", nullable = false)
@NotEmpty(message = "No executable arguments entered. At least one is required.")
private List<@NotBlank @Size(max = 1024) String> executable = new ArrayList<>();
@Basic
@Column(name = "cpu")
@Min(1)
private Integer cpu;
@Basic
@Column(name = "gpu")
@Min(1)
private Integer gpu;
@Column(name = "memory")
// Memory that stored in DB has data type of Integer and unit type of MB. If the memory retrieved from db
// is 2048, it means 2048 MB, NOT 2048 Bytes.
@Convert(converter = IntegerToLongConverter.class)
@Min(1)
private Long memory;
@Basic
@Column(name = "disk_mb")
@Min(1)
private Long diskMb;
@Basic
@Column(name = "network_mbps")
@Min(1)
private Long networkMbps;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "images", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode images;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "launcher_ext", columnDefinition = "TEXT DEFAULT NULL")
@Convert(converter = JsonAttributeConverter.class)
@ToString.Exclude
private JsonNode launcherExt;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "commands_configs",
joinColumns = {
@JoinColumn(name = "command_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> configs = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "commands_dependencies",
joinColumns = {
@JoinColumn(name = "command_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "file_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<FileEntity> dependencies = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "commands_tags",
joinColumns = {
@JoinColumn(name = "command_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@ToString.Exclude
private Set<TagEntity> tags = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "commands_applications",
joinColumns = {
@JoinColumn(name = "command_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "application_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@OrderColumn(name = "application_order", nullable = false)
@ToString.Exclude
private List<ApplicationEntity> applications = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(
name = "commands_cluster_criteria",
joinColumns = {
@JoinColumn(name = "command_id", referencedColumnName = "id", nullable = false, updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "criterion_id", referencedColumnName = "id", nullable = false, updatable = false)
}
)
@OrderColumn(name = "priority_order", nullable = false)
@ToString.Exclude
private List<CriterionEntity> clusterCriteria = new ArrayList<>();
/**
* Default Constructor.
*/
public CommandEntity() {
super();
}
/**
* Set the executable and any default arguments for this command.
*
* @param executable The executable and default arguments which can't be blank and there must be at least one
*/
public void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable) {
this.executable.clear();
this.executable.addAll(executable);
}
/**
* Set all the files associated as configuration files for this cluster.
*
* @param configs The configuration files to set
*/
public void setConfigs(@Nullable final Set<FileEntity> configs) {
this.configs.clear();
if (configs != null) {
this.configs.addAll(configs);
}
}
/**
* Set all the files associated as dependency files for this cluster.
*
* @param dependencies The dependency files to set
*/
public void setDependencies(@Nullable final Set<FileEntity> dependencies) {
this.dependencies.clear();
if (dependencies != null) {
this.dependencies.addAll(dependencies);
}
}
/**
* Set all the tags associated to this cluster.
*
* @param tags The dependency tags to set
*/
public void setTags(@Nullable final Set<TagEntity> tags) {
this.tags.clear();
if (tags != null) {
this.tags.addAll(tags);
}
}
/**
* Get the default number of CPUs for a job using this command.
*
* @return The number of CPUs or {@link Optional#empty()}
*/
public Optional<Integer> getCpu() {
return Optional.ofNullable(this.cpu);
}
/**
* Get the default number of GPUs for a job using this command.
*
* @return The number of GPUs or {@link Optional#empty()}
*/
public Optional<Integer> getGpu() {
return Optional.ofNullable(this.gpu);
}
/**
* Get the default memory for a job using this command.
*
* @return Optional of Integer as it could be null
*/
public Optional<Long> getMemory() {
return Optional.ofNullable(this.memory);
}
/**
* Get the default amount of disk space for the job using this command in MB.
*
* @return The amount of disk space in MB or {@link Optional#empty()}
*/
public Optional<Long> getDiskMb() {
return Optional.ofNullable(this.diskMb);
}
/**
* Get the default amount of network bandwidth to allocate to the job using this command in mbps.
*
* @return The amount of network bandwidth in mbps or {@link Optional#empty()}
*/
public Optional<Long> getNetworkMbps() {
return Optional.ofNullable(this.networkMbps);
}
/**
* Get the default set of images to run this job with if this command is selected.
*
* @return The default set of images or {@link Optional#empty()}
*/
public Optional<JsonNode> getImages() {
return Optional.ofNullable(this.images);
}
/**
* Get any metadata associated with this command pertaining to specifying details for various agent launchers.
*
* @return The metadata or {@link Optional#empty()} if there isn't any
*/
public Optional<JsonNode> getLauncherExt() {
return Optional.ofNullable(this.launcherExt);
}
/**
* Set any metadata pertaining to additional instructions for various launchers if this command is used.
*
* @param launcherExt The metadata
*/
public void setLauncherExt(@Nullable final JsonNode launcherExt) {
this.launcherExt = launcherExt;
}
/**
* Sets the applications for this command.
*
* @param applications The application that this command uses
* @throws PreconditionFailedException if the list of applications contains duplicates
*/
public void setApplications(
@Nullable final List<ApplicationEntity> applications
) throws PreconditionFailedException {
if (applications != null
&& applications.stream().map(ApplicationEntity::getUniqueId).distinct().count() != applications.size()) {
throw new PreconditionFailedException("List of applications to set cannot contain duplicates");
}
//Clear references to this command in existing applications
for (final ApplicationEntity application : this.applications) {
application.getCommands().remove(this);
}
this.applications.clear();
if (applications != null) {
//set the application for this command
this.applications.addAll(applications);
//Add the reverse reference in the new applications
for (final ApplicationEntity application : this.applications) {
application.getCommands().add(this);
}
}
}
/**
* Append an application to the list of applications this command uses.
*
* @param application The application to add. Not null.
* @throws PreconditionFailedException If the application is a duplicate of an existing application
*/
public void addApplication(@NotNull final ApplicationEntity application) throws PreconditionFailedException {
if (this.applications.contains(application)) {
throw new PreconditionFailedException(
"An application with id " + application.getUniqueId() + " is already added"
);
}
this.applications.add(application);
application.getCommands().add(this);
}
/**
* Remove an application from this command. Manages both sides of relationship.
*
* @param application The application to remove. Not null.
*/
public void removeApplication(@NotNull final ApplicationEntity application) {
this.applications.remove(application);
application.getCommands().remove(this);
}
/**
* Set the criteria, in priority order, that this command has for determining which available clusters to use
* for a job.
*
* @param clusterCriteria The cluster criteria
*/
public void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria) {
this.clusterCriteria.clear();
if (clusterCriteria != null) {
this.clusterCriteria.addAll(clusterCriteria);
}
}
/**
* Add a new cluster criterion as the lowest priority criterion to evaluate for this command.
*
* @param criterion The {@link CriterionEntity} to add
*/
public void addClusterCriterion(final CriterionEntity criterion) {
this.clusterCriteria.add(criterion);
}
/**
* Add a new cluster criterion with the given priority.
*
* @param criterion The new criterion to add
* @param priority The priority with which this criterion should be considered. {@literal 0} would be the highest
* priority and anything greater than the current size of the existing criteria will just be added
* to the end of the list. If a priority of {@code < 0} is passed in the criterion is added
* as the highest priority ({@literal 0}).
*/
public void addClusterCriterion(final CriterionEntity criterion, final int priority) {
if (priority <= HIGHEST_CRITERION_PRIORITY) {
this.clusterCriteria.add(HIGHEST_CRITERION_PRIORITY, criterion);
} else if (priority >= this.clusterCriteria.size()) {
this.clusterCriteria.add(criterion);
} else {
this.clusterCriteria.add(priority, criterion);
}
}
/**
* Remove the criterion with the given priority from the list of available criterion for this command.
*
* @param priority The priority of the criterion to remove.
* @return The {@link CriterionEntity} which was removed by this operation
* @throws IllegalArgumentException If this value is {@code < 0} or {@code > {@link List#size()}} as it becomes
* unclear what the user wants to do
*/
public CriterionEntity removeClusterCriterion(final int priority) throws IllegalArgumentException {
if (priority < HIGHEST_CRITERION_PRIORITY || priority >= this.clusterCriteria.size()) {
throw new IllegalArgumentException(
"The priority of the cluster criterion to remove must be "
+ HIGHEST_CRITERION_PRIORITY
+ "<= priority < "
+ this.clusterCriteria.size()
+ " for this command currently."
);
}
return this.clusterCriteria.remove(priority);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
| 2,738 |
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/entities/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.
*
*/
/**
* Entity classes that represent the Genie data model/internal state.
*
* @author tgianos
* @since 3.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.data.services.impl.jpa.entities;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,739 |
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/aspects/DataServiceRetryAspect.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.aspects;
import com.google.common.collect.ImmutableMap;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.internal.exceptions.checked.GenieCheckedException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException;
import com.netflix.genie.web.properties.DataServiceRetryProperties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.dao.QueryTimeoutException;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import javax.validation.ConstraintViolationException;
/**
* Aspect implementation of retrying the data service methods on certain failures.
*
* @author amajumdar
* @since 3.0.0
*/
@Aspect
@Slf4j
public class DataServiceRetryAspect implements Ordered {
private final RetryTemplate retryTemplate;
/**
* Constructor.
*
* @param dataServiceRetryProperties retry properties
*/
public DataServiceRetryAspect(final DataServiceRetryProperties dataServiceRetryProperties) {
this.retryTemplate = new RetryTemplate();
this.retryTemplate.setRetryPolicy(
new SimpleRetryPolicy(
dataServiceRetryProperties.getNoOfRetries(),
new ImmutableMap.Builder<Class<? extends Throwable>, Boolean>()
.put(CannotGetJdbcConnectionException.class, true)
.put(CannotAcquireLockException.class, true)
.put(DeadlockLoserDataAccessException.class, true)
.put(OptimisticLockingFailureException.class, true)
.put(PessimisticLockingFailureException.class, true)
.put(ConcurrencyFailureException.class, true)
// Will this work for cases where the write queries timeout on the client?
.put(QueryTimeoutException.class, true)
.put(TransientDataAccessResourceException.class, true)
.put(JpaSystemException.class, true)
.build()
)
);
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(dataServiceRetryProperties.getInitialInterval());
backOffPolicy.setMaxInterval(dataServiceRetryProperties.getMaxInterval());
this.retryTemplate.setBackOffPolicy(backOffPolicy);
}
/**
* Sets the retry listeners for the retry template in use.
*
* @param retryListeners retry listeners
*/
public void setRetryListeners(final RetryListener[] retryListeners) {
this.retryTemplate.setListeners(retryListeners);
}
/**
* Aspect implementation method of retrying the data service method on certain failures.
*
* @param pjp join point
* @return return the data method response
* @throws GenieException any exception thrown by the data service method
* @throws GenieCheckedException any exception thrown by one of the data service methods Genie code
*/
@Around("com.netflix.genie.web.aspects.SystemArchitecture.dataOperation()")
public Object profile(final ProceedingJoinPoint pjp) throws GenieException, GenieCheckedException {
try {
return retryTemplate.execute(context -> pjp.proceed());
} catch (
GenieException
| GenieCheckedException
| GenieRuntimeException
| ConstraintViolationException e
) {
throw e;
} catch (Throwable e) {
throw new GenieRuntimeException("Failed to execute data service method due to " + e.getMessage(), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getOrder() {
// Currently setting this to 0 since we want the retry to happen before the transaction interceptor.
return 0;
}
}
| 2,740 |
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/aspects/SystemArchitecture.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.aspects;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* Application pointcut expressions.
*
* @author amajumdar
* @since 3.0.0
*/
@Aspect
public class SystemArchitecture {
/**
* A join point is in the resource layer if the method is defined
* in a type in the com.netflix.genie.web.api.rest.v3.controllers package or any sub-package
* under that.
*/
@Pointcut("within(com.netflix.genie.web.apis.rest.v3.controllers..*)")
public void inResourceLayer() {
}
/**
* A join point is in the service layer if the method is defined
* in a type in the com.netflix.genie.web.services package or any sub-package
* under that.
*/
@Pointcut("within(com.netflix.genie.web.services..*)")
public void inServiceLayer() {
}
/**
* A join point is in the data service layer if the method is defined
* in a type in the com.netflix.genie.web.data.services package or any sub-package
* under that.
*/
@Pointcut("within(com.netflix.genie.web.data.services..*)")
public void inDataLayer() {
}
/**
* A resource service is the execution of any method defined on a controller.
* This definition assumes that interfaces are placed in the
* "resources" package, and that implementation types are in sub-packages.
*/
@Pointcut("execution(* com.netflix.genie.web.apis.rest.v3.controllers.*.*(..))")
public void resourceOperation() {
}
/**
* A service operation is the execution of any method defined on a
* service class/interface. This definition assumes that interfaces are placed in the
* "service" package, and that implementation types are in sub-packages.
*/
@Pointcut("execution(* com.netflix.genie.web.services.*.*(..))")
public void serviceOperation() {
}
/**
* A data service operation is the execution of any method defined on a
* dao interface. This definition assumes that interfaces are placed in the
* "dao" package, and that implementation types are in sub-packages.
*/
@Pointcut("execution(* com.netflix.genie.web.data.services.impl.jpa.*.*(..))")
public void dataOperation() {
}
}
| 2,741 |
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/aspects/HealthCheckMetricsAspect.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.aspects;
import com.google.common.collect.ImmutableSet;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Aspect around Spring Boot 'HealthIndicator' to publish metrics for status of individual indicator, as well as their
* turnaround time.
*
* @author mprimi
* @since 3.2.4
*/
@Aspect
@Slf4j
public class HealthCheckMetricsAspect {
static final String HEALTH_INDICATOR_TIMER_METRIC_NAME = "genie.health.indicator.timer";
private static final String HEALTH_INDICATOR_CLASS_TAG_NAME = "healthIndicatorClass";
private static final String HEALTH_INDICATOR_STATUS_TAG_NAME = "healthIndicatorStatus";
private final MeterRegistry registry;
/**
* Autowired constructor.
*
* @param registry metrics registry
*/
public HealthCheckMetricsAspect(final MeterRegistry registry) {
this.registry = registry;
}
/**
* Pointcut that matches invocations of {@code HealthIndicator::getHealth(..)}.
*/
@Pointcut(""
+ "target(org.springframework.boot.actuate.health.HealthIndicator+) && "
+ "execution(org.springframework.boot.actuate.health.Health getHealth(..))"
)
public void healthIndicatorGetHealth() {
}
/**
* Aspect around join point for {@code HealthIndicator::getHealth(..)}.
* Measures the turnaround time for the indicator call and publishes it as metric, tagged with indicator class
* and the status reported.
*
* @param joinPoint the join point
* @return health as reported by the indicator
* @throws Throwable in case of exception in the join point
*/
@Around("healthIndicatorGetHealth()")
@SuppressWarnings("checkstyle:IllegalThrows") // For propagating Throwable from joinPoint.proceed()
public Health aroundHealthIndicatorGetHealth(final ProceedingJoinPoint joinPoint) throws Throwable {
final String healthIndicatorClass = joinPoint.getTarget().getClass().getSimpleName();
log.debug(
"Intercepted: {}::{}({})",
healthIndicatorClass,
joinPoint.getSignature().getName(),
Arrays.toString(joinPoint.getArgs())
);
final long start = System.nanoTime();
Health h = null;
try {
h = (Health) joinPoint.proceed(joinPoint.getArgs());
} finally {
final long turnaround = System.nanoTime() - start;
final String healthStatus = (h != null) ? h.getStatus().getCode() : Status.UNKNOWN.getCode();
log.debug("Indicator {} status: {} (took {}ns)", healthIndicatorClass, healthStatus, turnaround);
final Set<Tag> tags = ImmutableSet.of(
Tag.of(HEALTH_INDICATOR_CLASS_TAG_NAME, healthIndicatorClass),
Tag.of(HEALTH_INDICATOR_STATUS_TAG_NAME, healthStatus)
);
this.registry
.timer(HEALTH_INDICATOR_TIMER_METRIC_NAME, tags)
.record(turnaround, TimeUnit.NANOSECONDS);
}
return h;
}
}
| 2,742 |
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/aspects/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.
*
*/
/**
* Various Spring aspects for Genie web.
*
* @author amajumdar
* @since 3.0.0
*/
package com.netflix.genie.web.aspects;
| 2,743 |
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/services/JobKillService.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.services;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobNotFoundException;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
/**
* Interface for services to kill jobs.
*
* @author tgianos
* @since 3.0.0
*/
@Validated
public interface JobKillService {
/**
* Kill the job with the given id if possible.
*
* @param id id of job to kill
* @param reason brief reason for requesting the job be killed
* @param request The optional {@link HttpServletRequest} information if the request needs to be forwarded
* @throws GenieJobNotFoundException When a job identified by {@literal jobId} can't be found in the system
* @throws GenieServerException if there is an unrecoverable error in the internal state of the Genie cluster
*/
void killJob(
@NotBlank(message = "No id entered. Unable to kill job.") String id,
@NotBlank(message = "No reason provided.") String reason,
@Nullable HttpServletRequest request
) throws GenieJobNotFoundException, GenieServerException;
}
| 2,744 |
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/services/ClusterLeaderService.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.services;
/**
* Service interface for the abstracts the details of leadership within nodes in a Genie cluster.
*
* @author mprimi
* @since 4.0.0
*/
public interface ClusterLeaderService {
/**
* Stop the service (i.e. renounce leadership and leave the election).
*/
void stop();
/**
* Start the service (i.e. join the the election).
*/
void start();
/**
* Whether or not this node is participating in the cluster leader election.
*
* @return true if the node is participating in leader election
*/
boolean isRunning();
/**
* Whether or not this node is the current cluster leader.
*
* @return true if the node is the current cluster leader
*/
boolean isLeader();
}
| 2,745 |
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/services/JobDirectoryServerService.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.services;
import com.netflix.genie.common.exceptions.GenieException;
import org.springframework.validation.annotation.Validated;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
/**
* This service abstracts away the details of responding to API requests for the files and directories created during
* the execution of a job in the Genie ecosystem. This service is read only.
*
* @author tgianos
* @since 4.0.0
*/
@Validated
public interface JobDirectoryServerService {
/**
* Given the {@code request} this API will write the resource to {@code response} if possible. If the resource
* doesn't exist or an error is generated an appropriate HTTP error response will be written to {@code response}
* instead.
*
* @param jobId The id of the job this request is for
* @param baseUrl The base URL used to generate all URLs for resources
* @param relativePath The relative path from the root of the job directory of the expected resource
* @param request The HTTP request containing all information about the request
* @param response The HTTP response where all results should be written
* @throws GenieException If there is an error serving the response
*/
void serveResource(
String jobId,
URL baseUrl,
String relativePath,
HttpServletRequest request,
HttpServletResponse response
) throws GenieException;
}
| 2,746 |
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/services/RequestForwardingService.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.services;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
/**
* A service whose implementation should be responsible for forwarding requests between Genie server nodes.
*
* @author tgianos
* @since 4.0.0
*/
public interface RequestForwardingService {
/**
* Send a kill request for the given job id to another Genie host.
*
* @param host The host to send the kill request to
* @param jobId The id of the job that should be killed
* @param request The optional Http request that triggered this kill forwarding action
*/
void kill(String host, String jobId, @Nullable HttpServletRequest request);
}
| 2,747 |
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/services/AttachmentService.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.services;
import com.netflix.genie.web.exceptions.checked.SaveAttachmentException;
import org.springframework.core.io.Resource;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Nullable;
import java.net.URI;
import java.util.Set;
/**
* APIs for saving a job attachments sent in with Genie requests.
*
* @author mprimi
* @since 4.0.0
*/
@Validated
public interface AttachmentService {
/**
* Save the attachments and return their URIs so agent executing the job can retrieve them.
*
* @param jobId The id of the job these attachments are for, if one was present in the job request
* This is strictly for debugging and logging.
* @param attachments The attachments sent by the user
* @return The set of {@link URI} which can be used to retrieve the attachments
* @throws SaveAttachmentException if an error is encountered while saving
*/
Set<URI> saveAttachments(@Nullable String jobId, Set<Resource> attachments) throws SaveAttachmentException;
}
| 2,748 |
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/services/ArchivedJobService.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.services;
import com.netflix.genie.web.dtos.ArchivedJobMetadata;
import com.netflix.genie.web.exceptions.checked.JobDirectoryManifestNotFoundException;
import com.netflix.genie.web.exceptions.checked.JobNotArchivedException;
import com.netflix.genie.web.exceptions.checked.JobNotFoundException;
/**
* A Service interface for working with the metadata and data of a job that was archived by the Agent upon completion.
*
* @author tgianos
* @since 4.0.0
*/
public interface ArchivedJobService {
/**
* Retrieve the metadata about the contents and location of a jobs archived artifacts.
*
* @param jobId The id of the job
* @return A {@link ArchivedJobMetadata} instance
* @throws JobNotFoundException When no job with id {@literal jobId} is found in the system
* @throws JobNotArchivedException If the job wasn't archived so no manifest could be retrieved
* @throws JobDirectoryManifestNotFoundException If the job was archived but the manifest can't be located
*/
ArchivedJobMetadata getArchivedJobMetadata(String jobId) throws
JobNotFoundException,
JobNotArchivedException,
JobDirectoryManifestNotFoundException;
}
| 2,749 |
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/services/JobResolverService.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.services;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobResolutionRuntimeException;
import com.netflix.genie.web.dtos.ResolvedJob;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Nonnull;
import javax.validation.Valid;
/**
* Service API for taking inputs from a user and resolving them to concrete information that the Genie system will use
* to execute the users job.
*
* @author tgianos
* @since 4.0.0
*/
@Validated
public interface JobResolverService {
/**
* Given the id of a job that was successfully submitted to the system this API will attempt to resolve all the
* concrete details (cluster, command, resources, etc) needed for the system to actually launch the job. Once these
* details are determined they are persisted and the job is marked as {@link JobStatus#RESOLVED}.
*
* @param id The id of the job to resolve. The job must exist and its status must return {@literal true} from
* {@link JobStatus}{@literal #isResolvable()}
* @return A {@link ResolvedJob} instance containing all the concrete information needed to execute the job
* @throws GenieJobResolutionException When the job cannot resolved due to unsatisfiable constraints
* @throws GenieJobResolutionRuntimeException When the job fails to resolve due to a runtime error.
*/
@Nonnull
ResolvedJob resolveJob(String id) throws GenieJobResolutionException, GenieJobResolutionRuntimeException;
/**
* Given a job request resolve all the details needed to run a job. This API is stateless and saves nothing.
*
* @param id The id of the job
* @param jobRequest The job request containing all details a user wants to have for their job
* @param apiJob {@literal true} if this job was submitted via the REST API. {@literal false} otherwise.
* @return The completely resolved job information within a {@link ResolvedJob} instance
* @throws GenieJobResolutionException When the job cannot resolved due to unsatisfiable constraints
* @throws GenieJobResolutionRuntimeException When the job fails to resolve due to a runtime error.
*/
@Nonnull
ResolvedJob resolveJob(
String id,
@Valid JobRequest jobRequest,
boolean apiJob
) throws GenieJobResolutionException, GenieJobResolutionRuntimeException;
}
| 2,750 |
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/services/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.
*
*/
/**
* Interfaces for core Genie services.
*
* @author tgianos
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,751 |
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/services/JobLaunchService.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.services;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException;
import com.netflix.genie.web.dtos.JobSubmission;
import com.netflix.genie.web.exceptions.checked.AgentLaunchException;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.SaveAttachmentException;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Nonnull;
import javax.validation.Valid;
/**
* Top level coordination service responsible for taking a job request and running the job if possible.
*
* @author tgianos
* @since 4.0.0
*/
@Validated
public interface JobLaunchService {
/**
* Launches a job on behalf of the user.
* <p>
* Given the information submitted to Genie this service will attempt to run the job which will include:
* - Saving the job submission information including attachments
* - Resolving the resources needed to run the job and persisting them
* - Launching the agent
*
* @param jobSubmission The payload of metadata and resources making up all the information needed to launch
* a job
* @return The id of the job. Upon return the job will at least be in {@link JobStatus#ACCEPTED} state
* @throws AgentLaunchException If the system was unable to launch an agent to handle job execution
* @throws GenieJobResolutionException If the job, based on user input and current system state, can't be
* successfully resolved for whatever reason
* @throws NotFoundException When a resource that is expected to exist, like a job or a cluster, is not
* found in the system at runtime for some reason
* @throws IdAlreadyExistsException If the unique identifier for the job conflicts with an already existing job
* @throws SaveAttachmentException When a job is submitted with attachments but there is an error saving them
*/
@Nonnull
String launchJob(@Valid JobSubmission jobSubmission) throws
AgentLaunchException,
GenieJobResolutionException,
IdAlreadyExistsException,
NotFoundException,
SaveAttachmentException;
}
| 2,752 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/RequestForwardingServiceImpl.java | /*
*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.services.impl;
import com.netflix.genie.common.internal.jobs.JobConstants;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.properties.JobsForwardingProperties;
import com.netflix.genie.web.services.RequestForwardingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* Default implementation of {@link RequestForwardingService}.
*
* @author tgianos
* @since 4.0.0
*/
@Slf4j
public class RequestForwardingServiceImpl implements RequestForwardingService {
private static final String JOB_ENDPOINT = "/api/v3/jobs/";
private static final String NAME_HEADER_COOKIE = "cookie";
private final RestTemplate restTemplate;
private final String hostname;
private final String apiScheme;
private final String apiPort;
/**
* Constructor.
*
* @param restTemplate The {@link RestTemplate} instance to use to call other Genie nodes API endpoints
* @param hostInfo The {@link GenieHostInfo} instance containing introspection information about
* the current node
* @param jobsForwardingProperties The properties related to forwarding requests
*/
public RequestForwardingServiceImpl(
final RestTemplate restTemplate,
final GenieHostInfo hostInfo,
final JobsForwardingProperties jobsForwardingProperties
) {
this.restTemplate = restTemplate;
this.hostname = hostInfo.getHostname();
this.apiScheme = jobsForwardingProperties.getScheme() + "://";
this.apiPort = ":" + jobsForwardingProperties.getPort();
}
/**
* {@inheritDoc}
*/
@Override
// TODO: Enable retries?
public void kill(final String host, final String jobId, @Nullable final HttpServletRequest request) {
final String endpoint = this.buildDestinationHost(host) + JOB_ENDPOINT + jobId;
log.info("Attempting to forward kill request by calling DELETE at {}", endpoint);
try {
this.restTemplate.execute(
endpoint,
HttpMethod.DELETE,
forwardRequest -> {
forwardRequest.getHeaders().add(JobConstants.GENIE_FORWARDED_FROM_HEADER, this.hostname);
if (request != null) {
this.copyRequestHeaders(request, forwardRequest);
}
},
null
);
} catch (final Exception e) {
log.error("Failed sending DELETE to {}. Error: {}", endpoint, e.getMessage(), e);
throw e;
}
}
private String buildDestinationHost(final String destinationHost) {
return this.apiScheme + destinationHost + this.apiPort;
}
/*
* Copied from legacy code in JobRestController.
*/
private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) {
// Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header.
final HttpHeaders headers = forwardRequest.getHeaders();
final Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
final String headerName = headerNames.nextElement();
if (!NAME_HEADER_COOKIE.equals(headerName)) {
final String headerValue = request.getHeader(headerName);
log.debug("Request Header: name = {} value = {}", headerName, headerValue);
headers.add(headerName, headerValue);
}
}
}
// Lets add the cookie as an header
final Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
final StringBuilder builder = new StringBuilder();
for (final Cookie cookie : cookies) {
if (builder.length() != 0) {
builder.append(",");
}
builder.append(cookie.getName()).append("=").append(cookie.getValue());
}
final String cookieValue = builder.toString();
headers.add(NAME_HEADER_COOKIE, cookieValue);
log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue);
}
forwardRequest.getHeaders().add(JobConstants.GENIE_FORWARDED_FROM_HEADER, this.hostname);
}
}
| 2,753 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/S3AttachmentServiceImpl.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.services.impl;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3URI;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.netflix.genie.common.internal.aws.s3.S3ClientFactory;
import com.netflix.genie.web.exceptions.checked.AttachmentTooLargeException;
import com.netflix.genie.web.exceptions.checked.SaveAttachmentException;
import com.netflix.genie.web.properties.AttachmentServiceProperties;
import com.netflix.genie.web.services.AttachmentService;
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 javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Implementation of the AttachmentService interface which saves attachments to AWS S3.
*
* @author mprimi
* @since 4.0.0
*/
@Slf4j
public class S3AttachmentServiceImpl implements AttachmentService {
private static final String METRICS_PREFIX = "genie.jobs.attachments.s3";
private static final String COUNT_DISTRIBUTION = METRICS_PREFIX + ".count.distribution";
private static final String LARGEST_SIZE_DISTRIBUTION = METRICS_PREFIX + ".largest.distribution";
private static final String TOTAL_SIZE_DISTRIBUTION = METRICS_PREFIX + ".totalSize.distribution";
private static final String SAVE_TIMER = METRICS_PREFIX + ".upload.timer";
private static final Set<URI> EMPTY_SET = ImmutableSet.of();
private static final String SLASH = "/";
private static final String S3 = "s3";
private final S3ClientFactory s3ClientFactory;
private final AttachmentServiceProperties properties;
private final MeterRegistry meterRegistry;
private final AmazonS3URI s3BaseURI;
/**
* Constructor.
*
* @param s3ClientFactory the s3 client factory
* @param attachmentServiceProperties the service properties
* @param meterRegistry the meter registry
*/
public S3AttachmentServiceImpl(
final S3ClientFactory s3ClientFactory,
final AttachmentServiceProperties attachmentServiceProperties,
final MeterRegistry meterRegistry
) {
this.s3ClientFactory = s3ClientFactory;
this.properties = attachmentServiceProperties;
this.meterRegistry = meterRegistry;
this.s3BaseURI = new AmazonS3URI(attachmentServiceProperties.getLocationPrefix());
}
/**
* {@inheritDoc}
*/
@Override
public Set<URI> saveAttachments(
@Nullable final String jobId,
final Set<Resource> attachments
) throws SaveAttachmentException {
// Track number of attachments, including zeroes
this.meterRegistry.summary(COUNT_DISTRIBUTION).record(attachments.size());
log.debug("Saving {} attachments for job request with id: {}", attachments.size(), jobId);
if (attachments.size() == 0) {
return EMPTY_SET;
}
// Check for attachment size limits
this.checkLimits(attachments);
final long start = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
// Upload all to S3
final Set<URI> attachmentURIs = this.uploadAllAttachments(jobId, attachments);
MetricsUtils.addSuccessTags(tags);
return attachmentURIs;
} catch (SaveAttachmentException e) {
log.error("Failed to save attachments (requested job id: {}): {}", jobId, e.getMessage(), e);
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} finally {
this.meterRegistry
.timer(SAVE_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
private void checkLimits(final Set<Resource> attachments) throws SaveAttachmentException {
final long singleSizeLimit = this.properties.getMaxSize().toBytes();
final long totalSizeLimit = this.properties.getMaxTotalSize().toBytes();
long totalSize = 0;
long largestSize = 0;
for (final Resource attachment : attachments) {
final String filename = attachment.getFilename();
final long attachmentSize;
try {
attachmentSize = attachment.contentLength();
} catch (IOException e) {
throw new SaveAttachmentException(
"Failed to get size of attachment: " + filename + ": " + e.getMessage(),
e
);
}
if (attachmentSize > largestSize) {
largestSize = attachmentSize;
}
totalSize += attachmentSize;
}
if (largestSize > singleSizeLimit) {
throw new AttachmentTooLargeException(
"Size of attachment exceeds the maximum allowed"
+ " (" + largestSize + " > " + singleSizeLimit + ")"
);
}
if (totalSize > totalSizeLimit) {
throw new AttachmentTooLargeException(
"Total size of attachments exceeds the maximum allowed"
+ " (" + totalSize + " > " + totalSizeLimit + ")"
);
}
this.meterRegistry.summary(LARGEST_SIZE_DISTRIBUTION).record(largestSize);
this.meterRegistry.summary(TOTAL_SIZE_DISTRIBUTION).record(totalSize);
}
private Set<URI> uploadAllAttachments(
@Nullable final String jobId,
final Set<Resource> attachments
) throws SaveAttachmentException {
final AmazonS3 s3Client = this.s3ClientFactory.getClient(this.s3BaseURI);
final String bundleId = UUID.randomUUID().toString();
final String commonPrefix = this.s3BaseURI.getKey() + SLASH + bundleId + SLASH;
log.debug(
"Uploading {} attachments for job request with id {} to: {}",
attachments.size(),
jobId,
commonPrefix
);
final Set<URI> attachmentURIs = Sets.newHashSet();
for (final Resource attachment : attachments) {
final String filename = attachment.getFilename();
if (StringUtils.isBlank(filename)) {
throw new SaveAttachmentException("Attachment filename is missing");
}
final String objectBucket = this.s3BaseURI.getBucket();
final String objectKey = commonPrefix + filename;
final ObjectMetadata metadata = new ObjectMetadata();
URI attachmentURI = null;
try (InputStream inputStream = attachment.getInputStream()) {
// Prepare object
metadata.setContentLength(attachment.contentLength());
attachmentURI = new URI(S3, objectBucket, SLASH + objectKey, null);
// Upload
s3Client.putObject(
objectBucket,
objectKey,
inputStream,
metadata
);
// Add attachment URI to the set
attachmentURIs.add(attachmentURI);
} catch (IOException | SdkClientException | URISyntaxException e) {
throw new SaveAttachmentException(
"Failed to upload attachment: " + attachmentURI + " - " + e.getMessage(),
e
);
}
}
return attachmentURIs;
}
}
| 2,754 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/JobDirectoryServerServiceImpl.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.services.impl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.genie.common.exceptions.GenieException;
import com.netflix.genie.common.exceptions.GenieNotFoundException;
import com.netflix.genie.common.exceptions.GeniePreconditionException;
import com.netflix.genie.common.exceptions.GenieServerException;
import com.netflix.genie.common.exceptions.GenieServerUnavailableException;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.DirectoryManifest;
import com.netflix.genie.web.agent.resources.AgentFileProtocolResolver;
import com.netflix.genie.web.agent.services.AgentFileStreamService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.dtos.ArchivedJobMetadata;
import com.netflix.genie.web.exceptions.checked.JobDirectoryManifestNotFoundException;
import com.netflix.genie.web.exceptions.checked.JobNotArchivedException;
import com.netflix.genie.web.exceptions.checked.JobNotFoundException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.resources.writers.DefaultDirectoryWriter;
import com.netflix.genie.web.services.ArchivedJobService;
import com.netflix.genie.web.services.JobDirectoryServerService;
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.http.client.utils.URIBuilder;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.ResourceRegionHttpMessageConverter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Default implementation of {@link JobDirectoryServerService}.
*
* @author tgianos
* @since 4.0.0
*/
@Slf4j
public class JobDirectoryServerServiceImpl implements JobDirectoryServerService {
private static final String SLASH = "/";
private static final String SERVE_RESOURCE_TIMER = "genie.files.serve.timer";
private static final String ARCHIVE_STATUS_TAG = "archiveStatus";
private final ResourceLoader resourceLoader;
private final PersistenceService persistenceService;
private final AgentFileStreamService agentFileStreamService;
private final MeterRegistry meterRegistry;
private final GenieResourceHandler.Factory genieResourceHandlerFactory;
private final ArchivedJobService archivedJobService;
private final AgentRoutingService agentRoutingService;
/**
* Constructor.
*
* @param resourceLoader The application resource loader used to get references to resources
* @param dataServices The {@link DataServices} instance to use
* @param agentFileStreamService The service providing file manifest for active agent jobs
* @param archivedJobService The {@link ArchivedJobService} implementation to use to get archived
* job data
* @param meterRegistry The meter registry used to keep track of metrics
* @param agentRoutingService The agent routing service
*/
public JobDirectoryServerServiceImpl(
final ResourceLoader resourceLoader,
final DataServices dataServices,
final AgentFileStreamService agentFileStreamService,
final ArchivedJobService archivedJobService,
final MeterRegistry meterRegistry,
final AgentRoutingService agentRoutingService
) {
this(
resourceLoader,
dataServices,
agentFileStreamService,
archivedJobService,
new GenieResourceHandler.Factory(),
meterRegistry,
agentRoutingService
);
}
/**
* Constructor that accepts a handler factory mock for easier testing.
*/
@VisibleForTesting
JobDirectoryServerServiceImpl(
final ResourceLoader resourceLoader,
final DataServices dataServices,
final AgentFileStreamService agentFileStreamService,
final ArchivedJobService archivedJobService,
final GenieResourceHandler.Factory genieResourceHandlerFactory,
final MeterRegistry meterRegistry,
final AgentRoutingService agentRoutingService
) {
this.resourceLoader = resourceLoader;
this.persistenceService = dataServices.getPersistenceService();
this.agentFileStreamService = agentFileStreamService;
this.meterRegistry = meterRegistry;
this.genieResourceHandlerFactory = genieResourceHandlerFactory;
this.archivedJobService = archivedJobService;
this.agentRoutingService = agentRoutingService;
}
/**
* {@inheritDoc}
*/
@Override
public void serveResource(
final String id,
final URL baseUrl,
final String relativePath,
final HttpServletRequest request,
final HttpServletResponse response
) throws GenieException {
final long start = System.nanoTime();
final Set<Tag> tags = Sets.newHashSet();
try {
// Normalize the base url. Make sure it ends in /.
final URI baseUri = new URI(baseUrl.toString() + SLASH).normalize();
// Lookup archive status and job execution type
final ArchiveStatus archiveStatus = this.persistenceService.getJobArchiveStatus(id);
tags.add(Tag.of(ARCHIVE_STATUS_TAG, archiveStatus.name()));
final DirectoryManifest manifest;
final URI jobDirRoot;
switch (archiveStatus) {
case NO_FILES:
// Job failed before any files were created. Nothing to serve.
throw new GenieNotFoundException("Job failed before any file was created: " + id);
case FAILED:
// Archive failed (also implies job is done). Return 404 without further processing
throw new GenieNotFoundException("Job failed to archive files: " + id);
case DISABLED:
// Not a possible state in database as of now [GENIE-657]
throw new GeniePreconditionException("Archive disabled for job " + id);
case UNKNOWN:
// Set by the server when an agent is AWOL long enough.
// Archive status is truly unknown. As of now, fall-through and attempt serving from archive.
case ARCHIVED:
// Serve file from archive
log.debug("Routing request to archive");
final ArchivedJobMetadata archivedJobMetadata = this.archivedJobService.getArchivedJobMetadata(id);
final String rangeHeader = request.getHeader(HttpHeaders.RANGE);
manifest = archivedJobMetadata.getManifest();
final URI baseJobDirRoot = archivedJobMetadata.getArchiveBaseUri();
jobDirRoot = new URIBuilder(baseJobDirRoot).setFragment(rangeHeader).build();
break;
case PENDING:
log.debug("Routing request to connected agent");
if (!this.agentRoutingService.isAgentConnectionLocal(id)) {
throw new GenieServerUnavailableException("Agent connection has moved or was terminated");
}
manifest = this.agentFileStreamService.getManifest(id).orElseThrow(
() -> new GenieServerUnavailableException("Manifest not found for job " + id)
);
jobDirRoot = AgentFileProtocolResolver.createUri(
id,
SLASH,
request.getHeader(HttpHeaders.RANGE)
);
break;
default:
throw new GenieServerException("Unknown archive status " + archiveStatus + "(" + id + ")");
}
log.debug(
"Serving file: {} for job: {} (archive status: {})",
relativePath,
id,
archiveStatus
);
// Common handling of archived, locally running v3 job or locally connected v4 job
this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
MetricsUtils.addSuccessTags(tags);
} catch (NotFoundException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw new GenieNotFoundException(e.getMessage(), e);
} catch (IOException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw new GenieServerException("Error serving response: " + e.getMessage(), e);
} catch (URISyntaxException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw new GenieServerException(e.getMessage(), e);
} catch (final JobNotArchivedException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw new GeniePreconditionException("Job outputs were not archived", e);
} catch (final JobNotFoundException | JobDirectoryManifestNotFoundException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw new GenieNotFoundException("Failed to retrieve job archived files metadata", e);
} catch (GenieException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} finally {
final long elapsed = System.nanoTime() - start;
this.meterRegistry.timer(SERVE_RESOURCE_TIMER, tags).record(elapsed, TimeUnit.NANOSECONDS);
}
}
private void handleRequest(
final URI baseUri,
final String relativePath,
final HttpServletRequest request,
final HttpServletResponse response,
final DirectoryManifest manifest,
final URI jobDirectoryRoot
) throws IOException, GenieNotFoundException, GenieServerException {
log.debug(
"Handle request, baseUri: '{}', relpath: '{}', jobRootUri: '{}'",
baseUri,
relativePath,
jobDirectoryRoot
);
final DirectoryManifest.ManifestEntry entry = manifest.getEntry(relativePath).orElseThrow(
() -> new GenieNotFoundException("No such entry in job manifest: " + relativePath)
);
if (entry.isDirectory()) {
// For now maintain the V3 structure
// TODO: Once we determine what we want for V4 use v3/v4 flags or some way to differentiate
// TODO: there's no unit test covering this section
final DefaultDirectoryWriter.Directory directory = new DefaultDirectoryWriter.Directory();
final List<DefaultDirectoryWriter.Entry> files = Lists.newArrayList();
final List<DefaultDirectoryWriter.Entry> directories = Lists.newArrayList();
try {
entry.getParent().ifPresent(
parentPath -> {
final DirectoryManifest.ManifestEntry parentEntry = manifest
.getEntry(parentPath)
.orElseThrow(IllegalArgumentException::new);
directory.setParent(createEntry(parentEntry, baseUri));
}
);
for (final String childPath : entry.getChildren()) {
final DirectoryManifest.ManifestEntry childEntry = manifest
.getEntry(childPath)
.orElseThrow(IllegalArgumentException::new);
if (childEntry.isDirectory()) {
directories.add(this.createEntry(childEntry, baseUri));
} else {
files.add(this.createEntry(childEntry, baseUri));
}
}
} catch (final IllegalArgumentException iae) {
throw new GenieServerException("Error while traversing files manifest: " + iae.getMessage(), iae);
}
directories.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
files.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
directory.setDirectories(directories);
directory.setFiles(files);
final String accept = request.getHeader(HttpHeaders.ACCEPT);
if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
response.setContentType(MediaType.TEXT_HTML_VALUE);
response
.getOutputStream()
.write(
DefaultDirectoryWriter
.directoryToHTML(entry.getName(), directory)
.getBytes(StandardCharsets.UTF_8)
);
} else {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
GenieObjectMapper.getMapper().writeValue(response.getOutputStream(), directory);
}
} else {
final URI location = jobDirectoryRoot.resolve(entry.getPath());
final String locationString = location.toString()
+ (jobDirectoryRoot.getFragment() != null ? ("#" + jobDirectoryRoot.getFragment()) : "");
log.debug("Get resource: {}", locationString);
final Resource jobResource = this.resourceLoader.getResource(locationString);
// Every file really should have a media type but if not use text/plain
final String mediaType = entry.getMimeType().orElse(MediaType.TEXT_PLAIN_VALUE);
final ResourceHttpRequestHandler handler = this.genieResourceHandlerFactory.get(mediaType, jobResource);
try {
handler.handleRequest(request, response);
} catch (ServletException e) {
throw new GenieServerException("Servlet exception: " + e.getMessage(), e);
}
}
}
private DefaultDirectoryWriter.Entry createEntry(
final DirectoryManifest.ManifestEntry manifestEntry,
final URI baseUri
) {
final DefaultDirectoryWriter.Entry entry = new DefaultDirectoryWriter.Entry();
// For backwards compatibility the V3 names ended in "/" for directories
if (manifestEntry.isDirectory()) {
entry.setName(
manifestEntry.getName().endsWith("/") ? manifestEntry.getName() : manifestEntry.getName() + "/"
);
} else {
entry.setName(manifestEntry.getName());
}
entry.setUrl(baseUri.resolve(manifestEntry.getPath()).toString());
entry.setSize(manifestEntry.getSize());
entry.setLastModified(manifestEntry.getLastModifiedTime());
return entry;
}
/**
* Helper class which overrides two entry points from {@link ResourceHttpRequestHandler} in order to be easily
* reusable for our use case while still leveraging all the work done in there for proper HTTP interaction.
*
* @author tgianos
* @since 4.0.0
*/
private static class GenieResourceHandler extends ResourceHttpRequestHandler {
private static final ResourceHttpMessageConverter RESOURCE_HTTP_MESSAGE_CONVERTER
= new ResourceHttpMessageConverter();
private static final ResourceRegionHttpMessageConverter RESOURCE_REGION_HTTP_MESSAGE_CONVERTER
= new ResourceRegionHttpMessageConverter();
private final MediaType mediaType;
private final Resource jobResource;
GenieResourceHandler(final String mediaType, final Resource jobResource) {
super();
// TODO: This throws InvalidMediaTypeException. Not sure if should bother handing it here or not seeing
// as the mime types were already derived successfully in the manifest creation
this.mediaType = MediaType.parseMediaType(mediaType);
this.jobResource = jobResource;
// Cheat to avoid assertions in the super handleRequest impl due to lack of being in an application context
this.setResourceHttpMessageConverter(RESOURCE_HTTP_MESSAGE_CONVERTER);
this.setResourceRegionHttpMessageConverter(RESOURCE_REGION_HTTP_MESSAGE_CONVERTER);
}
/**
* {@inheritDoc}
*/
@Override
protected Resource getResource(final HttpServletRequest request) throws IOException {
return this.jobResource;
}
/**
* {@inheritDoc}
*/
@Override
protected MediaType getMediaType(final HttpServletRequest request, final Resource resource) {
return this.mediaType;
}
/**
* Simple factory to avoid using 'new' inline, and facilitate mocking and testing.
*/
private static class Factory {
ResourceHttpRequestHandler get(final String mediaType, final Resource jobResource) {
return new GenieResourceHandler(mediaType, jobResource);
}
}
}
}
| 2,755 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/JobResolverServiceImpl.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.services.impl;
import brave.SpanCustomizer;
import brave.Tracer;
import com.netflix.genie.common.internal.dtos.Application;
import com.netflix.genie.common.internal.dtos.Cluster;
import com.netflix.genie.common.internal.dtos.ClusterMetadata;
import com.netflix.genie.common.internal.dtos.Command;
import com.netflix.genie.common.internal.dtos.ComputeResources;
import com.netflix.genie.common.internal.dtos.Criterion;
import com.netflix.genie.common.internal.dtos.Image;
import com.netflix.genie.common.internal.dtos.JobEnvironment;
import com.netflix.genie.common.internal.dtos.JobMetadata;
import com.netflix.genie.common.internal.dtos.JobRequest;
import com.netflix.genie.common.internal.dtos.JobSpecification;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieJobResolutionRuntimeException;
import com.netflix.genie.common.internal.jobs.JobConstants;
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.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.dtos.ResolvedJob;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.properties.JobResolutionProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.selectors.ClusterSelectionContext;
import com.netflix.genie.web.selectors.ClusterSelector;
import com.netflix.genie.web.selectors.CommandSelectionContext;
import com.netflix.genie.web.selectors.CommandSelector;
import com.netflix.genie.web.services.JobResolverService;
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.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.TargetClassAware;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.net.URI;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Implementation of the {@link JobResolverService} APIs.
*
* @author tgianos
* @since 4.0.0
*/
@Validated
public class JobResolverServiceImpl implements JobResolverService {
private static final Logger LOG = LoggerFactory.getLogger(JobResolverServiceImpl.class);
//region Metric Constants
/**
* How long it takes to completely resolve a job given inputs.
*/
private static final String RESOLVE_JOB_TIMER = "genie.services.jobResolver.resolve.timer";
/**
* How long it takes to resolve a command for a job given the supplied command criterion.
*/
private static final String RESOLVE_COMMAND_TIMER = "genie.services.jobResolver.resolveCommand.timer";
/**
* How long it takes to resolve a cluster for a job given the resolved command and the request criteria.
*/
private static final String RESOLVE_CLUSTER_TIMER = "genie.services.jobResolver.resolveCluster.timer";
/**
* How long it takes to resolve the applications for a given command.
*/
private static final String RESOLVE_APPLICATIONS_TIMER = "genie.services.jobResolver.resolveApplications.timer";
/**
* How long it takes to resolve a cluster for a job given the resolved command and the request criteria.
*/
private static final String GENERATE_CRITERIA_PERMUTATIONS_TIMER
= "genie.services.jobResolver.generateClusterCriteriaPermutations.timer";
/**
* How many times a cluster selector is invoked.
*/
private static final String CLUSTER_SELECTOR_COUNTER
= "genie.services.jobResolver.resolveCluster.clusterSelector.counter";
private static final int DEFAULT_CPU = 1;
private static final int DEFAULT_GPU = 0;
private static final long DEFAULT_MEMORY = 1_500L;
private static final long DEFAULT_DISK = 10_000L;
private static final long DEFAULT_NETWORK = 256L;
private static final String NO_RATIONALE = "No rationale provided";
private static final String NO_ID_FOUND = "No id found";
private static final String VERSION_4 = "4";
private static final Tag SAVED_TAG = Tag.of("saved", "true");
private static final Tag NOT_SAVED_TAG = Tag.of("saved", "false");
private static final Tag NO_CLUSTER_RESOLVED_ID = Tag.of(MetricsConstants.TagKeys.CLUSTER_ID, "None Resolved");
private static final Tag NO_CLUSTER_RESOLVED_NAME = Tag.of(MetricsConstants.TagKeys.CLUSTER_NAME, "None Resolved");
private static final Tag NO_COMMAND_RESOLVED_ID = Tag.of(MetricsConstants.TagKeys.COMMAND_ID, "None Resolved");
private static final Tag NO_COMMAND_RESOLVED_NAME = Tag.of(MetricsConstants.TagKeys.COMMAND_NAME, "None Resolved");
private static final String ID_FIELD = "id";
private static final String NAME_FIELD = "name";
private static final String STATUS_FIELD = "status";
private static final String VERSION_FIELD = "version";
private static final String CLUSTER_SELECTOR_STATUS_SUCCESS = "success";
private static final String CLUSTER_SELECTOR_STATUS_NO_PREFERENCE = "no preference";
//endregion
//region Members
private final PersistenceService persistenceService;
private final List<ClusterSelector> clusterSelectors;
private final CommandSelector commandSelector;
private final MeterRegistry registry;
// TODO: Switch to path
private final File defaultJobDirectory;
private final String defaultArchiveLocation;
private final Tracer tracer;
private final BraveTagAdapter tagAdapter;
private final JobResolutionProperties jobResolutionProperties;
//endregion
//region Public APIs
/**
* Constructor.
*
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param clusterSelectors The {@link ClusterSelector} implementations to use
* @param commandSelector The {@link CommandSelector} implementation to use
* @param registry The {@link MeterRegistry }metrics repository to use
* @param jobsProperties The properties for running a job set by the user
* @param jobResolutionProperties The {@link JobResolutionProperties} instance
* @param tracingComponents The {@link BraveTracingComponents} instance to use
*/
public JobResolverServiceImpl(
final DataServices dataServices,
@NotEmpty final List<ClusterSelector> clusterSelectors,
final CommandSelector commandSelector, // TODO: For now this is a single value but maybe support List
final MeterRegistry registry,
final JobsProperties jobsProperties,
final JobResolutionProperties jobResolutionProperties,
final BraveTracingComponents tracingComponents
) {
this.persistenceService = dataServices.getPersistenceService();
this.clusterSelectors = clusterSelectors;
this.commandSelector = commandSelector;
this.jobResolutionProperties = jobResolutionProperties;
final URI jobDirProperty = jobsProperties.getLocations().getJobs();
this.defaultJobDirectory = Paths.get(jobDirProperty).toFile();
final String archiveLocation = jobsProperties.getLocations().getArchives().toString();
this.defaultArchiveLocation = archiveLocation.endsWith(File.separator)
? archiveLocation
: archiveLocation + File.separator;
// Metrics
this.registry = registry;
// tracing
this.tracer = tracingComponents.getTracer();
this.tagAdapter = tracingComponents.getTagAdapter();
}
/**
* {@inheritDoc}
*/
@Override
@Nonnull
@Transactional
public ResolvedJob resolveJob(
final String id
) throws GenieJobResolutionException, GenieJobResolutionRuntimeException {
final long start = System.nanoTime();
final Set<Tag> tags = new HashSet<>();
tags.add(SAVED_TAG);
try {
LOG.info("Received request to resolve a job with id {}", id);
final JobStatus jobStatus = this.persistenceService.getJobStatus(id);
if (!jobStatus.isResolvable()) {
throw new IllegalArgumentException("Job " + id + " is already resolved: " + jobStatus);
}
final JobRequest jobRequest = this.persistenceService.getJobRequest(id);
// TODO: Possible improvement to combine this query with a few others to save DB trips but for now...
final boolean apiJob = this.persistenceService.isApiJob(id);
final JobResolutionContext context = new JobResolutionContext(
id,
jobRequest,
apiJob,
this.tracer.currentSpanCustomizer()
);
final ResolvedJob resolvedJob = this.resolve(context);
/*
* TODO: There is currently a gap in database schema where the resolved CPU value is not persisted. This
* means that it requires that the returned resolvedJob object here be used within the same call. If
* we for some reason eventually put the job id on a queue or something and pull data back from DB
* it WILL NOT be accurate. I'm purposely not doing this right now as it's not critical and modifying
* the schema will require a prod downtime and there are likely other fields (requestedNetwork,
* usedNetwork, usedDisk, resolvedDisk, requestedImage, usedImage) we want to add at the
* same time to minimize downtimes. - TJG 2/2/21
*/
this.persistenceService.saveResolvedJob(id, resolvedJob);
MetricsUtils.addSuccessTags(tags);
return resolvedJob;
} catch (final GenieJobResolutionException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw new GenieJobResolutionRuntimeException(t);
} finally {
this.registry
.timer(RESOLVE_JOB_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
/**
* {@inheritDoc}
*/
@Override
@Nonnull
public ResolvedJob resolveJob(
final String id,
@Valid final JobRequest jobRequest,
final boolean apiJob
) throws GenieJobResolutionException, GenieJobResolutionRuntimeException {
final long start = System.nanoTime();
final Set<Tag> tags = new HashSet<>();
tags.add(NOT_SAVED_TAG);
try {
LOG.info(
"Received request to resolve a job for id {} and request {}",
id,
jobRequest
);
final JobResolutionContext context = new JobResolutionContext(
id,
jobRequest,
apiJob,
this.tracer.currentSpanCustomizer()
);
final ResolvedJob resolvedJob = this.resolve(context);
MetricsUtils.addSuccessTags(tags);
return resolvedJob;
} catch (final GenieJobResolutionException e) {
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw new GenieJobResolutionRuntimeException(t);
} finally {
this.registry
.timer(RESOLVE_JOB_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
//endregion
//region Resolution Helpers
private ResolvedJob resolve(
final JobResolutionContext context
) throws GenieJobResolutionException, GenieJobResolutionRuntimeException {
this.tagSpanWithJobMetadata(context);
this.resolveCommand(context);
this.resolveCluster(context);
this.resolveApplications(context);
this.resolveComputeResources(context);
this.resolveImages(context);
this.resolveEnvironmentVariables(context);
this.resolveTimeout(context);
this.resolveArchiveLocation(context);
this.resolveJobDirectory(context);
return context.build();
}
/*
* Overall Algorithm:
*
* 1. Take command criterion from user job request and query database for all possible matching commands
* 2. Take clusterCriteria from jobRequest and clusterCriteria from each command and create uber query which finds
* ALL clusters that match at least one of the resulting merged criterion (merged meaning combining a job and
* command cluster criterion)
* 3. Iterate through commands from step 1 and evaluate job/command cluster criterion against resulting set of
* clusters from step 2. Filter out any commands that don't match any clusters. Save resulting cluster set for
* each command in map command -> Set<Cluster>
* 4. Pass set<command>, jobRequest, jobId, map<command<set<Cluster>> to command selector which will return single
* command
* 5. Using command result pass previously computed Set<Cluster> to cluster selector
* 6. Save results and run job
*/
private void resolveCommand(final JobResolutionContext context) throws GenieJobResolutionException {
final long start = System.nanoTime();
final Set<Tag> tags = new HashSet<>();
try {
final JobRequest jobRequest = context.getJobRequest();
final Criterion criterion = jobRequest.getCriteria().getCommandCriterion();
//region Algorithm Step 1
final Set<Command> commands = this.persistenceService.findCommandsMatchingCriterion(criterion, true);
// Short circuit if there are no commands
if (commands.isEmpty()) {
throw new GenieJobResolutionException("No command matching command criterion found");
}
//endregion
//region Algorithm Step 2
final Map<Command, List<Criterion>> commandClusterCriterions = this.generateClusterCriteriaPermutations(
commands,
jobRequest
);
final Set<Criterion> uniqueCriteria = this.flattenClusterCriteriaPermutations(commandClusterCriterions);
final Set<Cluster> allCandidateClusters = this.persistenceService.findClustersMatchingAnyCriterion(
uniqueCriteria,
true
);
if (allCandidateClusters.isEmpty()) {
throw new GenieJobResolutionException("No clusters available to run any candidate command on");
}
//endregion
//region Algorithm Step 3
final Map<Command, Set<Cluster>> commandClusters = this.generateCommandClustersMap(
commandClusterCriterions,
allCandidateClusters
);
// this should never really happen based on above check but just in case
if (commandClusters.isEmpty()) {
throw new GenieJobResolutionException("No clusters available to run any candidate command on");
}
// save the map for use later by cluster resolution
context.setCommandClusters(commandClusters);
//endregion
//region Algorithm Step 4
final ResourceSelectionResult<Command> result = this.commandSelector.select(
new CommandSelectionContext(
context.getJobId(),
jobRequest,
context.isApiJob(),
commandClusters
)
);
//endregion
final Command command = result
.getSelectedResource()
.orElseThrow(
() -> new GenieJobResolutionException(
"Expected a command but "
+ result.getSelectorClass().getSimpleName()
+ " didn't select anything. Rationale: "
+ result.getSelectionRationale().orElse(NO_RATIONALE)
)
);
LOG.debug(
"Selected command {} for criterion {} using {} due to {}",
command.getId(),
criterion,
result.getSelectorClass().getName(),
result.getSelectionRationale().orElse(NO_RATIONALE)
);
MetricsUtils.addSuccessTags(tags);
final String commandId = command.getId();
final String commandName = command.getMetadata().getName();
tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_ID, commandId));
tags.add(Tag.of(MetricsConstants.TagKeys.COMMAND_NAME, commandName));
final SpanCustomizer spanCustomizer = context.getSpanCustomizer();
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_COMMAND_ID_TAG, commandId);
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_COMMAND_NAME_TAG, commandName);
context.setCommand(command);
} catch (final GenieJobResolutionException e) {
// No candidates or selector choose none
tags.add(NO_COMMAND_RESOLVED_ID);
tags.add(NO_COMMAND_RESOLVED_NAME);
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} catch (final ResourceSelectionException t) {
// Selector runtime error
MetricsUtils.addFailureTagsWithException(tags, t);
throw new GenieJobResolutionRuntimeException(t);
} finally {
this.registry
.timer(RESOLVE_COMMAND_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
/*
* At this point we should have resolved a command and now we can use the map command -> clusters that was
* previously computed to invoke the cluster selectors to narrow down the candidate clusters to a single cluster
* for use.
*/
private void resolveCluster(final JobResolutionContext context) throws GenieJobResolutionException {
final long start = System.nanoTime();
final Set<Tag> tags = new HashSet<>();
final String jobId = context.getJobId();
try {
final Command command = context
.getCommand()
.orElseThrow(
() -> new IllegalStateException(
"Command not resolved before attempting to resolve a cluster for job " + jobId
)
);
final Set<Cluster> candidateClusters = context
.getCommandClusters()
.orElseThrow(
() -> new IllegalStateException("Command to candidate cluster map not available for job " + jobId)
)
.get(command);
if (candidateClusters == null || candidateClusters.isEmpty()) {
throw new IllegalStateException(
"Command " + command.getId() + " had no candidate clusters for job " + jobId
);
}
Cluster cluster = null;
for (final ClusterSelector clusterSelector : this.clusterSelectors) {
// Create subset of tags just for this selector. Copy existing tags if any.
final Set<Tag> selectorTags = new HashSet<>(tags);
// Note: This is done before the selection because if we do it after and the selector throws
// exception then we don't have this tag in the metrics. Which is unfortunate since the result
// does return the selector
final String clusterSelectorClass = this.getProxyObjectClassName(clusterSelector);
selectorTags.add(Tag.of(MetricsConstants.TagKeys.CLASS_NAME, clusterSelectorClass));
try {
final ResourceSelectionResult<Cluster> result = clusterSelector.select(
new ClusterSelectionContext(
jobId,
context.getJobRequest(),
context.isApiJob(),
command,
candidateClusters
)
);
final Optional<Cluster> selectedClusterOptional = result.getSelectedResource();
if (selectedClusterOptional.isPresent()) {
cluster = selectedClusterOptional.get();
LOG.debug(
"Successfully selected cluster {} using selector {} for job {} with rationale: {}",
cluster.getId(),
clusterSelectorClass,
jobId,
result.getSelectionRationale().orElse(NO_RATIONALE)
);
selectorTags.add(Tag.of(MetricsConstants.TagKeys.STATUS, CLUSTER_SELECTOR_STATUS_SUCCESS));
selectorTags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_ID, cluster.getId()));
selectorTags.add(
Tag.of(MetricsConstants.TagKeys.CLUSTER_NAME, cluster.getMetadata().getName())
);
break;
} else {
selectorTags.add(
Tag.of(MetricsConstants.TagKeys.STATUS, CLUSTER_SELECTOR_STATUS_NO_PREFERENCE)
);
selectorTags.add(NO_CLUSTER_RESOLVED_ID);
selectorTags.add(NO_CLUSTER_RESOLVED_NAME);
LOG.debug(
"Selector {} returned no preference with rationale: {}",
clusterSelectorClass,
result.getSelectionRationale().orElse(NO_RATIONALE)
);
}
} catch (final Exception e) {
// Swallow exception and proceed to next selector.
// This is a choice to provides "best-service": select a cluster as long as it matches criteria,
// even if one of the selectors encountered an error and cannot choose the best candidate.
MetricsUtils.addFailureTagsWithException(selectorTags, e);
LOG.warn(
"Cluster selector {} evaluation threw exception for job {}",
clusterSelectorClass,
jobId,
e
);
} finally {
this.registry.counter(CLUSTER_SELECTOR_COUNTER, selectorTags).increment();
}
}
if (cluster == null) {
throw new GenieJobResolutionException("No cluster resolved for job " + jobId);
}
LOG.debug("Resolved cluster {} for job {}", cluster.getId(), jobId);
context.setCluster(cluster);
MetricsUtils.addSuccessTags(tags);
final String clusterId = cluster.getId();
final String clusterName = cluster.getMetadata().getName();
tags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_ID, clusterId));
tags.add(Tag.of(MetricsConstants.TagKeys.CLUSTER_NAME, clusterName));
final SpanCustomizer spanCustomizer = context.getSpanCustomizer();
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_CLUSTER_ID_TAG, clusterId);
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_CLUSTER_NAME_TAG, clusterName);
} catch (final GenieJobResolutionException e) {
tags.add(NO_CLUSTER_RESOLVED_ID);
tags.add(NO_CLUSTER_RESOLVED_NAME);
MetricsUtils.addFailureTagsWithException(tags, e);
throw e;
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw new GenieJobResolutionRuntimeException(t);
} finally {
this.registry
.timer(RESOLVE_CLUSTER_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
private void resolveApplications(final JobResolutionContext context) throws GenieJobResolutionException {
final long start = System.nanoTime();
final Set<Tag> tags = new HashSet<>();
final String id = context.getJobId();
final JobRequest jobRequest = context.getJobRequest();
try {
final String commandId = context
.getCommand()
.orElseThrow(() -> new IllegalStateException("Command hasn't been resolved before applications"))
.getId();
LOG.debug("Selecting applications for job {} and command {}", id, commandId);
// TODO: What do we do about application status? Should probably check here
final List<Application> applications = new ArrayList<>();
if (jobRequest.getCriteria().getApplicationIds().isEmpty()) {
applications.addAll(this.persistenceService.getApplicationsForCommand(commandId));
} else {
for (final String applicationId : jobRequest.getCriteria().getApplicationIds()) {
applications.add(this.persistenceService.getApplication(applicationId));
}
}
LOG.debug(
"Resolved applications {} for job {}",
applications
.stream()
.map(Application::getId)
.reduce((one, two) -> one + "," + two)
.orElse(NO_ID_FOUND),
id
);
MetricsUtils.addSuccessTags(tags);
context.setApplications(applications);
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw new GenieJobResolutionRuntimeException(t);
} finally {
this.registry
.timer(RESOLVE_APPLICATIONS_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
private void resolveEnvironmentVariables(final JobResolutionContext context) {
final Command command = context
.getCommand()
.orElseThrow(
() -> new IllegalStateException("Command not resolved before attempting to resolve env variables")
);
final Cluster cluster = context
.getCluster()
.orElseThrow(
() -> new IllegalStateException("Cluster not resolved before attempting to resolve env variables")
);
final String id = context.getJobId();
final JobRequest jobRequest = context.getJobRequest();
final long jobMemory = context
.getComputeResources()
.orElseThrow(
() -> new IllegalStateException("Job memory not resolved before attempting to resolve env variables")
)
.getMemoryMb()
.orElseThrow(() -> new IllegalStateException("No memory has been resolved before attempting to resolve"));
// N.B. variables may be evaluated in a different order than they are added to this map (due to serialization).
// Hence variables in this set should not depend on each-other.
final Map<String, String> envVariables = new HashMap<>();
envVariables.put(JobConstants.GENIE_VERSION_ENV_VAR, VERSION_4);
envVariables.put(JobConstants.GENIE_CLUSTER_ID_ENV_VAR, cluster.getId());
envVariables.put(JobConstants.GENIE_CLUSTER_NAME_ENV_VAR, cluster.getMetadata().getName());
envVariables.put(JobConstants.GENIE_CLUSTER_TAGS_ENV_VAR, this.tagsToString(cluster.getMetadata().getTags()));
envVariables.put(JobConstants.GENIE_COMMAND_ID_ENV_VAR, command.getId());
envVariables.put(JobConstants.GENIE_COMMAND_NAME_ENV_VAR, command.getMetadata().getName());
envVariables.put(JobConstants.GENIE_COMMAND_TAGS_ENV_VAR, this.tagsToString(command.getMetadata().getTags()));
envVariables.put(JobConstants.GENIE_JOB_ID_ENV_VAR, id);
envVariables.put(JobConstants.GENIE_JOB_NAME_ENV_VAR, jobRequest.getMetadata().getName());
envVariables.put(JobConstants.GENIE_JOB_MEMORY_ENV_VAR, String.valueOf(jobMemory));
envVariables.put(JobConstants.GENIE_JOB_TAGS_ENV_VAR, this.tagsToString(jobRequest.getMetadata().getTags()));
envVariables.put(
JobConstants.GENIE_JOB_GROUPING_ENV_VAR,
jobRequest.getMetadata().getGrouping().orElse("")
);
envVariables.put(
JobConstants.GENIE_JOB_GROUPING_INSTANCE_ENV_VAR,
jobRequest.getMetadata().getGroupingInstance().orElse("")
);
envVariables.put(
JobConstants.GENIE_REQUESTED_COMMAND_TAGS_ENV_VAR,
this.tagsToString(jobRequest.getCriteria().getCommandCriterion().getTags())
);
final List<Criterion> clusterCriteria = jobRequest.getCriteria().getClusterCriteria();
final List<String> clusterCriteriaTags = new ArrayList<>(clusterCriteria.size());
for (int i = 0; i < clusterCriteria.size(); i++) {
final Criterion criterion = clusterCriteria.get(i);
final String criteriaTagsString = this.tagsToString(criterion.getTags());
envVariables.put(JobConstants.GENIE_REQUESTED_CLUSTER_TAGS_ENV_VAR + "_" + i, criteriaTagsString);
clusterCriteriaTags.add("[" + criteriaTagsString + "]");
}
envVariables.put(
JobConstants.GENIE_REQUESTED_CLUSTER_TAGS_ENV_VAR,
"[" + StringUtils.join(clusterCriteriaTags, ',') + "]"
);
envVariables.put(JobConstants.GENIE_USER_ENV_VAR, jobRequest.getMetadata().getUser());
envVariables.put(JobConstants.GENIE_USER_GROUP_ENV_VAR, jobRequest.getMetadata().getGroup().orElse(""));
context.setEnvironmentVariables(Collections.unmodifiableMap(envVariables));
}
private void resolveTimeout(final JobResolutionContext context) {
final JobRequest jobRequest = context.getJobRequest();
if (jobRequest.getRequestedAgentConfig().getTimeoutRequested().isPresent()) {
context.setTimeout(jobRequest.getRequestedAgentConfig().getTimeoutRequested().get());
} else if (context.isApiJob()) {
// For backwards V3 compatibility
context.setTimeout(com.netflix.genie.common.dto.JobRequest.DEFAULT_TIMEOUT_DURATION);
}
}
private void resolveComputeResources(final JobResolutionContext context) {
final ComputeResources req = context
.getJobRequest()
.getRequestedJobEnvironment()
.getRequestedComputeResources();
final ComputeResources command = context
.getCommand()
.orElseThrow(() -> new IllegalStateException("Command hasn't been resolved before compute resources"))
.getComputeResources();
final ComputeResources defaults = this.jobResolutionProperties.getDefaultComputeResources();
context.setComputeResources(
new ComputeResources.Builder()
.withCpu(this.resolveComputeResource(req::getCpu, command::getCpu, defaults::getCpu, DEFAULT_CPU))
.withGpu(this.resolveComputeResource(req::getGpu, command::getGpu, defaults::getGpu, DEFAULT_GPU))
.withMemoryMb(
this.resolveComputeResource(
req::getMemoryMb,
command::getMemoryMb,
defaults::getMemoryMb,
DEFAULT_MEMORY
)
)
.withDiskMb(
this.resolveComputeResource(req::getDiskMb, command::getDiskMb, defaults::getDiskMb, DEFAULT_DISK)
)
.withNetworkMbps(
this.resolveComputeResource(
req::getNetworkMbps,
command::getNetworkMbps,
defaults::getNetworkMbps,
DEFAULT_NETWORK
)
)
.build()
);
}
private <T> T resolveComputeResource(
final Supplier<Optional<T>> requestedResource,
final Supplier<Optional<T>> commandResource,
final Supplier<Optional<T>> configuredDefault,
final T hardCodedDefault
) {
return requestedResource
.get()
.orElse(
commandResource
.get()
.orElse(
configuredDefault
.get()
.orElse(hardCodedDefault)
)
);
}
private void resolveImages(final JobResolutionContext context) {
final Map<String, Image> requestImages = context
.getJobRequest()
.getRequestedJobEnvironment()
.getRequestedImages();
final Map<String, Image> commandImages = context
.getCommand()
.orElseThrow(() -> new IllegalStateException("No command resolved before trying to resolve images"))
.getImages();
final Map<String, Image> defaultImages = this.jobResolutionProperties.getDefaultImages();
// Find all the image keys
final Map<String, Image> resolvedImages = new HashMap<>(defaultImages);
for (final Map.Entry<String, Image> entry : commandImages.entrySet()) {
resolvedImages.merge(entry.getKey(), entry.getValue(), this::mergeImages);
}
for (final Map.Entry<String, Image> entry : requestImages.entrySet()) {
resolvedImages.merge(entry.getKey(), entry.getValue(), this::mergeImages);
}
context.setImages(resolvedImages);
}
private void resolveArchiveLocation(final JobResolutionContext context) {
// TODO: Disable ability to disable archival for all jobs during internal V4 migration.
// Will allow us to reach out to clients who may set this variable but still expect output after
// job completion due to it being served off the node after completion in V3 but now it won't.
// Put this back in once all use cases have been hunted down and users are sure of their expected
// behavior
context.setArchiveLocation(this.defaultArchiveLocation + context.getJobId());
}
private void resolveJobDirectory(final JobResolutionContext context) {
context.setJobDirectory(
context.getJobRequest()
.getRequestedAgentConfig()
.getRequestedJobDirectoryLocation()
.orElse(this.defaultJobDirectory)
);
}
//endregion
//region Additional Helpers
/**
* Helper method to generate all the possible viable cluster criterion permutations for the given set of commands
* and the given job request. The resulting map will be each command to its associated priority ordered list of
* merged cluster criteria. The priority order is generated as follows:
* <pre>
* for (commandClusterCriterion : command.getClusterCriteria()) {
* for (jobClusterCriterion : jobRequest.getClusterCriteria()) {
* // merge
* }
* }
* </pre>
*
* @param commands The set of {@link Command}s whose cluster criteria should be evaluated
* @param jobRequest The {@link JobRequest} whose cluster criteria should be combined with the commands
* @return The resulting map of each command to their associated merged criterion list in priority order
*/
private Map<Command, List<Criterion>> generateClusterCriteriaPermutations(
final Set<Command> commands,
final JobRequest jobRequest
) {
final long start = System.nanoTime();
try {
final Map<Command, List<Criterion>> mapBuilder = new HashMap<>();
for (final Command command : commands) {
final List<Criterion> listBuilder = new ArrayList<>();
for (final Criterion commandClusterCriterion : command.getClusterCriteria()) {
for (final Criterion jobClusterCriterion : jobRequest.getCriteria().getClusterCriteria()) {
try {
// Failing to merge the criteria is equivalent to a round-trip DB query that returns
// zero results. This is an in memory optimization which also solves the need to implement
// the db query as a join with a subquery.
listBuilder.add(this.mergeCriteria(commandClusterCriterion, jobClusterCriterion));
} catch (final IllegalArgumentException e) {
LOG.debug(
"Unable to merge command cluster criterion {} and job cluster criterion {}. Skipping.",
commandClusterCriterion,
jobClusterCriterion,
e
);
}
}
}
mapBuilder.put(command, Collections.unmodifiableList(listBuilder));
}
return Collections.unmodifiableMap(mapBuilder);
} finally {
this.registry
.timer(GENERATE_CRITERIA_PERMUTATIONS_TIMER)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
private Set<Criterion> flattenClusterCriteriaPermutations(final Map<Command, List<Criterion>> commandCriteriaMap) {
return commandCriteriaMap.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
}
/**
* This is an in memory evaluation of the matching done against persistence.
*
* @param cluster The cluster to evaluate the criterion against
* @param criterion The criterion the cluster is being tested against
* @return {@literal true} if the {@link Cluster} matches the {@link Criterion}
*/
private boolean clusterMatchesCriterion(final Cluster cluster, final Criterion criterion) {
// TODO: This runs the risk of diverging from DB query mechanism. Perhaps way to unite somewhat?
final ClusterMetadata metadata = cluster.getMetadata();
return criterion.getId().map(id -> cluster.getId().equals(id)).orElse(true)
&& criterion.getName().map(name -> metadata.getName().equals(name)).orElse(true)
&& criterion.getVersion().map(version -> metadata.getVersion().equals(version)).orElse(true)
&& criterion.getStatus().map(status -> metadata.getStatus().name().equals(status)).orElse(true)
&& metadata.getTags().containsAll(criterion.getTags());
}
private Map<Command, Set<Cluster>> generateCommandClustersMap(
final Map<Command, List<Criterion>> commandClusterCriteria,
final Set<Cluster> candidateClusters
) {
final Map<Command, Set<Cluster>> matrixBuilder = new HashMap<>();
for (final Map.Entry<Command, List<Criterion>> entry : commandClusterCriteria.entrySet()) {
final Command command = entry.getKey();
final Set<Cluster> matchedClustersBuilder = new HashSet<>();
// Loop through the criterion in the priority order first
for (final Criterion criterion : entry.getValue()) {
for (final Cluster candidateCluster : candidateClusters) {
if (this.clusterMatchesCriterion(candidateCluster, criterion)) {
LOG.debug(
"Cluster {} matched criterion {} for command {}",
candidateCluster.getId(),
criterion,
command.getId()
);
matchedClustersBuilder.add(candidateCluster);
}
}
final Set<Cluster> matchedClusters = Collections.unmodifiableSet(matchedClustersBuilder);
if (!matchedClusters.isEmpty()) {
// If we found some clusters the evaluation for this command is done
matrixBuilder.put(command, matchedClusters);
LOG.debug("For command {} matched clusters {}", command, matchedClusters);
// short circuit further criteria evaluation for this command
break;
}
}
// If the command never matched any clusters it should be filtered out
// of resulting map as no value would be added to the result builder
}
final Map<Command, Set<Cluster>> matrix = Collections.unmodifiableMap(matrixBuilder);
LOG.debug("Complete command -> clusters matrix: {}", matrix);
return matrix;
}
/**
* Helper method for merging two criterion.
* <p>
* This method makes several assumptions:
* - If any of these fields: {@literal id, name, version, status} are in both criterion their values must match
* or this criterion combination of criteria can't possibly be matched so an {@link IllegalArgumentException}
* is thrown
* - If only one criterion has any of these fields {@literal id, name, version, status} then that value is present
* in the resulting criterion
* - Any {@literal tags} present in either criterion are merged into the super set of both sets of tags
*
* @param one The first {@link Criterion}
* @param two The second {@link Criterion}
* @return A merged {@link Criterion} that can be used to search the database
* @throws IllegalArgumentException If the criteria can't be merged due to the described assumptions
*/
private Criterion mergeCriteria(final Criterion one, final Criterion two) throws IllegalArgumentException {
final Criterion.Builder builder = new Criterion.Builder();
builder.withId(
this.mergeCriteriaStrings(one.getId().orElse(null), two.getId().orElse(null), ID_FIELD)
);
builder.withName(
this.mergeCriteriaStrings(one.getName().orElse(null), two.getName().orElse(null), NAME_FIELD)
);
builder.withStatus(
this.mergeCriteriaStrings(one.getStatus().orElse(null), two.getStatus().orElse(null), STATUS_FIELD)
);
builder.withVersion(
this.mergeCriteriaStrings(one.getVersion().orElse(null), two.getVersion().orElse(null), VERSION_FIELD)
);
final Set<String> tags = new HashSet<>(one.getTags());
tags.addAll(two.getTags());
builder.withTags(tags);
return builder.build();
}
private String mergeCriteriaStrings(
@Nullable final String one,
@Nullable final String two,
final String fieldName
) throws IllegalArgumentException {
if (StringUtils.equals(one, two)) {
// This handles null == null for us
return one;
} else if (one == null) {
return two;
} else if (two == null) {
return one;
} else {
// Both have values but aren't equal
throw new IllegalArgumentException(fieldName + "'s were both present but not equal");
}
}
private Image mergeImages(final Image secondary, final Image primary) {
return new Image.Builder()
.withName(primary.getName().orElse(secondary.getName().orElse(null)))
.withTag(primary.getTag().orElse(secondary.getTag().orElse(null)))
.withArguments(primary.getArguments().isEmpty() ? secondary.getArguments() : primary.getArguments())
.build();
}
/**
* Helper to convert a set of tags into a string that is a suitable value for a shell environment variable.
* Adds double quotes as necessary (i.e. in case of spaces, newlines), performs escaping of in-tag quotes.
* Input tags are sorted to produce a deterministic output value.
*
* @param tags a set of tags or null
* @return a CSV string
*/
private String tagsToString(final Set<String> tags) {
final List<String> sortedTags = new ArrayList<>(tags);
// Sort tags for the sake of determinism (e.g., tests)
sortedTags.sort(Comparator.naturalOrder());
final String joinedString = StringUtils.join(sortedTags, ',');
// Escape quotes
return RegExUtils.replaceAll(RegExUtils.replaceAll(joinedString, "'", "\\'"), "\"", "\\\"");
}
private String getProxyObjectClassName(final Object possibleProxyObject) {
final String className;
if (possibleProxyObject instanceof TargetClassAware) {
final Class<?> targetClass = ((TargetClassAware) possibleProxyObject).getTargetClass();
if (targetClass != null) {
className = targetClass.getCanonicalName();
} else {
className = possibleProxyObject.getClass().getCanonicalName();
}
} else {
className = possibleProxyObject.getClass().getCanonicalName();
}
return className;
}
private void tagSpanWithJobMetadata(final JobResolutionContext context) {
final SpanCustomizer spanCustomizer = this.tracer.currentSpanCustomizer();
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_ID_TAG, context.getJobId());
final JobMetadata jobMetadata = context.getJobRequest().getMetadata();
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_NAME_TAG, jobMetadata.getName());
this.tagAdapter.tag(spanCustomizer, TracingConstants.JOB_USER_TAG, jobMetadata.getUser());
}
//endregion
//region Helper Classes
/**
* A helper data class for passing information around / along the resolution pipeline.
*
* @author tgianos
* @since 4.0.0
*/
@RequiredArgsConstructor
@Getter
@Setter
@ToString(doNotUseGetters = true)
static class JobResolutionContext {
private final String jobId;
private final JobRequest jobRequest;
private final boolean apiJob;
private final SpanCustomizer spanCustomizer;
private Command command;
private Cluster cluster;
private List<Application> applications;
private ComputeResources computeResources;
private Map<String, String> environmentVariables;
private Integer timeout;
private String archiveLocation;
private File jobDirectory;
private Map<Command, Set<Cluster>> commandClusters;
private Map<String, Image> images;
Optional<Command> getCommand() {
return Optional.ofNullable(this.command);
}
Optional<Cluster> getCluster() {
return Optional.ofNullable(this.cluster);
}
Optional<List<Application>> getApplications() {
return Optional.ofNullable(this.applications);
}
Optional<ComputeResources> getComputeResources() {
return Optional.ofNullable(this.computeResources);
}
Optional<Map<String, String>> getEnvironmentVariables() {
return Optional.ofNullable(this.environmentVariables);
}
Optional<Integer> getTimeout() {
return Optional.ofNullable(this.timeout);
}
Optional<String> getArchiveLocation() {
return Optional.ofNullable(this.archiveLocation);
}
Optional<File> getJobDirectory() {
return Optional.ofNullable(this.jobDirectory);
}
Optional<Map<Command, Set<Cluster>>> getCommandClusters() {
return Optional.ofNullable(this.commandClusters);
}
Optional<Map<String, Image>> getImages() {
return Optional.ofNullable(this.images);
}
ResolvedJob build() {
// Error checking
if (this.command == null) {
throw new IllegalStateException("Command was never resolved for job " + this.jobId);
}
if (this.cluster == null) {
throw new IllegalStateException("Cluster was never resolved for job " + this.jobId);
}
if (this.applications == null) {
throw new IllegalStateException("Applications were never resolved for job " + this.jobId);
}
if (this.computeResources == null) {
throw new IllegalStateException("Compute resources were never resolved for job " + this.jobId);
}
if (this.images == null) {
throw new IllegalStateException("Images were never resolved for job " + this.jobId);
}
if (this.environmentVariables == null) {
throw new IllegalStateException("Environment variables were never resolved for job " + this.jobId);
}
if (this.archiveLocation == null) {
throw new IllegalStateException("Archive location was never resolved for job " + this.jobId);
}
if (this.jobDirectory == null) {
throw new IllegalStateException("Job directory was never resolved for job " + this.jobId);
}
// Note: Currently no check for timeout due to it being ok for it to be null at the moment
final JobSpecification jobSpecification = new JobSpecification(
this.command.getExecutable(),
this.jobRequest.getCommandArgs(),
new JobSpecification.ExecutionResource(this.jobId, this.jobRequest.getResources()),
new JobSpecification.ExecutionResource(this.cluster.getId(), this.cluster.getResources()),
new JobSpecification.ExecutionResource(this.command.getId(), this.command.getResources()),
this.applications
.stream()
.map(
application -> new JobSpecification.ExecutionResource(
application.getId(),
application.getResources()
)
)
.collect(Collectors.toList()),
this.environmentVariables,
this.jobRequest.getRequestedAgentConfig().isInteractive(),
this.jobDirectory,
this.archiveLocation,
this.timeout
);
final JobEnvironment jobEnvironment = new JobEnvironment
.Builder()
.withComputeResources(this.computeResources)
.withEnvironmentVariables(this.environmentVariables)
.withImages(this.images)
.build();
return new ResolvedJob(jobSpecification, jobEnvironment, this.jobRequest.getMetadata());
}
}
//endregion
}
| 2,756 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/JobLaunchServiceImpl.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.services.impl;
import brave.SpanCustomizer;
import brave.Tracer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Sets;
import com.netflix.genie.common.dto.JobStatusMessages;
import com.netflix.genie.common.internal.dtos.ArchiveStatus;
import com.netflix.genie.common.internal.dtos.JobStatus;
import com.netflix.genie.common.internal.exceptions.checked.GenieJobResolutionException;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.dtos.JobSubmission;
import com.netflix.genie.web.dtos.ResolvedJob;
import com.netflix.genie.web.dtos.ResourceSelectionResult;
import com.netflix.genie.web.exceptions.checked.AgentLaunchException;
import com.netflix.genie.web.exceptions.checked.IdAlreadyExistsException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.exceptions.checked.ResourceSelectionException;
import com.netflix.genie.web.selectors.AgentLauncherSelectionContext;
import com.netflix.genie.web.selectors.AgentLauncherSelector;
import com.netflix.genie.web.services.JobLaunchService;
import com.netflix.genie.web.services.JobResolverService;
import com.netflix.genie.web.util.MetricsUtils;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nonnull;
import javax.validation.Valid;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Default implementation of the {@link JobLaunchService}.
*
* @author tgianos
* @since 4.0.0
*/
@Slf4j
public class JobLaunchServiceImpl implements JobLaunchService {
static final String BEGIN_LAUNCH_JOB_ANNOTATION = "Beginning to Launch Job";
static final String SAVED_JOB_SUBMISSION_ANNOTATION = "Saved Job Submission";
static final String RESOLVED_JOB_ANNOTATION = "Resolved Job";
static final String MARKED_JOB_ACCEPTED_ANNOTATION = "Marked Job Accepted";
static final String LAUNCHED_AGENT_ANNOTATION = "Launched Agent";
static final String SAVED_LAUNCHER_EXT_ANNOTATION = "Saved Launcher Ext Data";
static final String END_LAUNCH_JOB_ANNOTATION = "Completed Launching Job";
private static final String LAUNCH_JOB_TIMER = "genie.services.jobLaunch.launchJob.timer";
private static final String AGENT_LAUNCHER_SELECTOR_TIMER = "genie.services.jobLaunch.selectLauncher.timer";
private static final String AVAILABLE_LAUNCHERS_TAG = "numAvailableLaunchers";
private static final String SELECTOR_CLASS_TAG = "agentLauncherSelectorClass";
private static final String LAUNCHER_CLASS_TAG = "agentLauncherSelectedClass";
private static final int MAX_STATUS_UPDATE_ATTEMPTS = 5;
private static final int INITIAL_ATTEMPT = 0;
private static final String ACCEPTED_MESSAGE = "The job has been accepted by the system for execution";
private final PersistenceService persistenceService;
private final JobResolverService jobResolverService;
private final AgentLauncherSelector agentLauncherSelector;
private final Tracer tracer;
private final MeterRegistry registry;
/**
* Constructor.
*
* @param dataServices The {@link DataServices} instance to use
* @param jobResolverService {@link JobResolverService} implementation used to resolve job details
* @param agentLauncherSelector {@link AgentLauncher} implementation to launch agents
* @param tracingComponents {@link BraveTracingComponents} instance to use to get access to instrumentation
* @param registry {@link MeterRegistry} metrics repository
*/
public JobLaunchServiceImpl(
final DataServices dataServices,
final JobResolverService jobResolverService,
final AgentLauncherSelector agentLauncherSelector,
final BraveTracingComponents tracingComponents,
final MeterRegistry registry
) {
this.persistenceService = dataServices.getPersistenceService();
this.jobResolverService = jobResolverService;
this.agentLauncherSelector = agentLauncherSelector;
this.tracer = tracingComponents.getTracer();
this.registry = registry;
}
/**
* {@inheritDoc}
*/
@Override
@Nonnull
public String launchJob(
@Valid final JobSubmission jobSubmission
) throws
AgentLaunchException,
GenieJobResolutionException,
IdAlreadyExistsException,
NotFoundException {
final long start = System.nanoTime();
final SpanCustomizer span = this.tracer.currentSpanCustomizer();
span.annotate(BEGIN_LAUNCH_JOB_ANNOTATION);
final Set<Tag> tags = Sets.newHashSet();
try {
/*
* Steps:
*
* 1. Save the job information
* 2. Attempt to resolve the job information (includes saving)
* 3. Mark the job as accepted
* 4. Launch the agent process given the implementation configured for this Genie instance
* 5. If the agent launch fails mark the job failed else return
*/
final String jobId = this.persistenceService.saveJobSubmission(jobSubmission);
span.annotate(SAVED_JOB_SUBMISSION_ANNOTATION);
final ResolvedJob resolvedJob;
try {
resolvedJob = this.jobResolverService.resolveJob(jobId);
} catch (final Throwable t) {
final String message;
if (t instanceof GenieJobResolutionException) {
message = JobStatusMessages.FAILED_TO_RESOLVE_JOB;
} else {
message = JobStatusMessages.RESOLUTION_RUNTIME_ERROR;
}
MetricsUtils.addFailureTagsWithException(tags, t);
this.persistenceService.updateJobArchiveStatus(jobId, ArchiveStatus.NO_FILES);
if (
this.updateJobStatus(jobId, JobStatus.RESERVED, JobStatus.FAILED, message, INITIAL_ATTEMPT)
!= JobStatus.FAILED
) {
log.error("Updating status to failed didn't succeed");
}
throw t; // Caught below for metrics gathering
}
span.annotate(RESOLVED_JOB_ANNOTATION);
// Job state should be RESOLVED now. Mark it ACCEPTED to avoid race condition with agent starting up
// before we get return from launchAgent and trying to set it to CLAIMED
try {
final JobStatus updatedStatus = this.updateJobStatus(
jobId,
JobStatus.RESOLVED,
JobStatus.ACCEPTED,
ACCEPTED_MESSAGE,
INITIAL_ATTEMPT
);
if (updatedStatus != JobStatus.ACCEPTED) {
throw new AgentLaunchException("Unable to mark job accepted. Job state " + updatedStatus);
}
} catch (final Exception e) {
this.persistenceService.updateJobArchiveStatus(jobId, ArchiveStatus.NO_FILES);
// TODO: Failed to update the status to accepted. Try to set it to failed or rely on other cleanup
// mechanism? For now rely on janitor mechanisms
throw e;
}
span.annotate(MARKED_JOB_ACCEPTED_ANNOTATION);
// TODO: at the moment this is not populated, it's going to be a null node (not null)
final JsonNode requestedLauncherExt = this.persistenceService.getRequestedLauncherExt(jobId);
final Optional<JsonNode> launcherExt;
try {
final AgentLauncher launcher = this.selectLauncher(jobId, jobSubmission, resolvedJob);
tags.add(Tag.of(LAUNCHER_CLASS_TAG, launcher.getClass().getCanonicalName()));
launcherExt = launcher.launchAgent(resolvedJob, requestedLauncherExt);
} catch (final AgentLaunchException e) {
this.persistenceService.updateJobArchiveStatus(jobId, ArchiveStatus.NO_FILES);
this.updateJobStatus(jobId, JobStatus.ACCEPTED, JobStatus.FAILED, e.getMessage(), INITIAL_ATTEMPT);
// TODO: How will we get the ID back to the user? Should we add it to an exception? We don't get
// We don't get the ID until after saveJobSubmission so if that fails we'd still return nothing
// Probably need multiple exceptions to be thrown from this API (if we go with checked)
throw e;
}
span.annotate(LAUNCHED_AGENT_ANNOTATION);
if (launcherExt.isPresent()) {
try {
this.persistenceService.updateLauncherExt(jobId, launcherExt.get());
} catch (final Exception e) {
// Being unable to update the launcher ext is not optimal however
// it's not worth returning an error to the user at this point as
// the agent has launched and we have all the other pieces in place
log.error("Unable to update the launcher ext for job {}", jobId, e);
}
}
span.annotate(SAVED_LAUNCHER_EXT_ANNOTATION);
MetricsUtils.addSuccessTags(tags);
return jobId;
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw t;
} finally {
span.annotate(END_LAUNCH_JOB_ANNOTATION);
this.registry
.timer(LAUNCH_JOB_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
private AgentLauncher selectLauncher(
final String jobId,
final JobSubmission jobSubmission,
final ResolvedJob resolvedJob
) throws AgentLaunchException {
final Collection<AgentLauncher> availableLaunchers = this.agentLauncherSelector.getAgentLaunchers();
log.debug("Selecting agent launcher for job {} ({} available)", jobId, availableLaunchers.size());
final AgentLauncherSelectionContext context = new AgentLauncherSelectionContext(
jobId,
jobSubmission.getJobRequest(),
jobSubmission.getJobRequestMetadata(),
resolvedJob,
availableLaunchers
);
final Set<Tag> tags = Sets.newHashSet();
final long start = System.nanoTime();
tags.add(Tag.of(AVAILABLE_LAUNCHERS_TAG, String.valueOf(availableLaunchers.size())));
tags.add(Tag.of(SELECTOR_CLASS_TAG, this.agentLauncherSelector.getClass().getSimpleName()));
final ResourceSelectionResult<AgentLauncher> selectionResult;
try {
selectionResult = this.agentLauncherSelector.select(context);
final AgentLauncher selectedLauncher = selectionResult.getSelectedResource().orElseThrow(
() -> new ResourceSelectionException(
"No AgentLauncher selected: "
+ selectionResult.getSelectionRationale().orElse("Rationale unknown")
)
);
MetricsUtils.addSuccessTags(tags);
tags.add(Tag.of(LAUNCHER_CLASS_TAG, selectedLauncher.getClass().getSimpleName()));
log.debug("Selected launcher {} for job {}", selectedLauncher, jobId);
return selectedLauncher;
} catch (ResourceSelectionException e) {
log.error("Error selecting agent launcher", e);
MetricsUtils.addFailureTagsWithException(tags, e);
throw new AgentLaunchException("Failed to select an Agent Launcher", e);
} finally {
this.registry
.timer(AGENT_LAUNCHER_SELECTOR_TIMER, tags)
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
/**
* Helper method to update the job status ONLY IF the job is not in a final state already. This will maintain the
* final state that may have been set elsewhere by another process (e.g. kill request).
*
* @param jobId The id of the job to update status for
* @param desiredStatus The {@link JobStatus} that is the status the job should be in the database after
* exiting this method
* @param desiredStatusMessage The status message for the database
* @param attemptNumber The number of attempts that have been made to update this job status
* @return The {@link JobStatus} in the database after the final attempt of this method
*/
private JobStatus updateJobStatus(
final String jobId,
final JobStatus expectedStatus,
final JobStatus desiredStatus,
final String desiredStatusMessage,
final int attemptNumber
) throws NotFoundException {
final int nextAttemptNumber = attemptNumber + 1;
final JobStatus currentStatus = this.persistenceService.updateJobStatus(
jobId,
expectedStatus,
desiredStatus,
desiredStatusMessage
);
if (currentStatus.isFinished()) {
log.info(
"Won't change job status of {} from {} to {} desired status as {} is already a final status",
jobId,
currentStatus,
desiredStatus,
currentStatus
);
return currentStatus;
} else if (currentStatus == desiredStatus) {
log.debug("Successfully updated status of {} from {} to {}", jobId, expectedStatus, desiredStatus);
return currentStatus;
} else {
log.error(
"Job {} status changed from expected {} to {}. Couldn't update to {}. Attempt {}",
jobId,
expectedStatus,
currentStatus,
desiredStatus,
nextAttemptNumber
);
// Recursive call that should break out if update is successful or job is now in a final state
// or if attempts reach the max attempts
if (nextAttemptNumber < MAX_STATUS_UPDATE_ATTEMPTS) {
return this.updateJobStatus(
jobId,
currentStatus,
desiredStatus,
desiredStatusMessage,
nextAttemptNumber
);
} else {
// breakout condition, stop attempting to update DB
log.error(
"Out of attempts to update job {} status to {}. Unable to complete status update",
jobId,
desiredStatus
);
return currentStatus;
}
}
}
}
| 2,757 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/LocalFileSystemAttachmentServiceImpl.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.services.impl;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.netflix.genie.web.exceptions.checked.AttachmentTooLargeException;
import com.netflix.genie.web.exceptions.checked.SaveAttachmentException;
import com.netflix.genie.web.properties.AttachmentServiceProperties;
import com.netflix.genie.web.services.AttachmentService;
import org.springframework.core.io.Resource;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.UUID;
/**
* Implementation of {@link AttachmentService} that saves the files to a local directory.
* <p>
* N.B.: This implementation is currently used for integration tests and lacks some aspects that would make it usable in
* production environments (e.g., garbage collection of old files, metrics, etc.).
*
* @author mprimi
* @since 4.0.0
*/
public class LocalFileSystemAttachmentServiceImpl implements AttachmentService {
private final Path attachmentsDirectoryPath;
private final AttachmentServiceProperties attachmentServiceProperties;
/**
* Constructor.
*
* @param attachmentServiceProperties the service properties
* @throws IOException when failing to create the attachments directory
*/
public LocalFileSystemAttachmentServiceImpl(
final AttachmentServiceProperties attachmentServiceProperties
) throws IOException {
this.attachmentServiceProperties = attachmentServiceProperties;
this.attachmentsDirectoryPath = Paths.get(attachmentServiceProperties.getLocationPrefix());
// Create base attachments directory
Files.createDirectories(this.attachmentsDirectoryPath);
}
/**
* {@inheritDoc}
*/
@Override
public Set<URI> saveAttachments(
@Nullable final String jobId,
final Set<Resource> attachments
) throws SaveAttachmentException {
if (attachments.isEmpty()) {
return Sets.newHashSet();
}
final Path attachmentsBasePath = this.attachmentsDirectoryPath.resolve(UUID.randomUUID().toString());
try {
Files.createDirectories(attachmentsBasePath);
} catch (IOException e) {
throw new SaveAttachmentException("Failed to create directory for attachments: " + e.getMessage(), e);
}
long totalSize = 0;
final ImmutableSet.Builder<URI> setBuilder = ImmutableSet.builder();
for (final Resource attachment : attachments) {
try (InputStream inputStream = attachment.getInputStream()) {
final long attachmentSize = attachment.contentLength();
final String filename = attachment.getFilename();
if (attachmentSize > this.attachmentServiceProperties.getMaxSize().toBytes()) {
throw new AttachmentTooLargeException("Attachment is too large: " + filename);
}
totalSize += attachmentSize;
if (totalSize > this.attachmentServiceProperties.getMaxTotalSize().toBytes()) {
throw new AttachmentTooLargeException("Attachments total size is too large");
}
final Path attachmentPath = attachmentsBasePath.resolve(
filename != null ? filename : UUID.randomUUID().toString()
);
Files.copy(inputStream, attachmentPath);
setBuilder.add(attachmentPath.toUri());
} catch (IOException e) {
throw new SaveAttachmentException("Failed to save attachment: " + e.getMessage(), e);
}
}
return setBuilder.build();
}
}
| 2,758 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/ClusterLeaderServiceCuratorImpl.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.services.impl;
import com.netflix.genie.web.services.ClusterLeaderService;
import org.springframework.integration.zookeeper.leader.LeaderInitiator;
/**
* Implementation of {@link ClusterLeaderService} using Spring's {@link LeaderInitiator} (Zookeeper/Curator based
* leader election mechanism).
*
* @author mprimi
* @since 4.0.0
*/
public class ClusterLeaderServiceCuratorImpl implements ClusterLeaderService {
private LeaderInitiator leaderInitiator;
/**
* Constructor.
*
* @param leaderInitiator the leader initiator component
*/
public ClusterLeaderServiceCuratorImpl(final LeaderInitiator leaderInitiator) {
this.leaderInitiator = leaderInitiator;
}
/**
* {@inheritDoc}
*/
@Override
public void stop() {
this.leaderInitiator.stop();
}
/**
* {@inheritDoc}
*/
@Override
public void start() {
this.leaderInitiator.start();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRunning() {
return this.leaderInitiator.isRunning();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLeader() {
return this.leaderInitiator.getContext().isLeader();
}
}
| 2,759 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/ArchivedJobServiceImpl.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.services.impl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Sets;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.common.internal.dtos.DirectoryManifest;
import com.netflix.genie.common.internal.exceptions.unchecked.GenieRuntimeException;
import com.netflix.genie.common.internal.services.JobArchiveService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.data.services.PersistenceService;
import com.netflix.genie.web.dtos.ArchivedJobMetadata;
import com.netflix.genie.web.exceptions.checked.JobDirectoryManifestNotFoundException;
import com.netflix.genie.web.exceptions.checked.JobNotArchivedException;
import com.netflix.genie.web.exceptions.checked.JobNotFoundException;
import com.netflix.genie.web.exceptions.checked.NotFoundException;
import com.netflix.genie.web.services.ArchivedJobService;
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.cache.annotation.Cacheable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
/**
* Default implementation of {@link ArchivedJobService}.
*
* @author tgianos
* @since 4.0.0
*/
@Slf4j
public class ArchivedJobServiceImpl implements ArchivedJobService {
@VisibleForTesting
static final String GET_METADATA_NUM_RETRY_PROPERTY_NAME = "genie.retry.archived-job-get-metadata.noOfRetries";
private static final String GET_METADATA_INITIAL_DELAY_PROPERTY_NAME
= "genie.retry.archived-job-get-metadata.initialDelay";
private static final String GET_METADATA_MULTIPLIER_PROPERTY_NAME
= "genie.retry.archived-job-get-metadata.multiplier";
private static final String SLASH = "/";
private static final String GET_ARCHIVED_JOB_METADATA_METRIC_NAME
= "genie.web.services.archivedJobService.getArchivedJobMetadata.timer";
private final PersistenceService persistenceService;
private final ResourceLoader resourceLoader;
private final MeterRegistry meterRegistry;
/**
* Constructor.
*
* @param dataServices The {@link DataServices} instance to use
* @param resourceLoader The {@link ResourceLoader} used to get resources
* @param meterRegistry The {@link MeterRegistry} used to collect metrics
*/
public ArchivedJobServiceImpl(
final DataServices dataServices,
final ResourceLoader resourceLoader,
final MeterRegistry meterRegistry
) {
this.persistenceService = dataServices.getPersistenceService();
this.resourceLoader = resourceLoader;
this.meterRegistry = meterRegistry;
}
/**
* {@inheritDoc}
*/
@Override
@Cacheable(
cacheNames = {
"archivedJobMetadata"
},
sync = true
)
@Retryable(
maxAttemptsExpression = "#{${" + ArchivedJobServiceImpl.GET_METADATA_NUM_RETRY_PROPERTY_NAME + ":5}}",
include = {
JobDirectoryManifestNotFoundException.class
},
backoff = @Backoff(
delayExpression = "#{${" + ArchivedJobServiceImpl.GET_METADATA_INITIAL_DELAY_PROPERTY_NAME + ":1000}}",
multiplierExpression = "#{${" + ArchivedJobServiceImpl.GET_METADATA_MULTIPLIER_PROPERTY_NAME + ":2.0}}"
)
)
public ArchivedJobMetadata getArchivedJobMetadata(
final String jobId
) throws JobNotFoundException, JobNotArchivedException, JobDirectoryManifestNotFoundException {
final Instant startTime = Instant.now();
log.debug("Attempting to fetch archived job metadata for job {}", jobId);
final Set<Tag> tags = Sets.newHashSet();
try {
final String archiveLocation;
try {
archiveLocation = this.persistenceService
.getJobArchiveLocation(jobId)
.orElseThrow(() -> new JobNotArchivedException("Job " + jobId + " wasn't archived"));
} catch (final NotFoundException nfe) {
throw new JobNotFoundException(nfe);
}
final URI jobDirectoryRoot;
try {
jobDirectoryRoot = new URI(archiveLocation + SLASH).normalize();
} catch (final URISyntaxException e) {
throw new GenieRuntimeException("Unable to create URI from archive location: " + archiveLocation, e);
}
// TODO: This is pretty hardcoded and we may want to store direct link
// to manifest in database or something
final URI manifestLocation;
if (StringUtils.isBlank(JobArchiveService.MANIFEST_DIRECTORY)) {
manifestLocation = jobDirectoryRoot.resolve(JobArchiveService.MANIFEST_NAME).normalize();
} else {
manifestLocation = jobDirectoryRoot
.resolve(JobArchiveService.MANIFEST_DIRECTORY + SLASH)
.resolve(JobArchiveService.MANIFEST_NAME)
.normalize();
}
final Resource manifestResource = this.resourceLoader.getResource(manifestLocation.toString());
if (manifestResource == null || !manifestResource.exists()) {
throw new JobDirectoryManifestNotFoundException(
"No job directory manifest exists at " + manifestLocation
);
}
final DirectoryManifest manifest;
try (InputStream manifestData = manifestResource.getInputStream()) {
manifest = GenieObjectMapper
.getMapper()
.readValue(manifestData, DirectoryManifest.class);
} catch (final IOException e) {
throw new GenieRuntimeException("Unable to read job directory manifest from " + manifestLocation, e);
}
MetricsUtils.addSuccessTags(tags);
return new ArchivedJobMetadata(jobId, manifest, jobDirectoryRoot);
} catch (final Throwable t) {
MetricsUtils.addFailureTagsWithException(tags, t);
throw t;
} finally {
log.debug("Finished attempting to fetch archived job metadata for job {}", jobId);
this.meterRegistry
.timer(GET_ARCHIVED_JOB_METADATA_METRIC_NAME, tags)
.record(Duration.between(startTime, Instant.now()));
}
}
}
| 2,760 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/ClusterLeaderServiceLocalLeaderImpl.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.services.impl;
import com.netflix.genie.web.services.ClusterLeaderService;
import com.netflix.genie.web.tasks.leader.LocalLeader;
/**
* Implementation of {@link ClusterLeaderService} using statically configured {@link LocalLeader} module.
*
* @author mprimi
* @since 4.0.0
*/
public class ClusterLeaderServiceLocalLeaderImpl implements ClusterLeaderService {
private final LocalLeader localLeader;
/**
* Constructor.
*
* @param localLeader the local leader module
*/
public ClusterLeaderServiceLocalLeaderImpl(final LocalLeader localLeader) {
this.localLeader = localLeader;
}
/**
* {@inheritDoc}
*/
@Override
public void stop() {
this.localLeader.stop();
}
/**
* {@inheritDoc}
*/
@Override
public void start() {
this.localLeader.start();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRunning() {
return this.localLeader.isRunning();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLeader() {
return this.localLeader.isLeader();
}
}
| 2,761 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/services/impl/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.
*
*/
/**
* Implementations of services specific to a web application.
*
* @author tgianos
* @since 3.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.services.impl;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,762 |
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/spring/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Classes related to configuring a running Spring Boot application.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,763 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/processors/GenieDefaultPropertiesPostProcessor.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.processors;
import com.netflix.genie.common.internal.util.PropertySourceUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.util.Arrays;
/**
* Adds default properties to the Spring environment before application refresh.
*
* @author tgianos
* @since 4.0.0
*/
public class GenieDefaultPropertiesPostProcessor implements EnvironmentPostProcessor {
static final String DEFAULT_PROPERTY_SOURCE_NAME = "genie-web-defaults";
static final String DEFAULT_PROD_PROPERTY_SOURCE_NAME = "genie-web-prod-defaults";
private static final String DEFAULT_PROPERTIES_FILE = "genie-web-defaults.yml";
private static final String PROD_PROFILE = "prod";
private static final String DEFAULT_PROD_PROPERTIES_FILE = "genie-web-prod-defaults.yml";
/**
* {@inheritDoc}
*/
@Override
public void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application) {
final Resource defaultProperties = new ClassPathResource(DEFAULT_PROPERTIES_FILE);
final PropertySource<?> defaultSource
= PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROPERTY_SOURCE_NAME, defaultProperties);
environment.getPropertySources().addLast(defaultSource);
if (Arrays.asList(environment.getActiveProfiles()).contains(PROD_PROFILE)) {
final Resource defaultProdProperties = new ClassPathResource(DEFAULT_PROD_PROPERTIES_FILE);
final PropertySource<?> defaultProdSource
= PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROD_PROPERTY_SOURCE_NAME, defaultProdProperties);
environment.getPropertySources().addBefore(DEFAULT_PROPERTY_SOURCE_NAME, defaultProdSource);
}
}
}
| 2,764 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/processors/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Any environment post processors for Spring that are needed.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.processors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,765 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/actuators/LeaderElectionActuator.java | /*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.actuators;
import com.google.common.collect.ImmutableMap;
import com.netflix.genie.web.services.ClusterLeaderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import java.util.Map;
/**
* An actuator endpoint that exposes leadership status and allows stop/start/restart of the leader election service.
* Useful when a specific set of nodes should be given priority to win the leader election (e.g., because they are
* running newer code).
*
* @author mprimi
* @since 4.0.0
*/
@Endpoint(id = "leaderElection")
@Slf4j
public class LeaderElectionActuator {
private static final String RUNNING = "running";
private static final String LEADER = "leader";
private final ClusterLeaderService clusterLeaderService;
/**
* Constructor.
*
* @param clusterLeaderService the cluster leader service
*/
public LeaderElectionActuator(final ClusterLeaderService clusterLeaderService) {
this.clusterLeaderService = clusterLeaderService;
}
/**
* Provides the current leader service status: whether the leader service is running and whether the node is leader.
*
* @return a map of attributes
*/
@ReadOperation
public Map<String, Object> getStatus() {
return ImmutableMap.<String, Object>builder()
.put(RUNNING, this.clusterLeaderService.isRunning())
.put(LEADER, this.clusterLeaderService.isLeader())
.build();
}
/**
* Forces the node to leave the leader election, then re-join it.
*
* @param action the action to perform
*/
@WriteOperation
public void doAction(final Action action) {
switch (action) {
case START:
log.info("Starting leader election service");
this.clusterLeaderService.start();
break;
case STOP:
log.info("Stopping leader election service");
this.clusterLeaderService.stop();
break;
case RESTART:
log.info("Restarting leader election service");
this.clusterLeaderService.stop();
this.clusterLeaderService.start();
break;
default:
log.error("Unknown action: " + action);
throw new UnsupportedOperationException("Unknown action: " + action.name());
}
}
/**
* Operations that this actuator can perform on the leader service.
*/
public enum Action {
/**
* Stop the leader election service.
*/
STOP,
/**
* Start the leader election service.
*/
START,
/**
* Stop then start the leader election service.
*/
RESTART,
/**
* NOOP action for the purpose of testing unknown actions.
*/
TEST,
}
}
| 2,766 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/actuators/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.
*
*/
/**
* Actuator endpoints.
*
* @author mprimi
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.actuators;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,767 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/CachingAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
/**
* Auto configuration to enable Spring Boot Caching annotation support.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@AutoConfigureBefore(
{
CacheAutoConfiguration.class
}
)
@EnableCaching
public class CachingAutoConfiguration {
}
| 2,768 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/ValidationAutoConfiguration.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validator;
/**
* Configuration for bean validation within Genie.
*
* @author tgianos
* @since 3.0.0
*/
@Configuration
public class ValidationAutoConfiguration {
/**
* Setup bean validation.
*
* @return The bean validator
*/
@Bean
@ConditionalOnMissingBean(Validator.class)
public LocalValidatorFactoryBean localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
/**
* Setup method parameter bean validation.
*
* @return The method validation processor
*/
@Bean
@ConditionalOnMissingBean(MethodValidationPostProcessor.class)
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
| 2,769 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/ZookeeperAutoConfiguration.java | /*
*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import com.netflix.genie.web.agent.services.impl.AgentRoutingServiceCuratorDiscoveryImpl;
import com.netflix.genie.web.properties.ZookeeperProperties;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.zookeeper.config.LeaderInitiatorFactoryBean;
/**
* Auto configuration for Zookeper components.
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
ZookeeperProperties.class
}
)
@AutoConfigureAfter(
{
org.springframework.cloud.zookeeper.ZookeeperAutoConfiguration.class
}
)
@ConditionalOnBean(CuratorFramework.class)
public class ZookeeperAutoConfiguration {
/**
* The leadership initialization factory bean which will create a LeaderInitiator to kick off the leader election
* process within this node for the cluster if Zookeeper is configured.
*
* @param client The curator framework client to use
* @param zookeeperProperties The Zookeeper properties to use
* @return The factory bean
*/
@Bean
@ConditionalOnMissingBean(LeaderInitiatorFactoryBean.class)
public LeaderInitiatorFactoryBean leaderInitiatorFactory(
final CuratorFramework client,
final ZookeeperProperties zookeeperProperties
) {
final LeaderInitiatorFactoryBean factoryBean = new LeaderInitiatorFactoryBean();
factoryBean.setClient(client);
factoryBean.setPath(zookeeperProperties.getLeaderPath());
factoryBean.setRole("cluster");
return factoryBean;
}
/**
* The Curator-based Service Discovery bean.
*
* @param client The curator framework client to use
* @param zookeeperProperties The Zookeeper properties to use
* @return {@link ServiceDiscovery} bean for instances of type {@link AgentRoutingServiceCuratorDiscoveryImpl.Agent}
*/
@Bean
@ConditionalOnMissingBean(ServiceDiscovery.class)
ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery(
final CuratorFramework client,
final ZookeeperProperties zookeeperProperties
) {
return ServiceDiscoveryBuilder.builder(AgentRoutingServiceCuratorDiscoveryImpl.Agent.class)
.basePath(zookeeperProperties.getDiscoveryPath())
.client(client)
.build();
}
/**
* The Curator-client connection state listenable.
*
* @param client The curator framework client to use
* @return {@link ServiceDiscovery} bean for instances of type {@link AgentRoutingServiceCuratorDiscoveryImpl.Agent}
*/
@Bean
@ConditionalOnMissingBean(Listenable.class)
Listenable<ConnectionStateListener> listenableCuratorConnectionState(
final CuratorFramework client
) {
return client.getConnectionStateListenable();
}
}
| 2,770 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/RetryAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
/**
* Auto configuration which enables {@link org.springframework.retry.annotation.Retryable} for method calls on beans.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableRetry
public class RetryAutoConfiguration {
}
| 2,771 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/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.
*
*/
/**
* Various Spring configurations for Genie web.
*
* @author tgianos
* @since 3.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,772 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/TasksAutoConfiguration.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks;
import com.netflix.genie.web.properties.TasksExecutorPoolProperties;
import com.netflix.genie.web.properties.TasksSchedulerPoolProperties;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* Configuration of beans for asynchronous tasks within Genie.
*
* @author tgianos
* @since 3.0.0
*/
@Configuration
@EnableScheduling
@EnableConfigurationProperties(
{
TasksExecutorPoolProperties.class,
TasksSchedulerPoolProperties.class,
}
)
public class TasksAutoConfiguration {
/**
* Get an {@link Executor} to use for executing processes from tasks.
*
* @return The executor to use
*/
// TODO: Remove once agent job runs complete
@Bean
@ConditionalOnMissingBean(Executor.class)
public Executor processExecutor() {
final Executor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(null, null));
return executor;
}
/**
* Get a task scheduler.
*
* @param tasksSchedulerPoolProperties The properties regarding the thread pool to use for task scheduling
* @return The task scheduler
*/
@Bean
@ConditionalOnMissingBean(name = "genieTaskScheduler")
public ThreadPoolTaskScheduler genieTaskScheduler(
final TasksSchedulerPoolProperties tasksSchedulerPoolProperties
) {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(tasksSchedulerPoolProperties.getSize());
scheduler.setThreadNamePrefix(tasksSchedulerPoolProperties.getThreadNamePrefix());
return scheduler;
}
/**
* Get a task executor for executing tasks asynchronously that don't need to be scheduled at a recurring rate.
*
* @param tasksExecutorPoolProperties The properties for the task executor thread pool
* @return The task executor the system to use
*/
@Bean
@ConditionalOnMissingBean(name = "genieAsyncTaskExecutor")
public AsyncTaskExecutor genieAsyncTaskExecutor(final TasksExecutorPoolProperties tasksExecutorPoolProperties) {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(tasksExecutorPoolProperties.getSize());
executor.setThreadNamePrefix(tasksExecutorPoolProperties.getThreadNamePrefix());
return executor;
}
/**
* Synchronous task executor.
*
* @return The synchronous task executor to use
*/
@Bean
@ConditionalOnMissingBean(name = "genieSyncTaskExecutor")
public SyncTaskExecutor genieSyncTaskExecutor() {
return new SyncTaskExecutor();
}
}
| 2,773 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for tasks module of the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,774 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/leader/LeaderAutoConfiguration.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks.leader;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.events.GenieEventBus;
import com.netflix.genie.web.properties.AgentCleanupProperties;
import com.netflix.genie.web.properties.ArchiveStatusCleanupProperties;
import com.netflix.genie.web.properties.DatabaseCleanupProperties;
import com.netflix.genie.web.properties.LeadershipProperties;
import com.netflix.genie.web.properties.UserMetricsProperties;
import com.netflix.genie.web.services.ClusterLeaderService;
import com.netflix.genie.web.services.impl.ClusterLeaderServiceCuratorImpl;
import com.netflix.genie.web.services.impl.ClusterLeaderServiceLocalLeaderImpl;
import com.netflix.genie.web.spring.actuators.LeaderElectionActuator;
import com.netflix.genie.web.spring.autoconfigure.ZookeeperAutoConfiguration;
import com.netflix.genie.web.spring.autoconfigure.tasks.TasksAutoConfiguration;
import com.netflix.genie.web.tasks.leader.AgentJobCleanupTask;
import com.netflix.genie.web.tasks.leader.ArchiveStatusCleanupTask;
import com.netflix.genie.web.tasks.leader.DatabaseCleanupTask;
import com.netflix.genie.web.tasks.leader.LeaderTask;
import com.netflix.genie.web.tasks.leader.LeaderTasksCoordinator;
import com.netflix.genie.web.tasks.leader.LocalLeader;
import com.netflix.genie.web.tasks.leader.UserMetricsTask;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.integration.zookeeper.leader.LeaderInitiator;
import org.springframework.scheduling.TaskScheduler;
import java.util.Set;
/**
* Beans for Leadership of a Genie cluster.
*
* @author tgianos
* @since 3.1.0
*/
@Configuration
@EnableConfigurationProperties(
{
AgentCleanupProperties.class,
ArchiveStatusCleanupProperties.class,
DatabaseCleanupProperties.class,
LeadershipProperties.class,
UserMetricsProperties.class,
}
)
@AutoConfigureAfter(
{
TasksAutoConfiguration.class,
ZookeeperAutoConfiguration.class
}
)
public class LeaderAutoConfiguration {
/**
* Create the LeadershipTasksCoordination bean used to start and stop all leadership related tasks based on
* whether leadership is granted or revoked.
*
* @param taskScheduler The task scheduler to use for scheduling leadership tasks
* @param tasks The leadership tasks to schedule
* @return The leader coordinator
*/
@Bean
@ConditionalOnMissingBean(LeaderTasksCoordinator.class)
public LeaderTasksCoordinator leaderTasksCoordinator(
@Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
final Set<LeaderTask> tasks
) {
return new LeaderTasksCoordinator(taskScheduler, tasks);
}
/**
* Create a {@link DatabaseCleanupTask} if one is required.
*
* @param cleanupProperties The properties to use to configure this task
* @param environment The application {@link Environment} to pull properties from
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param registry The metrics registry
* @return The {@link DatabaseCleanupTask} instance to use if the conditions match
*/
@Bean
@ConditionalOnProperty(value = DatabaseCleanupProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(DatabaseCleanupTask.class)
public DatabaseCleanupTask databaseCleanupTask(
final DatabaseCleanupProperties cleanupProperties,
final Environment environment,
final DataServices dataServices,
final MeterRegistry registry
) {
return new DatabaseCleanupTask(
cleanupProperties,
environment,
dataServices,
registry
);
}
/**
* If required get a {@link UserMetricsTask} instance for use.
*
* @param registry The metrics registry
* @param dataServices The {@link DataServices} instance to use
* @param userMetricsProperties The properties
* @return The {@link UserMetricsTask} instance
*/
@Bean
@ConditionalOnProperty(value = UserMetricsProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(UserMetricsTask.class)
public UserMetricsTask userMetricsTask(
final MeterRegistry registry,
final DataServices dataServices,
final UserMetricsProperties userMetricsProperties
) {
return new UserMetricsTask(
registry,
dataServices,
userMetricsProperties
);
}
/**
* If required, get a {@link AgentJobCleanupTask} instance for use.
*
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param agentCleanupProperties the agent cleanup properties
* @param registry the metrics registry
* @param agentRoutingService the agent routing service
* @return a {@link AgentJobCleanupTask}
*/
@Bean
@ConditionalOnProperty(value = AgentCleanupProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(AgentJobCleanupTask.class)
public AgentJobCleanupTask agentJobCleanupTask(
final DataServices dataServices,
final AgentCleanupProperties agentCleanupProperties,
final MeterRegistry registry,
final AgentRoutingService agentRoutingService
) {
return new AgentJobCleanupTask(
dataServices,
agentCleanupProperties,
registry,
agentRoutingService
);
}
/**
* If required, get a {@link ArchiveStatusCleanupTask} instance for use.
*
* @param dataServices The {@link DataServices} encapsulation instance to use
* @param agentRoutingService the agent routing service
* @param archiveStatusCleanupProperties the archive status cleanup properties
* @param registry the metrics registry
* @return a {@link AgentJobCleanupTask}
*/
@Bean
@ConditionalOnProperty(value = ArchiveStatusCleanupProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(ArchiveStatusCleanupTask.class)
public ArchiveStatusCleanupTask archiveStatusCleanupTask(
final DataServices dataServices,
final AgentRoutingService agentRoutingService,
final ArchiveStatusCleanupProperties archiveStatusCleanupProperties,
final MeterRegistry registry
) {
return new ArchiveStatusCleanupTask(
dataServices,
agentRoutingService,
archiveStatusCleanupProperties,
registry
);
}
/**
* Create a {@link ClusterLeaderService} based on Zookeeper/Curator if {@link LeaderInitiator} is
* available and the bean does not already exist.
*
* @param leaderInitiator the Spring Zookeeper/Curator based leader election component
* @return a {@link ClusterLeaderService}
*/
@Bean
@ConditionalOnBean(LeaderInitiator.class)
@ConditionalOnMissingBean(ClusterLeaderService.class)
public ClusterLeaderService curatorClusterLeaderService(final LeaderInitiator leaderInitiator) {
return new ClusterLeaderServiceCuratorImpl(leaderInitiator);
}
/**
* If Zookeeper isn't available and this node is forced to be the leader create the local leader
* bean which will fire appropriate events.
*
* @param genieEventBus The genie event bus implementation to use
* @param leadershipProperties Properties related to static leadership configuration for the Genie cluster
* @return The local leader bean
*/
@Bean
@ConditionalOnMissingBean(
{
LeaderInitiator.class,
LocalLeader.class
}
)
public LocalLeader localLeader(
final GenieEventBus genieEventBus,
final LeadershipProperties leadershipProperties
) {
return new LocalLeader(genieEventBus, leadershipProperties.isEnabled());
}
/**
* Create a {@link ClusterLeaderService} based on static configuration if {@link LocalLeader} is
* available and the bean does not already exist.
*
* @param localLeader the configuration-based leader election component
* @return a {@link ClusterLeaderService}
*/
@Bean
@ConditionalOnBean(LocalLeader.class)
@ConditionalOnMissingBean(ClusterLeaderService.class)
public ClusterLeaderService localClusterLeaderService(final LocalLeader localLeader) {
return new ClusterLeaderServiceLocalLeaderImpl(localLeader);
}
/**
* Create a {@link LeaderElectionActuator} bean if one is not already defined and if
* {@link ClusterLeaderService} is available. This bean is an endpoint that gets registered in Spring Actuator.
*
* @param clusterLeaderService the cluster leader service
* @return a {@link LeaderElectionActuator}
*/
@Bean
@ConditionalOnBean(ClusterLeaderService.class)
@ConditionalOnMissingBean(LeaderElectionActuator.class)
public LeaderElectionActuator leaderElectionActuator(final ClusterLeaderService clusterLeaderService) {
return new LeaderElectionActuator(clusterLeaderService);
}
}
| 2,775 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/leader/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for the leader tasks module of the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks.leader;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,776 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/node/NodeAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.tasks.node;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.properties.DiskCleanupProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.tasks.node.DiskCleanupTask;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.commons.exec.Executor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.TaskScheduler;
import java.io.IOException;
/**
* Auto configuration for tasks that run on every Genie server node.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
DiskCleanupProperties.class,
}
)
public class NodeAutoConfiguration {
/**
* If required get a {@link DiskCleanupTask} instance for use.
*
* @param properties The disk cleanup properties to use.
* @param scheduler The scheduler to use to schedule the cron trigger.
* @param jobsDir The resource representing the location of the job directory
* @param dataServices The {@link DataServices} instance to use
* @param jobsProperties The jobs properties to use
* @param processExecutor The process executor to use to delete directories
* @param registry The metrics registry
* @return The {@link DiskCleanupTask} instance
* @throws IOException When it is unable to open a file reference to the job directory
*/
@Bean
@ConditionalOnProperty(value = DiskCleanupProperties.ENABLED_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(DiskCleanupTask.class)
public DiskCleanupTask diskCleanupTask(
final DiskCleanupProperties properties,
@Qualifier("genieTaskScheduler") final TaskScheduler scheduler,
@Qualifier("jobsDir") final Resource jobsDir,
final DataServices dataServices,
final JobsProperties jobsProperties,
final Executor processExecutor,
final MeterRegistry registry
) throws IOException {
return new DiskCleanupTask(
properties,
scheduler,
jobsDir,
dataServices,
jobsProperties,
processExecutor,
registry
);
}
}
| 2,777 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/tasks/node/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for the node tasks module of the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.tasks.node;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,778 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/ApisAutoConfiguration.java | /*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.apis;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import com.netflix.genie.web.properties.HttpProperties;
import com.netflix.genie.web.properties.JobsProperties;
import com.netflix.genie.web.properties.RetryProperties;
import com.netflix.genie.web.resources.writers.DefaultDirectoryWriter;
import com.netflix.genie.web.resources.writers.DirectoryWriter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.filter.CharacterEncodingFilter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
/**
* Configuration for external API tier.
*
* @author tgianos
* @since 3.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
HttpProperties.class,
RetryProperties.class
}
)
public class ApisAutoConfiguration {
/**
* Get a resource loader.
*
* @return a DefaultResourceLoader
*/
@Bean
@ConditionalOnMissingBean(ResourceLoader.class)
public ResourceLoader resourceLoader() {
return new DefaultResourceLoader();
}
/**
* Get RestTemplate for calling between Genie nodes.
*
* @param httpProperties The properties related to Genie's HTTP client configuration
* @param restTemplateBuilder The Spring REST template builder to use
* @return The rest template to use
*/
@Bean
@ConditionalOnMissingBean(name = "genieRestTemplate")
public RestTemplate genieRestTemplate(
final HttpProperties httpProperties,
final RestTemplateBuilder restTemplateBuilder
) {
return restTemplateBuilder
.setConnectTimeout(Duration.of(httpProperties.getConnect().getTimeout(), ChronoUnit.MILLIS))
.setReadTimeout(Duration.of(httpProperties.getRead().getTimeout(), ChronoUnit.MILLIS))
.build();
}
/**
* Get RetryTemplate.
*
* @param retryProperties The http retry properties to use
* @return The retry template to use
*/
@Bean
@ConditionalOnMissingBean(name = "genieRetryTemplate")
public RetryTemplate genieRetryTemplate(final RetryProperties retryProperties) {
final RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(
new SimpleRetryPolicy(
retryProperties.getNoOfRetries(),
Collections.singletonMap(Exception.class, true)
)
);
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(retryProperties.getInitialInterval());
backOffPolicy.setMaxInterval(retryProperties.getMaxInterval());
retryTemplate.setBackOffPolicy(backOffPolicy);
return retryTemplate;
}
/**
* Get the directory writer to use.
*
* @return A default directory writer
*/
@Bean
@ConditionalOnMissingBean(DirectoryWriter.class)
public DefaultDirectoryWriter directoryWriter() {
return new DefaultDirectoryWriter();
}
/**
* Get the jobs dir as a Spring Resource. Will create if it doesn't exist.
*
* @param resourceLoader The resource loader to use
* @param jobsProperties The jobs properties to use
* @return The job dir as a resource
* @throws IOException on error reading or creating the directory
*/
@Bean
@ConditionalOnMissingBean(name = "jobsDir", value = Resource.class)
public Resource jobsDir(
final ResourceLoader resourceLoader,
final JobsProperties jobsProperties
) throws IOException {
final String jobsDirLocation = jobsProperties.getLocations().getJobs().toString();
final Resource tmpJobsDirResource = resourceLoader.getResource(jobsDirLocation);
if (tmpJobsDirResource.exists() && !tmpJobsDirResource.getFile().isDirectory()) {
throw new IllegalStateException(jobsDirLocation + " exists but isn't a directory. Unable to continue");
}
// We want the resource to end in a slash for use later in the generation of URL's
final String slash = "/";
String localJobsDir = jobsDirLocation;
if (!jobsDirLocation.endsWith(slash)) {
localJobsDir = localJobsDir + slash;
}
final Resource jobsDirResource = resourceLoader.getResource(localJobsDir);
if (!jobsDirResource.exists()) {
final File file = jobsDirResource.getFile();
if (!file.mkdirs()) {
throw new IllegalStateException(
"Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist."
);
}
}
return jobsDirResource;
}
/**
* Character encoding filter that forces content-type in response to be UTF-8.
*
* @return The encoding filter
*/
@Bean
public CharacterEncodingFilter characterEncodingFilter() {
final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.name());
// This effectively obliterates any upstream default and/or encoding detectors
// As a result, everything is served as UTF-8
characterEncodingFilter.setForceEncoding(true);
return characterEncodingFilter;
}
/**
* Customizer for {@link com.fasterxml.jackson.databind.ObjectMapper} used by controllers.
*
* @return an {@link Jackson2ObjectMapperBuilderCustomizer}
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer() {
return builder -> {
// Register the same PropertyFilters that are registered in the static GenieObjectMapper
builder.filters(GenieObjectMapper.FILTER_PROVIDER);
};
}
}
| 2,779 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configurations for the {@literal apis} package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.apis;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,780 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3/hateoas/HateoasAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.apis.rest.v3.hateoas;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ApplicationModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.ClusterModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.CommandModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.EntityModelAssemblers;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobExecutionModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobMetadataModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobRequestModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.JobSearchResultModelAssembler;
import com.netflix.genie.web.apis.rest.v3.hateoas.assemblers.RootModelAssembler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring auto configuration for HATEOAS module beans.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class HateoasAutoConfiguration {
/**
* Provide a resource assembler for application resources if none already exists.
*
* @return A {@link ApplicationModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(ApplicationModelAssembler.class)
public ApplicationModelAssembler applicationResourceAssembler() {
return new ApplicationModelAssembler();
}
/**
* Provide a resource assembler for cluster resources if none already exists.
*
* @return A {@link ClusterModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(ClusterModelAssembler.class)
public ClusterModelAssembler clusterResourceAssembler() {
return new ClusterModelAssembler();
}
/**
* Provide a resource assembler for command resources if none already exists.
*
* @return A {@link CommandModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(CommandModelAssembler.class)
public CommandModelAssembler commandResourceAssembler() {
return new CommandModelAssembler();
}
/**
* Provide a resource assembler for job execution resources if none already exists.
*
* @return A {@link JobExecutionModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(JobExecutionModelAssembler.class)
public JobExecutionModelAssembler jobExecutionResourceAssembler() {
return new JobExecutionModelAssembler();
}
/**
* Provide a resource assembler for job metadata resources if none already exists.
*
* @return A {@link JobMetadataModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(JobMetadataModelAssembler.class)
public JobMetadataModelAssembler jobMetadataResourceAssembler() {
return new JobMetadataModelAssembler();
}
/**
* Provide a resource assembler for job request resources if none already exists.
*
* @return A {@link JobRequestModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(JobRequestModelAssembler.class)
public JobRequestModelAssembler jobRequestResourceAssembler() {
return new JobRequestModelAssembler();
}
/**
* Provide a resource assembler for job resources if none already exists.
*
* @return A {@link JobModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(JobModelAssembler.class)
public JobModelAssembler jobResourceAssembler() {
return new JobModelAssembler();
}
/**
* Provide a resource assembler for job search result resources if none already exists.
*
* @return A {@link JobSearchResultModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(JobSearchResultModelAssembler.class)
public JobSearchResultModelAssembler jobSearchResultResourceAssembler() {
return new JobSearchResultModelAssembler();
}
/**
* Provide a resource assembler for the api root resource if none already exists.
*
* @return A {@link RootModelAssembler} instance
*/
@Bean
@ConditionalOnMissingBean(RootModelAssembler.class)
public RootModelAssembler rootResourceAssembler() {
return new RootModelAssembler();
}
/**
* An encapsulation of all the V3 resource assemblers.
*
* @param applicationModelAssembler The application assembler
* @param clusterModelAssembler The cluster assembler
* @param commandModelAssembler The command assembler
* @param jobExecutionModelAssembler The job execution assembler
* @param jobMetadataModelAssembler The job metadata assembler
* @param jobRequestModelAssembler The job request assembler
* @param jobModelAssembler The job assembler
* @param jobSearchResultModelAssembler The job search result assembler
* @param rootModelAssembler The root assembler
* @return A {@link EntityModelAssemblers} instance
*/
@Bean
@ConditionalOnMissingBean(EntityModelAssemblers.class)
public EntityModelAssemblers resourceAssemblers(
final ApplicationModelAssembler applicationModelAssembler,
final ClusterModelAssembler clusterModelAssembler,
final CommandModelAssembler commandModelAssembler,
final JobExecutionModelAssembler jobExecutionModelAssembler,
final JobMetadataModelAssembler jobMetadataModelAssembler,
final JobRequestModelAssembler jobRequestModelAssembler,
final JobModelAssembler jobModelAssembler,
final JobSearchResultModelAssembler jobSearchResultModelAssembler,
final RootModelAssembler rootModelAssembler
) {
return new EntityModelAssemblers(
applicationModelAssembler,
clusterModelAssembler,
commandModelAssembler,
jobExecutionModelAssembler,
jobMetadataModelAssembler,
jobRequestModelAssembler,
jobModelAssembler,
jobSearchResultModelAssembler,
rootModelAssembler
);
}
}
| 2,781 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/apis/rest/v3/hateoas/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configurations for the {@literal hateoas} package for the V3 REST API.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.apis.rest.v3.hateoas;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,782 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/health/HealthAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.health;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.health.GenieAgentHealthIndicator;
import com.netflix.genie.web.properties.HealthProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Auto configuration for Health indicators related to Genie.
*
* @author tgianos
* @see com.netflix.genie.web.health
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
HealthProperties.class
}
)
public class HealthAutoConfiguration {
/**
* Provide a health indicator tied to agent related information if one hasn't already been provided elsewhere.
*
* @param agentConnectionTrackingService the agent connection tracking service
* @return An instance of {@link GenieAgentHealthIndicator}
*/
@Bean
@ConditionalOnMissingBean(GenieAgentHealthIndicator.class)
public GenieAgentHealthIndicator genieAgentHealthIndicator(
final AgentConnectionTrackingService agentConnectionTrackingService
) {
return new GenieAgentHealthIndicator(agentConnectionTrackingService);
}
}
| 2,783 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/health/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for health module of to the Genie server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.health;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,784 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configurations for the {@literal agent} package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,785 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/interceptors/AgentRpcInterceptorsAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.interceptors;
import com.netflix.genie.web.agent.apis.rpc.v4.interceptors.SimpleLoggingInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* Spring Auto Configuration for default {@link io.grpc.ServerInterceptor} implementations for the Genie gRPC services.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class AgentRpcInterceptorsAutoConfiguration {
/**
* An interceptor which writes requests to the logs.
*
* @return Instance of {@link SimpleLoggingInterceptor}
*/
@Bean
@ConditionalOnMissingBean(SimpleLoggingInterceptor.class)
@Order // Defaults to lowest precedence when stored in a list
public SimpleLoggingInterceptor simpleLoggingInterceptor() {
return new SimpleLoggingInterceptor();
}
}
| 2,786 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/interceptors/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration of V4 gRPC interceptors for the agent to connect to.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.interceptors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,787 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/endpoints/AgentRpcEndpointsAutoConfiguration.java | /*
*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.endpoints;
import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter;
import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.proto.FileStreamServiceGrpc;
import com.netflix.genie.proto.HeartBeatServiceGrpc;
import com.netflix.genie.proto.JobKillServiceGrpc;
import com.netflix.genie.proto.JobServiceGrpc;
import com.netflix.genie.proto.PingServiceGrpc;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcAgentFileStreamServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcHeartBeatServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcJobKillServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcJobServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.GRpcPingServiceImpl;
import com.netflix.genie.web.agent.apis.rpc.v4.endpoints.JobServiceProtoErrorComposer;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.agent.services.AgentJobService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.properties.AgentFileStreamProperties;
import com.netflix.genie.web.properties.HeartBeatProperties;
import com.netflix.genie.web.services.RequestForwardingService;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* Configures various gRPC services and related beans if gRPC functionality is enabled.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@Slf4j
@EnableConfigurationProperties(
{
AgentFileStreamProperties.class,
HeartBeatProperties.class,
}
)
public class AgentRpcEndpointsAutoConfiguration {
private static final int SINGLE_THREAD = 1;
/**
* Get the task scheduler used by the HeartBeat Service.
*
* @return The task scheduler
*/
@Bean
@ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler")
public TaskScheduler heartBeatServiceTaskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(SINGLE_THREAD);
return scheduler;
}
/**
* Bean for converting errors in the job service to gRPC messages.
*
* @return An instance of {@link JobServiceProtoErrorComposer}
*/
@Bean
@ConditionalOnMissingBean(JobServiceProtoErrorComposer.class)
public JobServiceProtoErrorComposer jobServiceProtoErrorComposer() {
return new JobServiceProtoErrorComposer();
}
/**
* Provide an implementation of {@link com.netflix.genie.proto.FileStreamServiceGrpc.FileStreamServiceImplBase}
* if no other is provided.
*
* @param converter The {@link JobDirectoryManifestProtoConverter} instance to use
* @param taskScheduler The {@link TaskScheduler} to use to schedule tasks
* @param properties The service properties
* @param registry The meter registry
* @return An instance of {@link GRpcAgentFileStreamServiceImpl}
*/
@Bean
@ConditionalOnMissingBean(FileStreamServiceGrpc.FileStreamServiceImplBase.class)
public GRpcAgentFileStreamServiceImpl gRpcAgentFileStreamService(
final JobDirectoryManifestProtoConverter converter,
@Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
final AgentFileStreamProperties properties,
final MeterRegistry registry
) {
return new GRpcAgentFileStreamServiceImpl(converter, taskScheduler, properties, registry);
}
/**
* Provide an implementation of {@link com.netflix.genie.proto.HeartBeatServiceGrpc.HeartBeatServiceImplBase}
* if no other is provided.
*
* @param agentConnectionTrackingService The {@link AgentConnectionTrackingService} implementation to use
* @param properties The service properties
* @param taskScheduler The {@link TaskScheduler} instance to use
* @param registry The meter registry
* @return A {@link GRpcHeartBeatServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(HeartBeatServiceGrpc.HeartBeatServiceImplBase.class)
public GRpcHeartBeatServiceImpl gRpcHeartBeatService(
final AgentConnectionTrackingService agentConnectionTrackingService,
final HeartBeatProperties properties,
@Qualifier("heartBeatServiceTaskScheduler") final TaskScheduler taskScheduler,
final MeterRegistry registry
) {
return new GRpcHeartBeatServiceImpl(agentConnectionTrackingService, properties, taskScheduler, registry);
}
/**
* Provide an implementation of {@link com.netflix.genie.proto.JobKillServiceGrpc.JobKillServiceImplBase}
* if no other is provided.
*
* @param dataServices The {@link DataServices} instance to use
* @param agentRoutingService The {@link AgentRoutingService} instance to use to find where agents are
* connected
* @param requestForwardingService The {@link RequestForwardingService} implementation to use to forward requests to
* other Genie nodes
* @return A {@link GRpcJobKillServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(JobKillServiceGrpc.JobKillServiceImplBase.class)
public GRpcJobKillServiceImpl gRpcJobKillService(
final DataServices dataServices,
final AgentRoutingService agentRoutingService,
final RequestForwardingService requestForwardingService
) {
return new GRpcJobKillServiceImpl(dataServices, agentRoutingService, requestForwardingService);
}
/**
* Provide an implementation of {@link com.netflix.genie.proto.JobServiceGrpc.JobServiceImplBase} if no other is
* provided.
*
* @param agentJobService The {@link AgentJobService} instance to use
* @param jobServiceProtoConverter The {@link JobServiceProtoConverter} instance to use
* @param protoErrorComposer The {@link JobServiceProtoErrorComposer} instance to use
* @param meterRegistry The meter registry
* @return A {@link GRpcJobServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(JobServiceGrpc.JobServiceImplBase.class)
public GRpcJobServiceImpl gRpcJobService(
final AgentJobService agentJobService,
final JobServiceProtoConverter jobServiceProtoConverter,
final JobServiceProtoErrorComposer protoErrorComposer,
final MeterRegistry meterRegistry
) {
return new GRpcJobServiceImpl(agentJobService, jobServiceProtoConverter, protoErrorComposer, meterRegistry);
}
/**
* Provide an implementation of {@link com.netflix.genie.proto.PingServiceGrpc.PingServiceImplBase} if no
* other is provided.
*
* @param genieHostInfo The information about the Genie host
* @return Instance of {@link GRpcPingServiceImpl}
*/
@Bean
@ConditionalOnMissingBean(PingServiceGrpc.PingServiceImplBase.class)
public GRpcPingServiceImpl gRpcPingService(final GenieHostInfo genieHostInfo) {
return new GRpcPingServiceImpl(genieHostInfo);
}
}
| 2,788 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/v4/endpoints/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration of V4 gRPC endpoints for the agent to connect to.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.v4.endpoints;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,789 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/servers/AgentRpcServersAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.servers;
import brave.Tracing;
import brave.grpc.GrpcTracing;
import com.netflix.genie.web.agent.apis.rpc.servers.GRpcServerManager;
import com.netflix.genie.web.properties.GRpcServerProperties;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.netty.NettyServerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Controls whether a gRPC server is configured and started for this Genie node or not.
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
GRpcServerProperties.class,
}
)
@AutoConfigureAfter(
name = {
"com.netflix.springboot.grpc.server.GrpcServerAutoConfiguration"
}
)
@Slf4j
public class AgentRpcServersAutoConfiguration {
/**
* Create a {@link Server} if one isn't already present in the context.
*
* @param port The port this server should listen on
* @param services The gRPC services this server should serve
* @param serverInterceptors The {@link ServerInterceptor} implementations that should be applied to all services
* @param tracing The Brave {@link Tracing} instance to use
* @return A Netty server instance based on the provided information
*/
@Bean
@ConditionalOnMissingBean(Server.class)
public Server gRpcServer(
@Value("${grpc.server.port:0}") final int port, // TODO: finalize how to get configure this property
final Set<BindableService> services,
final List<ServerInterceptor> serverInterceptors,
final Tracing tracing
) {
final NettyServerBuilder builder = NettyServerBuilder.forPort(port);
final List<ServerInterceptor> finalServerInterceptors = new ArrayList<>(serverInterceptors);
finalServerInterceptors.add(GrpcTracing.create(tracing).newServerInterceptor());
// Add Service interceptors and add services to the server
services
.stream()
.map(BindableService::bindService)
.map(serviceDefinition -> ServerInterceptors.intercept(serviceDefinition, finalServerInterceptors))
.forEach(builder::addService);
return builder.build();
}
/**
* Create a {@link GRpcServerManager} instance to manage the lifecycle of the gRPC server if one isn't already
* defined.
*
* @param server The {@link Server} instance to manage
* @return A {@link GRpcServerManager} instance
*/
@Bean
@ConditionalOnMissingBean(GRpcServerManager.class)
public GRpcServerManager gRpcServerManager(final Server server) {
return new GRpcServerManager(server);
}
}
| 2,790 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/apis/rpc/servers/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for the RPC server used for the agent on the web server.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.apis.rpc.servers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,791 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/resources/AgentResourcesAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.resources;
import com.netflix.genie.web.agent.resources.AgentFileProtocolResolver;
import com.netflix.genie.web.agent.resources.AgentFileProtocolResolverRegistrar;
import com.netflix.genie.web.agent.services.AgentFileStreamService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Auto Configuration for {@link org.springframework.core.io.Resource} classes exposed in the Agent module.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
public class AgentResourcesAutoConfiguration {
/**
* Protocol resolver agent file resources.
*
* @param agentFileStreamService the agent file stream service
* @return a {@link AgentFileProtocolResolver}
*/
@Bean
@ConditionalOnMissingBean(AgentFileProtocolResolver.class)
public AgentFileProtocolResolver agentFileProtocolResolver(
final AgentFileStreamService agentFileStreamService
) {
return new AgentFileProtocolResolver(agentFileStreamService);
}
/**
* Registrar for the {@link AgentFileProtocolResolver}.
*
* @param agentFileProtocolResolver a protocol {@link AgentFileProtocolResolver} to register
* @return a {@link AgentFileProtocolResolverRegistrar}
*/
@Bean
@ConditionalOnMissingBean(AgentFileProtocolResolverRegistrar.class)
public AgentFileProtocolResolverRegistrar agentFileProtocolResolverRegistrar(
final AgentFileProtocolResolver agentFileProtocolResolver
) {
return new AgentFileProtocolResolverRegistrar(agentFileProtocolResolver);
}
}
| 2,792 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/resources/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configurations for the {@literal agent} module {@literal resources} package.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.resources;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,793 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/launchers/AgentLaunchersAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.launchers;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.web.agent.launchers.AgentLauncher;
import com.netflix.genie.web.agent.launchers.impl.LocalAgentLauncherImpl;
import com.netflix.genie.web.agent.launchers.impl.TitusAgentLauncherImpl;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.introspection.GenieWebHostInfo;
import com.netflix.genie.web.introspection.GenieWebRpcInfo;
import com.netflix.genie.web.properties.LocalAgentLauncherProperties;
import com.netflix.genie.web.properties.TitusAgentLauncherProperties;
import com.netflix.genie.web.util.ExecutorFactory;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.client.RestTemplate;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
/**
* Auto configuration for beans responsible for launching Genie Agent instances.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
LocalAgentLauncherProperties.class,
TitusAgentLauncherProperties.class
}
)
@AutoConfigureAfter(
{
RestTemplateAutoConfiguration.class
}
)
public class AgentLaunchersAutoConfiguration {
/**
* Provide a {@link RestTemplate} instance used for calling the Titus REST API if no other instance is provided.
*
* @param restTemplateBuilder The Spring {@link RestTemplateBuilder} instance to use
* @return The rest template to use
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(name = "titusRestTemplate")
public RestTemplate titusRestTemplate(final RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
/**
* Provides a default implementation of {@link TitusAgentLauncherImpl.TitusJobRequestAdapter} that is a no-op
* if no other implementation has been provided elsewhere.
*
* @return A no-op implementation
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(TitusAgentLauncherImpl.TitusJobRequestAdapter.class)
public TitusAgentLauncherImpl.TitusJobRequestAdapter titusJobRequestAdapter() {
// No-Op default implementation
return new TitusAgentLauncherImpl.TitusJobRequestAdapter() {
};
}
/**
* Provides a default implementation of {@link org.springframework.retry.RetryPolicy} that retries based on a set
* of HTTP status codes. Currently just {@link org.springframework.http.HttpStatus#SERVICE_UNAVAILABLE} and
* {@link org.springframework.http.HttpStatus#REQUEST_TIMEOUT}. Max retries set to 3.
*
* @return A {@link TitusAgentLauncherImpl.TitusAPIRetryPolicy} instance with the default settings applied
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(name = "titusAPIRetryPolicy", value = RetryPolicy.class)
public TitusAgentLauncherImpl.TitusAPIRetryPolicy titusAPIRetryPolicy() {
return new TitusAgentLauncherImpl.TitusAPIRetryPolicy(
EnumSet.of(HttpStatus.SERVICE_UNAVAILABLE, HttpStatus.REQUEST_TIMEOUT),
3
);
}
/**
* Provides a default implementation of {@link org.springframework.retry.backoff.BackOffPolicy} if no other has
* been defined in the context.
*
* @return A default {@link ExponentialBackOffPolicy} instance
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(name = "titusAPIBackoffPolicy", value = BackOffPolicy.class)
public ExponentialBackOffPolicy titusAPIBackoffPolicy() {
return new ExponentialBackOffPolicy();
}
/**
* Provides a default implementation of {@link RetryTemplate} that will be used to retry failed Titus api calls
* based on the retry policy and backoff policies defined in the application context.
*
* @param retryPolicy The {@link RetryPolicy} to use for Titus API call failures
* @param backOffPolicy The {@link BackOffPolicy} to use for Titus API call failures
* @return A {@link RetryTemplate} instance configured with the supplied retry and backoff policies
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
@ConditionalOnMissingBean(name = "titusAPIRetryTemplate", value = RetryTemplate.class)
public RetryTemplate titusAPIRetryTemplate(
@Qualifier("titusAPIRetryPolicy") final RetryPolicy retryPolicy,
@Qualifier("titusAPIBackoffPolicy") final BackOffPolicy backOffPolicy
) {
final RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);
return retryTemplate;
}
/**
* Provide a {@link TitusAgentLauncherImpl} implementation which launches agent processes in a dedicated Titus
* container if enabled via property.
*
* @param restTemplate the rest template
* @param retryTemplate The {@link RetryTemplate} instance to use to retry failed Titus API calls
* @param titusJobRequestAdapter The {@link TitusAgentLauncherImpl.TitusJobRequestAdapter} implementation to
* use
* @param genieHostInfo the metadata about the local server and host
* @param titusAgentLauncherProperties the configuration properties
* @param tracingComponents The {@link BraveTracingComponents} instance to use
* @param environment The application {@link Environment} used to pull dynamic properties after
* launch
* @param registry the metric registry
* @return a {@link TitusAgentLauncherImpl}
*/
@Bean
@ConditionalOnProperty(name = TitusAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
public TitusAgentLauncherImpl titusAgentLauncher(
@Qualifier("titusRestTemplate") final RestTemplate restTemplate,
@Qualifier("titusAPIRetryTemplate") final RetryTemplate retryTemplate,
final TitusAgentLauncherImpl.TitusJobRequestAdapter titusJobRequestAdapter,
final GenieHostInfo genieHostInfo,
final TitusAgentLauncherProperties titusAgentLauncherProperties,
final BraveTracingComponents tracingComponents,
final Environment environment,
final MeterRegistry registry
) {
final Cache<String, String> healthIndicatorCache = Caffeine.newBuilder()
.maximumSize(titusAgentLauncherProperties.getHealthIndicatorMaxSize())
.expireAfterWrite(
titusAgentLauncherProperties.getHealthIndicatorExpiration().getSeconds(),
TimeUnit.SECONDS
)
.build();
return new TitusAgentLauncherImpl(
restTemplate,
retryTemplate,
titusJobRequestAdapter,
healthIndicatorCache,
genieHostInfo,
titusAgentLauncherProperties,
tracingComponents,
environment,
registry
);
}
/**
* Provide an {@link ExecutorFactory} instance if no other was defined.
*
* @return Instance of {@link ExecutorFactory}
*/
@Bean
@ConditionalOnMissingBean(ExecutorFactory.class)
public ExecutorFactory processExecutorFactory() {
return new ExecutorFactory();
}
/**
* Provide a {@link AgentLauncher} implementation which launches local agent processes if enabled via property.
*
* @param genieWebHostInfo The {@link GenieWebHostInfo} of this instance
* @param genieWebRpcInfo The {@link GenieWebRpcInfo} of this instance
* @param dataServices The {@link DataServices} instance to use
* @param launcherProperties The properties related to launching an agent locally
* @param executorFactory The {@link ExecutorFactory} to use to launch agent processes
* @param tracingComponents The {@link BraveTracingComponents} instance to use
* @param registry The {@link MeterRegistry} to register metrics
* @return A {@link LocalAgentLauncherImpl} instance
*/
@Bean
@ConditionalOnProperty(name = LocalAgentLauncherProperties.ENABLE_PROPERTY, havingValue = "true")
public LocalAgentLauncherImpl localAgentLauncher(
final GenieWebHostInfo genieWebHostInfo,
final GenieWebRpcInfo genieWebRpcInfo,
final DataServices dataServices,
final LocalAgentLauncherProperties launcherProperties,
final ExecutorFactory executorFactory,
final BraveTracingComponents tracingComponents,
final MeterRegistry registry
) {
return new LocalAgentLauncherImpl(
genieWebHostInfo,
genieWebRpcInfo,
dataServices,
launcherProperties,
executorFactory,
tracingComponents,
registry
);
}
}
| 2,794 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/launchers/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for the {@literal launchers} package of the {@literal agent} module.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.launchers;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,795 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/inspectors/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Auto configuration for the {@literal inspectors} package for the {@literal agent} module.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.inspectors;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,796 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/inspectors/AgentInspectorsAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.inspectors;
import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.BlacklistedVersionAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.MinimumVersionAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.RejectAllJobsAgentMetadataInspector;
import com.netflix.genie.web.agent.inspectors.impl.WhitelistedVersionAgentMetadataInspector;
import com.netflix.genie.web.properties.AgentFilterProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Auto-configuration for the default implementations of {@link AgentMetadataInspector}s.
* <p>
* This configuration creates a set of pre-configured {@link AgentMetadataInspector} that the
* service loads and uses:
* - Version whitelist: accept agent only if version matches a given pattern
* - Version blacklist: reject agent if version matches a given pattern
* - Minimum version: reject agent whose version is lower than a given version
*
* @author mprimi
* @since 4.0.0
*/
@Configuration
@ConditionalOnProperty(value = AgentFilterProperties.VERSION_FILTER_ENABLED_PROPERTY, havingValue = "true")
@EnableConfigurationProperties(
{
AgentFilterProperties.class,
}
)
public class AgentInspectorsAutoConfiguration {
/**
* A {@link AgentMetadataInspector} that only accepts agents whose version matches a given regex.
*
* @param agentFilterProperties the agent filter properties
* @return a {@link WhitelistedVersionAgentMetadataInspector} instance
*/
@Bean
@ConditionalOnMissingBean(WhitelistedVersionAgentMetadataInspector.class)
public WhitelistedVersionAgentMetadataInspector whitelistedVersionAgentMetadataInspector(
final AgentFilterProperties agentFilterProperties
) {
return new WhitelistedVersionAgentMetadataInspector(
agentFilterProperties
);
}
/**
* A {@link AgentMetadataInspector} that rejects agents whose version matches a given regex.
*
* @param agentFilterProperties the agent filter properties
* @return a {@link BlacklistedVersionAgentMetadataInspector}
*/
@Bean
@ConditionalOnMissingBean(BlacklistedVersionAgentMetadataInspector.class)
public BlacklistedVersionAgentMetadataInspector blacklistedVersionAgentMetadataInspector(
final AgentFilterProperties agentFilterProperties
) {
return new BlacklistedVersionAgentMetadataInspector(agentFilterProperties);
}
/**
* A {@link AgentMetadataInspector} that rejects agents whose version is lower than a given version.
*
* @param agentFilterProperties the agent filter properties
* @return a {@link AgentMetadataInspector}
*/
@Bean
@ConditionalOnMissingBean(MinimumVersionAgentMetadataInspector.class)
public MinimumVersionAgentMetadataInspector minimumVersionAgentMetadataInspector(
final AgentFilterProperties agentFilterProperties
) {
return new MinimumVersionAgentMetadataInspector(agentFilterProperties);
}
/**
* A {@link AgentMetadataInspector} that may reject all agents based on system properties.
*
* @param environment the environment
* @return a {@link AgentMetadataInspector}
*/
@Bean
@ConditionalOnMissingBean(RejectAllJobsAgentMetadataInspector.class)
public RejectAllJobsAgentMetadataInspector rejectAllJobsAgentMetadataInspector(
final Environment environment
) {
return new RejectAllJobsAgentMetadataInspector(environment);
}
}
| 2,797 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/services/AgentServicesAutoConfiguration.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.web.spring.autoconfigure.agent.services;
import com.netflix.genie.common.internal.util.GenieHostInfo;
import com.netflix.genie.common.internal.util.PropertiesMapCache;
import com.netflix.genie.web.agent.inspectors.AgentMetadataInspector;
import com.netflix.genie.web.agent.services.AgentConfigurationService;
import com.netflix.genie.web.agent.services.AgentConnectionTrackingService;
import com.netflix.genie.web.agent.services.AgentFilterService;
import com.netflix.genie.web.agent.services.AgentJobService;
import com.netflix.genie.web.agent.services.AgentRoutingService;
import com.netflix.genie.web.agent.services.impl.AgentConfigurationServiceImpl;
import com.netflix.genie.web.agent.services.impl.AgentConnectionTrackingServiceImpl;
import com.netflix.genie.web.agent.services.impl.AgentFilterServiceImpl;
import com.netflix.genie.web.agent.services.impl.AgentJobServiceImpl;
import com.netflix.genie.web.agent.services.impl.AgentRoutingServiceCuratorDiscoveryImpl;
import com.netflix.genie.web.agent.services.impl.AgentRoutingServiceSingleNodeImpl;
import com.netflix.genie.web.data.services.DataServices;
import com.netflix.genie.web.properties.AgentConfigurationProperties;
import com.netflix.genie.web.properties.AgentConnectionTrackingServiceProperties;
import com.netflix.genie.web.properties.AgentRoutingServiceProperties;
import com.netflix.genie.web.services.JobResolverService;
import io.micrometer.core.instrument.MeterRegistry;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import java.util.List;
/**
* Auto configuration for services needed in the {@literal agent} module.
*
* @author tgianos
* @since 4.0.0
*/
@Configuration
@EnableConfigurationProperties(
{
AgentConfigurationProperties.class,
AgentRoutingServiceProperties.class,
AgentConnectionTrackingServiceProperties.class
}
)
public class AgentServicesAutoConfiguration {
/**
* Get a {@link AgentJobService} instance if there isn't already one.
*
* @param dataServices The {@link DataServices} instance to use
* @param jobResolverService The specification service to use
* @param agentFilterService The agent filter service to use
* @param agentConfigurationService The agent configuration service
* @param meterRegistry The metrics registry to use
* @return An {@link AgentJobServiceImpl} instance.
*/
@Bean
@ConditionalOnMissingBean(AgentJobService.class)
public AgentJobServiceImpl agentJobService(
final DataServices dataServices,
final JobResolverService jobResolverService,
final AgentFilterService agentFilterService,
final AgentConfigurationService agentConfigurationService,
final MeterRegistry meterRegistry
) {
return new AgentJobServiceImpl(
dataServices,
jobResolverService,
agentFilterService,
agentConfigurationService,
meterRegistry
);
}
/**
* Get an implementation of {@link AgentConnectionTrackingService} if one hasn't already been defined.
*
* @param agentRoutingService the agent routing service
* @param taskScheduler the task scheduler
* @param serviceProperties the service properties
* @return A {@link AgentConnectionTrackingServiceImpl} instance
*/
@Bean
@ConditionalOnMissingBean(AgentConnectionTrackingService.class)
public AgentConnectionTrackingService agentConnectionTrackingService(
final AgentRoutingService agentRoutingService,
@Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
final AgentConnectionTrackingServiceProperties serviceProperties
) {
return new AgentConnectionTrackingServiceImpl(
agentRoutingService,
taskScheduler,
serviceProperties
);
}
/**
* Get an implementation of {@link AgentRoutingService} if one hasn't already been defined.
* This bean is created if Zookeeper is disabled (single-node Genie deployments and tests).
*
* @param genieHostInfo The local genie host information
* @return A {@link AgentRoutingServiceSingleNodeImpl} instance
*/
@Bean
@ConditionalOnMissingBean(
{
AgentRoutingService.class,
ServiceDiscovery.class
}
)
public AgentRoutingService agentRoutingServiceSingleNodeImpl(
final GenieHostInfo genieHostInfo
) {
return new AgentRoutingServiceSingleNodeImpl(genieHostInfo);
}
/**
* Get an implementation of {@link AgentRoutingService} if one hasn't already been defined.
* This bean is created if Zookeeper is enabled, it uses Curator's {@link ServiceDiscovery}.
*
* @param genieHostInfo The local genie host information
* @param serviceDiscovery The Zookeeper Curator service discovery
* @param taskScheduler The task scheduler
* @param listenableCuratorConnectionState the connection state listenable
* @param registry The metrics registry
* @param properties The service properties
* @return A {@link AgentRoutingServiceCuratorDiscoveryImpl} instance
*/
@Bean
@ConditionalOnBean(ServiceDiscovery.class)
@ConditionalOnMissingBean(AgentRoutingService.class)
public AgentRoutingService agentRoutingServiceCurator(
final GenieHostInfo genieHostInfo,
final ServiceDiscovery<AgentRoutingServiceCuratorDiscoveryImpl.Agent> serviceDiscovery,
@Qualifier("genieTaskScheduler") final TaskScheduler taskScheduler,
final Listenable<ConnectionStateListener> listenableCuratorConnectionState,
final MeterRegistry registry,
final AgentRoutingServiceProperties properties
) {
return new AgentRoutingServiceCuratorDiscoveryImpl(
genieHostInfo,
serviceDiscovery,
taskScheduler,
listenableCuratorConnectionState,
registry,
properties
);
}
/**
* A {@link AgentFilterService} implementation that federates the decision to a set of
* {@link AgentMetadataInspector}s.
*
* @param agentMetadataInspectorsList the list of inspectors.
* @return An {@link AgentFilterService} instance.
*/
@Bean
@ConditionalOnMissingBean(AgentFilterService.class)
public AgentFilterServiceImpl agentFilterService(
final List<AgentMetadataInspector> agentMetadataInspectorsList
) {
return new AgentFilterServiceImpl(agentMetadataInspectorsList);
}
/**
* Provide a {@link AgentConfigurationService} if one is not defined.
*
* @param agentConfigurationProperties the service properties
* @param propertiesMapCacheFactory the properties map cache factory
* @param registry the metrics registry
* @return a {@link AgentConfigurationService} instance
*/
@Bean
@ConditionalOnMissingBean(AgentConfigurationService.class)
public AgentConfigurationServiceImpl agentConfigurationService(
final AgentConfigurationProperties agentConfigurationProperties,
final PropertiesMapCache.Factory propertiesMapCacheFactory,
final MeterRegistry registry
) {
return new AgentConfigurationServiceImpl(
agentConfigurationProperties,
propertiesMapCacheFactory.get(
agentConfigurationProperties.getCacheRefreshInterval(),
AgentConfigurationProperties.DYNAMIC_PROPERTIES_PREFIX
),
registry
);
}
}
| 2,798 |
0 | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent | Create_ds/genie/genie-web/src/main/java/com/netflix/genie/web/spring/autoconfigure/agent/services/package-info.java | /*
*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Agent services auto configuration.
*
* @author tgianos
* @since 4.0.0
*/
@ParametersAreNonnullByDefault
package com.netflix.genie.web.spring.autoconfigure.agent.services;
import javax.annotation.ParametersAreNonnullByDefault;
| 2,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.