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/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/startup/TitusGatewayConfiguration.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.titus.gateway.startup; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.gateway") public interface TitusGatewayConfiguration { @DefaultValue("true") boolean isProxyErrorLoggingEnabled(); }
9,400
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/startup/TitusGateway.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.titus.gateway.startup; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.Properties; import com.netflix.archaius.config.MapConfig; import com.netflix.archaius.guice.ArchaiusModule; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import com.netflix.governator.guice.jetty.Archaius2JettyModule; import com.netflix.titus.common.util.guice.ContainerEventBus; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TitusGateway { private static final Logger logger = LoggerFactory.getLogger(TitusGateway.class); @Argument(alias = "p", description = "Specify a properties file", required = true) private static String propertiesFile; public static void main(String[] args) throws Exception { try { Args.parse(TitusGateway.class, args); } catch (IllegalArgumentException e) { Args.usage(TitusGateway.class); System.exit(1); } try { LifecycleInjector injector = InjectorBuilder.fromModules( new TitusGatewayModule(true), new Archaius2JettyModule(), new ArchaiusModule() { @Override protected void configureArchaius() { bindDefaultConfig().toInstance(MapConfig.builder() .build()); bindApplicationConfigurationOverride().toInstance(loadPropertiesFile(propertiesFile)); } }).createInjector(); injector.getInstance(ContainerEventBus.class).submitInOrder(new ContainerEventBus.ContainerStartedEvent()); injector.awaitTermination(); } catch (Exception e) { logger.error("Unexpected error: {}", e.getMessage(), e); System.exit(2); } } private static MapConfig loadPropertiesFile(String propertiesFile) { if (propertiesFile == null) { return MapConfig.from(Collections.emptyMap()); } Properties properties = new Properties(); try (FileReader fr = new FileReader(propertiesFile)) { properties.load(fr); } catch (IOException e) { throw new IllegalArgumentException("Cannot load file: " + propertiesFile, e); } return MapConfig.from(properties); } }
9,401
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/startup/TitusGatewayModule.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.titus.gateway.startup; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.api.Config; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfo; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.api.model.callmetadata.CallMetadataConstants; import com.netflix.titus.common.environment.MyEnvironments; import com.netflix.titus.common.runtime.SystemAbortListener; import com.netflix.titus.common.runtime.SystemLogService; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.internal.DefaultTitusRuntime; import com.netflix.titus.common.runtime.internal.LoggingSystemAbortListener; import com.netflix.titus.common.runtime.internal.LoggingSystemLogService; import com.netflix.titus.common.util.archaius2.Archaius2ConfigurationLogger; import com.netflix.titus.common.util.code.CodeInvariants; import com.netflix.titus.common.util.code.CompositeCodeInvariants; import com.netflix.titus.common.util.code.LoggingCodeInvariants; import com.netflix.titus.common.util.code.SpectatorCodeInvariants; import com.netflix.titus.common.util.grpc.reactor.GrpcToReactorServerFactory; import com.netflix.titus.common.util.grpc.reactor.server.DefaultGrpcToReactorServerFactory; import com.netflix.titus.common.util.guice.ContainerEventBusModule; import com.netflix.titus.gateway.endpoint.GatewayEndpointModule; import com.netflix.titus.gateway.service.v3.V3ServiceModule; import com.netflix.titus.gateway.store.StoreModule; import com.netflix.titus.runtime.FeatureFlagModule; import com.netflix.titus.runtime.TitusEntitySanitizerModule; import com.netflix.titus.runtime.connector.eviction.EvictionConnectorModule; import com.netflix.titus.runtime.connector.jobmanager.JobEventPropagationUtil; import com.netflix.titus.runtime.connector.jobmanager.JobManagerConnectorModule; import com.netflix.titus.runtime.connector.jobmanager.JobManagerDataReplicationModule; import com.netflix.titus.runtime.connector.kubernetes.fabric8io.DefaultFabric8IOConnector; import com.netflix.titus.runtime.connector.kubernetes.fabric8io.Fabric8IOClients; import com.netflix.titus.runtime.connector.kubernetes.fabric8io.Fabric8IOConnector; import com.netflix.titus.runtime.connector.registry.TitusContainerRegistryModule; import com.netflix.titus.runtime.connector.relocation.RelocationClientConnectorModule; import com.netflix.titus.runtime.connector.relocation.RelocationDataReplicationModule; import com.netflix.titus.runtime.connector.titusmaster.TitusMasterConnectorModule; import com.netflix.titus.runtime.endpoint.admission.JobSecurityValidatorModule; import com.netflix.titus.runtime.endpoint.admission.TitusAdmissionModule; import com.netflix.titus.runtime.endpoint.common.EmptyLogStorageInfo; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; // Common module dependencies // Server dependencies /** * This is the "main" module where we wire everything up. If you see this module getting overly * complex, it's a good idea to break things off into separate ones and install them here instead. */ public final class TitusGatewayModule extends AbstractModule { public static final TypeLiteral<LogStorageInfo<Task>> V3_LOG_STORAGE_INFO = new TypeLiteral<LogStorageInfo<Task>>() { }; private final boolean enableREST; public TitusGatewayModule() { this(true); } public TitusGatewayModule(boolean enableREST) { this.enableREST = enableREST; } @Override protected void configure() { bind(Archaius2ConfigurationLogger.class).asEagerSingleton(); bind(Registry.class).toInstance(new DefaultRegistry()); bind(SystemLogService.class).to(LoggingSystemLogService.class); bind(SystemAbortListener.class).to(LoggingSystemAbortListener.class); bind(Fabric8IOConnector.class).to(DefaultFabric8IOConnector.class).asEagerSingleton(); install(new ContainerEventBusModule()); install(new TitusContainerRegistryModule()); install(new TitusEntitySanitizerModule()); install(new TitusAdmissionModule()); install(new JobSecurityValidatorModule()); // Feature flags install(new FeatureFlagModule()); install(new GatewayEndpointModule(enableREST)); install(new TitusMasterConnectorModule()); install(new JobManagerConnectorModule(JobEventPropagationUtil.CHECKPOINT_GATEWAY_CLIENT)); install(new JobManagerDataReplicationModule()); install(new EvictionConnectorModule()); install(new RelocationClientConnectorModule()); install(new RelocationDataReplicationModule()); bind(V3_LOG_STORAGE_INFO).toInstance(EmptyLogStorageInfo.INSTANCE); install(new V3ServiceModule()); install(new StoreModule()); } @Provides @Singleton TitusGatewayConfiguration getConfiguration(ConfigProxyFactory factory) { return factory.newProxy(TitusGatewayConfiguration.class); } @Provides @Singleton public TitusRuntime getTitusRuntime(Config config, SystemLogService systemLogService, SystemAbortListener systemAbortListener, Registry registry) { CodeInvariants codeInvariants = new CompositeCodeInvariants( LoggingCodeInvariants.getDefault(), new SpectatorCodeInvariants(registry.createId("titus.runtime.invariant.violations"), registry) ); return new DefaultTitusRuntime(MyEnvironments.newArchaius(config), codeInvariants, systemLogService, false, systemAbortListener, registry); } @Provides @Singleton public GrpcToReactorServerFactory getGrpcToReactorServerFactory(CallMetadataResolver callMetadataResolver) { return new DefaultGrpcToReactorServerFactory<>( CallMetadata.class, () -> callMetadataResolver.resolve().orElse(CallMetadataConstants.UNDEFINED_CALL_METADATA) ); } @Provides @Singleton public NamespacedKubernetesClient getFabric8IOClient() { return Fabric8IOClients.createFabric8IOClient(); } }
9,402
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/store/StoreModule.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.titus.gateway.store; import com.google.inject.AbstractModule; import com.netflix.titus.api.jobmanager.store.JobStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryJobStore; public class StoreModule extends AbstractModule { @Override protected void configure() { bind(JobStore.class).to(InMemoryJobStore.class); } }
9,403
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/eviction/GatewayGrpcEvictionService.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.titus.gateway.eviction; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.eviction.service.EvictionException; import com.netflix.titus.grpc.protogen.EvictionQuota; import com.netflix.titus.grpc.protogen.EvictionServiceEvent; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc; import com.netflix.titus.grpc.protogen.ObserverEventRequest; import com.netflix.titus.grpc.protogen.Reference; import com.netflix.titus.grpc.protogen.TaskTerminateRequest; import com.netflix.titus.grpc.protogen.TaskTerminateResponse; import com.netflix.titus.runtime.connector.eviction.EvictionServiceClient; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.attachCancellingCallback; import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toCoreReference; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toGrpcEvent; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toGrpcEvictionQuota; @Singleton public class GatewayGrpcEvictionService extends EvictionServiceGrpc.EvictionServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(GatewayGrpcEvictionService.class); private final EvictionServiceClient evictionServiceClient; @Inject public GatewayGrpcEvictionService(EvictionServiceClient evictionServiceClient) { this.evictionServiceClient = evictionServiceClient; } @Override public void getEvictionQuota(Reference request, StreamObserver<EvictionQuota> responseObserver) { Disposable disposable = evictionServiceClient.getEvictionQuota(toCoreReference(request)).subscribe( next -> responseObserver.onNext(toGrpcEvictionQuota(next)), e -> safeOnError(logger, e, responseObserver), responseObserver::onCompleted ); attachCancellingCallback(responseObserver, disposable); } @Override public void terminateTask(TaskTerminateRequest request, StreamObserver<TaskTerminateResponse> responseObserver) { Disposable disposable = evictionServiceClient.terminateTask(request.getTaskId(), request.getReason()) .subscribe( next -> { }, e -> { if (e instanceof EvictionException) { // TODO Improve error reporting responseObserver.onNext(TaskTerminateResponse.newBuilder() .setAllowed(true) .setReasonCode("failure") .setReasonMessage(e.getMessage()) .build() ); } else { safeOnError(logger, e, responseObserver); } }, () -> { responseObserver.onNext(TaskTerminateResponse.newBuilder().setAllowed(true).build()); responseObserver.onCompleted(); } ); attachCancellingCallback(responseObserver, disposable); } @Override public void observeEvents(ObserverEventRequest request, StreamObserver<EvictionServiceEvent> responseObserver) { Disposable disposable = evictionServiceClient.observeEvents(request.getIncludeSnapshot()).subscribe( event -> toGrpcEvent(event).ifPresent(responseObserver::onNext), e -> safeOnError(logger, e, responseObserver), responseObserver::onCompleted ); attachCancellingCallback(responseObserver, disposable); } }
9,404
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/eviction/EvictionModule.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.titus.gateway.eviction; import com.google.inject.AbstractModule; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc; public class EvictionModule extends AbstractModule { @Override protected void configure() { bind(EvictionServiceGrpc.EvictionServiceImplBase.class).to(GatewayGrpcEvictionService.class); } }
9,405
0
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway
Create_ds/titus-control-plane/titus-server-gateway/src/main/java/com/netflix/titus/gateway/eviction/EvictionResource.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.titus.gateway.eviction; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.netflix.titus.api.eviction.service.EvictionException; import com.netflix.titus.api.model.Tier; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.grpc.protogen.EvictionQuota; import com.netflix.titus.grpc.protogen.TaskTerminateResponse; import com.netflix.titus.runtime.connector.eviction.EvictionServiceClient; import com.netflix.titus.runtime.endpoint.common.rest.Responses; import com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import reactor.core.publisher.Mono; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api(tags = "Eviction service") @Path("/v3/eviction") @Singleton public class EvictionResource { private final EvictionServiceClient evictionServiceClient; @Inject public EvictionResource(EvictionServiceClient evictionServiceClient) { this.evictionServiceClient = evictionServiceClient; } @ApiOperation("Return the system eviction quota") @Path("quotas/system") @GET public EvictionQuota getSystemEvictionQuota() { return Responses.fromMono( evictionServiceClient .getEvictionQuota(Reference.system()) .map(GrpcEvictionModelConverters::toGrpcEvictionQuota) ); } @ApiOperation("Return a tier eviction quota") @Path("quotas/tiers/{tier}") @GET public EvictionQuota getTierEvictionQuota(@PathParam("tier") String tier) { return Responses.fromMono( evictionServiceClient .getEvictionQuota(Reference.tier(StringExt.parseEnumIgnoreCase(tier, Tier.class))) .map(GrpcEvictionModelConverters::toGrpcEvictionQuota) ); } @ApiOperation("Return a capacity group eviction quota") @Path("quotas/capacityGroups/{name}") @GET public EvictionQuota getCapacityGroupEvictionQuota(@PathParam("name") String capacityGroupName) { return Responses.fromMono( evictionServiceClient .getEvictionQuota(Reference.capacityGroup(capacityGroupName)) .map(GrpcEvictionModelConverters::toGrpcEvictionQuota) ); } @ApiOperation("Return a job eviction quota") @Path("quotas/jobs/{id}") @GET public EvictionQuota getJobEvictionQuota(@PathParam("id") String jobId) { return Responses.fromMono( evictionServiceClient .getEvictionQuota(Reference.job(jobId)) .map(GrpcEvictionModelConverters::toGrpcEvictionQuota) ); } @ApiOperation("Return a task eviction quota") @Path("quotas/tasks/{id}") @GET public EvictionQuota getTaskEvictionQuota(@PathParam("id") String taskId) { return Responses.fromMono( evictionServiceClient .getEvictionQuota(Reference.task(taskId)) .map(GrpcEvictionModelConverters::toGrpcEvictionQuota) ); } @ApiOperation("Terminate a task using the eviction service") @Path("tasks/{id}") @DELETE public TaskTerminateResponse terminateTask(@PathParam("id") String taskId, @QueryParam("reason") String reason) { return Responses.fromMono( evictionServiceClient .terminateTask(taskId, Evaluators.getOrDefault(reason, "Reason not provided")) .materialize() .flatMap(event -> { switch (event.getType()) { case ON_ERROR: if (event.getThrowable() instanceof EvictionException) { return Mono.just(TaskTerminateResponse.newBuilder() .setAllowed(false) .setReasonCode("failure") .setReasonMessage(event.getThrowable().getMessage()) .build() ); } return Mono.error(event.getThrowable()); case ON_COMPLETE: return Mono.just(TaskTerminateResponse.newBuilder() .setAllowed(true) .setReasonCode("normal") .setReasonMessage("Terminated") .build() ); } return Mono.empty(); }) ); } }
9,406
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/FunctionalTest.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.titus.testkit.junit.category; /** * A functional test is a {@link RemoteIntegrationTest} that is appropriate for reoccurring functional/regression testing. */ public interface FunctionalTest extends RemoteIntegrationTest { }
9,407
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/SmokeTest.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.titus.testkit.junit.category; /** * A smoke test is {@link FunctionalTest} that is appropriate for use during regular smoke testing. */ public interface SmokeTest extends FunctionalTest { }
9,408
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/PerformanceTest.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.titus.testkit.junit.category; /** * A performance test is a {@link RemoteIntegrationTest} that is appropriate for stress and performance testing and evaluation. */ public interface PerformanceTest extends RemoteIntegrationTest { }
9,409
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/RemoteIntegrationTest.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.titus.testkit.junit.category; /** * Integration tests that require external services, and cannot be run in isolation. */ public interface RemoteIntegrationTest { }
9,410
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/IntegrationNotParallelizableTest.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.titus.testkit.junit.category; /** * Integration tests that cannot run in parallel should include this annotation (and only this one). */ public interface IntegrationNotParallelizableTest { }
9,411
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/junit/category/IntegrationTest.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.titus.testkit.junit.category; /** * A marker annotation for the integration tests. */ public interface IntegrationTest { }
9,412
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/model
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/model/clustermembership/ClusterMemberGenerator.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.titus.testkit.model.clustermembership; import java.util.Collections; import com.netflix.titus.api.clustermembership.model.ClusterMember; import com.netflix.titus.api.clustermembership.model.ClusterMemberAddress; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadership; import com.netflix.titus.api.clustermembership.model.ClusterMemberLeadershipState; import com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision; import com.netflix.titus.common.util.CollectionsExt; public final class ClusterMemberGenerator { public static ClusterMember activeClusterMember(String memberId) { return activeClusterMember(memberId, "10.0.0.1"); } public static ClusterMember activeClusterMember(String memberId, String ipAddress) { return ClusterMember.newBuilder() .withMemberId(memberId) .withEnabled(true) .withActive(true) .withRegistered(true) .withClusterMemberAddresses(Collections.singletonList( ClusterMemberAddress.newBuilder() .withIpAddress(ipAddress) .withPortNumber(8081) .withProtocol("https") .withSecure(true) .withDescription("REST endpoint") .build() )) .withLabels(Collections.singletonMap("resourceVersion", "1")) .build(); } public static ClusterMembershipRevision<ClusterMember> clusterMemberRegistrationRevision(ClusterMember current) { long now = System.currentTimeMillis(); return ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(current.toBuilder() .withLabels(CollectionsExt.copyAndAdd(current.getLabels(), "changedAt", "" + now)) .build() ) .withCode("registered") .withMessage("Registering") .withTimestamp(now) .build(); } public static ClusterMembershipRevision<ClusterMember> clusterMemberUnregistrationRevision(ClusterMember current) { long now = System.currentTimeMillis(); return ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(current.toBuilder() .withLabels(CollectionsExt.copyAndAdd(current.getLabels(), "changedAt", "" + now)) .build() ) .withCode("unregistered") .withMessage("Unregistering") .withTimestamp(now) .build(); } public static ClusterMembershipRevision<ClusterMember> clusterMemberUpdateRevision(ClusterMembershipRevision<ClusterMember> currentRevision) { long now = System.currentTimeMillis(); ClusterMember current = currentRevision.getCurrent(); return ClusterMembershipRevision.<ClusterMember>newBuilder() .withCurrent(current.toBuilder() .withLabels(CollectionsExt.copyAndAdd(current.getLabels(), "changedAt", "" + now)) .build() ) .withCode("updated") .withMessage("Random update to generate next revision number") .withRevision(currentRevision.getRevision() + 1) .withTimestamp(now) .build(); } public static ClusterMembershipRevision<ClusterMemberLeadership> leaderRevision(ClusterMembershipRevision<ClusterMember> memberRevision) { return ClusterMembershipRevision.<ClusterMemberLeadership>newBuilder() .withCurrent(ClusterMemberLeadership.newBuilder() .withMemberId(memberRevision.getCurrent().getMemberId()) .withLeadershipState(ClusterMemberLeadershipState.Leader) .build() ) .build(); } }
9,413
0
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit
Create_ds/titus-control-plane/titus-common-testkit/src/main/java/com/netflix/titus/testkit/rx/TitusRxSubscriber.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.titus.testkit.rx; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.Disposable; public class TitusRxSubscriber<T> implements Subscriber<T>, Disposable { private static final Object COMPLETED_MARKER = "CompletedMarker"; private static final Object ERROR_MARKER = "ErrorMarker"; private final List<Object> emits = new CopyOnWriteArrayList<>(); private final BlockingQueue<T> items = new LinkedBlockingQueue<>(); private final ReentrantLock lock = new ReentrantLock(); private volatile Subscription subscription; private volatile Throwable error; private volatile boolean disposed; private final Object eventWaitLock = new Object(); @Override public void onSubscribe(Subscription s) { subscription = s; s.request(Long.MAX_VALUE); } @Override public void onNext(T value) { tryEmit(value); notifyClients(); } @Override public void onError(Throwable t) { tryEmit(ERROR_MARKER); this.error = t; notifyClients(); } @Override public void onComplete() { tryEmit(COMPLETED_MARKER); notifyClients(); } @Override public void dispose() { if (subscription != null) { subscription.cancel(); this.disposed = true; } notifyClients(); } @Override public boolean isDisposed() { return disposed; } public boolean isOpen() { return emits.isEmpty() || !isMarker(last()); } public boolean hasError() { return !isOpen() && last() == ERROR_MARKER; } public Throwable getError() { Preconditions.checkState(hasError(), "Subscription not terminated with an error"); return error; } public List<T> getAllItems() { return (List<T>) emits.stream().filter(v -> !isMarker(v)).collect(Collectors.toList()); } public T takeNext() { return afterTakeNext(items.poll()); } public T takeNext(Duration duration) throws InterruptedException { return afterTakeNext(items.poll(duration.toMillis(), TimeUnit.MILLISECONDS)); } public T takeUntil(Predicate<T> predicate, Duration duration) throws InterruptedException { long deadline = System.currentTimeMillis() + duration.toMillis(); while (deadline > System.currentTimeMillis()) { long leftTime = deadline - System.currentTimeMillis(); if (leftTime <= 0) { return null; } T next = afterTakeNext(items.poll(leftTime, TimeUnit.MILLISECONDS)); if (next == null) { return null; } if (predicate.apply(next)) { return next; } } return null; } public List<T> takeNext(int n, Duration timeout) throws InterruptedException, IllegalStateException { List<T> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { T next = takeNext(timeout); if (next == null) { if (result.size() != n) { throw new IllegalStateException("Did not receive the required number of items: " + n + ", only received: " + result.size()); } break; } result.add(next); } return result; } private void notifyClients() { synchronized (eventWaitLock) { eventWaitLock.notifyAll(); } } public void failIfClosed() { if (isOpen()) { return; } if (error == null) { throw new IllegalStateException("Stream completed"); } throw new IllegalStateException("Stream terminated with an error", error); } public boolean awaitClosed(Duration timeout) throws InterruptedException { long deadline = System.currentTimeMillis() + timeout.toMillis(); while (isOpen() && (deadline - System.currentTimeMillis()) > 0) { synchronized (eventWaitLock) { if (isOpen() && (deadline - System.currentTimeMillis()) > 0) { eventWaitLock.wait(deadline - System.currentTimeMillis()); } } } return !isOpen(); } private T afterTakeNext(T value) { if (value == COMPLETED_MARKER) { return null; } if (value == ERROR_MARKER) { throw new RuntimeException(error); } return value; } private void tryEmit(Object value) { Preconditions.checkState(lock.tryLock(), "Concurrent emits"); try { Preconditions.checkState(isOpen(), "Concurrent emits"); emits.add(value); if (!isMarker(value)) { items.add((T) value); } } finally { lock.unlock(); } } private boolean isMarker(Object value) { return value == COMPLETED_MARKER || value == ERROR_MARKER; } private Object last() { return emits.get(emits.size() - 1); } }
9,414
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/JobFunctionsTest.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.titus.api.jobmanager.model.job; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.testkit.model.job.JobDescriptorGenerator; import com.netflix.titus.testkit.model.job.JobGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class JobFunctionsTest { private static final Task REFERENCE_TASK = JobGenerator.batchTasks(JobGenerator.batchJobs(JobDescriptorGenerator.oneTaskBatchJobDescriptor()).getValue()).getValue(); private final Clock clock = Clocks.system(); @Test public void testGetTimeInStateForCompletedTask() { TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.Finished).withTimestamp(5000).build(); Task task = REFERENCE_TASK.toBuilder() .withStatus(checked) .withStatusHistory( TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(), TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build(), TaskStatus.newBuilder().withState(TaskState.StartInitiated).withTimestamp(200).build(), TaskStatus.newBuilder().withState(TaskState.Started).withTimestamp(1000).build(), TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(2000).build() ) .build(); assertThat(JobFunctions.getTimeInState(task, TaskState.Accepted, clock)).contains(100L); assertThat(JobFunctions.getTimeInState(task, TaskState.Launched, clock)).contains(100L); assertThat(JobFunctions.getTimeInState(task, TaskState.StartInitiated, clock)).contains(800L); assertThat(JobFunctions.getTimeInState(task, TaskState.Started, clock)).contains(1000L); assertThat(JobFunctions.getTimeInState(task, TaskState.KillInitiated, clock)).contains(3000L); assertThat(JobFunctions.getTimeInState(task, TaskState.Finished, clock).get()).isGreaterThan(0); } @Test public void testGetTimeInStateForFailedTask() { TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(1000).build(); Task task = REFERENCE_TASK.toBuilder() .withStatus(checked) .withStatusHistory( TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(), TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build() ) .build(); assertThat(JobFunctions.getTimeInState(task, TaskState.Accepted, clock)).contains(100L); assertThat(JobFunctions.getTimeInState(task, TaskState.Launched, clock)).contains(900L); assertThat(JobFunctions.getTimeInState(task, TaskState.StartInitiated, clock)).isEmpty(); assertThat(JobFunctions.getTimeInState(task, TaskState.Started, clock)).isEmpty(); assertThat(JobFunctions.getTimeInState(task, TaskState.KillInitiated, clock).get()).isGreaterThan(0); assertThat(JobFunctions.getTimeInState(task, TaskState.Finished, clock)).isEmpty(); } @Test public void testHasTransition() { TaskStatus checked = TaskStatus.newBuilder().withState(TaskState.KillInitiated).withTimestamp(1000).build(); Task task = REFERENCE_TASK.toBuilder() .withStatus(checked) .withStatusHistory( TaskStatus.newBuilder().withState(TaskState.Accepted).withTimestamp(0).build(), TaskStatus.newBuilder().withState(TaskState.Launched).withTimestamp(100).build(), TaskStatus.newBuilder().withState(TaskState.StartInitiated).withReasonCode("step1").withTimestamp(100).build(), TaskStatus.newBuilder().withState(TaskState.StartInitiated).withReasonCode("step2").withTimestamp(100).build() ) .build(); assertThat(JobFunctions.containsExactlyTaskStates(task, TaskState.Accepted, TaskState.Launched, TaskState.StartInitiated, TaskState.KillInitiated)).isTrue(); } @Test public void testFindHardConstraint() { Job<BatchJobExt> job = JobFunctions.appendHardConstraint(JobGenerator.oneBatchJob(), "MyConstraint", "good"); assertThat(JobFunctions.findHardConstraint(job, "myConstraint")).contains("good"); assertThat(JobFunctions.findSoftConstraint(job, "myConstraint")).isEmpty(); } @Test public void testFindSoftConstraint() { Job<BatchJobExt> job = JobFunctions.appendSoftConstraint(JobGenerator.oneBatchJob(), "MyConstraint", "good"); assertThat(JobFunctions.findHardConstraint(job, "myConstraint")).isEmpty(); assertThat(JobFunctions.findSoftConstraint(job, "myConstraint")).contains("good"); } @Test public void testGroupTasksByResubmitOrder() { List<Task> group1 = taskWithReplacements(3); List<Task> group2 = taskWithReplacements(5); Task badOne = JobGenerator.oneBatchTask().toBuilder().withOriginalId("missing").build(); List<Task> mixed = CollectionsExt.merge(group1, group2, Collections.singletonList(badOne)); Collections.shuffle(mixed); Pair<Map<String, List<Task>>, List<Task>> result = JobFunctions.groupTasksByResubmitOrder(mixed); Map<String, List<Task>> ordered = result.getLeft(); List<Task> rejected = result.getRight(); // Ordered assertThat(ordered).hasSize(2); List<Task> firstOrder = ordered.get(group1.get(0).getId()); assertThat(firstOrder).isEqualTo(group1); List<Task> secondOrder = ordered.get(group2.get(0).getId()); assertThat(secondOrder).isEqualTo(group2); // Rejected assertThat(rejected).hasSize(1); assertThat(rejected.get(0).getId()).isEqualTo(badOne.getId()); } private static List<Task> taskWithReplacements(int size) { BatchJobTask first = JobGenerator.oneBatchTask(); List<Task> result = new ArrayList<>(); result.add(first); Task last = first; for (int i = 1; i < size; i++) { BatchJobTask next = JobGenerator.oneBatchTask().toBuilder() .withJobId(first.getJobId()) .withOriginalId(first.getId()) .withResubmitOf(last.getId()) .build(); result.add(next); last = next; } return result; } }
9,415
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/JobCompatibilityTest.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.titus.api.jobmanager.model.job; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.migration.SelfManagedMigrationPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ExponentialBackoffRetryPolicy; import com.netflix.titus.testkit.model.job.JobDescriptorGenerator; import org.junit.Test; import static com.netflix.titus.common.util.CollectionsExt.copyAndAdd; import static org.assertj.core.api.Assertions.assertThat; public class JobCompatibilityTest { @Test public void testIdenticalJobs() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobCompatibility compatibility = JobCompatibility.of(reference, reference.toBuilder().build()); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testDifferentOwners() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withOwner(Owner.newBuilder().withTeamEmail("other+123@netflix.com").build()) .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testDifferentApplicationName() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withApplicationName("otherApp") .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testDifferentJobGroupInfo() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withJobGroupInfo(reference.getJobGroupInfo().toBuilder() .withSequence("020") .build()) .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testServiceExtInformationIsIgnored() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withExtensions(ServiceJobExt.newBuilder() .withCapacity(Capacity.newBuilder() .withMin(0) .withDesired(100) .withMax(200) .build()) .withMigrationPolicy(SelfManagedMigrationPolicy.newBuilder().build()) .withRetryPolicy(ExponentialBackoffRetryPolicy.newBuilder().build()) .build()) .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testDisruptionBudgetIsIgnored() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withDisruptionBudget(DisruptionBudget.newBuilder() .withDisruptionBudgetPolicy(SelfManagedDisruptionBudgetPolicy.newBuilder() .withRelocationTimeMs(100) .build()) .build()) .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testEnvIsIgnored() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withContainer(reference.getContainer().but(container -> container.toBuilder().withEnv(copyAndAdd(container.getEnv(), "SOME", "OVERRIDE")) )) .build(); JobCompatibility compatibility = JobCompatibility.of(reference, other); assertThat(compatibility.isCompatible()).isTrue(); } @Test public void testJobAttributesAreIgnored() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withAttributes(copyAndAdd(reference.getAttributes(), "spinnaker.useApplicationDefaultSecurityGroup", "true")) .build(); JobCompatibility compatibility1 = JobCompatibility.of(reference, other); assertThat(compatibility1.isCompatible()).isTrue(); JobDescriptor<ServiceJobExt> incompatible = reference.toBuilder() .withAttributes(copyAndAdd(reference.getAttributes(), "titus.value", "important")) .build(); JobCompatibility compatibility2 = JobCompatibility.of(reference, incompatible); assertThat(compatibility2.isCompatible()).isTrue(); } @Test public void testContainerAttributesNotPrefixedWithTitusAreCompatible() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withContainer(reference.getContainer().but(container -> container.toBuilder().withAttributes(copyAndAdd(container.getAttributes(), "some.app.attribute", "some value")) )) .build(); JobCompatibility compatibility1 = JobCompatibility.of(reference, other); assertThat(compatibility1.isCompatible()).isTrue(); JobDescriptor<ServiceJobExt> incompatible = reference.toBuilder() .withContainer(reference.getContainer().but(container -> container.toBuilder().withAttributes(copyAndAdd(container.getAttributes(), "titusParameter.cpu.burstEnabled", "true")) )) .build(); JobCompatibility compatibility2 = JobCompatibility.of(reference, incompatible); assertThat(compatibility2.isCompatible()).isFalse(); } @Test public void testSecurityAttributesNotPrefixedWithTitusAreCompatible() { JobDescriptor<ServiceJobExt> reference = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> other = reference.toBuilder() .withContainer(reference.getContainer().but(container -> container.toBuilder() .withSecurityProfile(container.getSecurityProfile().toBuilder() .withAttributes(copyAndAdd( container.getSecurityProfile().getAttributes(), "NETFLIX_APP_METADATA_SIG", "some signature") ).build()) .build() )) .build(); JobCompatibility compatibility1 = JobCompatibility.of(reference, other); assertThat(compatibility1.isCompatible()).isTrue(); JobDescriptor<ServiceJobExt> incompatible = reference.toBuilder() .withContainer(reference.getContainer().but(container -> container.toBuilder() .withSecurityProfile(container.getSecurityProfile().toBuilder() .withAttributes(copyAndAdd( container.getSecurityProfile().getAttributes(), "titus.secure.attribute", "false") ).build()) .build() )) .build(); JobCompatibility compatibility2 = JobCompatibility.of(reference, incompatible); assertThat(compatibility2.isCompatible()).isFalse(); } @Test public void testSanitizationCanFailOpen() { // when jobs are cloned, they can have different values for sanitized fields // if sanitization fails open for one but not for the other JobDescriptor<ServiceJobExt> base = JobDescriptorGenerator.oneTaskServiceJobDescriptor(); JobDescriptor<ServiceJobExt> from = base.toBuilder() .withContainer(base.getContainer().but(c -> c.getSecurityProfile().toBuilder().withIamRole("simpleName"))) .withAttributes(copyAndAdd(base.getAttributes(), JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IAM, "true")) .build(); JobDescriptor<ServiceJobExt> to = base.toBuilder() .withContainer(base.getContainer().but(c -> c.getSecurityProfile().toBuilder().withIamRole("arn:aws:fullyQualified/12345/simpleName"))) .build(); assertThat(JobCompatibility.of(from, to).isCompatible()).isTrue(); JobDescriptor<ServiceJobExt> from2 = base.toBuilder() .withContainer(base.getContainer().but(c -> c.getImage().toBuilder().withDigest("foo-digest-123").build())) .build(); JobDescriptor<ServiceJobExt> to2 = base.toBuilder() .withContainer(base.getContainer().but(c -> c.getImage().toBuilder().withDigest("").build())) .withAttributes(copyAndAdd(base.getAttributes(), JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IMAGE, "true")) .build(); assertThat(JobCompatibility.of(from2, to2).isCompatible()).isTrue(); } }
9,416
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/LogStorageInfosTest.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.titus.api.jobmanager.model.job; import java.util.HashMap; import java.util.Map; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfo.S3LogLocation; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfos.S3Account; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfos.S3Bucket; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.testkit.model.job.JobGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LogStorageInfosTest { private static final S3LogLocation DEFAULT_LOG_LOCATION = new S3LogLocation( "defaultAccountName", "defaultAccountId", "defaultRegion", "defaultBucket", "defaultKey" ); @Test public void testToS3LogLocationTaskContext() { // Empty context assertS3LogLocationInTaskContextNotSet(LogStorageInfos.toS3LogLocationTaskContext(JobGenerator.oneBatchJob())); // Non empty context assertS3LogLocationInTaskContext( LogStorageInfos.toS3LogLocationTaskContext(newJob("bucketA", "pathB")), "bucketA", "pathB" ); } @Test public void testFindCustomS3BucketInJob() { // Empty context assertThat(LogStorageInfos.findCustomS3Bucket(JobGenerator.oneBatchJob())).isEmpty(); // Bucket only Job bucketOnlyJob = newJob("bucketA", null); assertThat(LogStorageInfos.findCustomS3Bucket(bucketOnlyJob)).contains(new S3Bucket("bucketA")); // Bucket and path Job customizedJob = newJob("bucketA", "pathB"); assertThat(LogStorageInfos.findCustomS3Bucket(customizedJob)).contains(new S3Bucket("bucketA")); assertThat(LogStorageInfos.findCustomPathPrefix(customizedJob.getJobDescriptor())).contains("pathB"); } @Test public void testFindCustomS3BucketInTask() { // Empty context assertThat(LogStorageInfos.findCustomS3Bucket(JobGenerator.oneBatchTask())).isEmpty(); // Non empty context Task customizedTask = newTask("bucketA", "pathB"); S3Bucket s3Bucket = LogStorageInfos.findCustomS3Bucket(customizedTask).orElse(null); assertThat(s3Bucket.getBucketName()).isEqualTo("bucketA"); String customPathPrefix = LogStorageInfos.findCustomPathPrefix(customizedTask).orElse(null); assertThat(customPathPrefix).isEqualTo("pathB"); } @Test public void testParseS3AccessPointArn() { // No ARN assertThat(LogStorageInfos.parseS3AccessPointArn("myBucket")).isEmpty(); // Good ARN assertThat(LogStorageInfos.parseS3AccessPointArn("arn:aws:s3:us-west-2:123456789012:accesspoint/test")).contains( new S3Account("123456789012", "us-west-2") ); // Bad ARN assertThat(LogStorageInfos.parseS3AccessPointArn("arn:aws:ec2:us-west-2:123456789012:accesspoint/test")).isEmpty(); } @Test public void testBuildLogLocation() { // No bucket override assertThat(LogStorageInfos.buildLogLocation(JobGenerator.oneBatchTask(), DEFAULT_LOG_LOCATION)).isEqualTo(DEFAULT_LOG_LOCATION); // Plain custom bucket name assertThat(LogStorageInfos.buildLogLocation(newTask("bucketA", "pathB"), DEFAULT_LOG_LOCATION)).isEqualTo( new S3LogLocation( DEFAULT_LOG_LOCATION.getAccountName(), DEFAULT_LOG_LOCATION.getAccountId(), DEFAULT_LOG_LOCATION.getRegion(), "bucketA", "pathB/defaultKey" ) ); // Custom bucket name with S3 ARN. assertThat(LogStorageInfos.buildLogLocation( newTask("arn:aws:s3:us-west-2:123456789012:accesspoint/test", "pathB"), DEFAULT_LOG_LOCATION) ).isEqualTo( new S3LogLocation( "123456789012", "123456789012", "us-west-2", "arn:aws:s3:us-west-2:123456789012:accesspoint/test", "pathB/defaultKey" ) ); } private Job newJob(String bucketName, String pathPrefix) { Job<BatchJobExt> job = JobGenerator.oneBatchJob(); Map<String, String> containerAttributes = new HashMap<>(job.getJobDescriptor().getContainer().getAttributes()); Evaluators.applyNotNull(bucketName, value -> containerAttributes.put(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_BUCKET_NAME, value)); Evaluators.applyNotNull(pathPrefix, value -> containerAttributes.put(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX, value)); return job.toBuilder() .withJobDescriptor(job.getJobDescriptor().toBuilder() .withContainer(job.getJobDescriptor().getContainer().toBuilder() .withAttributes(containerAttributes) .build() ) .build() ) .build(); } private Task newTask(String bucketName, String pathPrefix) { Task task = JobGenerator.oneBatchTask(); Map<String, String> taskContext = new HashMap<>(task.getTaskContext()); taskContext.put(TaskAttributes.TASK_ATTRIBUTE_S3_BUCKET_NAME, bucketName); taskContext.put(TaskAttributes.TASK_ATTRIBUTE_S3_PATH_PREFIX, pathPrefix); return task.toBuilder().withTaskContext(taskContext).build(); } private void assertS3LogLocationInTaskContextNotSet(Map<String, String> taskContext) { assertThat(taskContext).doesNotContainKey(TaskAttributes.TASK_ATTRIBUTE_S3_BUCKET_NAME); assertThat(taskContext).doesNotContainKey(TaskAttributes.TASK_ATTRIBUTE_S3_PATH_PREFIX); } private void assertS3LogLocationInTaskContext(Map<String, String> taskContext, String bucketName, String pathPrefix) { assertThat(taskContext).containsEntry(TaskAttributes.TASK_ATTRIBUTE_S3_BUCKET_NAME, bucketName); assertThat(taskContext).containsEntry(TaskAttributes.TASK_ATTRIBUTE_S3_PATH_PREFIX, pathPrefix); } }
9,417
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/TimeWindowFunctionsTest.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.titus.api.jobmanager.model.job.disruptionbudget; import java.time.DayOfWeek; import java.time.Month; import java.util.function.Supplier; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.time.Clocks; import com.netflix.titus.common.util.time.TestClock; import org.junit.Test; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class TimeWindowFunctionsTest { private final TestClock clock = Clocks.testWorldClock(2000, Month.JANUARY, 1); private final TitusRuntime titusRuntime = TitusRuntimes.test(clock); @Test public void testEmptyTimeWindowPredicate() { Supplier<Boolean> predicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, TimeWindow.empty()); assertThat(predicate.get()).isTrue(); } @Test public void testTimeWindowPredicateInUtc() { TimeWindow timeWindow = TimeWindow.newBuilder() .withDays(Day.Monday) .withwithHourlyTimeWindows(8, 16) .build(); Supplier<Boolean> predicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, timeWindow); // Before 8 clock.jumpForwardTo(DayOfWeek.MONDAY).resetTime(7, 0, 0); assertThat(predicate.get()).isFalse(); // During the day clock.resetTime(11, 0, 0); assertThat(predicate.get()).isTrue(); // After 16 clock.resetTime(17, 0, 0); assertThat(predicate.get()).isFalse(); } @Test public void testTimeWindowPredicateInPst() { TimeWindow timeWindow = TimeWindow.newBuilder() .withDays(Day.Monday) .withwithHourlyTimeWindows(8, 16) .withTimeZone("PST") .build(); Supplier<Boolean> predicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, timeWindow); // 8am UTC (== 0am PST) clock.jumpForwardTo(DayOfWeek.MONDAY).resetTime(10, 0, 0); assertThat(predicate.get()).isFalse(); // 4pm UTC (== 8am PST) clock.resetTime(16, 0, 0); assertThat(predicate.get()).isTrue(); // 8pm UTC (== 12pm PST) clock.resetTime(20, 0, 0); } @Test public void testMultipleTimeWindowsPredicate() { TimeWindow timeWindow1 = TimeWindow.newBuilder() .withDays(Day.Monday, Day.Tuesday, Day.Wednesday, Day.Thursday) .withwithHourlyTimeWindows(8, 11, 13, 16) .build(); TimeWindow timeWindow2 = TimeWindow.newBuilder() .withDays(Day.Friday) .withwithHourlyTimeWindows(8, 13) .build(); Supplier<Boolean> predicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, asList(timeWindow1, timeWindow2)); // Wednesday clock.jumpForwardTo(DayOfWeek.WEDNESDAY).resetTime(7, 0, 0); assertThat(predicate.get()).isFalse(); clock.jumpForwardTo(DayOfWeek.WEDNESDAY).resetTime(10, 0, 0); assertThat(predicate.get()).isTrue(); clock.jumpForwardTo(DayOfWeek.WEDNESDAY).resetTime(12, 0, 0); assertThat(predicate.get()).isFalse(); clock.jumpForwardTo(DayOfWeek.WEDNESDAY).resetTime(15, 0, 0); assertThat(predicate.get()).isTrue(); clock.jumpForwardTo(DayOfWeek.WEDNESDAY).resetTime(18, 0, 0); assertThat(predicate.get()).isFalse(); // Friday clock.jumpForwardTo(DayOfWeek.FRIDAY).resetTime(7, 0, 0); assertThat(predicate.get()).isFalse(); clock.jumpForwardTo(DayOfWeek.FRIDAY).resetTime(12, 0, 0); assertThat(predicate.get()).isTrue(); clock.jumpForwardTo(DayOfWeek.FRIDAY).resetTime(15, 0, 0); assertThat(predicate.get()).isFalse(); } }
9,418
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/JobAssertionsTest.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.titus.api.jobmanager.model.job.sanitizer; import java.util.Collections; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableMap; import com.netflix.titus.api.jobmanager.model.job.Image; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.testkit.model.job.JobEbsVolumeGenerator; import com.netflix.titus.testkit.model.job.JobIpAllocationGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class JobAssertionsTest { private final JobConfiguration configuration = mock(JobConfiguration.class); private final JobAssertions jobAssertions = new JobAssertions(configuration, id -> ResourceDimension.empty()); @Test public void testEmptyMapOfEnvironmentVariableNames() { Map<String, String> violations = jobAssertions.validateEnvironmentVariableNames(Collections.emptyMap()); assertThat(violations).isEmpty(); } @Test public void testGoodEnvironmentVariableNames() { Map<String, String> violations = jobAssertions.validateEnvironmentVariableNames(ImmutableMap.of( "THIS_IS_GOOD_123", "good name", "_THIS_IS_2_GOOD", "good name", "_AND_THIS", "good name" )); assertThat(violations).isEmpty(); } @Test public void testBadEnvironmentVariableNames() { assertThat(jobAssertions.validateEnvironmentVariableNames(ImmutableMap.of( "THIS_IS_GOOD_123", "good name", "this is bad", "bad value", "1_THIS_IS_NOT_GOOD", "bad name", "", "bad value" )).keySet()).containsExactlyInAnyOrder("empty", "invalidFirstCharacter", "invalidCharacter"); assertThat(jobAssertions.validateEnvironmentVariableNames(ImmutableMap.of( "This_is_bad", "bad value", "and_this_is_bad", "bad value" )).keySet()).containsExactlyInAnyOrder("invalidFirstCharacter", "invalidCharacter"); } @Test public void testImageDigestValidation() { Image image = Image.newBuilder() .withName("imageName") .withDigest("sha256:abcdef0123456789abcdef0123456789abcdef0123456789") .build(); Map<String, String> violations = jobAssertions.validateImage(image); assertThat(violations).isEmpty(); } @Test public void testInvalidDigestValidation() { Image image = Image.newBuilder() .withName("imageName") .withDigest("sha256:XYZ") .build(); Map<String, String> violations = jobAssertions.validateImage(image); assertThat(violations).hasSize(1); } @Test public void testEbsAndIpZoneMatchValidation() { int size = 4; List<String> availabilityZones = JobEbsVolumeGenerator.availabilityZones().getValues(size); List<EbsVolume> ebsVolumes = JobEbsVolumeGenerator.jobEbsVolumes(size).toList(); List<SignedIpAddressAllocation> ipAddressAllocations = JobIpAllocationGenerator.jobIpAllocations(size).toList(); for (int i = 0; i < size; i++) { String az = availabilityZones.get(i); EbsVolume updatedEbsVolume = ebsVolumes.get(i).toBuilder() .withVolumeAvailabilityZone(az) .build(); ebsVolumes.set(i, updatedEbsVolume); SignedIpAddressAllocation updatedIpAllocation = ipAddressAllocations.get(i).toBuilder() .withIpAddressAllocation(ipAddressAllocations.get(i).getIpAddressAllocation().toBuilder() .withIpAddressLocation(ipAddressAllocations.get(i).getIpAddressAllocation().getIpAddressLocation().toBuilder() .withAvailabilityZone(az) .build()) .build()) .build(); ipAddressAllocations.set(i, updatedIpAllocation); } Map<String, String> violations = jobAssertions.matchingEbsAndIpZones(ebsVolumes, ipAddressAllocations); assertThat(violations).hasSize(0); } @Test public void testEbsAndIpZoneDoNotMatchValidation() { int size = 4; List<String> availabilityZones = JobEbsVolumeGenerator.availabilityZones().getValues(size); List<EbsVolume> ebsVolumes = JobEbsVolumeGenerator.jobEbsVolumes(size).toList(); List<SignedIpAddressAllocation> ipAddressAllocations = JobIpAllocationGenerator.jobIpAllocations(size).toList(); for (int i = 0; i < size; i++) { String az = availabilityZones.get(i); EbsVolume updatedEbsVolume = ebsVolumes.get(i).toBuilder() .withVolumeAvailabilityZone(az) .build(); ebsVolumes.set(i, updatedEbsVolume); } Map<String, String> violations = jobAssertions.matchingEbsAndIpZones(ebsVolumes, ipAddressAllocations); assertThat(violations).hasSize(1); } }
9,419
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/JobModelSanitizationTest.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.titus.api.jobmanager.model.job.sanitizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import com.google.common.collect.ImmutableMap; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.DefaultDecoder; import com.netflix.archaius.DefaultPropertyFactory; import com.netflix.archaius.config.MapConfig; import com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Image; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.JobModel; import com.netflix.titus.api.jobmanager.model.job.PlatformSidecar; import com.netflix.titus.api.jobmanager.model.job.ServiceJobTask; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.ContainerHealthProvider; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.Day; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.volume.SaaSVolumeSource; import com.netflix.titus.api.jobmanager.model.job.volume.Volume; import com.netflix.titus.api.jobmanager.model.job.volume.VolumeSource; import com.netflix.titus.api.model.EfsMount; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import com.netflix.titus.common.model.sanitizer.VerifierMode; import com.netflix.titus.common.model.sanitizer.ValidationError; import com.netflix.titus.testkit.model.job.JobGenerator; import org.junit.Before; import org.junit.Test; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.changeDisruptionBudget; import static com.netflix.titus.common.util.CollectionsExt.first; import static com.netflix.titus.common.util.CollectionsExt.last; import static com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator.budget; import static com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator.percentageOfHealthyPolicy; import static com.netflix.titus.testkit.model.eviction.DisruptionBudgetGenerator.unlimitedRate; import static com.netflix.titus.testkit.model.job.JobDescriptorGenerator.oneTaskBatchJobDescriptor; import static com.netflix.titus.testkit.model.job.JobDescriptorGenerator.oneTaskServiceJobDescriptor; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class JobModelSanitizationTest { private static final ResourceDimension MAX_CONTAINER_SIZE = new ResourceDimension(64, 16, 256_000_000, 256_000_000, 10_000, 64); private static final MapConfig CONFIG = MapConfig.from(ImmutableMap.of( "titusMaster.job.configuration.defaultSecurityGroups", "sg-12345,sg-34567", "titusMaster.job.configuration.defaultIamRole", "iam-12345", "titusMaster.job.configuration.containerHealthProviders", "eureka,healthCheckPoller" )); private final JobConfiguration constraints = new ConfigProxyFactory(CONFIG, DefaultDecoder.INSTANCE, new DefaultPropertyFactory(CONFIG)) .newProxy(JobConfiguration.class); private EntitySanitizer entitySanitizer; @Before public void setUp() { entitySanitizer = newJobSanitizer(VerifierMode.Strict); } @Test public void testValidBatchJob() { // In test descriptor, make sure we do not use default network throughput. Job<BatchJobExt> job = JobGenerator.batchJobs( oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(c -> c.getContainerResources().toBuilder().withNetworkMbps(256).build())) ).getValue(); assertThat(entitySanitizer.validate(job)).isEmpty(); assertThat(entitySanitizer.sanitize(job)).isEmpty(); } @Test public void testNetworkAllocationAdjustment() { Job<BatchJobExt> job = JobGenerator.batchJobs( oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(c -> c.getContainerResources().toBuilder().withNetworkMbps(10).build())) ).getValue(); assertThat(entitySanitizer.validate(job)).isEmpty(); Optional<Job<BatchJobExt>> updated = entitySanitizer.sanitize(job); assertThat(updated).isPresent(); assertThat(updated.get().getJobDescriptor().getContainer().getContainerResources().getNetworkMbps()).isEqualTo(128); } @Test public void testJobWithNullFieldValues() { Job<BatchJobExt> job = JobGenerator.batchJobs( oneTaskBatchJobDescriptor().but(jd -> jd.toBuilder().withContainer(null).build() ) ).getValue(); assertThat(entitySanitizer.sanitize(job)).isEmpty(); assertThat(entitySanitizer.validate(job)).isNotEmpty(); } @Test public void testJobWithTooLargeContainerInStrictMode() { assertThat(entitySanitizer.validate(newTooLargeJob())).hasSize(1); } @Test public void testJobWithTooLargeContainerInPermissiveMode() { assertThat(newJobSanitizer(VerifierMode.Permissive).validate(newTooLargeJob())).isEmpty(); } private Job<BatchJobExt> newTooLargeJob() { return JobGenerator.batchJobs( oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(container -> container.getContainerResources().toBuilder().withCpu(100).build() )) ).getValue(); } @Test public void testBatchTaskWithNullFieldValues() { BatchJobTask task = JobGenerator.batchTasks(JobGenerator.batchJobs(oneTaskBatchJobDescriptor()).getValue()).getValue().toBuilder() .withStatus(null) .build(); assertThat(entitySanitizer.sanitize(task)).isEmpty(); assertThat(entitySanitizer.validate(task)).isNotEmpty(); } @Test public void testServiceTaskWithNullFieldValues() { ServiceJobTask task = JobGenerator.serviceTasks(JobGenerator.serviceJobs(oneTaskServiceJobDescriptor()).getValue()).getValue().toBuilder() .withStatus(null) .build(); assertThat(entitySanitizer.sanitize(task)).isEmpty(); assertThat(entitySanitizer.validate(task)).isNotEmpty(); } @Test public void testBatchJobWithInvalidSecurityGroups() { JobDescriptor<BatchJobExt> jobDescriptor = oneTaskBatchJobDescriptor(); JobDescriptor<BatchJobExt> noSecurityProfileDescriptor = JobModel.newJobDescriptor(jobDescriptor) .withContainer(JobModel.newContainer(jobDescriptor.getContainer()) .withSecurityProfile( JobModel.newSecurityProfile(jobDescriptor.getContainer().getSecurityProfile()) .withSecurityGroups(Collections.singletonList("abcd")) .build()) .build() ).build(); Job<BatchJobExt> job = JobGenerator.batchJobs(noSecurityProfileDescriptor).getValue(); // Security group violation expected assertThat(entitySanitizer.validate(job)).hasSize(1); } @Test public void testBatchWithNoSecurityGroup() { JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(c -> c.getSecurityProfile().toBuilder().withSecurityGroups(Collections.emptyList()).build() )); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getField()).contains("securityGroups"); } @Test public void testBatchWithTooManySecurityGroups() { JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(c -> c.getSecurityProfile().toBuilder().withSecurityGroups( asList("sg-1", "sg-2", "sg-3", "sg-4", "sg-5", "sg-6", "sg-7") ).build() )); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getField()).contains("securityGroups"); } @Test public void testBatchWithNoIamRole() { JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().but(c -> c.getSecurityProfile().toBuilder().withIamRole("").build() )); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getField()).contains("iamRole"); } @Test public void testBatchJobWithMissingImageTagAndDigest() { JobDescriptor<BatchJobExt> jobDescriptor = oneTaskBatchJobDescriptor(); JobDescriptor<BatchJobExt> noImageTagAndDigestDescriptor = JobModel.newJobDescriptor(jobDescriptor) .withContainer(JobModel.newContainer(jobDescriptor.getContainer()) .withImage(Image.newBuilder() .withName("imageName") .build() ) .build() ).build(); Job<BatchJobExt> job = JobGenerator.batchJobs(noImageTagAndDigestDescriptor).getValue(); // Image digest and tag violation expected Set<ValidationError> violations = entitySanitizer.validate(job); assertThat(violations).hasSize(1); assertThat(violations.iterator().next().getMessage().contains("must specify a valid digest or tag")); } @Test public void testBatchJobWithIncompleteEfsDefinition() { JobDescriptor<BatchJobExt> jobDescriptor = oneTaskBatchJobDescriptor(); JobDescriptor<BatchJobExt> incompleteEfsDefinition = JobModel.newJobDescriptor(jobDescriptor) .withContainer(JobModel.newContainer(jobDescriptor.getContainer()) .withContainerResources( JobModel.newContainerResources(jobDescriptor.getContainer().getContainerResources()) .withEfsMounts(Collections.singletonList( new EfsMount("efsId#1", "/data", null, null) )) .build()) .build() ).build(); Job<BatchJobExt> job = JobGenerator.batchJobs(incompleteEfsDefinition).getValue(); // EFS violation expected assertThat(entitySanitizer.validate(job)).hasSize(1); // Now do cleanup Job<BatchJobExt> sanitized = entitySanitizer.sanitize(job).get(); assertThat(entitySanitizer.validate(sanitized)).isEmpty(); } @Test public void testJobWithShmTooLarge() { JobDescriptor<BatchJobExt> jobDescriptor = oneTaskBatchJobDescriptor(); JobDescriptor<BatchJobExt> shmTooLarge = JobModel.newJobDescriptor(jobDescriptor) .withContainer(JobModel.newContainer(jobDescriptor.getContainer()) .withContainerResources( JobModel.newContainerResources(jobDescriptor.getContainer().getContainerResources()) .withMemoryMB(1024) .withShmMB(2048) .build() ).build() ).build(); Job<BatchJobExt> job = JobGenerator.batchJobs(shmTooLarge).getValue(); assertThat(entitySanitizer.validate(job)).hasSize(1); } @Test public void testJobWithUnsetShm() { JobDescriptor<BatchJobExt> jobDescriptor = oneTaskBatchJobDescriptor(); JobDescriptor<BatchJobExt> shmUnset = JobModel.newJobDescriptor(jobDescriptor) .withContainer(JobModel.newContainer(jobDescriptor.getContainer()) .withContainerResources( JobModel.newContainerResources(jobDescriptor.getContainer().getContainerResources()) .withShmMB(0) .build() ).build() ).build(); Job<BatchJobExt> job = JobGenerator.batchJobs(shmUnset).getValue(); assertThat(job.getJobDescriptor().getContainer().getContainerResources().getShmMB()).isZero(); // Now do cleanup Job<BatchJobExt> sanitized = entitySanitizer.sanitize(job).get(); assertThat(entitySanitizer.validate(sanitized)).isEmpty(); assertThat(sanitized.getJobDescriptor().getContainer().getContainerResources().getShmMB()) .isEqualTo(constraints.getShmMegabytesDefault()); } @Test public void testJobWithTooLargeEntryPoint() { // Make key/value pair size 1MB char[] manyChars = new char[1025]; Arrays.fill(manyChars, '0'); String bigString = new String(manyChars); List<String> entryPoint = new ArrayList<>(); for (int i = 0; i < JobAssertions.MAX_ENTRY_POINT_SIZE_SIZE_KB; i++) { entryPoint.add(bigString); } JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().toBuilder().withEntryPoint(entryPoint).build()); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getDescription()).contains("Entry point size exceeds the limit 16KB"); } @Test public void testJobWithTooLargeEnvironmentVariables() { // Make key/value pair size 1MB char[] manyChars = new char[512 * 1024]; Arrays.fill(manyChars, '0'); String bigString = new String(manyChars); Map<String, String> largeEnv = new HashMap<>(); for (int i = 0; i < JobConfiguration.MAX_ENVIRONMENT_VARIABLES_SIZE_KB; i++) { largeEnv.put(bigString + i, bigString); } JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.getContainer().toBuilder().withEnv(largeEnv).build()); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getDescription()).contains("Container environment variables size exceeds the limit"); } @Test public void testJobWithValidContainerHealthProvider() { Set<ValidationError> violations = entitySanitizer.validate(newJobWithContainerHealthProvider("eureka")); assertThat(violations).hasSize(0); } @Test public void testJobWithInvalidContainerHealthProvider() { Set<ValidationError> violations = entitySanitizer.validate(newJobWithContainerHealthProvider("not_healthy")); assertThat(violations).hasSize(1); assertThat(first(violations).getDescription()).isEqualTo("Unknown container health service: not_healthy"); } @Test public void testJobWithInvalidDisruptionBudgetTimeWindow() { JobDescriptor<BatchJobExt> badJobDescriptor = changeDisruptionBudget( oneTaskBatchJobDescriptor(), budget(percentageOfHealthyPolicy(50), unlimitedRate(), Collections.singletonList(TimeWindow.newBuilder() .withDays(Day.Monday) .withwithHourlyTimeWindows(16, 8) .withTimeZone("PST") .build() )) ); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(1); assertThat(first(violations).getDescription()).isEqualTo("'startHour'(16) must be < 'endHour'(8)"); } @Test public void testJobWithInvalidPlatformSidecar() { PlatformSidecar badPS = PlatformSidecar.newBuilder().withName("BAD_NAME").withChannel("BAD_CHANNEL").build(); JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.toBuilder().withPlatformSidecars(Collections.singletonList(badPS)).build()); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(2); } @Test public void testJobWithInvalidVolume() { VolumeSource vs = new SaaSVolumeSource("BAD_SAAS_NAME"); Volume badVolume = Volume.newBuilder().withName("BAD_NAME").withVolumeSource(vs).build(); JobDescriptor<BatchJobExt> badJobDescriptor = oneTaskBatchJobDescriptor().but(jd -> jd.toBuilder().withVolumes(Collections.singletonList(badVolume)).build()); Set<ValidationError> violations = entitySanitizer.validate(badJobDescriptor); assertThat(violations).hasSize(2); } private JobDescriptor<BatchJobExt> newJobWithContainerHealthProvider(String healthProviderName) { return changeDisruptionBudget( oneTaskBatchJobDescriptor(), budget(percentageOfHealthyPolicy(50), unlimitedRate(), Collections.emptyList()).toBuilder() .withContainerHealthProviders(Collections.singletonList(ContainerHealthProvider.named(healthProviderName))) .build() ); } private EntitySanitizer newJobSanitizer(VerifierMode verifierMode) { return new JobSanitizerBuilder() .withVerifierMode(verifierMode) .withJobConstraintConfiguration(constraints) .withJobAsserts(new JobAssertions(constraints, capacityGroup -> MAX_CONTAINER_SIZE)) .build(); } }
9,420
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/SchedulingConstraintValidatorTest.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.titus.api.jobmanager.model.job.sanitizer; import com.google.common.collect.ImmutableMap; import com.netflix.titus.api.jobmanager.JobConstraints; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class SchedulingConstraintValidatorTest { private Validator validator; private static final String EL_EXPRESSION_MESSAGE = "#{#this.class.name.substring(0,5) == 'com.g' ? 'FOO' : T(java.lang.Runtime).getRuntime().exec(new java.lang.String(T(java.util.Base64).getDecoder().decode('dG91Y2ggL3RtcC9wd25lZA=='))).class.name}"; private static final String RCE_VIOLATION_MESSAGE = "Unrecognized constraints [\\#\\{\\#this.class.name.substring(0,5) == 'com.g' ? 'foo' : t(java.lang.runtime).getruntime().exec(new java.lang.string(t(java.util.base64).getdecoder().decode('dg91y2ggl3rtcc9wd25lza=='))).class.name\\}]"; @Before public void setUp() { validator = Validation.buildDefaultValidatorFactory().getValidator(); } @Test public void testValidSchedulingConstraint() { Map<String, String> validConstraintMap = JobConstraints.CONSTRAINT_NAMES.stream().collect(Collectors.toMap(Function.identity(), containerName -> "random_string")); assertThat(validator.validate(new ConstraintMap(validConstraintMap))).isEmpty(); } @Test public void testInvalidSchedulingConstraint() { String randomKey = UUID.randomUUID().toString(); String expectedViolationString = "Unrecognized constraints [" + randomKey + "]"; Map<String, String> invalidConstraintMap = ImmutableMap.of(randomKey, "test"); Set<ConstraintViolation<ConstraintMap>> violations = validator.validate(new ConstraintMap(invalidConstraintMap)); ConstraintViolation<ConstraintMap> constraintMapConstraintViolation = violations.stream().findFirst().orElseThrow(() -> new AssertionError("Expected violation not found")); assertThat(constraintMapConstraintViolation.getMessage()).isEqualTo(expectedViolationString); } @Test public void testRceAttemptInSchedulingConstraint() { Map<String, String> invalidConstraintMap = ImmutableMap.of(EL_EXPRESSION_MESSAGE, "test"); Set<ConstraintViolation<ConstraintMap>> violations = validator.validate(new ConstraintMap(invalidConstraintMap)); ConstraintViolation<ConstraintMap> constraintMapConstraintViolation = violations.stream().findFirst().orElseThrow(() -> new AssertionError("Expected violation not found")); assertThat(constraintMapConstraintViolation.getMessageTemplate()).isEqualTo(RCE_VIOLATION_MESSAGE); } static class ConstraintMap { @SchedulingConstraintValidator.SchedulingConstraint final Map<String, String> constraintMap; public ConstraintMap(Map<String, String> map) { this.constraintMap = map; } } }
9,421
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/loadbalancer/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/loadbalancer/model/sanitizer/DefaultLoadBalancerJobValidatorTest.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.titus.api.loadbalancer.model.sanitizer; import java.util.Optional; import java.util.concurrent.TimeUnit; import com.netflix.titus.api.jobmanager.model.job.Container; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Image; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.JobState; import com.netflix.titus.api.jobmanager.model.job.JobStatus; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.service.LoadBalancerException; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryLoadBalancerStore; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultLoadBalancerJobValidatorTest { private static Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerJobValidatorTest.class); private static final long TIMEOUT_MS = 30_000; private V3JobOperations jobOperations; private LoadBalancerStore loadBalancerStore; private LoadBalancerValidationConfiguration loadBalancerValidationConfiguration; private DefaultLoadBalancerJobValidator loadBalancerValidator; private static final String JOB_ID = "Titus-123"; @Before public void setUp() throws Exception { jobOperations = mock(V3JobOperations.class); loadBalancerStore = new InMemoryLoadBalancerStore(); loadBalancerValidationConfiguration = mock(LoadBalancerValidationConfiguration.class); loadBalancerValidator = new DefaultLoadBalancerJobValidator(jobOperations, loadBalancerStore, loadBalancerValidationConfiguration); } @Test public void testValidateJobExists() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.empty()); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.JobNotFound); } @Test public void testValidateJobAccepted() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Finished) .build()) .build())); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.UnexpectedJobState); } @Test public void testValidateJobIsService() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<BatchJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<BatchJobExt>newBuilder() .build()) .build())); Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(JobManagerException.class); assertThat(((JobManagerException) thrown).getErrorCode()).isEqualTo(JobManagerException.ErrorCode.NotServiceJob); } @Test public void testValidateMaxLoadBalancers() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<ServiceJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<ServiceJobExt>newBuilder() .withExtensions(ServiceJobExt.newBuilder().build()) .withContainer(Container.newBuilder() .withImage(Image.newBuilder().build()) .withContainerResources(ContainerResources.newBuilder() .withAllocateIP(true) .build()) .build()) .build()) .build())); when(loadBalancerValidationConfiguration.getMaxLoadBalancersPerJob()).thenReturn(30); for (int i = 0; i < loadBalancerValidationConfiguration.getMaxLoadBalancersPerJob() + 1; i++) { loadBalancerStore.addOrUpdateLoadBalancer(new JobLoadBalancer(JOB_ID, "LoadBalancer-" + i), JobLoadBalancer.State.ASSOCIATED).await(TIMEOUT_MS, TimeUnit.MILLISECONDS); } Throwable thrown = catchThrowable(() -> loadBalancerValidator.validateJobId(JOB_ID)); assertThat(thrown).isInstanceOf(LoadBalancerException.class); assertThat(((LoadBalancerException) thrown).getErrorCode()).isEqualTo(LoadBalancerException.ErrorCode.JobMaxLoadBalancers); } @Test public void testValidJob() throws Exception { when(jobOperations.getJob(JOB_ID)).thenReturn(Optional.of(Job.<ServiceJobExt>newBuilder() .withId(JOB_ID) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .build()) .withJobDescriptor(JobDescriptor.<ServiceJobExt>newBuilder() .withExtensions(ServiceJobExt.newBuilder().build()) .withContainer(Container.newBuilder() .withImage(Image.newBuilder().build()) .withContainerResources(ContainerResources.newBuilder() .withAllocateIP(true) .build()) .build()) .build()) .build())); assertThatCode(() -> loadBalancerValidator.validateJobId(JOB_ID)).doesNotThrowAnyException(); } }
9,422
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/agent/loadbalancer/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/agent/loadbalancer/model/sanitizer/LoadBalancerSanitizerBuilderTest.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.titus.api.agent.loadbalancer.model.sanitizer; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerSanitizerBuilder; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LoadBalancerSanitizerBuilderTest { private final EntitySanitizer sanitizer = new LoadBalancerSanitizerBuilder().build(); @Test public void testJobLoadBalancerValidation() throws Exception { JobLoadBalancer jobLoadBalancer = new JobLoadBalancer("Some JobId", "Some LoadBalancerId"); assertThat(sanitizer.validate(jobLoadBalancer)).isEmpty(); } @Test public void testEmptyJobIdValidation() throws Exception { JobLoadBalancer jobLoadBalancer = new JobLoadBalancer("", "Some LoadBalancerId"); assertThat(sanitizer.validate(jobLoadBalancer)).hasSize(1); } @Test public void testEmptyLoadBalancerIdValidation() throws Exception { JobLoadBalancer jobLoadBalancer = new JobLoadBalancer("Some JobId", ""); assertThat(sanitizer.validate(jobLoadBalancer)).hasSize(1); } }
9,423
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/appscale
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/appscale/model/PolicyConfigurationTest.java
package com.netflix.titus.api.appscale.model; import com.netflix.titus.api.json.ObjectMappers; import org.junit.Test; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; public class PolicyConfigurationTest { @Test public void deserializePolicyConfiguration() { String policyConfigStrNoMetricDimensions = "{\n" + " \"name\": null,\n" + " \"policyType\": \"StepScaling\",\n" + " \"stepScalingPolicyConfiguration\": {\n" + " \"metricAggregationType\": \"Maximum\",\n" + " \"adjustmentType\": \"ChangeInCapacity\",\n" + " \"minAdjustmentMagnitude\": null,\n" + " \"steps\": [\n" + " {\n" + " \"scalingAdjustment\": 1,\n" + " \"metricIntervalLowerBound\": 0.0,\n" + " \"metricIntervalUpperBound\": null\n" + " }\n" + " ],\n" + " \"coolDownSec\": 60\n" + " },\n" + " \"alarmConfiguration\": {\n" + " \"name\": null,\n" + " \"region\": null,\n" + " \"actionsEnabled\": true,\n" + " \"comparisonOperator\": \"GreaterThanThreshold\",\n" + " \"evaluationPeriods\": 1,\n" + " \"threshold\": 2.0,\n" + " \"metricNamespace\": \"titus/integrationTest\",\n" + " \"metricName\": \"RequestCount\",\n" + " \"statistic\": \"Sum\",\n" + " \"periodSec\": 60\n" + " },\n" + " \"targetTrackingPolicy\": null\n" + "}"; PolicyConfiguration policyConfigNoMetricDimension = ObjectMappers.readValue(ObjectMappers.appScalePolicyMapper(), policyConfigStrNoMetricDimensions, PolicyConfiguration.class); assertThat(policyConfigNoMetricDimension).isNotNull(); assertThat(policyConfigNoMetricDimension.getAlarmConfiguration().getDimensions()).isNull(); String policyConfigStrWithMetricDimensions = "{\n" + " \"name\": null,\n" + " \"policyType\": \"StepScaling\",\n" + " \"stepScalingPolicyConfiguration\": {\n" + " \"metricAggregationType\": \"Maximum\",\n" + " \"adjustmentType\": \"ChangeInCapacity\",\n" + " \"minAdjustmentMagnitude\": null,\n" + " \"steps\": [\n" + " {\n" + " \"scalingAdjustment\": 1,\n" + " \"metricIntervalLowerBound\": 0.0,\n" + " \"metricIntervalUpperBound\": null\n" + " }\n" + " ],\n" + " \"coolDownSec\": 60\n" + " },\n" + " \"alarmConfiguration\": {\n" + " \"name\": null,\n" + " \"region\": null,\n" + " \"actionsEnabled\": true,\n" + " \"comparisonOperator\": \"GreaterThanThreshold\",\n" + " \"evaluationPeriods\": 1,\n" + " \"threshold\": 2.0,\n" + " \"metricNamespace\": \"titus/integrationTest\",\n" + " \"metricName\": \"RequestCount\",\n" + " \"statistic\": \"Sum\",\n" + " \"periodSec\": 60,\n" + " \"unknownField\": 100,\n" + " \"dimensions\": [\n" + " {\n" + " \"Name\": \"foo\",\n" + " \"Value\": \"bar\"\n" + " },\n" + " {\n" + " \"Name\": \"tier\",\n" + " \"Value\": \"1\"\n" + " }\n" + " ]\n" + " },\n" + " \"targetTrackingPolicy\": null\n" + "}"; PolicyConfiguration policyConfigWithMetricDimensions = ObjectMappers.readValue(ObjectMappers.appScalePolicyMapper(), policyConfigStrWithMetricDimensions, PolicyConfiguration.class); assertThat(policyConfigWithMetricDimensions).isNotNull(); assertThat(policyConfigWithMetricDimensions.getAlarmConfiguration().getDimensions()).isNotNull(); assertThat(policyConfigWithMetricDimensions.getAlarmConfiguration().getDimensions().size()).isEqualTo(2); } }
9,424
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/appscale/model
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/appscale/model/sanitizer/ScalingPolicyModelSanitizationTest.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.titus.api.appscale.model.sanitizer; import java.util.Set; import com.netflix.titus.api.appscale.model.AlarmConfiguration; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.PolicyConfiguration; import com.netflix.titus.api.appscale.model.StepScalingPolicyConfiguration; import com.netflix.titus.api.appscale.model.TargetTrackingPolicy; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import com.netflix.titus.common.model.sanitizer.ValidationError; import com.netflix.titus.common.util.CollectionsExt; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class ScalingPolicyModelSanitizationTest { @Test public void testInvalidScalingConfigurationWithBothPolicies() { PolicyConfiguration policyConfiguration = PolicyConfiguration .newBuilder() .withStepScalingPolicyConfiguration(mock(StepScalingPolicyConfiguration.class)) .withAlarmConfiguration(mock(AlarmConfiguration.class)) .withTargetTrackingPolicy(mock(TargetTrackingPolicy.class)) .build(); AutoScalingPolicy autoScalingPolicy = AutoScalingPolicy .newBuilder() .withPolicyConfiguration(policyConfiguration) .build(); Set<ValidationError> validationErrors = newScalingPolicySanitizer().validate(autoScalingPolicy); assertThat(validationErrors).hasSize(1); assertThat(CollectionsExt.first(validationErrors).getDescription()).isEqualTo("exactly one scaling policy should be set"); } @Test public void testInvalidStepScalingPolicyNoAlarmConfiguration() { PolicyConfiguration policyConfiguration = PolicyConfiguration .newBuilder() .withStepScalingPolicyConfiguration(mock(StepScalingPolicyConfiguration.class)) .build(); AutoScalingPolicy autoScalingPolicy = AutoScalingPolicy .newBuilder() .withPolicyConfiguration(policyConfiguration) .build(); Set<ValidationError> validationErrors = newScalingPolicySanitizer().validate(autoScalingPolicy); assertThat(validationErrors).hasSize(1); assertThat(CollectionsExt.first(validationErrors).getDescription()).isEqualTo("alarmConfiguration must be specified for a step scaling policy"); } private EntitySanitizer newScalingPolicySanitizer() { return new ScalingPolicySanitizerBuilder().build(); } }
9,425
0
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/supervisor/service
Create_ds/titus-control-plane/titus-api/src/test/java/com/netflix/titus/api/supervisor/service/resolver/AggregatingLocalMasterReadinessResolverTest.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.titus.api.supervisor.service.resolver; import java.util.Arrays; import java.util.Iterator; import com.netflix.titus.api.supervisor.model.ReadinessState; import com.netflix.titus.api.supervisor.model.ReadinessStatus; import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import reactor.core.publisher.EmitterProcessor; import static org.mockito.Mockito.when; public class AggregatingLocalMasterReadinessResolverTest { private final TitusRuntime titusRuntime = TitusRuntimes.internal(); private final LocalMasterReadinessResolver delegate1 = Mockito.mock(LocalMasterReadinessResolver.class); private final LocalMasterReadinessResolver delegate2 = Mockito.mock(LocalMasterReadinessResolver.class); private final EmitterProcessor<ReadinessStatus> delegate1Processor = EmitterProcessor.create(1); private final EmitterProcessor<ReadinessStatus> delegate2Processor = EmitterProcessor.create(1); private AggregatingLocalMasterReadinessResolver resolver; @Before public void setUp() { when(delegate1.observeLocalMasterReadinessUpdates()).thenReturn(delegate1Processor); when(delegate2.observeLocalMasterReadinessUpdates()).thenReturn(delegate2Processor); resolver = new AggregatingLocalMasterReadinessResolver(Arrays.asList(delegate1, delegate2), titusRuntime); } @Test(timeout = 30_000) public void testAggregation() { Iterator<ReadinessStatus> it = resolver.observeLocalMasterReadinessUpdates().toIterable().iterator(); // Enabled + Disabled == Disabled delegate1Processor.onNext(newStatus(ReadinessState.Enabled)); delegate2Processor.onNext(newStatus(ReadinessState.Disabled)); Assertions.assertThat(it.next().getState()).isEqualTo(ReadinessState.Disabled); // Enabled + Enabled == Enabled delegate2Processor.onNext(newStatus(ReadinessState.Enabled)); Assertions.assertThat(it.next().getState()).isEqualTo(ReadinessState.Enabled); // Disabled + Enabled == Disabled delegate1Processor.onNext(newStatus(ReadinessState.Disabled)); Assertions.assertThat(it.next().getState()).isEqualTo(ReadinessState.Disabled); } private ReadinessStatus newStatus(ReadinessState state) { return ReadinessStatus.newBuilder().withState(state).build(); } }
9,426
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/FeatureRolloutPlans.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.titus.api; import com.netflix.titus.common.util.feature.FeatureRollout; public interface FeatureRolloutPlans { @FeatureRollout( featureId = "securityGroupsRequired", deadline = "03/30/2019", description = "Require all clients to provide the security group in the job descriptor." ) String SECURITY_GROUPS_REQUIRED_FEATURE = "securityGroupsRequired"; @FeatureRollout( featureId = "iamRoleRequired", deadline = "03/30/2019", description = "Require all clients to provide the IAM role in the job descriptor." ) String IAM_ROLE_REQUIRED_FEATURE = "iamRoleRequired"; @FeatureRollout( featureId = "entryPointStrictValidation", deadline = "06/30/2020", description = "Jobs with entry point binaries containing spaces are likely relying on the legacy shell parsing " + "being done by titus-executor, and are submitting entry points as a flat string, instead of breaking it into a list of arguments. " + "Jobs that have a command set will fall on the new code path that does not do any shell parsing, and does not need to be checked." ) String ENTRY_POINT_STRICT_VALIDATION_FEATURE = "entryPointStrictValidation"; @FeatureRollout( featureId = "environmentVariableNamesStrictValidation", deadline = "06/30/2019", description = "Restricts the environment variables names to ASCII letters, digits and '_', according to the http://pubs.opengroup.org/onlinepubs/9699919799 spec" ) String ENVIRONMENT_VARIABLE_NAMES_STRICT_VALIDATION_FEATURE = "environmentVariableNamesStrictValidation"; @FeatureRollout( featureId = "minDiskSizeStrictValidationFeature", deadline = "03/30/2019", description = "Lower bound on the disk size." ) String MIN_DISK_SIZE_STRICT_VALIDATION_FEATURE = "minDiskSizeStrictValidationFeature"; @FeatureRollout( featureId = "jobAuthorizationFeature", deadline = "06/30/2019", description = "Allowing job mutations for authorized users only " ) String JOB_AUTHORIZATION_FEATURE = "jobAuthorizationFeature"; @FeatureRollout( featureId = "accountIdAndSubnetsFeature", deadline = "10/01/2020", description = "Jobs should provide AWS accountId and corresponding subnets the container should launch in" ) String CONTAINER_ACCOUNT_ID_AND_SUBNETS_REQUIRED_FEATURE = "accountIdAndSubnetsFeature"; }
9,427
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/FeatureActivationConfiguration.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.titus.api; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; /** * This configuration interface is a centralized store for all feature flags. Putting all feature flags in one place * should improve the project maintenance. */ @Configuration(prefix = "titus.feature") public interface FeatureActivationConfiguration { /** * This flag enables the integration between the Titus Gateway and Task Relocation components. * <p> * This change was introduced in Q4/2018. The feature flag should be removed by the end of Q2/2019. */ @DefaultValue("true") boolean isMergingTaskMigrationPlanInGatewayEnabled(); /** * Toggle validation of compatibility between Jobs when moving tasks across them. It is useful during emergencies to * force tasks to be moved, but it adds risk of causing inconsistencies in Jobs with incompatible tasks. Use with * care. */ @DefaultValue("true") boolean isMoveTaskValidationEnabled(); /** * Enable binpacking of tasks based on how hard they are to relocate */ @DefaultValue("true") boolean isRelocationBinpackingEnabled(); /** * Enable shared informer on Titus gateway */ @DefaultValue("false") boolean isInjectingContainerStatesEnabled(); /** * Set to true to enable integration with Kubernetes capacity group CRD store. * Set to false to persist capacity group management data in Cassandra. */ @DefaultValue("false") boolean isKubeCapacityGroupIntegrationEnabled(); }
9,428
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/JobConstraints.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.titus.api.jobmanager; import java.util.Set; import static com.netflix.titus.common.util.CollectionsExt.asSet; /** * Constants and functions for job soft and hard constraints. Constraint names are case insensitive. */ public class JobConstraints { /** * Exclusive host for a task. */ public static final String EXCLUSIVE_HOST = "exclusivehost"; /** * Each task from a job is placed on a different agent. */ public static final String UNIQUE_HOST = "uniquehost"; /** * Availability zone balancing. */ public static final String ZONE_BALANCE = "zonebalance"; /** * Placement restricted to an agent that belongs to active ASG. */ public static final String ACTIVE_HOST = "activehost"; /** * Placement restricted to a specific availability zone. */ public static final String AVAILABILITY_ZONE = "availabilityzone"; /** * Placement restricted to an agent with the given machine id. */ public static final String MACHINE_ID = "machineid"; /** * Placement restricted to an agent in the given machine group. */ public static final String MACHINE_GROUP = "machinegroup"; /** * Placement restricted to an agent with the given machine type. */ public static final String MACHINE_TYPE = "machinetype"; /** * Constrain Kubernetes pod scheduling to nodes with a given Kubernetes backend version. */ public static final String KUBE_BACKEND = "kubebackend"; /** * Constrain Kubernetes pod scheduling to nodes with a given CPU model. */ public static final String CPU_MODEL= "cpumodel"; /** * Taints that are tolerated on Kubernetes Nodes. */ public static final String TOLERATION = "toleration"; public static final Set<String> CONSTRAINT_NAMES = asSet( UNIQUE_HOST, EXCLUSIVE_HOST, ZONE_BALANCE, ACTIVE_HOST, AVAILABILITY_ZONE, MACHINE_ID, MACHINE_GROUP, MACHINE_TYPE, KUBE_BACKEND, CPU_MODEL ); }
9,429
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/TaskAttributes.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.titus.api.jobmanager; public final class TaskAttributes { /* * Agent attributes. */ public static final String TASK_ATTRIBUTES_AGENT_REGION = "agent.region"; public static final String TASK_ATTRIBUTES_AGENT_ZONE = "agent.zone"; public static final String TASK_ATTRIBUTES_AGENT_AMI = "agent.ami"; public static final String TASK_ATTRIBUTES_AGENT_CLUSTER = "agent.cluster"; public static final String TASK_ATTRIBUTES_AGENT_ASG = "agent.asg"; public static final String TASK_ATTRIBUTES_AGENT_STACK = "agent.stack"; public static final String TASK_ATTRIBUTES_AGENT_HOST = "agent.host"; public static final String TASK_ATTRIBUTES_AGENT_HOST_IP = "agent.hostIp"; public static final String TASK_ATTRIBUTES_AGENT_INSTANCE_ID = "agent.instanceId"; public static final String TASK_ATTRIBUTES_AGENT_ITYPE = "agent.itype"; /** * Agent ENI resources. */ public static final String TASK_ATTRIBUTES_AGENT_RES = "agent.res"; /* * Kube attributes. */ public static final String TASK_ATTRIBUTES_KUBE_NODE_NAME = "kube.nodeName"; public static final String TASK_ATTRIBUTES_RESOURCE_POOL = "resourcePool"; public static final String TASK_ATTRIBUTES_POD_CREATED = "kube.podCreated"; /* * Task attributes. */ public static final String TASK_ATTRIBUTES_TASK_INDEX = "task.index"; public static final String TASK_ATTRIBUTES_TASK_RESUBMIT_OF = "task.resubmitOf"; public static final String TASK_ATTRIBUTES_TASK_ORIGINAL_ID = "task.originalId"; public static final String TASK_ATTRIBUTES_RESUBMIT_NUMBER = "task.resubmitNumber"; public static final String TASK_ATTRIBUTES_SYSTEM_RESUBMIT_NUMBER = "task.systemResubmitNumber"; public static final String TASK_ATTRIBUTES_EVICTION_RESUBMIT_NUMBER = "task.evictionResubmitNumber"; public static final String TASK_ATTRIBUTES_RETRY_DELAY = "task.retryDelay"; public static final String TASK_ATTRIBUTES_CONTAINER_IP = "task.containerIp"; public static final String TASK_ATTRIBUTES_CONTAINER_IPV4 = "task.containerIPv4"; public static final String TASK_ATTRIBUTES_CONTAINER_IPV6 = "task.containerIPv6"; public static final String TASK_ATTRIBUTES_ELASTIC_IPV4 = "task.elasticIPv4"; /* * TASK_ATTRIBUTES_TRANSITION_IPV4 is a special IP that represents the IP that * Tasks in the special Ipv6AndIpv4Fallback network Mode use. * It represents a kind of "NAT" ip. It should not be considered the normal * IPv4 for a task (you cannot ssh to it), therefore it gets a distinct attribute. */ public static final String TASK_ATTRIBUTES_TRANSITION_IPV4 = "task.transitionIPv4"; public static final String TASK_ATTRIBUTES_NETWORK_INTERFACE_ID = "task.networkInterfaceId"; public static final String TASK_ATTRIBUTES_NETWORK_INTERFACE_INDEX = "task.networkInterfaceIndex"; public static final String TASK_ATTRIBUTES_NETWORK_EFFECTIVE_MODE = "task.effectiveNetworkMode"; public static final String TASK_ATTRIBUTES_EXECUTOR_URI_OVERRIDE = "task.executorUriOverride"; public static final String TASK_ATTRIBUTES_TIER = "task.tier"; public static final String TASK_ATTRIBUTES_IP_ALLOCATION_ID = "task.ipAllocationId"; public static final String TASK_ATTRIBUTES_IN_USE_IP_ALLOCATION = "task.ipAllocationAlreadyInUseByTask"; public static final String TASK_ATTRIBUTES_EBS_VOLUME_ID = "task.ebs.volumeId"; public static final String TASK_ATTRIBUTES_NETWORK_SUBNETS = "task.networkSubnets"; public static final String TASK_ATTRIBUTES_NETWORK_SECURITY_GROUPS = "task.networkSecurityGroups"; /* * Log location attributes. */ public static final String TASK_ATTRIBUTE_LOG_PREFIX = "task.log."; public static final String TASK_ATTRIBUTE_S3_BUCKET_NAME = TASK_ATTRIBUTE_LOG_PREFIX + "s3BucketName"; public static final String TASK_ATTRIBUTE_S3_PATH_PREFIX = TASK_ATTRIBUTE_LOG_PREFIX + "s3PathPrefix"; public static final String TASK_ATTRIBUTE_LOG_UI_LOCATION = TASK_ATTRIBUTE_LOG_PREFIX + "uiLogLocation"; public static final String TASK_ATTRIBUTE_LOG_LIVE_STREAM = TASK_ATTRIBUTE_LOG_PREFIX + "liveStream"; public static final String TASK_ATTRIBUTE_LOG_S3_PREFIX = TASK_ATTRIBUTE_LOG_PREFIX + "s3."; public static final String TASK_ATTRIBUTE_LOG_S3_ACCOUNT_NAME = TASK_ATTRIBUTE_LOG_S3_PREFIX + "accountName"; public static final String TASK_ATTRIBUTE_LOG_S3_ACCOUNT_ID = TASK_ATTRIBUTE_LOG_S3_PREFIX + "accountId"; public static final String TASK_ATTRIBUTE_LOG_S3_BUCKET_NAME = TASK_ATTRIBUTE_LOG_S3_PREFIX + "bucketName"; public static final String TASK_ATTRIBUTE_LOG_S3_KEY = TASK_ATTRIBUTE_LOG_S3_PREFIX + "key"; public static final String TASK_ATTRIBUTE_LOG_S3_REGION = TASK_ATTRIBUTE_LOG_S3_PREFIX + "region"; /** * Task moved from one job to another. */ public static final String TASK_ATTRIBUTES_MOVED_FROM_JOB = "task.movedFromJob"; /* * Cell info. */ public static final String TASK_ATTRIBUTES_CELL = JobAttributes.JOB_ATTRIBUTES_CELL; public static final String TASK_ATTRIBUTES_STACK = JobAttributes.JOB_ATTRIBUTES_STACK; private TaskAttributes() { } }
9,430
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/JobAttributes.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.titus.api.jobmanager; /** * Constant keys for Job attributes. Attributes that begin with <b>titus.</b> are readonly system generated attributes * while attributes that begin with <b>titusParameter.</b> are user supplied parameters. */ public final class JobAttributes { public static final String TITUS_ATTRIBUTE_PREFIX = "titus."; public static final String TITUS_PARAMETER_ATTRIBUTE_PREFIX = "titusParameter."; public static final String TITUS_PARAMETER_AGENT_PREFIX = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent."; public static final String JOB_ATTRIBUTE_SANITIZATION_PREFIX = TITUS_ATTRIBUTE_PREFIX + "sanitization."; public static final String PREDICTION_ATTRIBUTE_PREFIX = TITUS_ATTRIBUTE_PREFIX + "runtimePrediction."; // Job Descriptor Attributes /** * Job creator. */ public static final String JOB_ATTRIBUTES_CREATED_BY = TITUS_ATTRIBUTE_PREFIX + "createdBy"; /** * Job call reason */ public static final String JOB_ATTRIBUTES_CALL_REASON = TITUS_ATTRIBUTE_PREFIX + "callReason"; /** * Federated stack name. All cells under the same federated stack must share the same value. */ public static final String JOB_ATTRIBUTES_STACK = TITUS_ATTRIBUTE_PREFIX + "stack"; /** * Unique Cell name for a deployment that the Job has been assigned to. */ public static final String JOB_ATTRIBUTES_CELL = TITUS_ATTRIBUTE_PREFIX + "cell"; /** * This attribute specifies the destination cell the federation is configured to route the API request to. */ public static final String JOB_ATTRIBUTE_ROUTING_CELL = TITUS_ATTRIBUTE_PREFIX + "routingCell"; /** * Job id. When this attribute is present it signals the control plane that the id was created by federation * and should be used instead of minting a new value for any CreateJob API calls. */ public static final String JOB_ATTRIBUTES_FEDERATED_JOB_ID = TITUS_ATTRIBUTE_PREFIX + "federatedJobId"; /** * This attribute is used to persist original federated Job id that may have been used to populate job id. */ public static final String JOB_ATTRIBUTES_ORIGINAL_FEDERATED_JOB_ID = TITUS_ATTRIBUTE_PREFIX + "originalFederatedJobId"; /** * Set to true when sanitization for iam roles fails open */ public static final String JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IAM = JOB_ATTRIBUTE_SANITIZATION_PREFIX + "skipped.iam"; /** * Set to true when sanitization for container images (digest) fails open */ public static final String JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IMAGE = JOB_ATTRIBUTE_SANITIZATION_PREFIX + "skipped.image"; /** * Set to true when sanitization for container EBS volumes fails open */ public static final String JOB_ATTRIBUTES_SANITIZATION_SKIPPED_EBS = JOB_ATTRIBUTE_SANITIZATION_PREFIX + "skipped.ebs"; /** * Set to true when job runtime prediction fails open */ public static final String JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION = JOB_ATTRIBUTE_SANITIZATION_PREFIX + "skipped.runtimePrediction"; /** * Information about the prediction selector used in the evaluation process. */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_SELECTOR_INFO = PREDICTION_ATTRIBUTE_PREFIX + "selectorInfo"; /** * Predicted runtime for a particular job in seconds, used in opportunistic CPU scheduling */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC = PREDICTION_ATTRIBUTE_PREFIX + "predictedRuntimeSec"; /** * Confidence of the predicted runtime for a particular job */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE = PREDICTION_ATTRIBUTE_PREFIX + "confidence"; /** * Metadata (identifier) about what model generated predictions for a particular job */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID = PREDICTION_ATTRIBUTE_PREFIX + "modelId"; /** * Metadata (version) of the service that generated predictions for a particular job */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION = PREDICTION_ATTRIBUTE_PREFIX + "version"; /** * All available runtime predictions with their associated confidence, as returned from the predictions service for * a particular job. * <p> * These are informational, if any particular prediction is selected for a job, it will be reflected by * {@link JobAttributes#JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC} and {@link JobAttributes#JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE}. */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE = PREDICTION_ATTRIBUTE_PREFIX + "available"; /** * AB test metadata associated with a prediction. */ public static final String JOB_ATTRIBUTES_RUNTIME_PREDICTION_AB_TEST = PREDICTION_ATTRIBUTE_PREFIX + "abTest"; /** * Do not parse entry point into shell command, argument list */ public static final String JOB_PARAMETER_ATTRIBUTES_ENTRY_POINT_SKIP_SHELL_PARSING = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "entryPoint.skipShellParsing"; /** * Allow jobs to completely opt-out of having their runtime automatically predicted during admission */ public static final String JOB_PARAMETER_SKIP_RUNTIME_PREDICTION = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "runtimePrediction.skip"; /** * (Experimental) allow jobs to request being placed into a particular cell (affinity) */ public static final String JOB_PARAMETER_ATTRIBUTES_CELL_REQUEST = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "cell.request"; /** * (Experimental) allow jobs to request not being placed into a comma separated list of cell names (anti affinity) */ public static final String JOB_PARAMETER_ATTRIBUTES_CELL_AVOID = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "cell.avoid"; /** * A comma separated list specifying which taints this job can tolerate during scheduling. This job must be able to tolerate * all taints in order to be scheduled on that machine. */ public static final String JOB_PARAMETER_ATTRIBUTES_TOLERATIONS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "tolerations"; public static final String JOB_PARAMETER_RESOURCE_POOLS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "resourcePools"; /** * Informs a job intent to allow containers that are running on bad agents to be terminated */ public static final String JOB_PARAMETER_TERMINATE_ON_BAD_AGENT = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "terminateContainerOnBadAgent"; /* * Job security attributes. */ /** * Prefix for attributes derived from Job Metatron details. */ public static final String METATRON_ATTRIBUTE_PREFIX = "metatron."; /** * The Metatron auth context received from Metatron for the metatron signed job. */ public static final String JOB_SECURITY_ATTRIBUTE_METATRON_AUTH_CONTEXT = METATRON_ATTRIBUTE_PREFIX + "authContext"; // Container Attributes /** * Allow the task to use more CPU (as based on time slicing) than specified. */ public static final String JOB_PARAMETER_ATTRIBUTES_ALLOW_CPU_BURSTING = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.allowCpuBursting"; /** * Allow the task to use more Network (as based on time and bandwidth slicing) than specified. */ public static final String JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_BURSTING = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.allowNetworkBursting"; /** * Elastic IP pool */ public static final String JOB_PARAMETER_ATTRIBUTE_EIP_POOL = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.elasticIPPool"; /** * Elastic IPs */ public static final String JOB_PARAMETER_ATTRIBUTE_EIPS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.elasticIPs"; /** * Sets SCHED_BATCH -- Linux batch scheduling, for cache-friendly handling of lowprio, batch-like, CPU-bound, 100% non-interactive tasks. */ public static final String JOB_PARAMETER_ATTRIBUTES_SCHED_BATCH = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.schedBatch"; /** * Allows the creation of nested containers. */ public static final String JOB_PARAMETER_ATTRIBUTES_ALLOW_NESTED_CONTAINERS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.allowNestedContainers"; /** * How long to wait for a task (container) to exit on its own after sending a SIGTERM -- after this period elapses, a SIGKILL will sent. */ public static final String JOB_PARAMETER_ATTRIBUTES_KILL_WAIT_SECONDS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.killWaitSeconds"; /** * Require a token or not on the imds */ public static final String JOB_CONTAINER_ATTRIBUTE_IMDS_REQUIRE_TOKEN = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.imds.requireToken"; /* * Log location container attributes (set in {@link Container#getAttributes()}. */ /** * Custom S3 bucket log location. */ public static final String JOB_CONTAINER_ATTRIBUTE_S3_BUCKET_NAME = "titusParameter.agent.log.s3BucketName"; /** * Custom S3 bucket path prefix. */ public static final String JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX = "titusParameter.agent.log.s3PathPrefix"; /** * If a user specifies a custom bucket location, the S3 writer role will include the container's IAM role. * Otherwise default role will be used which has access to a default S3 bucket. */ public static final String JOB_CONTAINER_ATTRIBUTE_S3_WRITER_ROLE = "titusParameter.agent.log.s3WriterRole"; /** * Subnets to launch the container in. */ public static final String JOB_CONTAINER_ATTRIBUTE_SUBNETS = "titusParameter.agent.subnets"; /** * AccountId to launch the container in. */ public static final String JOB_CONTAINER_ATTRIBUTE_ACCOUNT_ID = "titusParameter.agent.accountId"; /** * Enable service mesh. */ public static final String JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_ENABLED = "titusParameter.agent.service.serviceMesh.enabled"; /** * Container to use for service mesh. */ public static final String JOB_CONTAINER_ATTRIBUTE_SERVICEMESH_CONTAINER = "titusParameter.agent.service.serviceMesh.container"; /** * Set to true when sanitization for container images (digest) fails open */ public static final String JOB_ATTRIBUTES_SANITIZATION_SKIPPED_SERVICEMESH_IMAGE = JOB_ATTRIBUTE_SANITIZATION_PREFIX + "skipped.serviceMesh"; /** * Enable TSA for perf-related syscalls */ public static final String JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_PERF_ENABLED = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.seccompAgentEnabledForPerfSyscalls"; /** * Enable TSA for network-related syscalls */ public static final String JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_NET_ENABLED = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.seccompAgentEnabledForNetSyscalls"; /** * Enable traffic steering */ public static final String JOB_CONTAINER_ATTRIBUTE_TRAFFIC_STEERING_ENABLED = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "agent.trafficSteeringEnabled"; /* * EBS volume job attributes (set in {@link JobDescriptor#getAttributes()}. * EBS volume IDs are attributes as we do not expect to expose them directly as first-class Titus API * constructs but rather wait until the Kubernetes API to expose them directly. * We expect the value to be a comma separated list of valid/existing EBS volume IDs. */ public static final String JOB_ATTRIBUTES_EBS_VOLUME_IDS = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "ebs.volumeIds"; public static final String JOB_ATTRIBUTES_EBS_MOUNT_POINT = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "ebs.mountPoint"; public static final String JOB_ATTRIBUTES_EBS_MOUNT_PERM = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "ebs.mountPerm"; public static final String JOB_ATTRIBUTES_EBS_FS_TYPE = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "ebs.fsType"; /* * Job topology spreading. */ /** * By default job spreading is disabled for batch jobs and enabled for service jobs. The default behavior can * be overridden with this property. */ public static final String JOB_ATTRIBUTES_SPREADING_ENABLED = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "spreading.enabled"; /** * Overrides the default max skew for a job topology spreading. For a job with availability percentage limit disruption * budget policy, the skew is computed as a percentage of pods that can be taken down. For other disruption budgets * no max skew is set. Job topology spreading is a soft constraint, so violating tke max skew constraint does not * prevent a pod from being scheduled. */ public static final String JOB_ATTRIBUTES_SPREADING_MAX_SKEW = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "spreading.maxSkew"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_HOSTNAME_STYLE = TITUS_PARAMETER_AGENT_PREFIX + "hostnameStyle"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_JUMBO = TITUS_PARAMETER_AGENT_PREFIX + "allowNetworkJumbo"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_FUSE_ENABLED = TITUS_PARAMETER_AGENT_PREFIX + "fuseEnabled"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_ASSIGN_IPV6_ADDRESS = TITUS_PARAMETER_AGENT_PREFIX + "assignIPv6Address"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_CHECK_INTERVAL = TITUS_PARAMETER_AGENT_PREFIX + "log.uploadCheckInterval"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_LOG_STDIO_CHECK_INTERVAL = TITUS_PARAMETER_AGENT_PREFIX + "log.stdioCheckInterval"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_THRESHOLD_TIME = TITUS_PARAMETER_AGENT_PREFIX + "log.uploadThresholdTime"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_LOG_KEEP_LOCAL_FILE_AFTER_UPLOAD = TITUS_PARAMETER_AGENT_PREFIX + "log.keepLocalFileAfterUpload"; /** * */ public static final String JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_REGEXP = TITUS_PARAMETER_AGENT_PREFIX + "log.uploadRegexp"; private JobAttributes() { } }
9,431
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/LogStorageInfos.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.titus.api.jobmanager.model.job; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfo.S3LogLocation; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.StringExt; /** * Helper functions to process log store related data. */ public final class LogStorageInfos { private static final Pattern S3_ACCESS_POINT_ARN_RE = Pattern.compile( "arn:aws:s3:([^:]+):([^:]+):accesspoint/.*" ); /** * We copy the custom S3 log location into the task, so we can build {@link LogStorageInfo} without having the {@link Job} object. * This is an optimization that avoids reading job records from the archive store, when tasks are read. */ public static <E extends JobDescriptor.JobDescriptorExt> Map<String, String> toS3LogLocationTaskContext(Job<E> job) { Map<String, String> context = new HashMap<>(); Map<String, String> attributes = job.getJobDescriptor().getContainer().getAttributes(); Evaluators.applyNotNull( attributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_BUCKET_NAME), value -> context.put(TaskAttributes.TASK_ATTRIBUTE_S3_BUCKET_NAME, value) ); Evaluators.applyNotNull( attributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX), value -> context.put(TaskAttributes.TASK_ATTRIBUTE_S3_PATH_PREFIX, value) ); return context; } /** * Build a {@link S3LogLocation} for a task. If custom S3 log location is not configured, the default value is used. */ public static S3LogLocation buildLogLocation(Task task, S3LogLocation defaultLogLocation) { S3Bucket customS3Bucket = findCustomS3Bucket(task).orElse(null); String customPathPrefix = findCustomPathPrefix(task).orElse(null); if (customS3Bucket == null && customPathPrefix == null) { return defaultLogLocation; } String fullPrefix = customPathPrefix == null ? defaultLogLocation.getKey() : buildPathPrefix(customPathPrefix, defaultLogLocation.getKey()); if (customS3Bucket == null) { return new S3LogLocation( defaultLogLocation.getAccountName(), defaultLogLocation.getAccountId(), defaultLogLocation.getRegion(), defaultLogLocation.getBucket(), fullPrefix ); } return customS3Bucket.getS3Account() .map(account -> new S3LogLocation( account.getAccountId(), account.getAccountId(), account.getRegion(), customS3Bucket.getBucketName(), fullPrefix )) .orElseGet(() -> new S3LogLocation( defaultLogLocation.getAccountName(), defaultLogLocation.getAccountId(), defaultLogLocation.getRegion(), customS3Bucket.getBucketName(), fullPrefix )); } public static Optional<S3Bucket> findCustomS3Bucket(Job<?> job) { return findCustomS3Bucket(job.getJobDescriptor()); } public static Optional<S3Bucket> findCustomS3Bucket(JobDescriptor<?> jobDescriptor) { Map<String, String> attributes = jobDescriptor.getContainer().getAttributes(); String bucketName = attributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_BUCKET_NAME); return StringExt.isEmpty(bucketName) ? Optional.empty() : Optional.of(new S3Bucket(bucketName)); } public static Optional<S3Bucket> findCustomS3Bucket(Task task) { Map<String, String> attributes = task.getTaskContext(); String bucketName = attributes.get(TaskAttributes.TASK_ATTRIBUTE_S3_BUCKET_NAME); return StringExt.isEmpty(bucketName) ? Optional.empty() : Optional.of(new S3Bucket(bucketName)); } public static Optional<String> findCustomPathPrefix(JobDescriptor<?> jobDescriptor) { Map<String, String> attributes = jobDescriptor.getContainer().getAttributes(); String pathPrefix = attributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX); return StringExt.isEmpty(pathPrefix) ? Optional.empty() : Optional.of(pathPrefix); } public static Optional<String> findCustomPathPrefix(Task task) { return Optional.ofNullable(task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTE_S3_PATH_PREFIX)); } public static String buildPathPrefix(String first, String second) { if (StringExt.isEmpty(second)) { return first; } if (first.startsWith("/")) { return first + second; } return first + '/' + second; } /** * S3 access point ARN format: arn:aws:s3:region:account-id:accesspoint/resource * For example: arn:aws:s3:us-west-2:123456789012:accesspoint/test * If the bucket name is ARN, we use region/account id from the ARN. */ @VisibleForTesting static Optional<S3Account> parseS3AccessPointArn(String s3AccessPointArn) { String trimmed = StringExt.safeTrim(s3AccessPointArn); if (trimmed.isEmpty()) { return Optional.empty(); } Matcher matcher = S3_ACCESS_POINT_ARN_RE.matcher(s3AccessPointArn); if (!matcher.matches()) { return Optional.empty(); } return Optional.of(new S3Account(matcher.group(2), matcher.group(1))); } public static class S3Account { private final String accountId; private final String region; public S3Account(String accountId, String region) { this.accountId = accountId; this.region = region; } public String getAccountId() { return accountId; } public String getRegion() { return region; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3Account s3Account = (S3Account) o; return Objects.equals(accountId, s3Account.accountId) && Objects.equals(region, s3Account.region); } @Override public int hashCode() { return Objects.hash(accountId, region); } } public static class S3Bucket { private final String bucketName; private final Optional<S3Account> s3Account; public S3Bucket(String bucketName) { this.bucketName = bucketName; this.s3Account = parseS3AccessPointArn(bucketName); } public Optional<S3Account> getS3Account() { return s3Account; } public String getBucketName() { return bucketName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3Bucket s3Bucket = (S3Bucket) o; return Objects.equals(bucketName, s3Bucket.bucketName) && Objects.equals(s3Account, s3Bucket.s3Account); } @Override public int hashCode() { return Objects.hash(bucketName, s3Account); } @Override public String toString() { return "S3Bucket{" + "bucketName='" + bucketName + '\'' + ", s3Account=" + s3Account + '}'; } } }
9,432
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ServiceJobTask.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.titus.api.jobmanager.model.job; import java.util.List; import java.util.Map; import java.util.Optional; import com.netflix.titus.api.jobmanager.model.job.migration.MigrationDetails; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import static com.netflix.titus.common.util.CollectionsExt.nonNull; /** * */ @ClassFieldsNotNull public class ServiceJobTask extends Task { private final MigrationDetails migrationDetails; public ServiceJobTask(String id, String originalId, Optional<String> resubmitOf, String jobId, int resubmitNumber, int systemResubmitNumber, int evictionResubmitNumber, TaskStatus status, List<TaskStatus> statusHistory, List<TwoLevelResource> twoLevelResources, Map<String, String> taskContext, Map<String, String> attributes, MigrationDetails migrationDetails, Version version) { super(id, jobId, status, statusHistory, originalId, resubmitOf, resubmitNumber, systemResubmitNumber, evictionResubmitNumber, twoLevelResources, taskContext, attributes, version); this.migrationDetails = migrationDetails; } public MigrationDetails getMigrationDetails() { return migrationDetails; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ServiceJobTask that = (ServiceJobTask) o; return migrationDetails != null ? migrationDetails.equals(that.migrationDetails) : that.migrationDetails == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (migrationDetails != null ? migrationDetails.hashCode() : 0); return result; } @Override public String toString() { return "ServiceJobTask{" + "id='" + getId() + '\'' + ", jobId='" + getJobId() + '\'' + ", status=" + getStatus() + ", originalId='" + getOriginalId() + '\'' + ", resubmitOf=" + getResubmitOf() + ", resubmitNumber=" + getResubmitNumber() + ", systemResubmitNumber=" + getSystemResubmitNumber() + ", evictionResubmitNumber=" + getEvictionResubmitNumber() + ", twoLevelResources=" + getTwoLevelResources() + ", taskContext=" + getTaskContext() + ", attributes=" + getAttributes() + ", migrationDetails=" + migrationDetails + ", version=" + getVersion() + '}'; } @Override public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(ServiceJobTask serviceJobTask) { return new Builder(serviceJobTask); } public static class Builder extends TaskBuilder<ServiceJobTask, Builder> { private MigrationDetails migrationDetails; private Builder() { } private Builder(ServiceJobTask serviceJobTask) { newBuilder(this, serviceJobTask).withMigrationDetails(serviceJobTask.getMigrationDetails()); } public Builder withMigrationDetails(MigrationDetails migrationDetails) { this.migrationDetails = migrationDetails; return this; } public Builder but() { return but(new Builder().withMigrationDetails(migrationDetails)); } @Override public ServiceJobTask build() { migrationDetails = migrationDetails == null ? new MigrationDetails(false, 0, 0) : migrationDetails; return new ServiceJobTask(id, originalId, Optional.ofNullable(resubmitOf), jobId, resubmitNumber, systemResubmitNumber, evictionResubmitNumber, status, nonNull(statusHistory), nonNull(twoLevelResources), nonNull(taskContext), nonNull(attributes), migrationDetails, version ); } } }
9,433
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Image.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.titus.api.jobmanager.model.job; import com.netflix.titus.common.model.sanitizer.ClassInvariant; import com.netflix.titus.common.util.StringExt; /** * Image reference. */ @ClassInvariant(expr = "@asserts.validateImage(#this)") public class Image { private final String name; private final String digest; private final String tag; public Image(String name, String tag, String digest) { this.name = name; this.tag = tag; this.digest = digest; } public String getName() { return name; } public String getTag() { return tag; } public String getDigest() { return digest; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Image image = (Image) o; if (name != null ? !name.equals(image.name) : image.name != null) { return false; } if (tag != null ? !tag.equals(image.tag) : image.tag != null) { return false; } return digest != null ? digest.equals(image.digest) : image.digest == null; } public Builder toBuilder() { return newBuilder(this); } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (tag != null ? tag.hashCode() : 0); result = 31 * result + (digest != null ? digest.hashCode() : 0); return result; } @Override public String toString() { return "Image{" + "name='" + name + '\'' + ", tag='" + tag + '\'' + ", digest='" + digest + '\'' + '}'; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(Image image) { return new Builder(image); } public static final class Builder { private String name; private String tag; private String digest; private Builder() { } private Builder(Image image) { this.name = image.getName(); this.tag = image.getTag(); this.digest = image.getDigest(); } public Builder withName(String name) { this.name = name; return this; } public Builder withTag(String tag) { this.tag = tag; return this; } public Builder withDigest(String digest) { this.digest = digest; return this; } public Image build() { return new Image(name, StringExt.safeTrim(tag), StringExt.safeTrim(digest)); } } }
9,434
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ServiceJobProcesses.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.titus.api.jobmanager.model.job; public class ServiceJobProcesses { private boolean disableIncreaseDesired; private boolean disableDecreaseDesired; public ServiceJobProcesses(boolean disableIncreaseDesired, boolean disableDecreaseDesired) { this.disableIncreaseDesired = disableIncreaseDesired; this.disableDecreaseDesired = disableDecreaseDesired; } public boolean isDisableIncreaseDesired() { return disableIncreaseDesired; } public boolean isDisableDecreaseDesired() { return disableDecreaseDesired; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceJobProcesses that = (ServiceJobProcesses) o; if (disableIncreaseDesired != that.disableIncreaseDesired) { return false; } return disableDecreaseDesired == that.disableDecreaseDesired; } @Override public int hashCode() { int result = (disableIncreaseDesired ? 1 : 0); result = 31 * result + (disableDecreaseDesired ? 1 : 0); return result; } @Override public String toString() { return "ServiceJobProcesses{" + "disableIncreaseDesired=" + disableIncreaseDesired + ", disableDecreaseDesired=" + disableDecreaseDesired + '}'; } public static ServiceJobProcesses.Builder newBuilder() { return new ServiceJobProcesses.Builder(); } public static final class Builder { private boolean disableIncreaseDesired; private boolean disableDecreaseDesired; private Builder() { } public Builder withDisableIncreaseDesired(boolean disableIncreaseDesired) { this.disableIncreaseDesired = disableIncreaseDesired; return this; } public Builder withDisableDecreaseDesired(boolean disableDecreaseDesired) { this.disableDecreaseDesired = disableDecreaseDesired; return this; } public ServiceJobProcesses build() { return new ServiceJobProcesses(disableIncreaseDesired, disableDecreaseDesired); } } }
9,435
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobGroupInfo.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.titus.api.jobmanager.model.job; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; /** * */ @ClassFieldsNotNull public class JobGroupInfo { private final String stack; private final String detail; private final String sequence; public JobGroupInfo(String stack, String detail, String sequence) { this.stack = stack; this.detail = detail; this.sequence = sequence; } public String getStack() { return stack; } public String getDetail() { return detail; } public String getSequence() { return sequence; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JobGroupInfo that = (JobGroupInfo) o; if (stack != null ? !stack.equals(that.stack) : that.stack != null) { return false; } if (detail != null ? !detail.equals(that.detail) : that.detail != null) { return false; } return sequence != null ? sequence.equals(that.sequence) : that.sequence == null; } @Override public int hashCode() { int result = stack != null ? stack.hashCode() : 0; result = 31 * result + (detail != null ? detail.hashCode() : 0); result = 31 * result + (sequence != null ? sequence.hashCode() : 0); return result; } @Override public String toString() { return "JobGroupInfo{" + "stack='" + stack + '\'' + ", detail='" + detail + '\'' + ", sequence='" + sequence + '\'' + '}'; } public Builder toBuilder() { return newBuilder().withStack(stack).withDetail(detail).withSequence(sequence); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(JobGroupInfo jobGroupInfo) { return new Builder() .withStack(jobGroupInfo.getStack()) .withDetail(jobGroupInfo.getDetail()) .withSequence(jobGroupInfo.getSequence()); } public static final class Builder { private String stack; private String detail; private String sequence; private Builder() { } public Builder withStack(String stack) { this.stack = stack; return this; } public Builder withDetail(String detail) { this.detail = detail; return this; } public Builder withSequence(String sequence) { this.sequence = sequence; return this; } public JobGroupInfo build() { JobGroupInfo jobGroupInfo = new JobGroupInfo(stack, detail, sequence); return jobGroupInfo; } } }
9,436
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ContainerResources.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.titus.api.jobmanager.model.job; import java.util.List; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.Min; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.sanitizer.EfsMountsSanitizer; import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation; import com.netflix.titus.api.model.EfsMount; import com.netflix.titus.common.model.sanitizer.ClassInvariant; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.FieldInvariant; import com.netflix.titus.common.model.sanitizer.FieldSanitizer; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.common.util.CollectionsExt.nonNull; /** * */ @ClassInvariant.List({ // TODO This is also get checked during Gateway model validation. A change is needed to matchingEbsAndIpZones() to allow it to handle EbsVolume objects before TJC sanitization. // @ClassInvariant(expr = "@asserts.matchingEbsAndIpZones(ebsVolumes, signedIpAddressAllocations)", mode = VerifierMode.Strict), @ClassInvariant(condition = "shmMB <= memoryMB", message = "'shmMB' (#{shmMB}) must be <= 'memoryMB' (#{memoryMB})") }) public class ContainerResources { @FieldSanitizer(adjuster = "T(java.lang.Math).max(@constraints.getCpuMin(), value)") @FieldInvariant(value = "value > 0", message = "'cpu'(#{value}) must be > 0") private final double cpu; @Min(value = 0, message = "'gpu'(#{#root}) must be >= 0") private final int gpu; @FieldSanitizer(adjuster = "T(java.lang.Math).max(@constraints.getMemoryMegabytesMin(), value)") @Min(value = 1, message = "'memoryMB'(#{#root}) must be > 0") private final int memoryMB; @FieldSanitizer(adjuster = "T(java.lang.Math).max(@constraints.getDiskMegabytesMin(), value)") @Min(value = 1, message = "'diskMB'(#{#root}) must be > 0") private final int diskMB; @FieldSanitizer(adjuster = "T(java.lang.Math).max(@constraints.getNetworkMbpsMin(), value)") @Min(value = 1, message = "'networkMbps'(#{#root}) must be > 0") private final int networkMbps; @FieldSanitizer(sanitizer = EfsMountsSanitizer.class) @Valid private final List<EfsMount> efsMounts; private final boolean allocateIP; // If provided value is 0, rewrite to a common default @FieldSanitizer(adjuster = "value == 0 ? @constraints.getShmMegabytesDefault() : value") @Min(value = 0, message = "'shmMB'(#{#root}) must be >= 0") private final int shmMB; @Valid @CollectionInvariants(allowDuplicateValues = false) private final List<SignedIpAddressAllocation> signedIpAddressAllocations; @Valid @CollectionInvariants(allowDuplicateValues = false) private final List<EbsVolume> ebsVolumes; public ContainerResources(double cpu, int gpu, int memoryMB, int diskMB, int networkMbps, List<EfsMount> efsMounts, boolean allocateIP, int shmMB, List<SignedIpAddressAllocation> signedIpAddressAllocations, List<EbsVolume> ebsVolumes) { this.cpu = cpu; this.gpu = gpu; this.memoryMB = memoryMB; this.diskMB = diskMB; this.networkMbps = networkMbps; this.efsMounts = CollectionsExt.nonNullImmutableCopyOf(efsMounts); this.allocateIP = allocateIP; this.shmMB = shmMB; this.signedIpAddressAllocations = CollectionsExt.nonNullImmutableCopyOf(signedIpAddressAllocations); this.ebsVolumes = CollectionsExt.nonNullImmutableCopyOf(ebsVolumes); } public double getCpu() { return cpu; } public int getGpu() { return gpu; } public int getMemoryMB() { return memoryMB; } public int getDiskMB() { return diskMB; } public int getNetworkMbps() { return networkMbps; } public List<EfsMount> getEfsMounts() { return efsMounts; } public boolean isAllocateIP() { return allocateIP; } public int getShmMB() { return shmMB; } public List<SignedIpAddressAllocation> getSignedIpAddressAllocations() { return signedIpAddressAllocations; } public List<EbsVolume> getEbsVolumes() { return ebsVolumes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContainerResources that = (ContainerResources) o; return Double.compare(that.cpu, cpu) == 0 && gpu == that.gpu && memoryMB == that.memoryMB && diskMB == that.diskMB && networkMbps == that.networkMbps && allocateIP == that.allocateIP && shmMB == that.shmMB && efsMounts.equals(that.efsMounts) && signedIpAddressAllocations.equals(that.signedIpAddressAllocations) && ebsVolumes.equals(that.ebsVolumes); } @Override public int hashCode() { return Objects.hash(cpu, gpu, memoryMB, diskMB, networkMbps, efsMounts, allocateIP, shmMB, signedIpAddressAllocations, ebsVolumes); } @Override public String toString() { return "ContainerResources{" + "cpu=" + cpu + ", gpu=" + gpu + ", memoryMB=" + memoryMB + ", diskMB=" + diskMB + ", networkMbps=" + networkMbps + ", efsMounts=" + efsMounts + ", allocateIP=" + allocateIP + ", shmMB=" + shmMB + ", signedIpAddressAllocations=" + signedIpAddressAllocations + ", ebsVolumes=" + ebsVolumes + '}'; } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(ContainerResources containerResources) { return new Builder() .withCpu(containerResources.getCpu()) .withGpu(containerResources.getGpu()) .withMemoryMB(containerResources.getMemoryMB()) .withDiskMB(containerResources.getDiskMB()) .withNetworkMbps(containerResources.getNetworkMbps()) .withAllocateIP(containerResources.isAllocateIP()) .withEfsMounts(containerResources.getEfsMounts()) .withShmMB(containerResources.getShmMB()) .withSignedIpAddressAllocations(containerResources.getSignedIpAddressAllocations()) .withEbsVolumes(containerResources.getEbsVolumes()); } public static final class Builder { private double cpu; private int gpu; private int memoryMB; private int diskMB; private int networkMbps; private List<EfsMount> efsMounts; private boolean allocateIP; private int shmMB; private List<SignedIpAddressAllocation> signedIpAddressAllocations; private List<EbsVolume> ebsVolumes; private Builder() { } public Builder withCpu(double cpu) { this.cpu = cpu; return this; } public Builder withGpu(int gpu) { this.gpu = gpu; return this; } public Builder withMemoryMB(int memoryMB) { this.memoryMB = memoryMB; return this; } public Builder withDiskMB(int diskMB) { this.diskMB = diskMB; return this; } public Builder withNetworkMbps(int networkMbps) { this.networkMbps = networkMbps; return this; } public Builder withEfsMounts(List<EfsMount> efsMounts) { this.efsMounts = efsMounts; return this; } public Builder withAllocateIP(boolean allocateIP) { this.allocateIP = allocateIP; return this; } public Builder withShmMB(int shmMB) { this.shmMB = shmMB; return this; } public Builder withSignedIpAddressAllocations(List<SignedIpAddressAllocation> signedIpAddressAllocations) { this.signedIpAddressAllocations = signedIpAddressAllocations; return this; } public Builder withEbsVolumes(List<EbsVolume> ebsVolumes) { this.ebsVolumes = ebsVolumes; return this; } public Builder but() { return newBuilder() .withCpu(cpu) .withGpu(gpu) .withMemoryMB(memoryMB) .withDiskMB(diskMB) .withNetworkMbps(networkMbps) .withEfsMounts(efsMounts) .withShmMB(shmMB) .withSignedIpAddressAllocations(signedIpAddressAllocations) .withEbsVolumes(ebsVolumes); } public ContainerResources build() { ContainerResources containerResources = new ContainerResources( cpu, gpu, memoryMB, diskMB, networkMbps, nonNull(efsMounts), allocateIP, shmMB, nonNull(signedIpAddressAllocations), nonNull(ebsVolumes)); return containerResources; } } }
9,437
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/TaskStatus.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.titus.api.jobmanager.model.job; import java.util.Objects; import java.util.Set; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; /** * */ @ClassFieldsNotNull public class TaskStatus extends ExecutableStatus<TaskState> { public static final String REASON_NORMAL = "normal"; /** * Filled in to preserve state history continuity. */ public static final String REASON_STATE_MISSING = "filledIn"; /** * Task has a pod created for it (set in the Accepted state only). */ public static final String REASON_POD_CREATED = "podCreated"; /** * Pod scheduled by KubeScheduler. */ public static final String REASON_POD_SCHEDULED = "podScheduled"; /** * Job was explicitly terminated by a user. */ public static final String REASON_JOB_KILLED = "killed"; /** * Task was explicitly terminated by a user. */ public static final String REASON_TASK_KILLED = "killed"; /** * Task was terminated by an eviction service. */ public static final String REASON_TASK_EVICTED = "evicted"; /** * Task was lost, and its final status is unknown. */ public static final String REASON_TASK_LOST = "lost"; /** * Invalid container definition (security group, image name, etc). */ public static final String REASON_INVALID_REQUEST = "invalidRequest"; /** * Task was terminated as a result of job scaling down. */ public static final String REASON_SCALED_DOWN = "scaledDown"; /** * Task was terminated, as it did not progress to the next state in the expected time. */ public static final String REASON_STUCK_IN_STATE = "stuckInState"; /** * Task which was in KillInitiated state, was terminated, as it did not progress to the Finished state in the expected time. */ public static final String REASON_STUCK_IN_KILLING_STATE = "stuckInKillingState"; /** * Task was terminated, as its runtime limit was exceeded. */ public static final String REASON_RUNTIME_LIMIT_EXCEEDED = "runtimeLimitExceeded"; /** * Task completed with non zero error code. */ public static final String REASON_FAILED = "failed"; /** * Container crashed due to some internal system error. */ public static final String REASON_CRASHED = "crashed"; /** * Transient error, not an agent specific (for example AWS rate limiting). */ public static final String REASON_TRANSIENT_SYSTEM_ERROR = "transientSystemError"; /** * An error scoped to an agent instance on which a container was run. The agent should be quarantined or terminated. */ public static final String REASON_LOCAL_SYSTEM_ERROR = "localSystemError"; /** * Unrecognized error which cannot be classified neither as local/non-local or transient. * If there are multiple occurrences of this error, the agent should be quarantined or terminated. */ public static final String REASON_UNKNOWN_SYSTEM_ERROR = "unknownSystemError"; public static final String REASON_UNKNOWN = "unknown"; private static Set<String> SYSTEM_LEVEL_ERRORS = CollectionsExt.asSet( REASON_STUCK_IN_STATE, REASON_CRASHED, REASON_TRANSIENT_SYSTEM_ERROR, REASON_LOCAL_SYSTEM_ERROR, REASON_UNKNOWN_SYSTEM_ERROR ); public TaskStatus(TaskState taskState, String reasonCode, String reasonMessage, long timestamp) { super(taskState, reasonCode, reasonMessage, timestamp); } public static boolean hasSystemError(Task task) { if (isSystemError(task.getStatus())) { return true; } return JobFunctions.findTaskStatus(task, TaskState.KillInitiated).map(TaskStatus::isSystemError) .orElse(false); } public static boolean isSystemError(TaskStatus status) { if (status.getState() != TaskState.KillInitiated && status.getState() != TaskState.Finished) { return false; } String reasonCode = status.getReasonCode(); return !StringExt.isEmpty(reasonCode) && SYSTEM_LEVEL_ERRORS.contains(reasonCode); } public static boolean isEvicted(Task task) { if (task.getStatus().getState() != TaskState.Finished) { return false; } return JobFunctions.findTaskStatus(task, TaskState.KillInitiated) .map(killInitiatedState -> REASON_TASK_EVICTED.equals(killInitiatedState.getReasonCode()) ).orElse(false); } /** * Checks if task has a status (Accepted, reasonCode=podCreated). A matching task will have at least two * Accepted states in its history, so all of them must be checked. */ public static boolean hasPod(Task task) { if (isPodMarker(task.getStatus())) { return true; } for (TaskStatus status : task.getStatusHistory()) { if (isPodMarker(status)) { return true; } } return false; } private static boolean isPodMarker(TaskStatus status) { return status.getState() == TaskState.Accepted && REASON_POD_CREATED.equals(status.getReasonCode()); } public static boolean areEquivalent(TaskStatus first, TaskStatus second) { if (first.getState() != second.getState()) { return false; } if (!Objects.equals(first.getReasonCode(), second.getReasonCode())) { return false; } return Objects.equals(first.getReasonMessage(), second.getReasonMessage()); } public Builder toBuilder() { return newBuilder(this); } public static TaskStatus.Builder newBuilder() { return new TaskStatus.Builder(); } public static TaskStatus.Builder newBuilder(TaskStatus taskStatus) { return new TaskStatus.Builder(taskStatus); } public static class Builder extends AbstractBuilder<TaskState, Builder, TaskStatus> { private Builder() { } private Builder(TaskStatus status) { super(status); } @Override public TaskStatus build() { return new TaskStatus( state, reasonCode == null ? TaskStatus.REASON_UNKNOWN : reasonCode, toCompleteReasonMessage(), timestamp ); } } }
9,438
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/CapacityAttributes.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.titus.api.jobmanager.model.job; import java.util.Objects; import java.util.Optional; import com.netflix.titus.common.model.sanitizer.ClassInvariant; @ClassInvariant.List({ @ClassInvariant(condition = "!min.isPresent() || min.get() >=0", message = "'min'(#{min}) must be >= 0"), @ClassInvariant(condition = "!max.isPresent() || max.get() >=0", message = "'max'(#{max}) must be >= 0"), @ClassInvariant(condition = "!desired.isPresent() || desired.get() >=0", message = "'desired'(#{desired}) must be >= 0") }) public class CapacityAttributes { private final Optional<Integer> min; private final Optional<Integer> desired; private final Optional<Integer> max; public CapacityAttributes(Optional<Integer> min, Optional<Integer> desired, Optional<Integer> max) { this.min = min; this.desired = desired; this.max = max; } public Optional<Integer> getMin() { return min; } public Optional<Integer> getDesired() { return desired; } public Optional<Integer> getMax() { return max; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CapacityAttributes that = (CapacityAttributes) o; return Objects.equals(min, that.min) && Objects.equals(desired, that.desired) && Objects.equals(max, that.max); } @Override public int hashCode() { return Objects.hash(min, desired, max); } @Override public String toString() { return "CapacityAttributes{" + "min=" + min + ", desired=" + desired + ", max=" + max + '}'; } public Builder toBuilder() { return newBuilder(this); } public static CapacityAttributes.Builder newBuilder() { return new CapacityAttributes.Builder(); } public static Builder newBuilder(CapacityAttributes capacityAttributes) { Builder builder = new Builder(); builder.min = capacityAttributes.getMin(); builder.max = capacityAttributes.getMax(); builder.desired = capacityAttributes.getDesired(); return builder; } public static final class Builder { private Optional<Integer> min = Optional.empty(); private Optional<Integer> desired = Optional.empty(); private Optional<Integer> max = Optional.empty(); private Builder() { } public CapacityAttributes.Builder withMin(int min) { this.min = Optional.of(min); return this; } public CapacityAttributes.Builder withDesired(int desired) { this.desired = Optional.of(desired); return this; } public CapacityAttributes.Builder withMax(int max) { this.max = Optional.of(max); return this; } public CapacityAttributes build() { return new CapacityAttributes(min, desired, max); } } }
9,439
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Job.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.titus.api.jobmanager.model.job; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; import javax.validation.Valid; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.common.util.CollectionsExt.nonNull; import static java.util.Arrays.asList; /** * Immutable entity that represents an information about a Titus job in a distinct point in time. * Both job descriptor and job status may change over time, and for each change a new version of the {@link Job} * entity is created. For example, service job can be re-sized ({@link JobDescriptor} update), or change state from * {@link JobState#Accepted} to {@link JobState#Finished}. */ @ClassFieldsNotNull public class Job<E extends JobDescriptor.JobDescriptorExt> { private final String id; @Valid private final JobDescriptor<E> jobDescriptor; private final JobStatus status; private final List<JobStatus> statusHistory; private final Version version; public Job(String id, JobDescriptor<E> jobDescriptor, JobStatus status, List<JobStatus> statusHistory, Version version) { this.id = id; this.jobDescriptor = jobDescriptor; this.status = status; this.statusHistory = CollectionsExt.nullableImmutableCopyOf(statusHistory); // TODO Remove me. Version is a newly introduced field. If not set explicitly, assign a default value this.version = version == null ? Version.undefined() : version; } /** * A unique id (UUID) of a job, fixed for the job lifetime. */ public String getId() { return id; } /** * Job descriptor. */ public JobDescriptor<E> getJobDescriptor() { return jobDescriptor; } /** * Last known job state. */ public JobStatus getStatus() { return status; } /** * The history of previous statuses */ public List<JobStatus> getStatusHistory() { return statusHistory; } public Version getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Job<?> job = (Job<?>) o; return Objects.equals(id, job.id) && Objects.equals(jobDescriptor, job.jobDescriptor) && Objects.equals(status, job.status) && Objects.equals(statusHistory, job.statusHistory) && Objects.equals(version, job.version); } @Override public int hashCode() { return Objects.hash(id, jobDescriptor, status, statusHistory, version); } @Override public String toString() { return "Job{" + "id='" + id + '\'' + ", jobDescriptor=" + jobDescriptor + ", status=" + status + ", statusHistory=" + statusHistory + ", version=" + version + '}'; } @SafeVarargs public final Job<E> but(Function<Job<E>, Job<E>>... modifiers) { Job<E> result = this; for (Function<Job<E>, Job<E>> modifier : modifiers) { result = modifier.apply(result); } return result; } public Builder<E> toBuilder() { return new Builder<E>() .withId(id) .withJobDescriptor(jobDescriptor) .withStatus(status) .withStatusHistory(statusHistory) .withVersion(version); } public static <E extends JobDescriptor.JobDescriptorExt> Builder<E> newBuilder() { return new Builder<>(); } public static final class Builder<E extends JobDescriptor.JobDescriptorExt> { private String id; private JobDescriptor<E> jobDescriptor; private JobStatus status; private List<JobStatus> statusHistory; private Version version; private Builder() { } public Builder<E> withId(String id) { this.id = id; return this; } public Builder<E> withJobDescriptor(JobDescriptor<E> jobDescriptor) { this.jobDescriptor = jobDescriptor; return this; } public Builder<E> withStatus(JobStatus status) { this.status = status; return this; } public Builder<E> withStatusHistory(List<JobStatus> statusHistory) { this.statusHistory = statusHistory; return this; } public Builder<E> withStatusHistory(JobStatus... statusHistory) { if (statusHistory.length == 0) { return withStatusHistory(Collections.emptyList()); } if (statusHistory.length == 1) { return withStatusHistory(Collections.singletonList(statusHistory[0])); } return withStatusHistory(asList(statusHistory)); } public Builder<E> withVersion(Version version) { this.version = version; return this; } public Job<E> build() { return new Job<>(id, jobDescriptor, status, nonNull(statusHistory), version); } } }
9,440
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/TaskState.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.titus.api.jobmanager.model.job; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public enum TaskState { /** * A task was passed to scheduler, but has no resources allocated yet. */ Accepted, /** * A task had resources allocated, and was passed to Kubernetes */ Launched, /** * An executor provisioned resources for a task. */ StartInitiated, /** * Task's container started. */ Started, /** * A user requested the task to be terminated. An executor is stopping the task, and releasing its allocated resources. */ KillInitiated, /** * No connectivity between Kubernetes and an agent running a task. Task's state cannot be determined until the connection is established again. */ Disconnected, /** * A task finished or was forced by a user to terminate. All resources previously assigned to this task are released. */ Finished; private static final Set<TaskState> SET_OF_ALL = new HashSet<>(Arrays.asList(TaskState.values())); public static boolean isRunning(TaskState taskState) { switch (taskState) { case Launched: case StartInitiated: case Started: case KillInitiated: case Disconnected: return true; case Accepted: case Finished: default: return false; } } public static boolean isTerminalState(TaskState taskState) { return taskState == TaskState.Finished; } public static boolean isBefore(TaskState checked, TaskState reference) { if (checked == TaskState.Disconnected || reference == TaskState.Disconnected) { return false; } return checked.ordinal() < reference.ordinal(); } public static boolean isAfter(TaskState checked, TaskState reference) { if (checked == TaskState.Disconnected || reference == TaskState.Disconnected) { return false; } return checked.ordinal() > reference.ordinal(); } public static Set<TaskState> setOfAll() { return SET_OF_ALL; } }
9,441
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/PlatformSidecar.java
package com.netflix.titus.api.jobmanager.model.job; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class PlatformSidecar { @NotNull @Pattern(regexp = "^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$", message = "platform sidecar names must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character") private final String name; @NotNull @Pattern(regexp = "^[a-z0-9]([\\-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([\\-a-z0-9]*[a-z0-9])?)*$", message = "channel names must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character") private final String channel; public final String arguments; public PlatformSidecar(String name, String channel, String arguments) { this.name = name; this.channel = channel; this.arguments = arguments; } public String getName() { return name; } public String getChannel() { return channel; } public String getArguments() { return arguments; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlatformSidecar that = (PlatformSidecar) o; return Objects.equals(name, that.name) && Objects.equals(channel, that.channel) && Objects.equals(arguments, that.arguments); } @Override public int hashCode() { return Objects.hash(name, channel, arguments); } @Override public String toString() { return "PlatformSidecar{" + "name='" + name + '\'' + ", channel='" + channel + '\'' + ", arguments=" + arguments + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String name; private String channel; private String arguments; public Builder withName(String name) { this.name = name; return this; } public Builder withChannel(String channel) { this.channel = channel; return this; } public Builder withArguments(String arguments) { this.arguments = arguments; return this; } public PlatformSidecar build() { return new PlatformSidecar(name, channel, arguments); } } }
9,442
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Container.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.titus.api.jobmanager.model.job; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import javax.validation.Valid; import com.google.common.base.Preconditions; import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobAssertions; import com.netflix.titus.api.jobmanager.model.job.sanitizer.SchedulingConstraintSetValidator.SchedulingConstraintSet; import com.netflix.titus.api.jobmanager.model.job.sanitizer.SchedulingConstraintValidator; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.FieldInvariant; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.common.util.CollectionsExt.asSet; import static com.netflix.titus.common.util.CollectionsExt.nonNull; @ClassFieldsNotNull @SchedulingConstraintSet public class Container { public static final String RESOURCE_CPU = "cpu"; public static final String RESOURCE_GPU = "gpu"; public static final String RESOURCE_MEMORY = "memoryMB"; public static final String RESOURCE_DISK = "diskMB"; public static final String RESOURCE_NETWORK = "networkMbps"; public static final Set<String> PRIMARY_RESOURCES = asSet(Container.RESOURCE_CPU, Container.RESOURCE_MEMORY, Container.RESOURCE_DISK, Container.RESOURCE_NETWORK); // attributes for Metatron public static final String ATTRIBUTE_NETFLIX_APP_METADATA = "NETFLIX_APP_METADATA"; public static final String ATTRIBUTE_NETFLIX_APP_METADATA_SIG = "NETFLIX_APP_METADATA_SIG"; @Valid private final ContainerResources containerResources; @Valid private final SecurityProfile securityProfile; @Valid private final Image image; @CollectionInvariants private final Map<String, String> attributes; @CollectionInvariants @FieldInvariant( value = "@asserts.isEntryPointNotTooLarge(value)", message = "Entry point size exceeds the limit " + JobAssertions.MAX_ENTRY_POINT_SIZE_SIZE_KB + "KB" ) private final List<String> entryPoint; @CollectionInvariants private final List<String> command; @CollectionInvariants(allowEmptyKeys = false) @FieldInvariant( value = "@asserts.areEnvironmentVariablesNotTooLarge(value)", message = "Container environment variables size exceeds the limit" ) private final Map<String, String> env; @CollectionInvariants @SchedulingConstraintValidator.SchedulingConstraint private final Map<String, String> softConstraints; @CollectionInvariants @SchedulingConstraintValidator.SchedulingConstraint private final Map<String, String> hardConstraints; @CollectionInvariants private final List<VolumeMount> volumeMounts; public Container(ContainerResources containerResources, SecurityProfile securityProfile, Image image, Map<String, String> attributes, List<String> entryPoint, List<String> command, Map<String, String> env, Map<String, String> softConstraints, Map<String, String> hardConstraints, List<VolumeMount> volumeMounts ) { this.containerResources = containerResources; this.securityProfile = securityProfile; this.image = image; this.attributes = CollectionsExt.nullableImmutableCopyOf(attributes); this.entryPoint = CollectionsExt.nullableImmutableCopyOf(entryPoint); this.command = CollectionsExt.nullableImmutableCopyOf(command); this.env = CollectionsExt.nullableImmutableCopyOf(env); this.softConstraints = CollectionsExt.nullableImmutableCopyOf(softConstraints); this.hardConstraints = CollectionsExt.nullableImmutableCopyOf(hardConstraints); this.volumeMounts = CollectionsExt.nullableImmutableCopyOf(volumeMounts); } public ContainerResources getContainerResources() { return containerResources; } public SecurityProfile getSecurityProfile() { return securityProfile; } public Image getImage() { return image; } public Map<String, String> getAttributes() { return attributes; } public List<String> getEntryPoint() { return entryPoint; } public List<String> getCommand() { return command; } public Map<String, String> getEnv() { return env; } public Map<String, String> getSoftConstraints() { return softConstraints; } public Map<String, String> getHardConstraints() { return hardConstraints; } public List<VolumeMount> getVolumeMounts() { return volumeMounts; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Container container = (Container) o; if (containerResources != null ? !containerResources.equals(container.containerResources) : container.containerResources != null) { return false; } if (securityProfile != null ? !securityProfile.equals(container.securityProfile) : container.securityProfile != null) { return false; } if (image != null ? !image.equals(container.image) : container.image != null) { return false; } if (attributes != null ? !attributes.equals(container.attributes) : container.attributes != null) { return false; } if (entryPoint != null ? !entryPoint.equals(container.entryPoint) : container.entryPoint != null) { return false; } if (command != null ? !command.equals(container.command) : container.command != null) { return false; } if (env != null ? !env.equals(container.env) : container.env != null) { return false; } if (softConstraints != null ? !softConstraints.equals(container.softConstraints) : container.softConstraints != null) { return false; } if (hardConstraints != null ? !hardConstraints.equals(container.hardConstraints) : container.hardConstraints != null) { return false; } if (volumeMounts != null ? !volumeMounts.equals(container.volumeMounts) : container.volumeMounts != null) { return false; } return true; } @Override public int hashCode() { int result = containerResources != null ? containerResources.hashCode() : 0; result = 31 * result + (securityProfile != null ? securityProfile.hashCode() : 0); result = 31 * result + (image != null ? image.hashCode() : 0); result = 31 * result + (attributes != null ? attributes.hashCode() : 0); result = 31 * result + (entryPoint != null ? entryPoint.hashCode() : 0); result = 31 * result + (command != null ? command.hashCode() : 0); result = 31 * result + (env != null ? env.hashCode() : 0); result = 31 * result + (softConstraints != null ? softConstraints.hashCode() : 0); result = 31 * result + (hardConstraints != null ? hardConstraints.hashCode() : 0); result = 31 * result + (volumeMounts != null ? volumeMounts.hashCode() : 0); return result; } @Override public String toString() { return "Container{" + "containerResources=" + containerResources + ", securityProfile=" + securityProfile + ", image=" + image + ", attributes=" + attributes + ", entryPoint=" + entryPoint + ", command=" + command + ", env=" + env + ", softConstraints=" + softConstraints + ", hardConstraints=" + hardConstraints + ", volumeMounts=" + volumeMounts + '}'; } public Container but(Function<Container, Object> mapperFun) { Object result = mapperFun.apply(this); if (result instanceof Container) { return (Container) result; } if (result instanceof Container.Builder) { return ((Container.Builder) result).build(); } if (result instanceof ContainerResources) { return toBuilder().withContainerResources((ContainerResources) result).build(); } if (result instanceof ContainerResources.Builder) { return toBuilder().withContainerResources(((ContainerResources.Builder) result).build()).build(); } if (result instanceof SecurityProfile) { return toBuilder().withSecurityProfile((SecurityProfile) result).build(); } if (result instanceof SecurityProfile.Builder) { return toBuilder().withSecurityProfile(((SecurityProfile.Builder) result).build()).build(); } if (result instanceof Image) { return toBuilder().withImage((Image) result).build(); } if (result instanceof Image.Builder) { return toBuilder().withImage(((Image.Builder) result).build()).build(); } throw new IllegalArgumentException("Invalid result type " + result.getClass()); } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(Container container) { return new Builder() .withContainerResources(container.getContainerResources()) .withSecurityProfile(container.getSecurityProfile()) .withImage(container.getImage()) .withAttributes(container.getAttributes()) .withEntryPoint(container.getEntryPoint()) .withCommand(container.getCommand()) .withEnv(container.getEnv()) .withSoftConstraints(container.getSoftConstraints()) .withHardConstraints(container.getHardConstraints()) .withVolumeMounts(container.getVolumeMounts()); } public static final class Builder { private ContainerResources containerResources; private SecurityProfile securityProfile; private Image image; private Map<String, String> attributes; private List<String> entryPoint; private List<String> command; private Map<String, String> env; private Map<String, String> softConstraints; private Map<String, String> hardConstraints; private List<VolumeMount> volumeMounts; private Builder() { } public Builder withContainerResources(ContainerResources containerResources) { this.containerResources = containerResources; return this; } public Builder withSecurityProfile(SecurityProfile securityProfile) { this.securityProfile = securityProfile; return this; } public Builder withImage(Image image) { this.image = image; return this; } public Builder withAttributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public Builder withEntryPoint(List<String> entryPoint) { this.entryPoint = entryPoint; return this; } public Builder withCommand(List<String> command) { this.command = command; return this; } public Builder withEnv(Map<String, String> env) { this.env = env; return this; } public Builder withSoftConstraints(Map<String, String> softConstraints) { this.softConstraints = softConstraints; return this; } public Builder withHardConstraints(Map<String, String> hardConstraints) { this.hardConstraints = hardConstraints; return this; } public Builder withVolumeMounts(List<VolumeMount> volumeMounts) { this.volumeMounts = volumeMounts; return this; } public Container build() { Preconditions.checkNotNull(containerResources, "ContainerResources not defined"); Preconditions.checkNotNull(image, "Image not defined"); Container container = new Container( containerResources, securityProfile == null ? SecurityProfile.empty() : securityProfile, image, nonNull(attributes), entryPoint, command, nonNull(env), nonNull(softConstraints), nonNull(hardConstraints), nonNull(volumeMounts) ); return container; } } }
9,443
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobStatus.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.titus.api.jobmanager.model.job; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; /** * */ @ClassFieldsNotNull public class JobStatus extends ExecutableStatus<JobState> { public static final String REASON_UNKNOWN = "unknown"; public JobStatus(JobState state, String reasonCode, String reasonMessage, long timestamp) { super(state, reasonCode, reasonMessage, timestamp); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(JobStatus jobStatus) { return new Builder(jobStatus); } public static class Builder extends AbstractBuilder<JobState, Builder, JobStatus> { private Builder() { } private Builder(JobStatus jobStatus) { super(jobStatus); } @Override public JobStatus build() { return new JobStatus( state, reasonCode == null ? REASON_UNKNOWN : reasonCode, toCompleteReasonMessage(), timestamp ); } } }
9,444
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobType.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.titus.api.jobmanager.model.job; public enum JobType { SERVICE, BATCH }
9,445
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Capacity.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.titus.api.jobmanager.model.job; import javax.validation.constraints.Min; import com.netflix.titus.common.model.sanitizer.ClassInvariant; @ClassInvariant.List({ @ClassInvariant(condition = "min <= desired", message = "'min'(#{min}) must be <= 'desired'(#{desired})"), @ClassInvariant(condition = "desired <= max", message = "'desired'(#{desired}) must be <= 'max'(#{max})"), // needed because desired can be automatically adjusted based on min and max @ClassInvariant(condition = "min <= max", message = "'min'(#{min}) must be <= 'max'(#{max})") }) public class Capacity { @Min(value = 0, message = "'min' must be >= 0, but is #{#root}") private final int min; @Min(value = 0, message = "'desired' must be >= 0, but is #{#root}") private final int desired; @Min(value = 0, message = "'max' must be >= 0, but is #{#root}") private final int max; public Capacity(int min, int desired, int max) { this.min = min; this.desired = desired; this.max = max; } public int getMin() { return min; } public int getDesired() { return desired; } public int getMax() { return max; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Capacity capacity = (Capacity) o; if (min != capacity.min) { return false; } if (desired != capacity.desired) { return false; } return max == capacity.max; } @Override public int hashCode() { int result = min; result = 31 * result + desired; result = 31 * result + max; return result; } @Override public String toString() { return "Capacity{" + "min=" + min + ", desired=" + desired + ", max=" + max + '}'; } public Builder toBuilder() { return newBuilder(this); } public static Capacity.Builder newBuilder() { return new Capacity.Builder(); } public static Capacity.Builder newBuilder(Capacity capacity) { return new Capacity.Builder() .withMin(capacity.getMin()) .withDesired(capacity.getDesired()) .withMax(capacity.getMax()); } public static final class Builder { private int min = Integer.MIN_VALUE; private int desired; private int max = Integer.MAX_VALUE; private Builder() { } public Capacity.Builder withMin(int min) { this.min = min; return this; } public Capacity.Builder withDesired(int desired) { this.desired = desired; return this; } public Capacity.Builder withMax(int max) { this.max = max; return this; } public Capacity.Builder but() { return newBuilder().withMin(min).withDesired(desired).withMax(max); } public Capacity build() { return new Capacity(min, desired, max); } } }
9,446
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Task.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.titus.api.jobmanager.model.job; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_CELL; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_STACK; import static com.netflix.titus.api.jobmanager.TaskAttributes.TASK_ATTRIBUTES_CELL; import static com.netflix.titus.api.jobmanager.TaskAttributes.TASK_ATTRIBUTES_STACK; import static java.util.Arrays.asList; public abstract class Task { private final String id; private final String jobId; private final TaskStatus status; private final List<TaskStatus> statusHistory; private final String originalId; private final Optional<String> resubmitOf; private final int resubmitNumber; private final int systemResubmitNumber; private final int evictionResubmitNumber; private final List<TwoLevelResource> twoLevelResources; private final Map<String, String> taskContext; private final Map<String, String> attributes; private final Version version; protected Task(String id, String jobId, TaskStatus status, List<TaskStatus> statusHistory, String originalId, Optional<String> resubmitOf, int resubmitNumber, int systemResubmitNumber, int evictionResubmitNumber, List<TwoLevelResource> twoLevelResources, Map<String, String> taskContext, Map<String, String> attributes, Version version) { this.id = id; this.jobId = jobId; this.status = status; this.statusHistory = CollectionsExt.nullableImmutableCopyOf(statusHistory); this.originalId = originalId; this.resubmitOf = resubmitOf; this.resubmitNumber = resubmitNumber; this.systemResubmitNumber = systemResubmitNumber; this.evictionResubmitNumber = evictionResubmitNumber; this.twoLevelResources = CollectionsExt.nullableImmutableCopyOf(twoLevelResources); this.taskContext = CollectionsExt.nullableImmutableCopyOf(taskContext); this.attributes = attributes; // TODO Remove me. Version is a newly introduced field. If not set explicitly, assign a default value this.version = version == null ? Version.undefined() : version; } public String getId() { return id; } public String getJobId() { return jobId; } public TaskStatus getStatus() { return status; } public List<TaskStatus> getStatusHistory() { return statusHistory; } public String getOriginalId() { return originalId; } public Optional<String> getResubmitOf() { return resubmitOf; } public int getResubmitNumber() { return resubmitNumber; } public int getSystemResubmitNumber() { return systemResubmitNumber; } public int getEvictionResubmitNumber() { return evictionResubmitNumber; } public List<TwoLevelResource> getTwoLevelResources() { return twoLevelResources; } public Map<String, String> getTaskContext() { return taskContext; } public Map<String, String> getAttributes() { return attributes; } public Version getVersion() { return version; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Task task = (Task) o; return resubmitNumber == task.resubmitNumber && systemResubmitNumber == task.systemResubmitNumber && evictionResubmitNumber == task.evictionResubmitNumber && Objects.equals(id, task.id) && Objects.equals(jobId, task.jobId) && Objects.equals(status, task.status) && Objects.equals(statusHistory, task.statusHistory) && Objects.equals(originalId, task.originalId) && Objects.equals(resubmitOf, task.resubmitOf) && Objects.equals(twoLevelResources, task.twoLevelResources) && Objects.equals(taskContext, task.taskContext) && Objects.equals(attributes, task.attributes) && Objects.equals(version, task.version); } @Override public int hashCode() { return Objects.hash(id, jobId, status, statusHistory, originalId, resubmitOf, resubmitNumber, systemResubmitNumber, evictionResubmitNumber, twoLevelResources, taskContext, attributes, version); } @Override public String toString() { return "Task{" + "id='" + id + '\'' + ", jobId='" + jobId + '\'' + ", status=" + status + ", statusHistory=" + statusHistory + ", originalId='" + originalId + '\'' + ", resubmitOf=" + resubmitOf + ", resubmitNumber=" + resubmitNumber + ", systemResubmitNumber=" + systemResubmitNumber + ", evictionResubmitNumber=" + evictionResubmitNumber + ", twoLevelResources=" + twoLevelResources + ", taskContext=" + taskContext + ", attributes=" + attributes + ", version=" + version + '}'; } public abstract TaskBuilder<?, ?> toBuilder(); public static abstract class TaskBuilder<T extends Task, B extends TaskBuilder<T, B>> { protected String id; protected String jobId; protected TaskStatus status; protected List<TaskStatus> statusHistory; protected String originalId; protected String resubmitOf; protected int resubmitNumber; protected int systemResubmitNumber; protected int evictionResubmitNumber; protected List<TwoLevelResource> twoLevelResources; protected Map<String, String> taskContext; protected Map<String, String> attributes; protected Version version; public B withId(String id) { this.id = id; return self(); } public B withJobId(String jobId) { this.jobId = jobId; return self(); } public B withStatus(TaskStatus status) { this.status = status; return self(); } public B withStatusHistory(List<TaskStatus> statusHistory) { this.statusHistory = statusHistory; return self(); } public B withStatusHistory(TaskStatus... statusHistory) { if (statusHistory.length == 0) { return withStatusHistory(Collections.emptyList()); } if (statusHistory.length == 1) { return withStatusHistory(Collections.singletonList(statusHistory[0])); } return withStatusHistory(asList(statusHistory)); } public B withOriginalId(String originalId) { this.originalId = originalId; return self(); } public B withResubmitOf(String resubmitOf) { this.resubmitOf = resubmitOf; return self(); } public B withResubmitNumber(int resubmitNumber) { this.resubmitNumber = resubmitNumber; return self(); } public B withSystemResubmitNumber(int systemResubmitNumber) { this.systemResubmitNumber = systemResubmitNumber; return self(); } public B withEvictionResubmitNumber(int evictionResubmitNumber) { this.evictionResubmitNumber = evictionResubmitNumber; return self(); } public B withTwoLevelResources(List<TwoLevelResource> twoLevelResources) { this.twoLevelResources = twoLevelResources; return self(); } public B withTwoLevelResources(TwoLevelResource... twoLevelResources) { if (twoLevelResources.length == 0) { return withTwoLevelResources(Collections.emptyList()); } if (twoLevelResources.length == 1) { return withTwoLevelResources(Collections.singletonList(twoLevelResources[0])); } return withTwoLevelResources(asList(twoLevelResources)); } public B addToTaskContext(String key, String value) { if (taskContext == null) { return withTaskContext(Collections.singletonMap(key, value)); } return withTaskContext(CollectionsExt.copyAndAdd(taskContext, key, value)); } public B addAllToTaskContext(Map<String, String> toAdd) { return withTaskContext(CollectionsExt.merge(taskContext, toAdd)); } public B withTaskContext(Map<String, String> taskContext) { this.taskContext = taskContext; return self(); } public B withAttributes(Map<String, String> attributes) { this.attributes = attributes; return self(); } public B withCellInfo(Job<?> job) { final Map<String, String> jobAttributes = job.getJobDescriptor().getAttributes(); if (CollectionsExt.containsKeys(jobAttributes, JOB_ATTRIBUTES_CELL)) { addToTaskContext(TASK_ATTRIBUTES_CELL, jobAttributes.get(JOB_ATTRIBUTES_CELL)); } if (CollectionsExt.containsKeys(jobAttributes, JOB_ATTRIBUTES_STACK)) { addToTaskContext(TASK_ATTRIBUTES_STACK, jobAttributes.get(JOB_ATTRIBUTES_STACK)); } return self(); } public B withCellInfo(Task task) { final Map<String, String> oldTaskContext = task.getTaskContext(); if (CollectionsExt.containsKeys(oldTaskContext, TASK_ATTRIBUTES_CELL)) { addToTaskContext(TASK_ATTRIBUTES_CELL, oldTaskContext.get(TASK_ATTRIBUTES_CELL)); } if (CollectionsExt.containsKeys(oldTaskContext, TASK_ATTRIBUTES_STACK)) { addToTaskContext(TASK_ATTRIBUTES_STACK, oldTaskContext.get(TASK_ATTRIBUTES_STACK)); } return self(); } public B withVersion(Version version) { this.version = version; return self(); } public abstract T build(); protected B but(TaskBuilder<T, B> newBuilder) { return newBuilder.withId(id) .withJobId(jobId) .withStatus(status) .withStatusHistory(statusHistory) .withOriginalId(originalId) .withResubmitOf(resubmitOf) .withResubmitNumber(resubmitNumber) .withSystemResubmitNumber(resubmitNumber) .withEvictionResubmitNumber(evictionResubmitNumber) .withTwoLevelResources(twoLevelResources) .withTaskContext(taskContext) .withAttributes(attributes) .withVersion(version); } protected B newBuilder(TaskBuilder<T, B> newBuilder, Task task) { return newBuilder .withId(task.getId()) .withJobId(task.getJobId()) .withStatus(task.getStatus()) .withStatusHistory(task.getStatusHistory()) .withOriginalId(task.getOriginalId()) .withResubmitOf(task.getResubmitOf().orElse(null)) .withResubmitNumber(task.getResubmitNumber()) .withSystemResubmitNumber(task.getSystemResubmitNumber()) .withEvictionResubmitNumber(task.getEvictionResubmitNumber()) .withTwoLevelResources(task.getTwoLevelResources()) .withTaskContext(task.getTaskContext()) .withAttributes(task.getAttributes()) .withVersion(task.getVersion()); } protected B self() { return (B) this; } } }
9,447
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Owner.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.titus.api.jobmanager.model.job; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; /** */ public class Owner { @NotNull(message = "'teamEmail' missing") @Pattern(regexp = ".*@.*", message = "Invalid email address") private final String teamEmail; public Owner(String teamEmail) { this.teamEmail = teamEmail; } public String getTeamEmail() { return teamEmail; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Owner owner = (Owner) o; return teamEmail != null ? teamEmail.equals(owner.teamEmail) : owner.teamEmail == null; } @Override public int hashCode() { return teamEmail != null ? teamEmail.hashCode() : 0; } @Override public String toString() { return "Owner{" + "teamEmail='" + teamEmail + '\'' + '}'; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(Owner owner) { return new Builder() .withTeamEmail(owner.getTeamEmail()); } public static final class Builder { private String teamEmail; private Builder() { } public Builder withTeamEmail(String teamEmail) { this.teamEmail = teamEmail; return this; } public Owner build() { Owner owner = new Owner(teamEmail); return owner; } } }
9,448
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/BasicContainer.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.titus.api.jobmanager.model.job; import java.util.Collections; import java.util.List; import java.util.Map; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import com.google.common.base.Preconditions; import com.netflix.titus.api.jobmanager.model.job.sanitizer.JobAssertions; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.FieldInvariant; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.common.util.CollectionsExt.nonNull; public class BasicContainer { @NotNull @Pattern(regexp = "[a-z0-9]([-a-z0-9]*[a-z0-9])?", message = "container name must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character") private final String name; @Valid private final Image image; @CollectionInvariants @FieldInvariant( value = "@asserts.isEntryPointNotTooLarge(value)", message = "Entry point size exceeds the limit " + JobAssertions.MAX_ENTRY_POINT_SIZE_SIZE_KB + "KB" ) private final List<String> entryPoint; @CollectionInvariants private final List<String> command; @CollectionInvariants(allowEmptyKeys = false) @FieldInvariant( value = "@asserts.areEnvironmentVariablesNotTooLarge(value)", message = "Container environment variables size exceeds the limit" ) private final Map<String, String> env; @CollectionInvariants private final List<VolumeMount> volumeMounts; public BasicContainer( String name, Image image, List<String> entryPoint, List<String> command, Map<String, String> env, List<VolumeMount> volumeMounts ) { this.name = name; this.image = image; this.entryPoint = CollectionsExt.nullableImmutableCopyOf(entryPoint); this.command = CollectionsExt.nullableImmutableCopyOf(command); this.env = CollectionsExt.nullableImmutableCopyOf(env); this.volumeMounts = CollectionsExt.nullableImmutableCopyOf(volumeMounts); } public String getName() { return name; } public Image getImage() { return image; } public List<String> getEntryPoint() { return entryPoint; } public List<String> getCommand() { return command; } public Map<String, String> getEnv() { return env; } public List<VolumeMount> getVolumeMounts() { return volumeMounts; } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(BasicContainer basicContainer) { return new Builder() .withName(basicContainer.getName()) .withImage(basicContainer.getImage()) .withEntryPoint(basicContainer.getEntryPoint()) .withCommand(basicContainer.getCommand()) .withEnv(basicContainer.getEnv()) .withVolumeMounts(basicContainer.getVolumeMounts()); } public static final class Builder { private String name; private Image image; private List<String> entryPoint; private List<String> command; private Map<String, String> env; private List<VolumeMount> volumeMounts; public Builder withName(String name) { this.name = name; return this; } public Builder withImage(Image image) { this.image = image; return this; } public Builder withEntryPoint(List<String> entryPoint) { if (entryPoint == null) { entryPoint = Collections.emptyList(); } this.entryPoint = entryPoint; return this; } public Builder withCommand(List<String> command) { if (command == null) { command = Collections.emptyList(); } this.command = command; return this; } public Builder withEnv(Map<String, String> env) { this.env = env; return this; } public Builder withVolumeMounts(List<VolumeMount> volumeMounts) { this.volumeMounts = volumeMounts; return this; } public BasicContainer build() { Preconditions.checkNotNull(image, "Image not defined"); return new BasicContainer( name, image, entryPoint, command, nonNull(env), nonNull(volumeMounts) ); } } }
9,449
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobFunctions.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.titus.api.jobmanager.model.job; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; 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.Function; import java.util.stream.Collectors; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor.JobDescriptorExt; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.ContainerHealthProvider; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnlimitedDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.retry.DelayedRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ExponentialBackoffRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ImmediateRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.RetryPolicy; import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.retry.Retryer; import com.netflix.titus.common.util.retry.Retryers; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.common.util.tuple.Pair; /** * Collection of functions for working with jobs and tasks. */ public final class JobFunctions { private static final String DEFAULT_APPLICATION = "DEFAULT"; private static final DisruptionBudget NO_DISRUPTION_BUDGET_MARKER = DisruptionBudget.newBuilder() .withDisruptionBudgetPolicy(SelfManagedDisruptionBudgetPolicy.newBuilder().build()) .withDisruptionBudgetRate(UnlimitedDisruptionBudgetRate.newBuilder().build()) .withContainerHealthProviders(Collections.emptyList()) .withTimeWindows(Collections.emptyList()) .build(); private JobFunctions() { } public static DisruptionBudget getNoDisruptionBudgetMarker() { return NO_DISRUPTION_BUDGET_MARKER; } public static JobType getJobType(Job<?> job) { return isServiceJob(job) ? JobType.SERVICE : JobType.BATCH; } public static JobType getJobType(JobDescriptor<?> jobDescriptor) { return isServiceJob(jobDescriptor) ? JobType.SERVICE : JobType.BATCH; } public static boolean isBatchJob(Job<?> job) { return job.getJobDescriptor().getExtensions() instanceof BatchJobExt; } public static boolean isBatchJob(JobDescriptor<?> jobDescriptor) { return jobDescriptor.getExtensions() instanceof BatchJobExt; } public static Job<BatchJobExt> asBatchJob(Job<?> job) { if (isBatchJob(job)) { return (Job<BatchJobExt>) job; } throw JobManagerException.notBatchJob(job.getId()); } public static JobDescriptor<BatchJobExt> asBatchJob(JobDescriptor<?> jobDescriptor) { if (isBatchJob(jobDescriptor)) { return (JobDescriptor<BatchJobExt>) jobDescriptor; } throw JobManagerException.notBatchJobDescriptor(jobDescriptor); } public static boolean isServiceJob(Job<?> job) { return job.getJobDescriptor().getExtensions() instanceof ServiceJobExt; } public static boolean isServiceJob(JobDescriptor<?> jobDescriptor) { return jobDescriptor.getExtensions() instanceof ServiceJobExt; } public static boolean isDisabled(Job<?> job) { return JobFunctions.isServiceJob(job) && !((ServiceJobExt) job.getJobDescriptor().getExtensions()).isEnabled(); } public static Job<ServiceJobExt> asServiceJob(Job<?> job) { if (isServiceJob(job)) { return (Job<ServiceJobExt>) job; } throw JobManagerException.notServiceJob(job.getId()); } public static JobDescriptor<ServiceJobExt> asServiceJob(JobDescriptor<?> jobDescriptor) { if (isServiceJob(jobDescriptor)) { return (JobDescriptor<ServiceJobExt>) jobDescriptor; } throw JobManagerException.notServiceJobDescriptor(jobDescriptor); } public static int getJobDesiredSize(Job<?> job) { return isServiceJob(job) ? ((ServiceJobExt) job.getJobDescriptor().getExtensions()).getCapacity().getDesired() : ((BatchJobExt) job.getJobDescriptor().getExtensions()).getSize(); } public static boolean isBatchTask(Task task) { return task instanceof BatchJobTask; } public static boolean isServiceTask(Task task) { return task instanceof ServiceJobTask; } public static boolean hasDisruptionBudget(JobDescriptor<?> jobDescriptor) { return !NO_DISRUPTION_BUDGET_MARKER.equals(jobDescriptor.getDisruptionBudget()); } public static boolean hasDisruptionBudget(Job<?> job) { return !NO_DISRUPTION_BUDGET_MARKER.equals(job.getJobDescriptor().getDisruptionBudget()); } /** * @return true if the task is or was at some point in time in the started state. */ public static boolean everStarted(Task task) { return findTaskStatus(task, TaskState.Started).isPresent(); } public static Job changeJobStatus(Job job, JobState jobState, String reasonCode) { JobStatus newStatus = JobModel.newJobStatus() .withState(jobState) .withReasonCode(reasonCode) .build(); return JobFunctions.changeJobStatus(job, newStatus); } public static Job changeJobStatus(Job job, JobStatus status) { JobStatus currentStatus = job.getStatus(); List<JobStatus> statusHistory = new ArrayList<>(job.getStatusHistory()); statusHistory.add(currentStatus); return job.toBuilder() .withStatus(status) .withStatusHistory(statusHistory) .build(); } public static JobDescriptor<BatchJobExt> changeBatchJobSize(JobDescriptor<BatchJobExt> jobDescriptor, int size) { BatchJobExt ext = jobDescriptor.getExtensions().toBuilder().withSize(size).build(); return jobDescriptor.toBuilder().withExtensions(ext).build(); } public static JobDescriptor<?> filterOutGeneratedAttributes(JobDescriptor<?> jobDescriptor) { return jobDescriptor.toBuilder().withAttributes( CollectionsExt.copyAndRemoveByKey(jobDescriptor.getAttributes(), key -> key.startsWith(JobAttributes.JOB_ATTRIBUTE_SANITIZATION_PREFIX) || key.startsWith(JobAttributes.PREDICTION_ATTRIBUTE_PREFIX) ) ).build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendJobDescriptorAttributes(JobDescriptor<E> jobDescriptor, Map<String, ?> attributes) { Map<String, String> asStrings = attributes.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())); return jobDescriptor.toBuilder() .withAttributes(CollectionsExt.copyAndAdd(jobDescriptor.getAttributes(), asStrings)) .build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendJobDescriptorAttribute(JobDescriptor<E> jobDescriptor, String attributeName, Object attributeValue) { return jobDescriptor.toBuilder() .withAttributes(CollectionsExt.copyAndAdd(jobDescriptor.getAttributes(), attributeName, "" + attributeValue)) .build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendContainerAttribute(JobDescriptor<E> jobDescriptor, String attributeName, Object attributeValue) { return jobDescriptor.toBuilder() .withContainer(jobDescriptor.getContainer().toBuilder() .withAttributes(CollectionsExt.copyAndAdd( jobDescriptor.getContainer().getAttributes(), attributeName, "" + attributeValue)) .build() ) .build(); } public static <E extends JobDescriptorExt> Job<E> appendContainerAttribute(Job<E> job, String attributeName, Object attributeValue) { return job.toBuilder() .withJobDescriptor(appendContainerAttribute(job.getJobDescriptor(), attributeName, attributeValue)) .build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendHardConstraint(JobDescriptor<E> jobDescriptor, String name, String value) { return jobDescriptor.toBuilder() .withContainer(jobDescriptor.getContainer().toBuilder() .withHardConstraints(CollectionsExt.copyAndAdd(jobDescriptor.getContainer().getHardConstraints(), name, value)) .build() ) .build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendSoftConstraint(JobDescriptor<E> jobDescriptor, String name, String value) { return jobDescriptor.toBuilder() .withContainer(jobDescriptor.getContainer().toBuilder() .withSoftConstraints(CollectionsExt.copyAndAdd(jobDescriptor.getContainer().getSoftConstraints(), name, value)) .build() ) .build(); } public static <E extends JobDescriptorExt> Job<E> appendHardConstraint(Job<E> job, String name, String value) { return job.toBuilder().withJobDescriptor(appendHardConstraint(job.getJobDescriptor(), name, value)).build(); } public static <E extends JobDescriptorExt> Job<E> appendSoftConstraint(Job<E> job, String name, String value) { return job.toBuilder().withJobDescriptor(appendSoftConstraint(job.getJobDescriptor(), name, value)).build(); } public static <E extends JobDescriptorExt> Job<E> appendJobDescriptorAttribute(Job<E> job, String attributeName, Object attributeValue) { return job.toBuilder() .withJobDescriptor(appendJobDescriptorAttribute(job.getJobDescriptor(), attributeName, attributeValue)) .build(); } /** * Constraint names are case insensitive. */ public static <E extends JobDescriptorExt> Optional<String> findHardConstraint(Job<E> job, String name) { return findConstraint(job.getJobDescriptor().getContainer().getHardConstraints(), name); } public static <E extends JobDescriptorExt> Optional<String> findHardConstraint(JobDescriptor<E> jobDescriptor, String name) { return findConstraint(jobDescriptor.getContainer().getHardConstraints(), name); } /** * Constraint names are case insensitive. */ public static <E extends JobDescriptorExt> Optional<String> findSoftConstraint(Job<E> job, String name) { return findConstraint(job.getJobDescriptor().getContainer().getSoftConstraints(), name); } private static Optional<String> findConstraint(Map<String, String> constraints, String name) { if (CollectionsExt.isNullOrEmpty(constraints)) { return Optional.empty(); } for (String key : constraints.keySet()) { if (key.equalsIgnoreCase(name)) { return Optional.ofNullable(constraints.get(key)); } } return Optional.empty(); } public static Task appendTaskAttribute(Task task, String attributeName, Object attributeValue) { return task.toBuilder() .withAttributes(CollectionsExt.copyAndAdd(task.getAttributes(), attributeName, "" + attributeValue)) .build(); } public static Task appendTaskContext(Task task, String contextName, Object contextValue) { return task.toBuilder() .withTaskContext(CollectionsExt.copyAndAdd(task.getTaskContext(), contextName, "" + contextValue)) .build(); } public static Job<BatchJobExt> changeBatchJobSize(Job<BatchJobExt> job, int size) { return job.toBuilder().withJobDescriptor(changeBatchJobSize(job.getJobDescriptor(), size)).build(); } public static JobDescriptor<ServiceJobExt> changeServiceJobCapacity(JobDescriptor<ServiceJobExt> jobDescriptor, int size) { return changeServiceJobCapacity(jobDescriptor, Capacity.newBuilder().withMin(size).withDesired(size).withMax(size).build()); } public static JobDescriptor<ServiceJobExt> changeServiceJobCapacity(JobDescriptor<ServiceJobExt> jobDescriptor, Capacity capacity) { return jobDescriptor.toBuilder() .withExtensions(jobDescriptor.getExtensions().toBuilder() .withCapacity(capacity) .build() ) .build(); } public static Job<ServiceJobExt> changeServiceJobCapacity(Job<ServiceJobExt> job, Capacity capacity) { return job.toBuilder().withJobDescriptor(changeServiceJobCapacity(job.getJobDescriptor(), capacity)).build(); } public static Job<ServiceJobExt> changeServiceJobCapacity(Job<ServiceJobExt> job, CapacityAttributes capacityAttributes) { Capacity.Builder newCapacityBuilder = job.getJobDescriptor().getExtensions().getCapacity().toBuilder(); capacityAttributes.getDesired().ifPresent(newCapacityBuilder::withDesired); capacityAttributes.getMax().ifPresent(newCapacityBuilder::withMax); capacityAttributes.getMin().ifPresent(newCapacityBuilder::withMin); return job.toBuilder().withJobDescriptor(changeServiceJobCapacity(job.getJobDescriptor(), newCapacityBuilder.build())).build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> changeSecurityGroups(JobDescriptor<E> jobDescriptor, List<String> securityGroups) { return jobDescriptor.but(jd -> jd.getContainer() .but(c -> c.getSecurityProfile().toBuilder().withSecurityGroups(securityGroups).build())); } public static <E extends JobDescriptorExt> JobDescriptor<E> incrementJobDescriptorSize(JobDescriptor<E> jobDescriptor, int delta) { if (isServiceJob(jobDescriptor)) { Capacity oldCapacity = ((ServiceJobExt) jobDescriptor.getExtensions()).getCapacity(); Capacity newCapacity = oldCapacity.toBuilder().withDesired(oldCapacity.getDesired() + delta).build(); return (JobDescriptor<E>) changeServiceJobCapacity((JobDescriptor<ServiceJobExt>) jobDescriptor, newCapacity); } JobDescriptor<BatchJobExt> batchDescriptor = (JobDescriptor<BatchJobExt>) jobDescriptor; return (JobDescriptor<E>) changeBatchJobSize(batchDescriptor, batchDescriptor.getExtensions().getSize() + delta); } public static <E extends JobDescriptorExt> Job<E> incrementJobSize(Job<E> job, int delta) { return job.toBuilder().withJobDescriptor(incrementJobDescriptorSize(job.getJobDescriptor(), delta)).build(); } public static Job<ServiceJobExt> changeJobEnabledStatus(Job<ServiceJobExt> job, boolean enabled) { JobDescriptor<ServiceJobExt> jobDescriptor = job.getJobDescriptor().toBuilder() .withExtensions(job.getJobDescriptor().getExtensions().toBuilder() .withEnabled(enabled) .build() ) .build(); return job.toBuilder().withJobDescriptor(jobDescriptor).build(); } public static Job<ServiceJobExt> changeServiceJobProcesses(Job<ServiceJobExt> job, ServiceJobProcesses processes) { return job.toBuilder().withJobDescriptor(job.getJobDescriptor().but(jd -> jd.getExtensions().toBuilder().withServiceJobProcesses(processes).build() )).build(); } public static Task changeTaskStatus(Task task, TaskStatus status) { return taskStatusChangeBuilder(task, status).build(); } public static Task changeTaskStatus(Task task, TaskState taskState, String reasonCode, String reasonMessage, Clock clock) { TaskStatus newStatus = JobModel.newTaskStatus() .withState(taskState) .withReasonCode(reasonCode) .withReasonMessage(reasonMessage) .withTimestamp(clock.wallTime()) .build(); return taskStatusChangeBuilder(task, newStatus).build(); } public static Task fixArchivedTaskStatus(Task task, Clock clock) { Task fixed = task.toBuilder() .withStatus(TaskStatus.newBuilder() .withState(TaskState.Finished) .withReasonCode("inconsistent") .withReasonMessage("Expecting task in Finished state, but is " + task.getStatus().getState()) .withTimestamp(clock.wallTime()) .build() ) .withStatusHistory(CollectionsExt.copyAndAdd(task.getStatusHistory(), task.getStatus())) .build(); return fixed; } public static Task addAllocatedResourcesToTask(Task task, TaskStatus status, TwoLevelResource twoLevelResource, Map<String, String> taskContext) { return taskStatusChangeBuilder(task, status) .withTwoLevelResources(twoLevelResource) .addAllToTaskContext(taskContext) .build(); } public static <E extends JobDescriptorExt> Function<Job<E>, Job<E>> withJobId(String jobId) { return job -> job.toBuilder().withId(jobId).build(); } public static <E extends JobDescriptorExt> Function<Job<E>, Job<E>> withApplicationName(String appName) { return job -> job.toBuilder().withJobDescriptor(job.getJobDescriptor().toBuilder().withApplicationName(appName).build()).build(); } public static Function<JobDescriptor<BatchJobExt>, JobDescriptor<BatchJobExt>> ofBatchSize(int size) { return jd -> JobFunctions.changeBatchJobSize(jd, size); } public static Function<JobDescriptor<ServiceJobExt>, JobDescriptor<ServiceJobExt>> ofServiceSize(int size) { return jd -> JobFunctions.changeServiceJobCapacity(jd, size); } public static <E extends JobDescriptorExt> Function<JobDescriptor<E>, JobDescriptor<E>> havingProvider(String name, String... attributes) { ContainerHealthProvider newProvider = ContainerHealthProvider.newBuilder() .withName(name) .withAttributes(CollectionsExt.asMap(attributes)) .build(); return jd -> { List<ContainerHealthProvider> existing = jd.getDisruptionBudget().getContainerHealthProviders().stream() .filter(p -> !p.getName().equals(name)) .collect(Collectors.toList()); List<ContainerHealthProvider> providers = new ArrayList<>(existing); providers.add(newProvider); return jd.toBuilder() .withDisruptionBudget( jd.getDisruptionBudget().toBuilder() .withContainerHealthProviders(providers) .build() ).build(); }; } public static <E extends JobDescriptorExt> Function<JobDescriptor<E>, JobDescriptor<E>> withDisruptionBudget(DisruptionBudget disruptionBudget) { return jobDescriptor -> jobDescriptor.toBuilder().withDisruptionBudget(disruptionBudget).build(); } public static <E extends JobDescriptorExt> Function<Job<E>, Job<E>> withJobDisruptionBudget(DisruptionBudget disruptionBudget) { return job -> job.toBuilder() .withJobDescriptor(job.getJobDescriptor().toBuilder().withDisruptionBudget(disruptionBudget).build()) .build(); } private static Task.TaskBuilder taskStatusChangeBuilder(Task task, TaskStatus status) { TaskStatus currentStatus = task.getStatus(); List<TaskStatus> statusHistory = new ArrayList<>(task.getStatusHistory()); statusHistory.add(currentStatus); return task.toBuilder() .withStatus(status) .withStatusHistory(statusHistory); } public static Retryer retryerFrom(RetryPolicy retryPolicy) { if (retryPolicy instanceof ImmediateRetryPolicy) { return Retryers.immediate(); } if (retryPolicy instanceof DelayedRetryPolicy) { return Retryers.interval(((DelayedRetryPolicy) retryPolicy).getDelayMs(), TimeUnit.MILLISECONDS); } if (retryPolicy instanceof ExponentialBackoffRetryPolicy) { ExponentialBackoffRetryPolicy exponential = (ExponentialBackoffRetryPolicy) retryPolicy; return Retryers.exponentialBackoff(exponential.getInitialDelayMs(), exponential.getMaxDelayMs(), TimeUnit.MILLISECONDS); } throw new IllegalArgumentException("Unknown RetryPolicy type " + retryPolicy.getClass()); } public static Retryer retryer(Job<?> job) { RetryPolicy retryPolicy = getRetryPolicy(job); return retryerFrom(retryPolicy); } public static RetryPolicy getRetryPolicy(Job<?> job) { JobDescriptorExt ext = job.getJobDescriptor().getExtensions(); return ext instanceof BatchJobExt ? ((BatchJobExt) ext).getRetryPolicy() : ((ServiceJobExt) ext).getRetryPolicy(); } public static <E extends JobDescriptorExt> JobDescriptor<E> changeRetryPolicy(JobDescriptor<E> input, RetryPolicy retryPolicy) { if (input.getExtensions() instanceof BatchJobExt) { JobDescriptor<BatchJobExt> batchJob = (JobDescriptor<BatchJobExt>) input; return (JobDescriptor<E>) batchJob.but(jd -> batchJob.getExtensions().toBuilder().withRetryPolicy(retryPolicy).build()); } JobDescriptor<ServiceJobExt> serviceJob = (JobDescriptor<ServiceJobExt>) input; return (JobDescriptor<E>) serviceJob.but(jd -> serviceJob.getExtensions().toBuilder().withRetryPolicy(retryPolicy).build()); } public static JobDescriptor<BatchJobExt> changeRetryLimit(JobDescriptor<BatchJobExt> input, int retryLimit) { RetryPolicy newRetryPolicy = input.getExtensions().getRetryPolicy().toBuilder().withRetries(retryLimit).build(); return input.but(jd -> input.getExtensions().toBuilder().withRetryPolicy(newRetryPolicy).build()); } public static <E extends JobDescriptorExt> JobDescriptor<E> changeDisruptionBudget(JobDescriptor<E> input, DisruptionBudget disruptionBudget) { return input.toBuilder().withDisruptionBudget(disruptionBudget).build(); } public static <E extends JobDescriptorExt> Job<E> changeDisruptionBudget(Job<E> input, DisruptionBudget disruptionBudget) { return input.toBuilder().withJobDescriptor(changeDisruptionBudget(input.getJobDescriptor(), disruptionBudget)).build(); } public static <E extends JobDescriptorExt> Job<E> appendCallMetadataJobAttributes(Job<E> input, CallMetadata callMetadata) { // Add call metadata as job attribute Map<String, String> callMetadataAttribute = new HashMap<>(); String callerId = callMetadata.getCallers().isEmpty() ? "unknown" : callMetadata.getCallers().get(0).getId(); callMetadataAttribute.put(JobAttributes.JOB_ATTRIBUTES_CREATED_BY, callerId); callMetadataAttribute.put(JobAttributes.JOB_ATTRIBUTES_CALL_REASON, callMetadata.getCallReason()); JobDescriptor<E> jobDescriptor = input.getJobDescriptor(); Map<String, String> updatedAttributes = CollectionsExt.merge(jobDescriptor.getAttributes(), callMetadataAttribute); return input.toBuilder().withJobDescriptor(jobDescriptor.toBuilder().withAttributes(updatedAttributes).build()).build(); } public static <E extends JobDescriptorExt> Job<E> updateJobAttributes(Job<E> input, Map<String, String> attributes) { JobDescriptor<E> jobDescriptor = input.getJobDescriptor(); Map<String, String> updatedAttributes = CollectionsExt.merge(jobDescriptor.getAttributes(), attributes); return input.toBuilder().withJobDescriptor(jobDescriptor.toBuilder().withAttributes(updatedAttributes).build()).build(); } public static <E extends JobDescriptorExt> Job<E> deleteJobAttributes(Job<E> input, Set<String> keys) { return input.toBuilder().withJobDescriptor(deleteJobAttributes(input.getJobDescriptor(), keys)).build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> deleteJobAttributes(JobDescriptor<E> input, Set<String> keys) { Map<String, String> updatedAttributes = CollectionsExt.copyAndRemove(input.getAttributes(), keys); return input.toBuilder().withAttributes(updatedAttributes).build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> appendJobSecurityAttributes(JobDescriptor<E> input, Map<String, String> attributes) { SecurityProfile securityProfile = input.getContainer().getSecurityProfile(); Map<String, String> updatedAttributes = CollectionsExt.merge(securityProfile.getAttributes(), attributes); return input.toBuilder() .withContainer(input.getContainer().toBuilder() .withSecurityProfile(securityProfile.toBuilder() .withAttributes(updatedAttributes) .build()) .build()) .build(); } public static <E extends JobDescriptorExt> JobDescriptor<E> deleteJobSecurityAttributes(JobDescriptor<E> input, Set<String> keys) { SecurityProfile securityProfile = input.getContainer().getSecurityProfile(); Map<String, String> updatedAttributes = CollectionsExt.copyAndRemove(securityProfile.getAttributes(), keys); return input.toBuilder() .withContainer(input.getContainer().toBuilder() .withSecurityProfile(securityProfile.toBuilder() .withAttributes(updatedAttributes) .build()) .build()) .build(); } public static Optional<Long> getTimeInState(Task task, TaskState checkedState, Clock clock) { return findTaskStatus(task, checkedState).map(checkedStatus -> { TaskState currentState = task.getStatus().getState(); if (currentState == checkedState) { return clock.wallTime() - task.getStatus().getTimestamp(); } if (TaskState.isAfter(checkedState, currentState)) { return 0L; } return findStatusAfter(task, checkedState).map(after -> after.getTimestamp() - checkedStatus.getTimestamp()).orElse(0L); }); } public static Task moveTask(String jobIdFrom, String jobIdTo, Task taskBefore) { return taskBefore.toBuilder() .withJobId(jobIdTo) .addToTaskContext(TaskAttributes.TASK_ATTRIBUTES_MOVED_FROM_JOB, jobIdFrom) .build(); } /** * Check that the given task transitioned through the expected states. Duplicates of a state are collapsed into single state. */ public static boolean containsExactlyTaskStates(Task task, TaskState... expectedStates) { if (expectedStates.length == 0) { return false; } TaskState taskState = task.getStatus().getState(); List<TaskStatus> statusHistory = task.getStatusHistory(); if (expectedStates.length == 1 && statusHistory.isEmpty()) { return taskState == expectedStates[0]; } // For non-single state values, we have to eliminate possible duplicates. Set<TaskState> expectedPreviousStates = CollectionsExt.asSet(expectedStates); Set<TaskState> taskStates = statusHistory.stream().map(ExecutableStatus::getState).collect(Collectors.toSet()); taskStates.add(taskState); return expectedPreviousStates.equals(taskStates); } public static Optional<JobStatus> findJobStatus(Job<?> job, JobState checkedState) { if (job.getStatus() == null) { return Optional.empty(); } if (job.getStatus().getState() == checkedState) { return Optional.of(job.getStatus()); } for (JobStatus jobStatus : job.getStatusHistory()) { if (jobStatus.getState() == checkedState) { return Optional.of(jobStatus); } } return Optional.empty(); } public static Optional<TaskStatus> findTaskStatus(Task task, TaskState checkedState) { if (task.getStatus().getState() == checkedState) { return Optional.of(task.getStatus()); } for (TaskStatus taskStatus : task.getStatusHistory()) { if (taskStatus.getState() == checkedState) { return Optional.of(taskStatus); } } return Optional.empty(); } public static Optional<TaskStatus> findStatusAfter(Task task, TaskState before) { TaskStatus after = null; for (TaskStatus status : task.getStatusHistory()) { if (TaskState.isAfter(status.getState(), before)) { if (after == null) { after = status; } else if (TaskState.isAfter(after.getState(), status.getState())) { after = status; } } } if (after == null && TaskState.isAfter(task.getStatus().getState(), before)) { after = task.getStatus(); } return Optional.ofNullable(after); } /** * Jobs can include a fractional runtime duration prediction in seconds, which are parsed with millisecond resolution. * * @return a duration (if present) with millisecond resolution * @see JobAttributes#JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC */ public static Optional<Duration> getJobRuntimePrediction(Job job) { return getJobRuntimePrediction(job.getJobDescriptor()); } /** * Jobs can include a fractional runtime duration prediction in seconds, which are parsed with millisecond resolution. * * @return a duration (if present) with millisecond resolution * @see JobAttributes#JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC */ @SuppressWarnings("unchecked") public static Optional<Duration> getJobRuntimePrediction(JobDescriptor jobDescriptor) { if (!isBatchJob(jobDescriptor)) { return Optional.empty(); } Map<String, String> attributes = ((JobDescriptor<BatchJobExt>) jobDescriptor).getAttributes(); return Optional.ofNullable(attributes.get(JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC)) .flatMap(StringExt::parseDouble) .map(seconds -> ((long) (seconds * 1000))) // seconds -> milliseconds .map(Duration::ofMillis); } public static String getEffectiveCapacityGroup(Job job) { String capacityGroup = job.getJobDescriptor().getCapacityGroup(); if (StringExt.isEmpty(capacityGroup)) { capacityGroup = job.getJobDescriptor().getApplicationName(); } return StringExt.isEmpty(capacityGroup) ? DEFAULT_APPLICATION : capacityGroup; } public static <E extends JobDescriptorExt> JobDescriptor<E> jobWithEbsVolumes(JobDescriptor<E> jd, List<EbsVolume> ebsVolumes, Map<String, String> ebsVolumeAttributes) { return jd .but(d -> d.getContainer() .but(c -> c.getContainerResources().toBuilder().withEbsVolumes(ebsVolumes).build())) .but(j -> ebsVolumeAttributes); } public static <E extends JobDescriptorExt> JobDescriptor<E> jobWithIpAllocations(JobDescriptor<E> jd, List<SignedIpAddressAllocation> ipAllocations) { return jd .but(j -> j.getContainer() .but(c -> c.getContainerResources().toBuilder().withSignedIpAddressAllocations(ipAllocations).build())); } /** * Split tasks into groups with the same original id and order them by their resubmit order. Tasks that do not fit * into any such group are returned as a second parameter in the result. Keys in the returned map contain * task original ids. Lists start with the original task followed by its resubmits. */ public static Pair<Map<String, List<Task>>, List<Task>> groupTasksByResubmitOrder(Collection<Task> tasks) { if (tasks.isEmpty()) { return Pair.of(Collections.emptyMap(), Collections.emptyList()); } Map<String, Task> tasksById = new HashMap<>(); Map<String, List<Task>> mapped = new HashMap<>(); tasks.forEach(task -> { tasksById.put(task.getId(), task); if (task.getId().equals(task.getOriginalId())) { mapped.put(task.getId(), new ArrayList<>()); } }); Map<String, Task> parentIdToNextTask = new HashMap<>(); tasks.forEach(task -> { String parentId = task.getResubmitOf().orElse(null); if (parentId != null && tasksById.containsKey(parentId)) { parentIdToNextTask.put(parentId, task); } }); Map<String, Task> left = new HashMap<>(tasksById); mapped.forEach((originalId, list) -> { Task current = tasksById.get(originalId); while (current != null) { list.add(current); left.remove(current.getId()); current = parentIdToNextTask.get(current.getId()); } }); List<Task> rejected = new ArrayList<>(left.values()); return Pair.of(mapped, rejected); } }
9,450
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ExecutableStatus.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.titus.api.jobmanager.model.job; /** */ public abstract class ExecutableStatus<STATE extends Enum<STATE>> { private final STATE state; private final String reasonCode; private final String reasonMessage; private final long timestamp; protected ExecutableStatus(STATE state, String reasonCode, String reasonMessage, long timestamp) { this.state = state; this.reasonCode = reasonCode; this.reasonMessage = reasonMessage; this.timestamp = timestamp; } public STATE getState() { return state; } public String getReasonCode() { return reasonCode; } public String getReasonMessage() { return reasonMessage; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExecutableStatus<?> that = (ExecutableStatus<?>) o; if (timestamp != that.timestamp) { return false; } if (state != null ? !state.equals(that.state) : that.state != null) { return false; } if (reasonCode != null ? !reasonCode.equals(that.reasonCode) : that.reasonCode != null) { return false; } return reasonMessage != null ? reasonMessage.equals(that.reasonMessage) : that.reasonMessage == null; } @Override public int hashCode() { int result = state != null ? state.hashCode() : 0; result = 31 * result + (reasonCode != null ? reasonCode.hashCode() : 0); result = 31 * result + (reasonMessage != null ? reasonMessage.hashCode() : 0); result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); return result; } @Override public String toString() { return getClass().getSimpleName() + "{" + "state=" + state + ", reasonCode='" + reasonCode + '\'' + ", reasonMessage='" + reasonMessage + '\'' + ", timestamp=" + timestamp + '}'; } public static abstract class AbstractBuilder< STATE extends Enum<STATE>, B extends AbstractBuilder<STATE, B, S>, S extends ExecutableStatus<STATE> > { protected STATE state; protected String reasonCode; protected String reasonMessage; protected long timestamp = System.currentTimeMillis(); AbstractBuilder() { } AbstractBuilder(S status) { this.state = status.getState(); this.reasonCode = status.getReasonCode(); this.reasonMessage = status.getReasonMessage(); this.timestamp = status.getTimestamp(); } public B withState(STATE state) { this.state = state; return self(); } public B withReasonCode(String reasonCode) { this.reasonCode = reasonCode; return self(); } public B withReasonMessage(String reasonMessage) { this.reasonMessage = reasonMessage; return self(); } public B withTimestamp(long timestamp) { this.timestamp = timestamp; return self(); } public abstract S build(); private B self() { return (B) this; } protected String toCompleteReasonMessage() { return reasonMessage == null ? "<not_given>" : reasonMessage; } } }
9,451
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobModel.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.titus.api.jobmanager.model.job; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.migration.SelfManagedMigrationPolicy; import com.netflix.titus.api.jobmanager.model.job.migration.SystemDefaultMigrationPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.DelayedRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.DelayedRetryPolicyBuilder; import com.netflix.titus.api.jobmanager.model.job.retry.ExponentialBackoffRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ExponentialBackoffRetryPolicyBuilder; import com.netflix.titus.api.jobmanager.model.job.retry.ImmediateRetryPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ImmediateRetryPolicyBuilder; /** * A collection of factory, and help methods operating on job data model. */ public final class JobModel { private JobModel() { } public static Capacity.Builder newCapacity() { return Capacity.newBuilder(); } public static CapacityAttributes.Builder newCapacityAttributes() { return CapacityAttributes.newBuilder(); } public static CapacityAttributes.Builder newCapacityAttributes(Capacity capacity) { return CapacityAttributes.newBuilder() .withMin(capacity.getMin()) .withMax(capacity.getMax()) .withDesired(capacity.getDesired()); } public static ServiceJobProcesses.Builder newServiceJobProcesses() { return ServiceJobProcesses.newBuilder(); } public static Capacity.Builder newCapacity(Capacity capacity) { return Capacity.newBuilder(capacity); } public static Image.Builder newImage() { return Image.newBuilder(); } public static Image.Builder newImage(Image image) { return Image.newBuilder(image); } public static JobStatus.Builder newJobStatus() { return JobStatus.newBuilder(); } public static JobStatus.Builder newJobStatus(JobStatus jobStatus) { return JobStatus.newBuilder(jobStatus); } public static TaskStatus.Builder newTaskStatus() { return TaskStatus.newBuilder(); } public static TaskStatus.Builder newTaskStatus(TaskStatus taskStatus) { return TaskStatus.newBuilder(taskStatus); } public static ContainerResources.Builder newContainerResources() { return ContainerResources.newBuilder(); } public static ContainerResources.Builder newContainerResources(ContainerResources containerResources) { return ContainerResources.newBuilder(containerResources); } public static SecurityProfile.Builder newSecurityProfile() { return SecurityProfile.newBuilder(); } public static SecurityProfile.Builder newSecurityProfile(SecurityProfile securityProfile) { return SecurityProfile.newBuilder(securityProfile); } public static NetworkConfiguration.Builder newNetworkConfiguration() { return NetworkConfiguration.newBuilder(); } public static NetworkConfiguration.Builder newNetworkConfiguration(NetworkConfiguration networkConfiguration) { return NetworkConfiguration.newBuilder(networkConfiguration); } public static Container.Builder newContainer() { return Container.newBuilder(); } public static Container.Builder newContainer(Container container) { return Container.newBuilder(container); } public static ImmediateRetryPolicyBuilder newImmediateRetryPolicy() { return ImmediateRetryPolicy.newBuilder(); } public static DelayedRetryPolicyBuilder newDelayedRetryPolicy() { return DelayedRetryPolicy.newBuilder(); } public static ExponentialBackoffRetryPolicyBuilder newExponentialBackoffRetryPolicy() { return ExponentialBackoffRetryPolicy.newBuilder(); } public static SystemDefaultMigrationPolicy.Builder newSystemDefaultMigrationPolicy() { return SystemDefaultMigrationPolicy.newBuilder(); } public static SelfManagedMigrationPolicy.Builder newSelfManagedMigrationPolicy() { return SelfManagedMigrationPolicy.newBuilder(); } public static <E extends JobDescriptor.JobDescriptorExt> JobDescriptor.Builder<E> newJobDescriptor() { return JobDescriptor.newBuilder(); } public static <E extends JobDescriptor.JobDescriptorExt> JobDescriptor.Builder<E> newJobDescriptor(JobDescriptor<E> jobDescriptor) { return JobDescriptor.newBuilder(jobDescriptor); } public static Owner.Builder newOwner() { return Owner.newBuilder(); } public static Owner.Builder newOwner(Owner owner) { return Owner.newBuilder(owner); } public static JobGroupInfo.Builder newJobGroupInfo() { return JobGroupInfo.newBuilder(); } public static JobGroupInfo.Builder newJobGroupInfo(JobGroupInfo jobGroupInfo) { return JobGroupInfo.newBuilder(jobGroupInfo); } public static <E extends JobDescriptor.JobDescriptorExt> Job.Builder<E> newJob() { return Job.newBuilder(); } public static BatchJobExt.Builder newBatchJobExt() { return BatchJobExt.newBuilder(); } public static BatchJobExt.Builder newBatchJobExt(BatchJobExt batchJobExt) { return BatchJobExt.newBuilder(batchJobExt); } public static BatchJobTask.Builder newBatchJobTask() { return BatchJobTask.newBuilder(); } public static BatchJobTask.Builder newBatchJobTask(BatchJobTask task) { return BatchJobTask.newBuilder(task); } public static ServiceJobExt.Builder newServiceJobExt() { return ServiceJobExt.newBuilder(); } public static ServiceJobExt.Builder newServiceJobExt(ServiceJobExt serviceJobExt) { return ServiceJobExt.newBuilder(serviceJobExt); } public static ServiceJobTask.Builder newServiceJobTask() { return ServiceJobTask.newBuilder(); } public static ServiceJobTask.Builder newServiceJobTask(ServiceJobTask task) { return ServiceJobTask.newBuilder(task); } }
9,452
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/SecurityProfile.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.titus.api.jobmanager.model.job; import java.util.List; import java.util.Map; import javax.validation.constraints.Size; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.FieldInvariant; import com.netflix.titus.common.util.CollectionsExt; import static com.netflix.titus.common.util.CollectionsExt.nonNull; /** */ @ClassFieldsNotNull public class SecurityProfile { private static final SecurityProfile EMPTY = newBuilder().build(); @FieldInvariant(value = "@asserts.isValidSyntax(value)", message = "Syntactically invalid security group ids: #{value}") @Size(min = 1, max = 6, message = "Number of security groups must be between 1 and 6") private final List<String> securityGroups; @FieldInvariant(value = "@asserts.isValidIamRole(value)", message = "Syntactically invalid IAM role: #{value}") private final String iamRole; @CollectionInvariants private final Map<String, String> attributes; public SecurityProfile(List<String> securityGroups, String iamRole, Map<String, String> attributes) { this.securityGroups = CollectionsExt.nullableImmutableCopyOf(securityGroups); this.iamRole = iamRole; this.attributes = CollectionsExt.nullableImmutableCopyOf(attributes); } public List<String> getSecurityGroups() { return securityGroups; } public String getIamRole() { return iamRole; } public Map<String, String> getAttributes() { return attributes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SecurityProfile that = (SecurityProfile) o; if (securityGroups != null ? !securityGroups.equals(that.securityGroups) : that.securityGroups != null) { return false; } if (iamRole != null ? !iamRole.equals(that.iamRole) : that.iamRole != null) { return false; } return attributes != null ? attributes.equals(that.attributes) : that.attributes == null; } @Override public int hashCode() { int result = securityGroups != null ? securityGroups.hashCode() : 0; result = 31 * result + (iamRole != null ? iamRole.hashCode() : 0); result = 31 * result + (attributes != null ? attributes.hashCode() : 0); return result; } @Override public String toString() { return "SecurityProfile{" + "securityGroups=" + securityGroups + ", iamRole='" + iamRole + '\'' + ", attributes=" + attributes + '}'; } public Builder toBuilder() { return newBuilder(this); } public static SecurityProfile empty() { return EMPTY; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(SecurityProfile securityProfile) { return new Builder() .withSecurityGroups(securityProfile.getSecurityGroups()) .withIamRole(securityProfile.getIamRole()) .withAttributes(securityProfile.getAttributes()); } public static final class Builder { private List<String> securityGroups; private String iamRole; private Map<String, String> attributes; private Builder() { } public Builder withSecurityGroups(List<String> securityGroups) { this.securityGroups = securityGroups; return this; } public Builder withIamRole(String iamRole) { this.iamRole = iamRole; return this; } public Builder withAttributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public Builder but() { return newBuilder().withSecurityGroups(securityGroups).withIamRole(iamRole); } public SecurityProfile build() { return new SecurityProfile(nonNull(securityGroups), iamRole, nonNull(attributes)); } } }
9,453
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobDescriptor.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.titus.api.jobmanager.model.job; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import javax.validation.Valid; import javax.validation.constraints.Size; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnlimitedDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.volume.Volume; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.ClassInvariant; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.Template; import com.netflix.titus.common.model.sanitizer.VerifierMode; import com.netflix.titus.common.util.CollectionsExt; /** * */ @ClassFieldsNotNull @ClassInvariant.List({ @ClassInvariant(expr = "@asserts.notExceedsComputeResources(capacityGroup, container)", mode = VerifierMode.Strict), @ClassInvariant(expr = "@asserts.notExceedsIpAllocations(container, extensions)", mode = VerifierMode.Strict), @ClassInvariant(expr = "@asserts.notExceedsEbsVolumes(container, extensions)", mode = VerifierMode.Strict) }) public class JobDescriptor<E extends JobDescriptor.JobDescriptorExt> { private static final DisruptionBudget DEFAULT_DISRUPTION_BUDGET = DisruptionBudget.newBuilder() .withDisruptionBudgetPolicy(SelfManagedDisruptionBudgetPolicy.newBuilder().build()) .withDisruptionBudgetRate(UnlimitedDisruptionBudgetRate.newBuilder().build()) .withTimeWindows(Collections.emptyList()) .withContainerHealthProviders(Collections.emptyList()) .build(); /** * A marker interface for {@link JobDescriptor} extensions. */ public interface JobDescriptorExt { } @Valid private final Owner owner; @Size(min = 1, message = "Empty string not allowed") private final String applicationName; @Template private final String capacityGroup; @Valid private final JobGroupInfo jobGroupInfo; @CollectionInvariants private final Map<String, String> attributes; @Valid private final Container container; @Valid private final DisruptionBudget disruptionBudget; @Valid private final NetworkConfiguration networkConfiguration; @CollectionInvariants private final List<BasicContainer> extraContainers; @Valid private final List<Volume> volumes; @Valid private final List<PlatformSidecar> platformSidecars; @Valid private final E extensions; public JobDescriptor(Owner owner, String applicationName, String capacityGroup, JobGroupInfo jobGroupInfo, Map<String, String> attributes, Container container, DisruptionBudget disruptionBudget, NetworkConfiguration networkConfiguration, List<BasicContainer> extraContainers, List<Volume> volumes, List<PlatformSidecar> platformSidecars, E extensions) { this.owner = owner; this.applicationName = applicationName; this.capacityGroup = capacityGroup; this.jobGroupInfo = jobGroupInfo; this.attributes = CollectionsExt.nullableImmutableCopyOf(attributes); this.container = container; this.extensions = extensions; //TODO remove this once we start storing the disruption budget if (disruptionBudget == null) { this.disruptionBudget = DEFAULT_DISRUPTION_BUDGET; } else { this.disruptionBudget = disruptionBudget; } if (networkConfiguration == null) { this.networkConfiguration = NetworkConfiguration.newBuilder().build(); } else { this.networkConfiguration = networkConfiguration; } if (extraContainers == null) { extraContainers = Collections.emptyList(); } this.extraContainers = extraContainers; if (volumes == null) { volumes = Collections.emptyList(); } this.volumes = volumes; if (platformSidecars == null) { platformSidecars = Collections.emptyList(); } this.platformSidecars = platformSidecars; } /** * Owner of a job (see Owner entity description for more information). */ public Owner getOwner() { return owner; } /** * Arbitrary name, not interpreted by Titus. Does not have to be unique. If not provided, a default * name, that depends on job type (batch or service) is set. */ public String getApplicationName() { return applicationName; } /** * Capacity group associated with a job. */ public String getCapacityGroup() { return capacityGroup; } /** * Mostly relevant for service jobs, but applicable to batch jobs as well, provides further grouping * criteria for a job. */ public JobGroupInfo getJobGroupInfo() { return jobGroupInfo; } /** * Arbitrary set of key/value pairs. Names starting with 'titus' (case does not matter) are reserved for internal use. */ public Map<String, String> getAttributes() { return attributes; } /** * Container to be executed for a job. */ public Container getContainer() { return container; } /** * Disruption budget to use for a job. */ public DisruptionBudget getDisruptionBudget() { return disruptionBudget; } /** * Network configuration for a job */ public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; } /** * Extra containers to be run alongside the main container for a job */ public List<BasicContainer> getExtraContainers() { return extraContainers; } /** * Volumes represent a list of volumes that are available for containers in a job to volumeMount */ public List<Volume> getVolumes() { return volumes; } /** * Volumes represent a list of volumes that are available for containers in a job to volumeMount */ public List<PlatformSidecar> getPlatformSidecars() { return platformSidecars; } /** * Returns job type specific data. */ public E getExtensions() { return extensions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JobDescriptor<?> that = (JobDescriptor<?>) o; return Objects.equals(owner, that.owner) && Objects.equals(applicationName, that.applicationName) && Objects.equals(capacityGroup, that.capacityGroup) && Objects.equals(jobGroupInfo, that.jobGroupInfo) && Objects.equals(attributes, that.attributes) && Objects.equals(container, that.container) && Objects.equals(disruptionBudget, that.disruptionBudget) && Objects.equals(networkConfiguration, that.networkConfiguration) && Objects.equals(extraContainers, that.extraContainers) && Objects.equals(volumes, that.volumes) && Objects.equals(platformSidecars, that.platformSidecars) && Objects.equals(extensions, that.extensions); } @Override public int hashCode() { return Objects.hash(owner, applicationName, capacityGroup, jobGroupInfo, attributes, container, disruptionBudget, networkConfiguration, extraContainers, volumes, platformSidecars, extensions); } @Override public String toString() { return "JobDescriptor{" + "owner=" + owner + ", applicationName='" + applicationName + '\'' + ", capacityGroup='" + capacityGroup + '\'' + ", jobGroupInfo=" + jobGroupInfo + ", attributes=" + attributes + ", container=" + container + ", disruptionBudget=" + disruptionBudget + ", networkConfiguration=" + networkConfiguration + ", extraContainers=" + extraContainers + ", volumes=" + volumes + ", platformSidecars=" + platformSidecars + ", extensions=" + extensions + '}'; } @SafeVarargs public final JobDescriptor<E> but(Function<JobDescriptor<E>, JobDescriptor<E>>... modifiers) { JobDescriptor<E> result = this; for (Function<JobDescriptor<E>, JobDescriptor<E>> modifier : modifiers) { result = modifier.apply(result); } return result; } public JobDescriptor<E> but(Function<JobDescriptor<E>, Object> mapperFun) { Object result = mapperFun.apply(this); if (result instanceof JobDescriptor) { return (JobDescriptor<E>) result; } if (result instanceof JobDescriptor.Builder) { return ((JobDescriptor.Builder<E>) result).build(); } if (result instanceof NetworkConfiguration) { return toBuilder().withNetworkConfiguration((NetworkConfiguration) result).build(); } if (result instanceof NetworkConfiguration.Builder) { return toBuilder().withNetworkConfiguration(((NetworkConfiguration.Builder) result).build()).build(); } if (result instanceof Owner) { return toBuilder().withOwner((Owner) result).build(); } if (result instanceof Owner.Builder) { return toBuilder().withOwner(((Owner.Builder) result).build()).build(); } if (result instanceof JobGroupInfo) { return toBuilder().withJobGroupInfo((JobGroupInfo) result).build(); } if (result instanceof JobGroupInfo.Builder) { return toBuilder().withJobGroupInfo(((JobGroupInfo.Builder) result).build()).build(); } if (result instanceof Container) { return toBuilder().withContainer((Container) result).build(); } if (result instanceof Container.Builder) { return toBuilder().withContainer(((Container.Builder) result).build()).build(); } if (result instanceof DisruptionBudget) { return toBuilder().withDisruptionBudget((DisruptionBudget) result).build(); } if (result instanceof DisruptionBudget.Builder) { return toBuilder().withDisruptionBudget(((DisruptionBudget.Builder) result).build()).build(); } if (result instanceof JobDescriptorExt) { return toBuilder().withExtensions((E) result).build(); } if (result instanceof BatchJobExt.Builder) { return toBuilder().withExtensions((E) ((BatchJobExt.Builder) result).build()).build(); } if (result instanceof ServiceJobExt.Builder) { return toBuilder().withExtensions((E) ((ServiceJobExt.Builder) result).build()).build(); } if (result instanceof Map) { return toBuilder().withAttributes((Map<String, String>) result).build(); } throw new IllegalArgumentException("Invalid result type " + result.getClass()); } public Builder<E> toBuilder() { return newBuilder(this); } public static <E extends JobDescriptor.JobDescriptorExt> Builder<E> newBuilder() { return new Builder<>(); } public static <E extends JobDescriptor.JobDescriptorExt> Builder<E> newBuilder(JobDescriptor<E> jobDescriptor) { return new Builder<E>() .withOwner(jobDescriptor.getOwner()) .withApplicationName(jobDescriptor.getApplicationName()) .withCapacityGroup(jobDescriptor.getCapacityGroup()) .withJobGroupInfo(jobDescriptor.getJobGroupInfo()) .withAttributes(jobDescriptor.getAttributes()) .withContainer(jobDescriptor.getContainer()) .withDisruptionBudget(jobDescriptor.getDisruptionBudget()) .withNetworkConfiguration(jobDescriptor.getNetworkConfiguration()) .withExtraContainers(jobDescriptor.getExtraContainers()) .withVolumes(jobDescriptor.getVolumes()) .withPlatformSidecars(jobDescriptor.getPlatformSidecars()) .withExtensions(jobDescriptor.getExtensions()); } public static final class Builder<E extends JobDescriptor.JobDescriptorExt> { private Owner owner; private String applicationName; private String capacityGroup; private JobGroupInfo jobGroupInfo; private Map<String, String> attributes; private Container container; private DisruptionBudget disruptionBudget; private NetworkConfiguration networkConfiguration; private List<BasicContainer> extraContainers; private List<Volume> volumes; private List<PlatformSidecar> platformSidecars; private E extensions; private Builder() { } public Builder<E> withOwner(Owner owner) { this.owner = owner; return this; } public Builder<E> withApplicationName(String applicationName) { this.applicationName = applicationName; return this; } public Builder<E> withCapacityGroup(String capacityGroup) { this.capacityGroup = capacityGroup; return this; } public Builder<E> withJobGroupInfo(JobGroupInfo jobGroupInfo) { this.jobGroupInfo = jobGroupInfo; return this; } public Builder<E> withAttributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public Builder<E> withContainer(Container container) { this.container = container; return this; } public Builder<E> withDisruptionBudget(DisruptionBudget disruptionBudget) { this.disruptionBudget = disruptionBudget; return this; } public Builder<E> withNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; return this; } public Builder<E> withExtraContainers(List<BasicContainer> extraContainersList) { this.extraContainers = extraContainersList; return this; } public Builder<E> withVolumes(List<Volume> volumes) { this.volumes = volumes; return this; } public Builder<E> withPlatformSidecars(List<PlatformSidecar> platformSidecars) { this.platformSidecars = platformSidecars; return this; } public Builder<E> withExtensions(E extensions) { this.extensions = extensions; return this; } public Builder<E> but() { return new Builder<E>() .withOwner(owner) .withApplicationName(applicationName) .withCapacityGroup(capacityGroup) .withJobGroupInfo(jobGroupInfo) .withAttributes(attributes) .withContainer(container) .withDisruptionBudget(disruptionBudget) .withNetworkConfiguration(networkConfiguration) .withExtraContainers(extraContainers) .withVolumes(volumes) .withPlatformSidecars(platformSidecars) .withExtensions(extensions); } public JobDescriptor<E> build() { JobDescriptor<E> jobDescriptor = new JobDescriptor<>(owner, applicationName, capacityGroup, jobGroupInfo, attributes, container, disruptionBudget, networkConfiguration, extraContainers, volumes, platformSidecars, extensions); return jobDescriptor; } } }
9,454
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/Version.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.titus.api.jobmanager.model.job; import java.util.Objects; /** * TODO Add monotonically increasing `revision` number unique within a cell */ public class Version { private static final Version UNDEFINED = new Version(-1); private final long timestamp; public Version(long timestamp) { this.timestamp = timestamp; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Version version = (Version) o; return timestamp == version.timestamp; } @Override public int hashCode() { return Objects.hash(timestamp); } @Override public String toString() { return "Version{" + "timestamp=" + timestamp + '}'; } public Builder toBuilder() { return newBuilder().withTimestamp(timestamp); } public static Version undefined() { return UNDEFINED; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private long timestamp; private Builder() { } public Builder withTimestamp(long timestamp) { this.timestamp = timestamp; return this; } public Version build() { return new Version(timestamp); } } }
9,455
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobState.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.titus.api.jobmanager.model.job; /** */ public enum JobState { /** * A job is persisted in Titus, and ready to be scheduled or running. */ Accepted, /** * A job still has running tasks, that were requested to terminate. No more tasks for this job are deployed. * Job policy update operations are not allowed. */ KillInitiated, /** * A job has no running tasks, and no more tasks for it are created. Job policy update operations are not allowed. */ Finished }
9,456
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/LogStorageInfo.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.titus.api.jobmanager.model.job; import java.util.Objects; import java.util.Optional; /** * Provides location information where container log files are stored (live and persisted). */ public interface LogStorageInfo<TASK> { class LogLinks { private final Optional<String> liveLink; private final Optional<String> logLink; private final Optional<String> snapshotLink; public LogLinks(Optional<String> liveLink, Optional<String> logLink, Optional<String> snapshotLink) { this.liveLink = liveLink; this.logLink = logLink; this.snapshotLink = snapshotLink; } public Optional<String> getLiveLink() { return liveLink; } public Optional<String> getLogLink() { return logLink; } public Optional<String> getSnapshotLink() { return snapshotLink; } } class S3LogLocation { private final String accountName; private final String accountId; private final String region; private final String bucket; private final String key; public S3LogLocation(String accountName, String accountId, String region, String bucket, String key) { this.accountName = accountName; this.accountId = accountId; this.region = region; this.bucket = bucket; this.key = key; } public String getAccountName() { return accountName; } public String getAccountId() { return accountId; } public String getRegion() { return region; } public String getBucket() { return bucket; } public String getKey() { return key; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3LogLocation that = (S3LogLocation) o; return Objects.equals(accountName, that.accountName) && Objects.equals(accountId, that.accountId) && Objects.equals(region, that.region) && Objects.equals(bucket, that.bucket) && Objects.equals(key, that.key); } @Override public int hashCode() { return Objects.hash(accountName, accountId, region, bucket, key); } @Override public String toString() { return "S3LogLocation{" + "accountName='" + accountName + '\'' + ", accountId='" + accountId + '\'' + ", region='" + region + '\'' + ", bucket='" + bucket + '\'' + ", key='" + key + '\'' + '}'; } } /** * Get log links for a given task. */ LogLinks getLinks(TASK task); /** * Link to TitusUI with the task's log page. */ Optional<String> getTitusUiLink(TASK task); /** * Get S3 location containing files of a given task. */ Optional<S3LogLocation> getS3LogLocation(TASK task, boolean onlyIfScheduled); }
9,457
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/VolumeMount.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.titus.api.jobmanager.model.job; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class VolumeMount { @NotNull @Pattern(regexp = "[a-z0-9]([-a-z0-9]*[a-z0-9])?", message = "volume name must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character") private final String volumeName; @NotNull @Pattern(regexp = "^/.*", message = "path must start with a leading slash") private final String mountPath; private final String mountPropagation; private final Boolean readOnly; private final String subPath; public VolumeMount(String volumeName, String mountPath, String mountPropagation, Boolean readOnly, String subPath) { this.volumeName = volumeName; this.mountPath = mountPath; this.mountPropagation = mountPropagation; this.readOnly = readOnly; this.subPath = subPath; } public static Builder newBuilder() { return new VolumeMount.Builder(); } public String getMountPropagation() { return mountPropagation; } public Boolean getReadOnly() { return readOnly; } public String getSubPath() { return subPath; } public String getMountPath() { return mountPath; } public String getVolumeName() { return volumeName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VolumeMount that = (VolumeMount) o; return Objects.equals(volumeName, that.volumeName) && Objects.equals(mountPath, that.mountPath) && Objects.equals(mountPropagation, that.mountPropagation) && Objects.equals(readOnly, that.readOnly) && Objects.equals(subPath, that.subPath); } @Override public int hashCode() { return Objects.hash(volumeName, mountPath, mountPropagation, readOnly, subPath); } @Override public String toString() { return "VolumeMount{" + "volumeName='" + volumeName + '\'' + ", mountPath='" + mountPath + '\'' + ", mountPropagation='" + mountPropagation + '\'' + ", readOnly=" + readOnly + ", subPath='" + subPath + '\'' + '}'; } public Builder toBuilder() { return newBuilder(); } public static final class Builder { private String volumeName; private String mountPath; private String mountPropagation; private Boolean readOnly; private String subPath; public Builder withVolumeName(String volumeName) { this.volumeName = volumeName; return this; } public Builder withMountPath(String mountPath) { this.mountPath = mountPath; return this; } public Builder withMountPropagation(String mountPropagation) { this.mountPropagation = mountPropagation; return this; } public Builder withReadOnly(Boolean readOnly) { this.readOnly = readOnly; return this; } public Builder withSubPath(String subPath) { this.subPath = subPath; return this; } public VolumeMount build() { return new VolumeMount(volumeName, mountPath, mountPropagation, readOnly, subPath); } } }
9,458
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/BatchJobTask.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.titus.api.jobmanager.model.job; import java.util.List; import java.util.Map; import java.util.Optional; import javax.validation.constraints.Min; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import static com.netflix.titus.common.util.CollectionsExt.nonNull; @ClassFieldsNotNull public class BatchJobTask extends Task { @Min(value = 0) private final int index; public BatchJobTask(String id, int index, String originalId, Optional<String> resubmitOf, String jobId, int resubmitNumber, int systemResubmitNumber, int evictionResubmitNumber, TaskStatus status, List<TaskStatus> statusHistory, List<TwoLevelResource> twoLevelResources, Map<String, String> taskContext, Map<String, String> attributes, Version version) { super(id, jobId, status, statusHistory, originalId, resubmitOf, resubmitNumber, systemResubmitNumber, evictionResubmitNumber, twoLevelResources, taskContext, attributes, version); this.index = index; } public int getIndex() { return index; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } BatchJobTask that = (BatchJobTask) o; return index == that.index; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + index; return result; } @Override public String toString() { return "BatchJobTask{" + "id='" + getId() + '\'' + ", index=" + index + ", jobId='" + getJobId() + '\'' + ", status=" + getStatus() + ", originalId='" + getOriginalId() + '\'' + ", resubmitOf=" + getResubmitOf() + ", resubmitNumber=" + getResubmitNumber() + ", systemResubmitNumber=" + getSystemResubmitNumber() + ", evictionResubmitNumber=" + getEvictionResubmitNumber() + ", twoLevelResources=" + getTwoLevelResources() + ", taskContext=" + getTaskContext() + ", attributes=" + getAttributes() + ", version=" + getVersion() + '}'; } @Override public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(BatchJobTask task) { return new Builder(task); } public static final class Builder extends TaskBuilder<BatchJobTask, Builder> { private int index; private Builder() { } private Builder(BatchJobTask batchJobTask) { newBuilder(this, batchJobTask).withIndex(batchJobTask.getIndex()); } public Builder but() { return but(new Builder()).withIndex(index); } public Builder withIndex(int index) { this.index = index; return this; } @Override public BatchJobTask build() { return new BatchJobTask( id, index, originalId == null ? id : originalId, Optional.ofNullable(resubmitOf), jobId, resubmitNumber, systemResubmitNumber, evictionResubmitNumber, status, nonNull(statusHistory), nonNull(twoLevelResources), nonNull(taskContext), nonNull(attributes), version ); } } }
9,459
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/TwoLevelResource.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.titus.api.jobmanager.model.job; import javax.validation.constraints.Min; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; /** * */ @ClassFieldsNotNull public class TwoLevelResource { private final String name; private final String value; @Min(0) private final int index; private TwoLevelResource(String name, String value, int index) { this.name = name; this.value = value; this.index = index; } /** * Resource name (for example 'ENIs'). */ public String getName() { return name; } /** * Value associated with a resource at a given index position. For example, on a VM with 8 ENIs, * a task can be allocated ENI 5, and attach to it value "sg-e3e51a99:sg-f0f19494:sg-f2f19496", which are * task's security groups. */ public String getValue() { return value; } /** * Index of a sub-resource allocated to a given task. */ public int getIndex() { return index; } public Builder toBuilder() { return newBuilder() .withName(name) .withIndex(index) .withValue(value); } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String name; private String value; private int index; private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withValue(String value) { this.value = value; return this; } public Builder withIndex(int index) { this.index = index; return this; } public Builder but() { return newBuilder().withName(name).withValue(value).withIndex(index); } public TwoLevelResource build() { TwoLevelResource twoLevelResource = new TwoLevelResource(name, value, index); return twoLevelResource; } } }
9,460
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/JobCompatibility.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.titus.api.jobmanager.model.job; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.migration.SystemDefaultMigrationPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.ImmediateRetryPolicy; /** * Represents compatibility between Jobs for tasks to be * {@link com.netflix.titus.api.jobmanager.service.V3JobOperations#moveServiceTask(String, String, String, CallMetadata)} moved} * across them. * <p> * Jobs are compatible when their descriptors are identical, ignoring the following values: * * <ol> * <li>Owner</li> * <li>Application name</li> * <li>Job group info (stack, details, sequence)</li> * <li>Disruption budget</li> * <li>Any container attributes not prefixed with <tt>titus.</tt> or <tt>titusParameter.</tt></li> * <li>Any container.securityProfile attributes not prefixed with <tt>titus.</tt> or <tt>titusParameter.</tt></li> * <li>All information {@link ServiceJobExt specific to Service jobs}: capacity, retry policy, etc</li> * </ol> */ public class JobCompatibility { private final JobDescriptor<ServiceJobExt> from; private final JobDescriptor<ServiceJobExt> to; private final boolean compatible; private JobCompatibility(JobDescriptor<ServiceJobExt> from, JobDescriptor<ServiceJobExt> to, boolean compatible) { this.from = from; this.to = to; this.compatible = compatible; } public static JobCompatibility of(Job<ServiceJobExt> from, Job<ServiceJobExt> to) { return of(from.getJobDescriptor(), to.getJobDescriptor()); } public static JobCompatibility of(JobDescriptor<ServiceJobExt> from, JobDescriptor<ServiceJobExt> to) { boolean ignoreImage = isImageSanitizationSkipped(from) || isImageSanitizationSkipped(to); boolean ignoreIam = isIamSanitizationSkipped(from) || isIamSanitizationSkipped(to); JobDescriptor<ServiceJobExt> jobFromNormalized = unsetIgnoredFieldsForCompatibility(from, ignoreImage, ignoreIam); JobDescriptor<ServiceJobExt> jobToNormalized = unsetIgnoredFieldsForCompatibility(to, ignoreImage, ignoreIam); boolean identical = jobFromNormalized.equals(jobToNormalized); return new JobCompatibility(jobFromNormalized, jobToNormalized, identical); } private static boolean isImageSanitizationSkipped(JobDescriptor<?> jobDescriptor) { return Boolean.parseBoolean(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IMAGE)); } private static boolean isIamSanitizationSkipped(JobDescriptor<?> jobDescriptor) { return Boolean.parseBoolean(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_IAM)); } private static JobDescriptor<ServiceJobExt> unsetIgnoredFieldsForCompatibility(JobDescriptor<ServiceJobExt> descriptor, boolean ignoreImage, boolean ignoreIam) { Container container = descriptor.getContainer(); SecurityProfile securityProfile = container.getSecurityProfile(); Map<String, String> onlyTitusContainerAttributes = filterOutNonTitusAttributes(container.getAttributes()); Map<String, String> onlyTitusSecurityAttributes = filterOutNonTitusAttributes(securityProfile.getAttributes()); return descriptor.toBuilder() .withOwner(Owner.newBuilder().withTeamEmail("").build()) .withApplicationName("") .withJobGroupInfo(JobGroupInfo.newBuilder().build()) .withAttributes(Collections.emptyMap()) .withContainer(container.toBuilder() .withImage(ignoreImage ? Image.newBuilder().build() : container.getImage()) .withAttributes(onlyTitusContainerAttributes) .withSecurityProfile(securityProfile.toBuilder() .withAttributes(onlyTitusSecurityAttributes) .withIamRole(ignoreIam ? "" : container.getSecurityProfile().getIamRole()) .build()) .withEnv(Collections.emptyMap()) .build()) .withExtensions(ServiceJobExt.newBuilder() .withRetryPolicy(ImmediateRetryPolicy.newBuilder().withRetries(0).build()) .withMigrationPolicy(SystemDefaultMigrationPolicy.newBuilder().build()) .withCapacity(Capacity.newBuilder().build()) .withServiceJobProcesses(ServiceJobProcesses.newBuilder().build()) .withEnabled(true) .build()) .withDisruptionBudget(DisruptionBudget.none()) .build(); } private static Map<String, String> filterOutNonTitusAttributes(Map<String, String> attributes) { Map<String, String> onlyTitus = new HashMap<>(attributes); onlyTitus.entrySet().removeIf(entry -> !entry.getKey().startsWith(JobAttributes.TITUS_ATTRIBUTE_PREFIX) && !entry.getKey().startsWith(JobAttributes.TITUS_PARAMETER_ATTRIBUTE_PREFIX) ); return onlyTitus; } /** * @return {@link JobDescriptor} with values non-relevant for compatibility unset */ public JobDescriptor<ServiceJobExt> getNormalizedDescriptorFrom() { return from; } /** * @return {@link JobDescriptor} with values non-relevant for compatibility unset */ public JobDescriptor<ServiceJobExt> getNormalizedDescriptorTo() { return to; } public boolean isCompatible() { return compatible; } }
9,461
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/NetworkConfiguration.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.titus.api.jobmanager.model.job; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * */ @JsonIgnoreProperties(ignoreUnknown = true) public class NetworkConfiguration { final private int networkMode; public NetworkConfiguration(int networkMode) { this.networkMode = networkMode; } public int getNetworkMode() { return networkMode; } @JsonIgnore public String getNetworkModeName() { return networkModeToName(networkMode); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NetworkConfiguration netConfig = (NetworkConfiguration) o; return networkMode == netConfig.networkMode; } @Override public String toString() { return "NetworkConfiguration{" + "networkMode=" + networkMode + '}'; } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(NetworkConfiguration networkConfiguration) { return new Builder() .withNetworkMode(networkConfiguration.getNetworkMode()); } public static final class Builder { private int networkMode; public Builder withNetworkMode(int networkMode) { this.networkMode = networkMode; return this; } public NetworkConfiguration build() { return new NetworkConfiguration(networkMode); } } public static String networkModeToName(int mode) { // TODO: Use the generated protobuf version of this function if available? switch (mode) { case 0: return "UnknownNetworkMode"; case 1: return "Ipv4Only"; case 2: return "Ipv6AndIpv4"; case 3: return "Ipv6AndIpv4Fallback"; case 4: return "Ipv6Only"; case 5: return "HighScale"; default: return ""; } } }
9,462
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/DisruptionBudgetRate.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.titus.api.jobmanager.model.job.disruptionbudget; public abstract class DisruptionBudgetRate { }
9,463
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/RelocationLimitDisruptionBudgetPolicy.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Min; public class RelocationLimitDisruptionBudgetPolicy extends DisruptionBudgetPolicy { @Min(1) private final int limit; public RelocationLimitDisruptionBudgetPolicy(int limit) { this.limit = limit; } public int getLimit() { return limit; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RelocationLimitDisruptionBudgetPolicy that = (RelocationLimitDisruptionBudgetPolicy) o; return limit == that.limit; } @Override public int hashCode() { return Objects.hash(limit); } @Override public String toString() { return "RelocationLimitDisruptionBudgetPolicy{" + "limit=" + limit + '}'; } public static final class Builder { private int limit; private Builder() { } public Builder withLimit(int limit) { this.limit = limit; return this; } public Builder but() { return newBuilder().withLimit(limit); } public RelocationLimitDisruptionBudgetPolicy build() { return new RelocationLimitDisruptionBudgetPolicy(limit); } } }
9,464
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/RatePercentagePerIntervalDisruptionBudgetRate.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class RatePercentagePerIntervalDisruptionBudgetRate extends DisruptionBudgetRate { @Min(1) @Max(3600_000) private final long intervalMs; @Min(0) @Max(100) private final double percentageLimitPerInterval; public RatePercentagePerIntervalDisruptionBudgetRate(long intervalMs, double percentageLimitPerInterval) { this.intervalMs = intervalMs; this.percentageLimitPerInterval = percentageLimitPerInterval; } public long getIntervalMs() { return intervalMs; } public double getPercentageLimitPerInterval() { return percentageLimitPerInterval; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RatePercentagePerIntervalDisruptionBudgetRate that = (RatePercentagePerIntervalDisruptionBudgetRate) o; return intervalMs == that.intervalMs && Double.compare(that.percentageLimitPerInterval, percentageLimitPerInterval) == 0; } @Override public int hashCode() { return Objects.hash(intervalMs, percentageLimitPerInterval); } @Override public String toString() { return "RatePercentagePerIntervalDisruptionBudgetRate{" + "intervalMs=" + intervalMs + ", percentageLimitPerInterval=" + percentageLimitPerInterval + '}'; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private long intervalMs; private double percentageLimitPerInterval; private Builder() { } public Builder withIntervalMs(long intervalMs) { this.intervalMs = intervalMs; return this; } public Builder withPercentageLimitPerInterval(double percentageLimitPerInterval) { this.percentageLimitPerInterval = percentageLimitPerInterval; return this; } public Builder but() { return newBuilder().withIntervalMs(intervalMs).withPercentageLimitPerInterval(percentageLimitPerInterval); } public RatePercentagePerIntervalDisruptionBudgetRate build() { return new RatePercentagePerIntervalDisruptionBudgetRate(intervalMs, percentageLimitPerInterval); } } }
9,465
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/PercentagePerHourDisruptionBudgetRate.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class PercentagePerHourDisruptionBudgetRate extends DisruptionBudgetRate { @Min(0) @Max(100) private final double maxPercentageOfContainersRelocatedInHour; public PercentagePerHourDisruptionBudgetRate(double maxPercentageOfContainersRelocatedInHour) { this.maxPercentageOfContainersRelocatedInHour = maxPercentageOfContainersRelocatedInHour; } public double getMaxPercentageOfContainersRelocatedInHour() { return maxPercentageOfContainersRelocatedInHour; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PercentagePerHourDisruptionBudgetRate that = (PercentagePerHourDisruptionBudgetRate) o; return Double.compare(that.maxPercentageOfContainersRelocatedInHour, maxPercentageOfContainersRelocatedInHour) == 0; } @Override public int hashCode() { return Objects.hash(maxPercentageOfContainersRelocatedInHour); } @Override public String toString() { return "PercentagePerHourDisruptionBudgetRate{" + "maxPercentageOfContainersRelocatedInHour=" + maxPercentageOfContainersRelocatedInHour + '}'; } public static final class Builder { private double maxPercentageOfContainersRelocatedInHour; private Builder() { } public Builder withMaxPercentageOfContainersRelocatedInHour(double maxPercentageOfContainersRelocatedInHour) { this.maxPercentageOfContainersRelocatedInHour = maxPercentageOfContainersRelocatedInHour; return this; } public Builder but() { return newBuilder().withMaxPercentageOfContainersRelocatedInHour(maxPercentageOfContainersRelocatedInHour); } public PercentagePerHourDisruptionBudgetRate build() { return new PercentagePerHourDisruptionBudgetRate(maxPercentageOfContainersRelocatedInHour); } } }
9,466
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/TimeWindowFunctions.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.titus.api.jobmanager.model.job.disruptionbudget; import java.time.DayOfWeek; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.DateTimeExt; /** * Collection of helper functions for {@link TimeWindow}. */ public final class TimeWindowFunctions { public static boolean isEmpty(TimeWindow timeWindow) { return timeWindow.getDays().isEmpty() && timeWindow.getHourlyTimeWindows().isEmpty(); } /** * Returns predicate which when evaluated checks the current time against the defined time window. * If the time window is empty (does not define any days our hours), it matches any time. * * @returns true if the current time is within the time window, false otherwise */ public static Supplier<Boolean> isInTimeWindowPredicate(TitusRuntime titusRuntime, TimeWindow timeWindow) { if (isEmpty(timeWindow)) { return () -> true; } List<Function<DayOfWeek, Boolean>> dayPredicates = new ArrayList<>(); timeWindow.getDays().forEach(day -> dayPredicates.add(buildDayPredicate(day))); List<Function<Integer, Boolean>> hourPredicates = new ArrayList<>(); timeWindow.getHourlyTimeWindows().forEach(h -> hourPredicates.add(buildHourlyTimeWindows(h))); Function<DayOfWeek, Boolean> combinedDayPredicate = dayPredicates.isEmpty() ? day -> true : oneOf(dayPredicates); Function<Integer, Boolean> combinedHourPredicate = hourPredicates.isEmpty() ? hour -> true : oneOf(hourPredicates); ZoneId zoneId; try { zoneId = DateTimeExt.toZoneId(timeWindow.getTimeZone()); } catch (Exception e) { titusRuntime.getCodeInvariants().unexpectedError("Unrecognized time zone (data not properly validated)", e); return () -> false; } return () -> { ZonedDateTime dateTime = Instant.ofEpochMilli(titusRuntime.getClock().wallTime()).atZone(zoneId); return combinedDayPredicate.apply(dateTime.getDayOfWeek()) && combinedHourPredicate.apply(dateTime.getHour()); }; } /** * Returns predicate that evaluates to true only when {@link #isInTimeWindowPredicate(TitusRuntime, TimeWindow)} evaluates * to true for at least one of the provided time windows. */ public static Supplier<Boolean> isInTimeWindowPredicate(TitusRuntime titusRuntime, Collection<TimeWindow> timeWindows) { if (CollectionsExt.isNullOrEmpty(timeWindows)) { return () -> true; } List<Supplier<Boolean>> predicates = timeWindows.stream() .map(t -> isInTimeWindowPredicate(titusRuntime, t)) .collect(Collectors.toList()); return () -> { for (Supplier<Boolean> predicate : predicates) { if (predicate.get()) { return true; } } return false; }; } private static <T> Function<T, Boolean> oneOf(List<Function<T, Boolean>> basicPredicates) { return argument -> { if (basicPredicates.isEmpty()) { return true; } for (Function<T, Boolean> predicate : basicPredicates) { if (predicate.apply(argument)) { return true; } } return false; }; } private static Function<DayOfWeek, Boolean> buildDayPredicate(Day expectedDay) { DayOfWeek expectedDayOfWeek = expectedDay.toDayOfWeek(); return currentDayOfWeek -> currentDayOfWeek == expectedDayOfWeek; } private static Function<Integer, Boolean> buildHourlyTimeWindows(HourlyTimeWindow timeWindow) { if (timeWindow.getEndHour() < timeWindow.getStartHour()) { return epochMs -> true; } return currentHour -> timeWindow.getStartHour() <= currentHour && currentHour <= timeWindow.getEndHour(); } }
9,467
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/DisruptionBudgetFunctions.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.titus.api.jobmanager.model.job.disruptionbudget; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; public final class DisruptionBudgetFunctions { private DisruptionBudgetFunctions() { } public static boolean isLegacyJobDescriptor(JobDescriptor<?> jobDescriptor) { DisruptionBudget budget = jobDescriptor.getDisruptionBudget(); if (budget == null) { return true; } if (budget.getDisruptionBudgetPolicy() instanceof SelfManagedDisruptionBudgetPolicy) { SelfManagedDisruptionBudgetPolicy policy = (SelfManagedDisruptionBudgetPolicy) budget.getDisruptionBudgetPolicy(); return policy.getRelocationTimeMs() == 0; } return false; } public static boolean isLegacyJob(Job<?> job) { return isLegacyJobDescriptor(job.getJobDescriptor()); } public static boolean isSelfManaged(Job<?> job) { return job.getJobDescriptor().getDisruptionBudget().getDisruptionBudgetPolicy() instanceof SelfManagedDisruptionBudgetPolicy; } }
9,468
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/ContainerHealthProvider.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Collections; import java.util.Map; import java.util.Objects; import javax.validation.constraints.Size; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; import com.netflix.titus.common.model.sanitizer.FieldInvariant; @ClassFieldsNotNull public class ContainerHealthProvider { @Size(min = 1) @FieldInvariant(value = "@asserts.isValidContainerHealthServiceName(value)", message = "Unknown container health service: #{value}") private final String name; @CollectionInvariants private final Map<String, String> attributes; public ContainerHealthProvider(String name, Map<String, String> attributes) { this.name = name; this.attributes = attributes; } public String getName() { return name; } public Map<String, String> getAttributes() { return attributes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContainerHealthProvider that = (ContainerHealthProvider) o; return Objects.equals(name, that.name) && Objects.equals(attributes, that.attributes); } @Override public int hashCode() { return Objects.hash(name, attributes); } @Override public String toString() { return "ContainerHealthProvider{" + "name='" + name + '\'' + ", attributes=" + attributes + '}'; } public static Builder newBuilder() { return new Builder(); } public static ContainerHealthProvider named(String name) { return newBuilder().withName(name).withAttributes(Collections.emptyMap()).build(); } public static final class Builder { private String name; private Map<String, String> attributes; private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withAttributes(Map<String, String> attributes) { this.attributes = attributes; return this; } public Builder but() { return newBuilder().withName(name).withAttributes(attributes); } public ContainerHealthProvider build() { return new ContainerHealthProvider(name, attributes); } } }
9,469
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/DisruptionBudgetPolicy.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.titus.api.jobmanager.model.job.disruptionbudget; public abstract class DisruptionBudgetPolicy { }
9,470
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/Day.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.titus.api.jobmanager.model.job.disruptionbudget; import java.time.DayOfWeek; import java.util.EnumSet; import java.util.Map; import com.google.common.collect.ImmutableMap; public enum Day { Monday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.MONDAY; } }, Tuesday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.TUESDAY; } }, Wednesday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.WEDNESDAY; } }, Thursday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.THURSDAY; } }, Friday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.FRIDAY; } }, Saturday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.SATURDAY; } }, Sunday() { @Override public DayOfWeek toDayOfWeek() { return DayOfWeek.SUNDAY; } }; private static EnumSet<Day> WEEKDAYS = EnumSet.of(Monday, Tuesday, Wednesday, Thursday, Friday); private static EnumSet<Day> WEEKEND = EnumSet.of(Saturday, Sunday); private static Map<DayOfWeek, Day> DAY_OF_WEEK_TO_DAY_MAP = new ImmutableMap.Builder<DayOfWeek, Day>() .put(DayOfWeek.SUNDAY, Day.Sunday) .put(DayOfWeek.MONDAY, Day.Monday) .put(DayOfWeek.TUESDAY, Day.Tuesday) .put(DayOfWeek.WEDNESDAY, Day.Wednesday) .put(DayOfWeek.THURSDAY, Day.Thursday) .put(DayOfWeek.FRIDAY, Day.Friday) .put(DayOfWeek.SATURDAY, Day.Saturday) .build(); public abstract DayOfWeek toDayOfWeek(); public static EnumSet<Day> weekdays() { return WEEKDAYS; } public static EnumSet<Day> weekend() { return WEEKEND; } public static Day fromDayOfWeek(DayOfWeek dayOfWeek) { return DAY_OF_WEEK_TO_DAY_MAP.get(dayOfWeek); } }
9,471
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/SelfManagedDisruptionBudgetPolicy.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Min; public class SelfManagedDisruptionBudgetPolicy extends DisruptionBudgetPolicy { @Min(value = 0, message = "Relocation time must be non negative") private final long relocationTimeMs; public SelfManagedDisruptionBudgetPolicy(long relocationTimeMs) { this.relocationTimeMs = relocationTimeMs; } public long getRelocationTimeMs() { return relocationTimeMs; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SelfManagedDisruptionBudgetPolicy that = (SelfManagedDisruptionBudgetPolicy) o; return relocationTimeMs == that.relocationTimeMs; } @Override public int hashCode() { return Objects.hash(relocationTimeMs); } @Override public String toString() { return "SelfManagedDisruptionBudgetPolicy{" + "relocationTimeMs=" + relocationTimeMs + '}'; } public static final class Builder { private long relocationTimeMs; private Builder() { } public Builder withRelocationTimeMs(long relocationTimeMs) { this.relocationTimeMs = relocationTimeMs; return this; } public Builder but() { return newBuilder().withRelocationTimeMs(relocationTimeMs); } public SelfManagedDisruptionBudgetPolicy build() { return new SelfManagedDisruptionBudgetPolicy(relocationTimeMs); } } }
9,472
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/HourlyTimeWindow.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import com.netflix.titus.common.model.sanitizer.ClassInvariant; @ClassInvariant(condition = "startHour < endHour", message = "'startHour'(#{startHour}) must be < 'endHour'(#{endHour})") public class HourlyTimeWindow { @Min(0) @Max(24) private final int startHour; @Min(0) @Max(24) private final int endHour; public HourlyTimeWindow(int startHour, int endHour) { this.startHour = startHour; this.endHour = endHour; } public int getStartHour() { return startHour; } public int getEndHour() { return endHour; } public static HourlyTimeWindow newRange(int start, int end) { return new HourlyTimeWindow(start, end); } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HourlyTimeWindow that = (HourlyTimeWindow) o; return startHour == that.startHour && endHour == that.endHour; } @Override public int hashCode() { return Objects.hash(startHour, endHour); } @Override public String toString() { return "HourlyTimeWindow{" + "startHour=" + startHour + ", endHour=" + endHour + '}'; } public static final class Builder { private int startHour; private int endHour; private Builder() { } public Builder withStartHour(int startHour) { this.startHour = startHour; return this; } public Builder withEndHour(int endHour) { this.endHour = endHour; return this; } public Builder but() { return newBuilder().withStartHour(startHour).withEndHour(endHour); } public HourlyTimeWindow build() { return new HourlyTimeWindow(startHour, endHour); } } }
9,473
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/TimeWindow.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import javax.validation.Valid; import com.google.common.base.Preconditions; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.CollectionInvariants; @ClassFieldsNotNull public class TimeWindow { public static String DEFAULT_TIME_ZONE = "UTC"; private static final TimeWindow EMPTY = new TimeWindow(Collections.emptyList(), Collections.emptyList(), DEFAULT_TIME_ZONE); @CollectionInvariants private final List<Day> days; @CollectionInvariants @Valid private final List<HourlyTimeWindow> hourlyTimeWindows; private final String timeZone; public TimeWindow(List<Day> days, List<HourlyTimeWindow> hourlyTimeWindows, String timeZone) { this.days = days; this.hourlyTimeWindows = hourlyTimeWindows; this.timeZone = timeZone; } public List<Day> getDays() { return days; } public List<HourlyTimeWindow> getHourlyTimeWindows() { return hourlyTimeWindows; } public String getTimeZone() { return timeZone; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimeWindow that = (TimeWindow) o; return Objects.equals(days, that.days) && Objects.equals(hourlyTimeWindows, that.hourlyTimeWindows) && Objects.equals(timeZone, that.timeZone); } @Override public int hashCode() { return Objects.hash(days, hourlyTimeWindows, timeZone); } @Override public String toString() { return "TimeWindow{" + "days=" + days + ", hourlyTimeWindows=" + hourlyTimeWindows + ", timeZone='" + timeZone + '\'' + '}'; } public static TimeWindow empty() { return EMPTY; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private List<Day> days; private List<HourlyTimeWindow> hourlyTimeWindows; private String timeZone; private Builder() { } public Builder withDays(Day... days) { getOrCreateMutableDaysList().addAll(Arrays.asList(days)); return this; } public Builder withDays(Collection<Day> days) { this.days = new ArrayList<>(days); return this; } public Builder withHourlyTimeWindows(List<HourlyTimeWindow> hourlyTimeWindows) { this.hourlyTimeWindows = hourlyTimeWindows; return this; } public Builder withwithHourlyTimeWindows(int... startEndHours) { Preconditions.checkArgument(startEndHours.length % 2 == 0, "Expected pairs of start/end hours"); getOrCreateMutableHoursList(); for (int i = 0; i < startEndHours.length; i += 2) { this.hourlyTimeWindows.add(HourlyTimeWindow.newRange(startEndHours[i], startEndHours[i + 1])); } return this; } public Builder withTimeZone(String timeZone) { this.timeZone = timeZone; return this; } public Builder but() { return newBuilder().withDays(days).withHourlyTimeWindows(hourlyTimeWindows); } public TimeWindow build() { return new TimeWindow(days, hourlyTimeWindows, timeZone == null ? DEFAULT_TIME_ZONE : timeZone); } private List<Day> getOrCreateMutableDaysList() { if (this.days == null) { this.days = new ArrayList<>(); } else if (!(this.days instanceof ArrayList)) { this.days = new ArrayList<>(this.days); } return days; } private List<HourlyTimeWindow> getOrCreateMutableHoursList() { if (this.hourlyTimeWindows == null) { this.hourlyTimeWindows = new ArrayList<>(); } else if (!(this.hourlyTimeWindows instanceof ArrayList)) { this.hourlyTimeWindows = new ArrayList<>(this.hourlyTimeWindows); } return hourlyTimeWindows; } } }
9,474
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/RatePerIntervalDisruptionBudgetRate.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.titus.api.jobmanager.model.job.disruptionbudget; import java.time.Duration; import java.util.Objects; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class RatePerIntervalDisruptionBudgetRate extends DisruptionBudgetRate { @Min(1) @Max(3600_000) private final long intervalMs; @Min(1) private final int limitPerInterval; public RatePerIntervalDisruptionBudgetRate(long intervalMs, int limitPerInterval) { this.intervalMs = intervalMs; this.limitPerInterval = limitPerInterval; } public long getIntervalMs() { return intervalMs; } public int getLimitPerInterval() { return limitPerInterval; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RatePerIntervalDisruptionBudgetRate that = (RatePerIntervalDisruptionBudgetRate) o; return intervalMs == that.intervalMs && limitPerInterval == that.limitPerInterval; } @Override public int hashCode() { return Objects.hash(intervalMs, limitPerInterval); } @Override public String toString() { return "RatePerIntervalDisruptionBudgetRate{" + "intervalMs=" + intervalMs + ", limitPerInterval=" + limitPerInterval + '}'; } public static Builder newBuilder() { return new Builder(); } public static RatePerIntervalDisruptionBudgetRate relocationRate(Duration interval, int limit) { return new RatePerIntervalDisruptionBudgetRate(interval.toMillis(), limit); } public static final class Builder { private long intervalMs; private int limitPerInterval; private Builder() { } public Builder withIntervalMs(long intervalMs) { this.intervalMs = intervalMs; return this; } public Builder withLimitPerInterval(int limitPerInterval) { this.limitPerInterval = limitPerInterval; return this; } public Builder but() { return newBuilder().withIntervalMs(intervalMs).withLimitPerInterval(limitPerInterval); } public RatePerIntervalDisruptionBudgetRate build() { return new RatePerIntervalDisruptionBudgetRate(intervalMs, limitPerInterval); } } }
9,475
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/AvailabilityPercentageLimitDisruptionBudgetPolicy.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class AvailabilityPercentageLimitDisruptionBudgetPolicy extends DisruptionBudgetPolicy { @Min(0) @Max(100) private final double percentageOfHealthyContainers; public AvailabilityPercentageLimitDisruptionBudgetPolicy(double percentageOfHealthyContainers) { this.percentageOfHealthyContainers = percentageOfHealthyContainers; } public double getPercentageOfHealthyContainers() { return percentageOfHealthyContainers; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AvailabilityPercentageLimitDisruptionBudgetPolicy that = (AvailabilityPercentageLimitDisruptionBudgetPolicy) o; return Double.compare(that.percentageOfHealthyContainers, percentageOfHealthyContainers) == 0; } @Override public int hashCode() { return Objects.hash(percentageOfHealthyContainers); } @Override public String toString() { return "AvailabilityPercentageLimitDisruptionBudgetPolicy{" + "percentageOfHealthyContainers=" + percentageOfHealthyContainers + '}'; } public static final class Builder { private double percentageOfHealthyContainers; private Builder() { } public Builder withPercentageOfHealthyContainers(double percentageOfHealthyContainers) { this.percentageOfHealthyContainers = percentageOfHealthyContainers; return this; } public Builder but() { return newBuilder().withPercentageOfHealthyContainers(percentageOfHealthyContainers); } public AvailabilityPercentageLimitDisruptionBudgetPolicy build() { return new AvailabilityPercentageLimitDisruptionBudgetPolicy(percentageOfHealthyContainers); } } }
9,476
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/DisruptionBudget.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Collections; import java.util.List; import java.util.Objects; import javax.validation.Valid; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; @ClassFieldsNotNull public class DisruptionBudget { private static final DisruptionBudget NONE = DisruptionBudget.newBuilder() .withDisruptionBudgetPolicy(SelfManagedDisruptionBudgetPolicy.newBuilder().build()) .withDisruptionBudgetRate(UnlimitedDisruptionBudgetRate.newBuilder().build()) .withContainerHealthProviders(Collections.emptyList()) .withTimeWindows(Collections.emptyList()) .build(); @Valid private final DisruptionBudgetPolicy disruptionBudgetPolicy; @Valid private final DisruptionBudgetRate disruptionBudgetRate; @Valid private final List<TimeWindow> timeWindows; @Valid private final List<ContainerHealthProvider> containerHealthProviders; public DisruptionBudget(DisruptionBudgetPolicy disruptionBudgetPolicy, DisruptionBudgetRate disruptionBudgetRate, List<TimeWindow> timeWindows, List<ContainerHealthProvider> containerHealthProviders) { this.disruptionBudgetPolicy = disruptionBudgetPolicy; this.disruptionBudgetRate = disruptionBudgetRate; this.timeWindows = timeWindows; this.containerHealthProviders = containerHealthProviders; } public DisruptionBudgetPolicy getDisruptionBudgetPolicy() { return disruptionBudgetPolicy; } public DisruptionBudgetRate getDisruptionBudgetRate() { return disruptionBudgetRate; } public List<TimeWindow> getTimeWindows() { return timeWindows; } public List<ContainerHealthProvider> getContainerHealthProviders() { return containerHealthProviders; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DisruptionBudget that = (DisruptionBudget) o; return Objects.equals(disruptionBudgetPolicy, that.disruptionBudgetPolicy) && Objects.equals(disruptionBudgetRate, that.disruptionBudgetRate) && Objects.equals(timeWindows, that.timeWindows) && Objects.equals(containerHealthProviders, that.containerHealthProviders); } @Override public int hashCode() { return Objects.hash(disruptionBudgetPolicy, disruptionBudgetRate, timeWindows, containerHealthProviders); } @Override public String toString() { return "DisruptionBudget{" + "disruptionBudgetPolicy=" + disruptionBudgetPolicy + ", disruptionBudgetRate=" + disruptionBudgetRate + ", timeWindows=" + timeWindows + ", containerHealthProviders=" + containerHealthProviders + '}'; } public Builder toBuilder() { return newBuilder() .withContainerHealthProviders(containerHealthProviders) .withDisruptionBudgetPolicy(disruptionBudgetPolicy) .withDisruptionBudgetRate(disruptionBudgetRate) .withTimeWindows(timeWindows); } /** * For the migration time from the old to the new task migration mechanism, we will have to work with jobs * without the disruption budgets. The legacy jobs will be assigned a special disruption budget configuration * which will include the {@link SelfManagedDisruptionBudgetPolicy} policy with relocation time equal zero. * This method provide the legacy default value. */ public static DisruptionBudget none() { return NONE; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private DisruptionBudgetPolicy disruptionBudgetPolicy; private DisruptionBudgetRate disruptionBudgetRate; private List<TimeWindow> timeWindows; private List<ContainerHealthProvider> containerHealthProviders; private Builder() { } public Builder withDisruptionBudgetPolicy(DisruptionBudgetPolicy disruptionBudgetPolicy) { this.disruptionBudgetPolicy = disruptionBudgetPolicy; return this; } public Builder withDisruptionBudgetRate(DisruptionBudgetRate disruptionBudgetRate) { this.disruptionBudgetRate = disruptionBudgetRate; return this; } public Builder withTimeWindows(List<TimeWindow> timeWindows) { this.timeWindows = timeWindows; return this; } public Builder withContainerHealthProviders(List<ContainerHealthProvider> containerHealthProviders) { this.containerHealthProviders = containerHealthProviders; return this; } public Builder but() { return newBuilder().withDisruptionBudgetPolicy(disruptionBudgetPolicy).withDisruptionBudgetRate(disruptionBudgetRate).withTimeWindows(timeWindows).withContainerHealthProviders(containerHealthProviders); } public DisruptionBudget build() { return new DisruptionBudget(disruptionBudgetPolicy, disruptionBudgetRate, timeWindows, containerHealthProviders); } } }
9,477
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/UnhealthyTasksLimitDisruptionBudgetPolicy.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.titus.api.jobmanager.model.job.disruptionbudget; import java.util.Objects; import javax.validation.constraints.Min; public class UnhealthyTasksLimitDisruptionBudgetPolicy extends DisruptionBudgetPolicy { @Min(1) private final int limitOfUnhealthyContainers; public UnhealthyTasksLimitDisruptionBudgetPolicy(int limitOfUnhealthyContainers) { this.limitOfUnhealthyContainers = limitOfUnhealthyContainers; } public int getLimitOfUnhealthyContainers() { return limitOfUnhealthyContainers; } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UnhealthyTasksLimitDisruptionBudgetPolicy that = (UnhealthyTasksLimitDisruptionBudgetPolicy) o; return limitOfUnhealthyContainers == that.limitOfUnhealthyContainers; } @Override public int hashCode() { return Objects.hash(limitOfUnhealthyContainers); } @Override public String toString() { return "UnhealthyTasksLimitDisruptionBudgetPolicy{" + "limitOfUnhealthyContainers=" + limitOfUnhealthyContainers + '}'; } public static final class Builder { private int limitOfUnhealthyContainers; private Builder() { } public Builder withLimitOfUnhealthyContainers(int limitOfUnhealthyContainers) { this.limitOfUnhealthyContainers = limitOfUnhealthyContainers; return this; } public Builder but() { return newBuilder().withLimitOfUnhealthyContainers(limitOfUnhealthyContainers); } public UnhealthyTasksLimitDisruptionBudgetPolicy build() { return new UnhealthyTasksLimitDisruptionBudgetPolicy(limitOfUnhealthyContainers); } } }
9,478
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/disruptionbudget/UnlimitedDisruptionBudgetRate.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.titus.api.jobmanager.model.job.disruptionbudget; public class UnlimitedDisruptionBudgetRate extends DisruptionBudgetRate { private static final Builder BUILDER = new Builder(); private static final UnlimitedDisruptionBudgetRate INSTANCE = new UnlimitedDisruptionBudgetRate(); public UnlimitedDisruptionBudgetRate() { } @Override public int hashCode() { return 12345; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass() == UnlimitedDisruptionBudgetRate.class; } @Override public String toString() { return "UnlimitedDisruptionBudgetRate{}"; } public static Builder newBuilder() { return BUILDER; } public static final class Builder { private Builder() { } public UnlimitedDisruptionBudgetRate build() { return INSTANCE; } } }
9,479
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/DelayedRetryPolicy.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.titus.api.jobmanager.model.job.retry; import java.util.concurrent.TimeUnit; import javax.validation.constraints.Min; /** */ public class DelayedRetryPolicy extends RetryPolicy<DelayedRetryPolicy, DelayedRetryPolicyBuilder> { @Min(value = 0, message = "Delay cannot be negative") private final long delayMs; public DelayedRetryPolicy(long delayMs, int retries) { super(retries); this.delayMs = delayMs; } public long getDelayMs() { return delayMs; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } DelayedRetryPolicy that = (DelayedRetryPolicy) o; return delayMs == that.delayMs; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (delayMs ^ (delayMs >>> 32)); return result; } @Override public String toString() { return "DelayedRetryPolicy{" + "retries=" + getRetries() + "delayMs=" + delayMs + '}'; } @Override public DelayedRetryPolicyBuilder toBuilder() { return newBuilder() .withDelay(delayMs, TimeUnit.MILLISECONDS) .withRetries(getRetries()); } public static DelayedRetryPolicyBuilder newBuilder() { return new DelayedRetryPolicyBuilder(); } }
9,480
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/RetryPolicy.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.titus.api.jobmanager.model.job.retry; import javax.validation.constraints.Min; /** */ public abstract class RetryPolicy<P extends RetryPolicy<P, B>, B extends RetryPolicy.RetryPolicyBuilder<P, B>> { @Min(value = 0, message = "Required 0 or a positive number") private final int retries; protected RetryPolicy(int retries) { this.retries = retries; } public int getRetries() { return retries; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RetryPolicy that = (RetryPolicy) o; return retries == that.retries; } @Override public int hashCode() { return retries; } @Override public String toString() { return getClass().getSimpleName() + "{" + "retries=" + retries + '}'; } public abstract B toBuilder(); public static abstract class RetryPolicyBuilder<P extends RetryPolicy<P, B>, B extends RetryPolicyBuilder<P, B>> { protected int retries; public B withRetries(int retries) { this.retries = retries; return self(); } public abstract P build(); private B self() { return (B) this; } } }
9,481
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/ImmediateRetryPolicy.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.titus.api.jobmanager.model.job.retry; /** */ public class ImmediateRetryPolicy extends RetryPolicy<ImmediateRetryPolicy, ImmediateRetryPolicyBuilder> { public ImmediateRetryPolicy(int retries) { super(retries); } @Override public ImmediateRetryPolicyBuilder toBuilder() { return new ImmediateRetryPolicyBuilder().withRetries(getRetries()); } public static ImmediateRetryPolicyBuilder newBuilder() { return new ImmediateRetryPolicyBuilder(); } }
9,482
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/ImmediateRetryPolicyBuilder.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.titus.api.jobmanager.model.job.retry; public class ImmediateRetryPolicyBuilder extends RetryPolicy.RetryPolicyBuilder<ImmediateRetryPolicy, ImmediateRetryPolicyBuilder> { @Override public ImmediateRetryPolicy build() { return new ImmediateRetryPolicy(retries); } }
9,483
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/DelayedRetryPolicyBuilder.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.titus.api.jobmanager.model.job.retry; import java.util.concurrent.TimeUnit; public final class DelayedRetryPolicyBuilder extends RetryPolicy.RetryPolicyBuilder<DelayedRetryPolicy, DelayedRetryPolicyBuilder> { private long delayMs; DelayedRetryPolicyBuilder() { } public DelayedRetryPolicyBuilder withDelay(long delay, TimeUnit timeUnit) { this.delayMs = timeUnit.toMillis(delay); return this; } public DelayedRetryPolicy build() { return new DelayedRetryPolicy(delayMs, retries); } }
9,484
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/ExponentialBackoffRetryPolicyBuilder.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.titus.api.jobmanager.model.job.retry; public final class ExponentialBackoffRetryPolicyBuilder extends RetryPolicy.RetryPolicyBuilder<ExponentialBackoffRetryPolicy, ExponentialBackoffRetryPolicyBuilder> { private long initialDelayMs; private long maxDelayMs; ExponentialBackoffRetryPolicyBuilder() { } public ExponentialBackoffRetryPolicyBuilder withInitialDelayMs(long initialDelayMs) { this.initialDelayMs = initialDelayMs; return this; } public ExponentialBackoffRetryPolicyBuilder withMaxDelayMs(long maxDelayMs) { this.maxDelayMs = maxDelayMs; return this; } public ExponentialBackoffRetryPolicyBuilder but() { return ExponentialBackoffRetryPolicy.newBuilder().withInitialDelayMs(initialDelayMs).withMaxDelayMs(maxDelayMs).withRetries(retries); } public ExponentialBackoffRetryPolicy build() { return new ExponentialBackoffRetryPolicy(retries, initialDelayMs, maxDelayMs); } }
9,485
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/retry/ExponentialBackoffRetryPolicy.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.titus.api.jobmanager.model.job.retry; import javax.validation.constraints.Min; /** */ public class ExponentialBackoffRetryPolicy extends RetryPolicy<ExponentialBackoffRetryPolicy, ExponentialBackoffRetryPolicyBuilder> { @Min(value = 0, message = "Delay cannot be negative") private final long initialDelayMs; @Min(value = 0, message = "Delay cannot be negative") private final long maxDelayMs; public ExponentialBackoffRetryPolicy(int retries, long initialDelayMs, long maxDelayMs) { super(retries); this.initialDelayMs = initialDelayMs; this.maxDelayMs = maxDelayMs; } public long getInitialDelayMs() { return initialDelayMs; } public long getMaxDelayMs() { return maxDelayMs; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ExponentialBackoffRetryPolicy that = (ExponentialBackoffRetryPolicy) o; if (initialDelayMs != that.initialDelayMs) { return false; } return maxDelayMs == that.maxDelayMs; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (int) (initialDelayMs ^ (initialDelayMs >>> 32)); result = 31 * result + (int) (maxDelayMs ^ (maxDelayMs >>> 32)); return result; } @Override public String toString() { return "ExponentialBackoffRetryPolicy{" + "initialDelayMs=" + initialDelayMs + ", maxDelayMs=" + maxDelayMs + '}'; } @Override public ExponentialBackoffRetryPolicyBuilder toBuilder() { return newBuilder() .withInitialDelayMs(initialDelayMs) .withMaxDelayMs(maxDelayMs) .withRetries(getRetries()); } public static ExponentialBackoffRetryPolicyBuilder newBuilder() { return new ExponentialBackoffRetryPolicyBuilder(); } }
9,486
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ext/ServiceJobExt.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.titus.api.jobmanager.model.job.ext; import javax.validation.Valid; import com.netflix.titus.api.jobmanager.model.job.Capacity; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.ServiceJobProcesses; import com.netflix.titus.api.jobmanager.model.job.migration.MigrationPolicy; import com.netflix.titus.api.jobmanager.model.job.retry.RetryPolicy; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.FieldInvariant; /** */ @ClassFieldsNotNull public class ServiceJobExt implements JobDescriptor.JobDescriptorExt { @Valid @FieldInvariant(value = "value.getMax() <= @constraints.getMaxServiceJobSize()", message = "Service job too big #{value.getMax()} > #{@constraints.getMaxServiceJobSize()}") private final Capacity capacity; private final boolean enabled; @Valid private final RetryPolicy retryPolicy; @Valid private final ServiceJobProcesses serviceJobProcesses; @Valid private final MigrationPolicy migrationPolicy; public ServiceJobExt(Capacity capacity, boolean enabled, RetryPolicy retryPolicy, ServiceJobProcesses serviceJobProcesses, MigrationPolicy migrationPolicy) { this.capacity = capacity; this.enabled = enabled; this.retryPolicy = retryPolicy; this.serviceJobProcesses = serviceJobProcesses; this.migrationPolicy = migrationPolicy; } public Capacity getCapacity() { return capacity; } public boolean isEnabled() { return enabled; } public RetryPolicy getRetryPolicy() { return retryPolicy; } public ServiceJobProcesses getServiceJobProcesses() { return serviceJobProcesses; } public MigrationPolicy getMigrationPolicy() { return migrationPolicy; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceJobExt that = (ServiceJobExt) o; if (enabled != that.enabled) { return false; } if (capacity != null ? !capacity.equals(that.capacity) : that.capacity != null) { return false; } if (retryPolicy != null ? !retryPolicy.equals(that.retryPolicy) : that.retryPolicy != null) { return false; } if (serviceJobProcesses != null ? !serviceJobProcesses.equals(that.serviceJobProcesses) : that.serviceJobProcesses != null) { return false; } return migrationPolicy != null ? migrationPolicy.equals(that.migrationPolicy) : that.migrationPolicy == null; } @Override public int hashCode() { int result = capacity.hashCode(); result = 31 * result + (enabled ? 1 : 0); result = 31 * result + retryPolicy.hashCode(); result = 31 * result + (serviceJobProcesses != null ? serviceJobProcesses.hashCode() : 0); result = 31 * result + (migrationPolicy != null ? migrationPolicy.hashCode() : 0); return result; } @Override public String toString() { return "ServiceJobExt{" + "capacity=" + capacity + ", enabled=" + enabled + ", retryPolicy=" + retryPolicy + ", serviceJobProcesses=" + serviceJobProcesses + ", migrationPolicy=" + migrationPolicy + '}'; } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(ServiceJobExt serviceJobExt) { return new Builder() .withCapacity(serviceJobExt.getCapacity()) .withEnabled(serviceJobExt.isEnabled()) .withRetryPolicy(serviceJobExt.getRetryPolicy()) .withServiceJobProcesses(serviceJobExt.getServiceJobProcesses()) .withMigrationPolicy(serviceJobExt.getMigrationPolicy()); } public static final class Builder { private Capacity capacity; private boolean enabled; private RetryPolicy retryPolicy; private ServiceJobProcesses serviceJobProcesses; private MigrationPolicy migrationPolicy; private Builder() { } public Builder withCapacity(Capacity capacity) { this.capacity = capacity; return this; } public Builder withEnabled(boolean enabled) { this.enabled = enabled; return this; } public Builder withRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public Builder withServiceJobProcesses(ServiceJobProcesses serviceJobProcesses) { this.serviceJobProcesses = serviceJobProcesses; return this; } public Builder withMigrationPolicy(MigrationPolicy migrationPolicy) { this.migrationPolicy = migrationPolicy; return this; } public Builder but() { return newBuilder().withCapacity(capacity).withEnabled(enabled).withRetryPolicy(retryPolicy) .withServiceJobProcesses(serviceJobProcesses).withMigrationPolicy(migrationPolicy); } public ServiceJobExt build() { return new ServiceJobExt(capacity, enabled, retryPolicy, serviceJobProcesses, migrationPolicy); } } }
9,487
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ext/BatchJobExt.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.titus.api.jobmanager.model.job.ext; import java.util.Objects; import javax.validation.Valid; import javax.validation.constraints.Min; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.retry.RetryPolicy; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; import com.netflix.titus.common.model.sanitizer.FieldInvariant; /** * */ @ClassFieldsNotNull public class BatchJobExt implements JobDescriptor.JobDescriptorExt { public static final int RUNTIME_LIMIT_MIN = 5_000; @Min(value = 1, message = "Batch job must have at least one task") @FieldInvariant(value = "value <= @constraints.getMaxBatchJobSize()", message = "Batch job too big #{value} > #{@constraints.getMaxBatchJobSize()}") private final int size; @Min(value = RUNTIME_LIMIT_MIN, message = "Runtime limit too low (must be at least 5sec, but is #{#root}[ms])") @FieldInvariant(value = "value <= @constraints.getMaxRuntimeLimitSec() * 1000", message = "Runtime limit too high #{value} > #{@constraints.getMaxRuntimeLimitSec() * 1000}") private final long runtimeLimitMs; @Valid private final RetryPolicy retryPolicy; private final boolean retryOnRuntimeLimit; public BatchJobExt(int size, long runtimeLimitMs, RetryPolicy retryPolicy, boolean retryOnRuntimeLimit) { this.size = size; this.runtimeLimitMs = runtimeLimitMs; this.retryPolicy = retryPolicy; this.retryOnRuntimeLimit = retryOnRuntimeLimit; } public int getSize() { return size; } public long getRuntimeLimitMs() { return runtimeLimitMs; } public RetryPolicy getRetryPolicy() { return retryPolicy; } public boolean isRetryOnRuntimeLimit() { return retryOnRuntimeLimit; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BatchJobExt that = (BatchJobExt) o; return size == that.size && runtimeLimitMs == that.runtimeLimitMs && retryOnRuntimeLimit == that.retryOnRuntimeLimit && Objects.equals(retryPolicy, that.retryPolicy); } @Override public int hashCode() { return Objects.hash(size, runtimeLimitMs, retryPolicy, retryOnRuntimeLimit); } @Override public String toString() { return "BatchJobExt{" + "size=" + size + ", runtimeLimitMs=" + runtimeLimitMs + ", retryPolicy=" + retryPolicy + ", retryOnRuntimeLimit=" + retryOnRuntimeLimit + '}'; } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(BatchJobExt batchJobExt) { return new Builder() .withRuntimeLimitMs(batchJobExt.getRuntimeLimitMs()) .withRetryPolicy(batchJobExt.getRetryPolicy()) .withSize(batchJobExt.getSize()) .withRetryOnRuntimeLimit(batchJobExt.isRetryOnRuntimeLimit()); } public static final class Builder { private int size; private long runtimeLimitMs; private RetryPolicy retryPolicy; private boolean retryOnRuntimeLimit; private Builder() { } public Builder withSize(int size) { this.size = size; return this; } public Builder withRuntimeLimitMs(long runtimeLimitMs) { this.runtimeLimitMs = runtimeLimitMs; return this; } public Builder withRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public Builder withRetryOnRuntimeLimit(boolean retryOnRuntimeLimit) { this.retryOnRuntimeLimit = retryOnRuntimeLimit; return this; } public BatchJobExt build() { BatchJobExt batchJobExt = new BatchJobExt(size, runtimeLimitMs, retryPolicy, retryOnRuntimeLimit); return batchJobExt; } } }
9,488
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/JobConfiguration.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.titus.api.jobmanager.model.job.sanitizer; import java.util.List; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; /** * Defines defaults/constraints/limits for job descriptor values. */ @Configuration(prefix = "titusMaster.job.configuration") public interface JobConfiguration { long DEFAULT_RUNTIME_LIMIT_SEC = 432_000; // 5 days long MAX_RUNTIME_LIMIT_SEC = 864_000; // 10 days int MAX_ENVIRONMENT_VARIABLES_SIZE_KB = 32; /** * @deprecated Replaced by job specific {@link CustomJobConfiguration#getMaxBatchJobSize()} */ @Deprecated @DefaultValue("1000") int getMaxBatchJobSize(); /** * @deprecated Replaced by job specific {@link CustomJobConfiguration#getMaxServiceJobSize()} */ @Deprecated @DefaultValue("10000") int getMaxServiceJobSize(); @DefaultValue("1.0") double getCpuMin(); /** * An upper bound on CPUs a single container may allocate. The actual limit may be lower, as it also depends * on instance types available in a tier. */ @DefaultValue("96") int getCpuMax(); /** * An upper bound on GPUs a single container may allocate. The actual limit may be lower, as it also depends * on instance types available in a tier. */ @DefaultValue("16") int getGpuMax(); @DefaultValue("512") int getMemoryMegabytesMin(); /** * An upper bound on memory (megabytes) a single container may allocate. The actual limit may be lower, as it also depends * on instance types available in a tier. */ @DefaultValue("1152000") int getMemoryMegabytesMax(); @DefaultValue("10000") int getDiskMegabytesMin(); /** * An upper bound on disk (megabytes) a single container may allocate. The actual limit may be lower, as it also depends * on instance types available in a tier. */ @DefaultValue("1550000") int getDiskMegabytesMax(); @DefaultValue("128") int getNetworkMbpsMin(); /** * An upper bound on network (megabits per second) a single container may allocate. The actual limit may be lower, as it also depends * on instance types available in a tier. */ @DefaultValue("400000") int getNetworkMbpsMax(); /** * Default value for shared memory size if none is provided. This value is derived from the Docker * default value: https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources. */ @DefaultValue("64") int getShmMegabytesDefault(); @DefaultValue("" + DEFAULT_RUNTIME_LIMIT_SEC) long getDefaultRuntimeLimitSec(); @DefaultValue("" + MAX_RUNTIME_LIMIT_SEC) long getMaxRuntimeLimitSec(); /** * Default security group only set in V2 engine. */ List<String> getDefaultSecurityGroups(); /** * Default IAM profile only set in V2 engine. */ @DefaultValue("") String getDefaultIamRole(); @DefaultValue("true") boolean isEntryPointSizeLimitEnabled(); /** * Container health provider names. */ @DefaultValue("alwaysHealthy") String getContainerHealthProviders(); /** * The maximum size of all environment variables in bytes. This includes names, values and * 2 additional bytes for the equal sign and the NUL terminator for each key/value pair. */ @DefaultValue("" + MAX_ENVIRONMENT_VARIABLES_SIZE_KB) int getMaxTotalEnvironmentVariableSizeKB(); }
9,489
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/SchedulingConstraintValidator.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.titus.api.jobmanager.model.job.sanitizer; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashSet; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.validation.Constraint; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import com.netflix.titus.api.jobmanager.JobConstraints; import com.netflix.titus.common.model.sanitizer.internal.AbstractConstraintValidator; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; public class SchedulingConstraintValidator extends AbstractConstraintValidator<SchedulingConstraintValidator.SchedulingConstraint, Map<String, String>> { @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {SchedulingConstraintValidator.class}) public @interface SchedulingConstraint { String message() default "{SchedulingConstraint.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * Defines several {@link SchedulingConstraint} annotations on the same element. * * @see SchedulingConstraint */ @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @interface List { SchedulingConstraint value(); } } @Override public void initialize(SchedulingConstraint constraintAnnotation) { } @Override protected boolean isValid(Map<String, String> value, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) { HashSet<String> unknown = value.keySet().stream().map(String::toLowerCase).collect(Collectors.toCollection(HashSet::new)); unknown.removeAll(JobConstraints.CONSTRAINT_NAMES); if (unknown.isEmpty()) { return true; } constraintViolationBuilderFunction.apply("Unrecognized constraints " + unknown) .addConstraintViolation().disableDefaultConstraintViolation(); return false; } }
9,490
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/JobSanitizerBuilder.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.titus.api.jobmanager.model.job.sanitizer; import java.util.Optional; import com.google.common.base.Preconditions; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import com.netflix.titus.common.model.sanitizer.EntitySanitizerBuilder; import com.netflix.titus.common.model.sanitizer.VerifierMode; /** * */ public class JobSanitizerBuilder { public static final String JOB_STRICT_SANITIZER = "jobStrictSanitizer"; public static final String JOB_PERMISSIVE_SANITIZER = "jobPermissiveSanitizer"; public static final String DEFAULT_CAPACITY_GROUP = "DEFAULT"; private static final String MODEL_ROOT_PACKAGE = Job.class.getPackage().getName(); private final EntitySanitizerBuilder sanitizerBuilder = EntitySanitizerBuilder.stdBuilder(); private JobConfiguration jobConfiguration; private VerifierMode verifierMode = VerifierMode.Strict; private JobAssertions jobAssertions; public JobSanitizerBuilder withVerifierMode(VerifierMode verifierMode) { this.verifierMode = verifierMode; return this; } public JobSanitizerBuilder withJobConstraintConfiguration(JobConfiguration jobConfiguration) { this.jobConfiguration = jobConfiguration; return this; } public JobSanitizerBuilder withJobAsserts(JobAssertions jobAssertions) { this.jobAssertions = jobAssertions; return this; } public EntitySanitizer build() { Preconditions.checkNotNull(jobConfiguration, "JobConfiguration not set"); Preconditions.checkNotNull(jobAssertions, "Job assertions not set"); sanitizerBuilder .verifierMode(verifierMode) .processEntities(type -> type.getPackage().getName().startsWith(MODEL_ROOT_PACKAGE)) .addTemplateResolver(path -> { if (path.endsWith("capacityGroup")) { return Optional.of(DEFAULT_CAPACITY_GROUP); } return Optional.empty(); }) .addValidatorFactory(type -> { if (type.equals(SchedulingConstraintValidator.SchedulingConstraint.class)) { return Optional.of(new SchedulingConstraintValidator()); } if (type.equals(SchedulingConstraintSetValidator.SchedulingConstraintSet.class)) { return Optional.of(new SchedulingConstraintSetValidator()); } return Optional.empty(); }) .registerBean("constraints", jobConfiguration) .registerBean("asserts", jobAssertions); return sanitizerBuilder.build(); } }
9,491
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/CustomJobConfiguration.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.titus.api.jobmanager.model.job.sanitizer; import com.netflix.archaius.api.annotations.DefaultValue; /** * Job specific configuration, currently selected by the job's application name. Upper bound for all jobs is still * enforced by {@link JobConfiguration#getMaxBatchJobSize()} and {@link JobConfiguration#getMaxServiceJobSize()}. */ public interface CustomJobConfiguration { @DefaultValue("1000") int getMaxBatchJobSize(); @DefaultValue("2500") int getMaxServiceJobSize(); }
9,492
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/EfsMountsSanitizer.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.titus.api.jobmanager.model.job.sanitizer; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Optional; import java.util.function.Function; import com.netflix.titus.api.model.EfsMount; import static com.netflix.titus.common.util.CollectionsExt.first; import static java.lang.String.format; /** * {@link EfsMount} cleanup includes: * <ul> * <li>Adding default mount mode</li> * <li>Sorting mounts according to EFS mount point (shortest first)</li> * </ul> */ public class EfsMountsSanitizer implements Function<Object, Optional<Object>> { @Override public Optional<Object> apply(Object oneEfsMountOrCollection) { if (oneEfsMountOrCollection instanceof EfsMount) { return applyEfsMount((EfsMount) oneEfsMountOrCollection); } if (oneEfsMountOrCollection instanceof Collection) { Collection<EfsMount> collection = (Collection<EfsMount>) oneEfsMountOrCollection; if (collection.isEmpty()) { return Optional.empty(); } if (first(collection) instanceof EfsMount) { return applyEfsMounts(collection); } } throw new IllegalArgumentException( format("%s can be applied on %s or its collection", EfsMountsSanitizer.class, EfsMount.class) ); } private Optional<Object> applyEfsMount(EfsMount efsMount) { if (efsMount.getMountPerm() == null) { return Optional.of(EfsMount.newBuilder(efsMount).withMountPerm(EfsMount.MountPerm.RW).build()); } return Optional.empty(); } private Optional<Object> applyEfsMounts(Collection<EfsMount> efsMounts) { ArrayList<EfsMount> sorted = new ArrayList<>(efsMounts); sorted.sort(Comparator.comparing(EfsMount::getMountPoint)); for (int i = 0; i < sorted.size(); i++) { int current = i; applyEfsMount(sorted.get(i)).ifPresent(fixed -> sorted.set(current, (EfsMount) fixed)); } return Optional.of(sorted); } }
9,493
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/SchedulingConstraintSetValidator.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.titus.api.jobmanager.model.job.sanitizer; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashSet; import java.util.Set; import java.util.function.Function; import javax.validation.Constraint; import javax.validation.ConstraintValidatorContext; import javax.validation.Payload; import com.netflix.titus.api.jobmanager.model.job.Container; import com.netflix.titus.common.model.sanitizer.internal.AbstractConstraintValidator; import static java.lang.annotation.ElementType.TYPE; /** * */ public class SchedulingConstraintSetValidator extends AbstractConstraintValidator<SchedulingConstraintSetValidator.SchedulingConstraintSet, Container> { @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint(validatedBy = {SchedulingConstraintSetValidator.class}) public @interface SchedulingConstraintSet { String message() default "{SoftAndHardConstraint.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } @Override public void initialize(SchedulingConstraintSet constraintAnnotation) { } @Override protected boolean isValid(Container container, Function<String, ConstraintValidatorContext.ConstraintViolationBuilder> constraintViolationBuilderFunction) { if (container == null) { return true; } Set<String> common = new HashSet<>(container.getSoftConstraints().keySet()); common.retainAll(container.getHardConstraints().keySet()); if (common.isEmpty()) { return true; } constraintViolationBuilderFunction.apply( "Soft and hard constraints not unique. Shared constraints: " + common ).addConstraintViolation().disableDefaultConstraintViolation(); return false; } }
9,494
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/sanitizer/JobAssertions.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.titus.api.jobmanager.model.job.sanitizer; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.google.common.base.Strings; import com.netflix.titus.api.jobmanager.model.job.Container; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Image; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.vpc.IpAddressAllocation; import com.netflix.titus.api.jobmanager.model.job.vpc.SignedIpAddressAllocation; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.common.model.sanitizer.ValidationError; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import static com.netflix.titus.common.util.StringExt.isAsciiDigit; import static com.netflix.titus.common.util.StringExt.isAsciiLetter; /** * */ public class JobAssertions { private static final Charset UTF_8 = Charset.forName("UTF-8"); public static final int MAX_ENTRY_POINT_SIZE_SIZE_KB = 16; public static final int MAX_ENTRY_POINT_SIZE_SIZE_BYTES = MAX_ENTRY_POINT_SIZE_SIZE_KB * 1024; private static final Pattern SG_PATTERN = Pattern.compile("sg-.*"); private static final Pattern IMAGE_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9\\.\\\\/_-]+"); private static final Pattern IMAGE_TAG_PATTERN = Pattern.compile("[a-zA-Z0-9\\._-]+"); // Based on https://github.com/docker/distribution/blob/master/reference/reference.go private static final String DIGEST_ALGORITHM_SEPARATOR = "[+.-_]"; private static final String DIGEST_ALGORITHM_COMPONENT = "[A-Za-z][A-Za-z0-9]*"; private static final String DIGEST_ALGORITHM = String.format("%s[%s%s]*", DIGEST_ALGORITHM_COMPONENT, DIGEST_ALGORITHM_SEPARATOR, DIGEST_ALGORITHM_COMPONENT); private static final String DIGEST_HEX = "[0-9a-fA-F]{32,}"; private static final String DIGEST = String.format("%s:%s", DIGEST_ALGORITHM, DIGEST_HEX); private static final Pattern IMAGE_DIGEST_PATTERN = Pattern.compile(DIGEST); private final JobConfiguration configuration; private final Function<String, ResourceDimension> maxContainerSizeResolver; public JobAssertions(JobConfiguration configuration, Function<String, ResourceDimension> maxContainerSizeResolver) { this.configuration = configuration; this.maxContainerSizeResolver = maxContainerSizeResolver; } public boolean isValidSyntax(List<String> securityGroups) { return securityGroups.stream().allMatch(sg -> SG_PATTERN.matcher(sg).matches()); } public boolean isValidIamRole(String iamRole) { // TODO We should make full ARN validation String trimmed = StringExt.safeTrim(iamRole); return !trimmed.isEmpty() && !trimmed.contains(" "); } public boolean isEntryPointNotTooLarge(List<String> entryPoint) { if (!configuration.isEntryPointSizeLimitEnabled()) { return true; } if (CollectionsExt.isNullOrEmpty(entryPoint)) { return true; } int totalSize = entryPoint.stream().mapToInt(e -> StringExt.isEmpty(e) ? 0 : e.getBytes(UTF_8).length).sum(); return totalSize <= MAX_ENTRY_POINT_SIZE_SIZE_BYTES; } public Map<String, String> validateEnvironmentVariableNames(Map<String, String> environment) { if (CollectionsExt.isNullOrEmpty(environment)) { return Collections.emptyMap(); } Map<String, String> violations = new HashMap<>(); environment.forEach((key, value) -> { if (key.isEmpty()) { violations.put("empty", "the environment name cannot be an empty string"); return; } char first = key.charAt(0); if (!isAsciiUpperCase(first) && first != '_') { violations.put("invalidFirstCharacter", "the environment name must start with an upper case ASCII letter or '_'"); } if (key.length() == 1) { return; } for (int i = 1; i < key.length(); i++) { char c = key.charAt(i); if (!isAsciiUpperCase(c) && !isAsciiDigit(c) && c != '_') { violations.put("invalidCharacter", "the environment name characters may be an upper case ASCII letter, a digit or '_'"); break; } } }); return violations; } private boolean isAsciiUpperCase(char c) { return isAsciiLetter(c) && Character.isUpperCase(c); } public boolean areEnvironmentVariablesNotTooLarge(Map<String, String> environment) { if (CollectionsExt.isNullOrEmpty(environment)) { return true; } int totalSize = environment.entrySet().stream().mapToInt(entry -> { int keySize = StringExt.isEmpty(entry.getKey()) ? 0 : entry.getKey().getBytes(UTF_8).length; int valueSize = StringExt.isEmpty(entry.getValue()) ? 0 : entry.getValue().getBytes(UTF_8).length; // The 2 additional bytes are for the equal sign and the NUL terminator. return keySize + valueSize + 2; }).sum(); return totalSize <= configuration.getMaxTotalEnvironmentVariableSizeKB() * 1024; } public boolean isValidContainerHealthServiceName(String name) { String[] validNames = configuration.getContainerHealthProviders().split(","); if (CollectionsExt.isNullOrEmpty(validNames)) { return false; } for (String validName : validNames) { if (validName.equals(name)) { return true; } } return false; } public Map<String, String> validateImage(Image image) { // As class-level constraints are evaluated after field-level constraints we have to check for null value here. if (image == null) { return Collections.emptyMap(); } Map<String, String> violations = new HashMap<>(); if (!IMAGE_NAME_PATTERN.matcher(image.getName()).matches()) { violations.put("name", "image name is not valid"); } boolean validDigest = !Strings.isNullOrEmpty(image.getDigest()) && IMAGE_DIGEST_PATTERN.matcher(image.getDigest()).matches(); boolean validTag = !Strings.isNullOrEmpty(image.getTag()) && IMAGE_TAG_PATTERN.matcher(image.getTag()).matches(); if (!validDigest && !validTag) { violations.put("noValidImageDigestOrTag", "must specify a valid digest or tag"); } return violations; } public Map<String, String> notExceedsComputeResources(String capacityGroup, Container container) { // As class-level constraints are evaluated after field-level constraints we have to check for null value here. if (container == null) { return Collections.emptyMap(); } ResourceDimension maxContainerSize = maxContainerSizeResolver.apply(capacityGroup); ContainerResources resources = container.getContainerResources(); Map<String, String> violations = new HashMap<>(); check(resources::getCpu, maxContainerSize::getCpu).ifPresent(v -> violations.put("container.containerResources.cpu", v)); check(resources::getGpu, maxContainerSize::getGpu).ifPresent(v -> violations.put("container.containerResources.gpu", v)); check(resources::getMemoryMB, maxContainerSize::getMemoryMB).ifPresent(v -> violations.put("container.containerResources.memoryMB", v)); check(resources::getDiskMB, maxContainerSize::getDiskMB).ifPresent(v -> violations.put("container.containerResources.diskMB", v)); check(resources::getNetworkMbps, maxContainerSize::getNetworkMbs).ifPresent(v -> violations.put("container.containerResources.networkMbps", v)); return violations; } public Map<String, String> notExceedsIpAllocations(Container container, JobDescriptor.JobDescriptorExt extension) { // As class-level constraints are evaluated after field-level constraints we have to check for null value here. if (container == null) { return Collections.emptyMap(); } int numIpAllocations = container.getContainerResources().getSignedIpAddressAllocations().size(); int numInstances = extension instanceof ServiceJobExt ? ((ServiceJobExt) extension).getCapacity().getMax() : ((BatchJobExt) extension).getSize(); if (numIpAllocations > 0 && numInstances > numIpAllocations) { return Collections.singletonMap("container.containerResources.signedIpAllocations", "Above number of max task instances " + numInstances); } return Collections.emptyMap(); } public Map<String, String> notExceedsEbsVolumes(Container container, JobDescriptor.JobDescriptorExt extension) { // As class-level constraints are evaluated after field-level constraints we have to check for null value here. if (container == null) { return Collections.emptyMap(); } int numEbsVolumes = container.getContainerResources().getEbsVolumes().size(); int numInstances = extension instanceof ServiceJobExt ? ((ServiceJobExt) extension).getCapacity().getMax() : ((BatchJobExt) extension).getSize(); if (numEbsVolumes > 0 && numInstances > numEbsVolumes) { return Collections.singletonMap("container.containerResources.ebsVolumes", "Above number of max task instances " + numInstances); } return Collections.emptyMap(); } public Map<String, String> matchingEbsAndIpZones(List<EbsVolume> ebsVolumes, List<SignedIpAddressAllocation> ipSignedAddressAllocations) { return validateMatchingEbsAndIpZones(ebsVolumes, ipSignedAddressAllocations).stream() .collect(Collectors.toMap(ValidationError::getField, ValidationError::getDescription)); } public static Set<ValidationError> validateMatchingEbsAndIpZones(List<EbsVolume> ebsVolumes, List<SignedIpAddressAllocation> ipSignedAddressAllocations) { if (ebsVolumes == null || ipSignedAddressAllocations == null) { return Collections.emptySet(); } if (ebsVolumes.isEmpty() || ipSignedAddressAllocations.isEmpty()) { return Collections.emptySet(); } int numElements = Math.min(ebsVolumes.size(), ipSignedAddressAllocations.size()); for (int i = 0; i < numElements; i++) { EbsVolume ebsVolume = ebsVolumes.get(i); IpAddressAllocation ipAddressAllocation = ipSignedAddressAllocations.get(i).getIpAddressAllocation(); if (!ebsVolume.getVolumeAvailabilityZone().equals(ipAddressAllocation.getIpAddressLocation().getAvailabilityZone())) { return Collections.singleton(new ValidationError( "containerResources.ebsVolumes", String.format( "EBS volume %s zone %s conflicts with Static IP %s zone %s and index %d", ebsVolume.getVolumeId(), ebsVolume.getVolumeAvailabilityZone(), ipAddressAllocation.getAllocationId(), ipAddressAllocation.getIpAddressLocation().getAvailabilityZone(), i ) )); } } return Collections.emptySet(); } private <N extends Number> Optional<String> check(Supplier<N> jobResource, Supplier<N> maxAllowed) { if (jobResource.get().doubleValue() > maxAllowed.get().doubleValue()) { return Optional.of("Above maximum allowed value " + maxAllowed.get()); } return Optional.empty(); } }
9,495
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ebs/EbsVolume.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.titus.api.jobmanager.model.job.ebs; import java.util.Objects; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import com.google.common.base.Preconditions; public class EbsVolume { public enum MountPerm {RO, RW} public EbsVolume(String volumeId, String volumeAvailabilityZone, int volumeCapacityGB, String mountPath, MountPerm mountPerm, String fsType) { this.volumeId = volumeId; this.volumeAvailabilityZone = volumeAvailabilityZone; this.volumeCapacityGB = volumeCapacityGB; this.mountPath = mountPath; this.mountPermissions = mountPerm; this.fsType = fsType; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } @NotNull @Size(min = 1, max = 512, message = "EBS volume ID cannot be empty or greater than 512 bytes") private final String volumeId; @Size(min = 1, max = 512, message = "EBS volume AZ cannot be empty or greater than 512 bytes") private final String volumeAvailabilityZone; private final int volumeCapacityGB; @NotNull @Size(min = 1, max = 1024, message = "EBS volume mount path cannot be empty or greater than 1024 bytes") private final String mountPath; @NotNull(message = "'mountPermissions' is null") private final MountPerm mountPermissions; @NotNull @Size(min = 1, max = 512, message = "EBS volume FS type cannot be empty or greater than 512 bytes") private final String fsType; public String getVolumeId() { return volumeId; } public String getVolumeAvailabilityZone() { return volumeAvailabilityZone; } public int getVolumeCapacityGB() { return volumeCapacityGB; } public String getMountPath() { return mountPath; } public MountPerm getMountPermissions() { return mountPermissions; } public String getFsType() { return fsType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EbsVolume ebsVolume = (EbsVolume) o; return volumeCapacityGB == ebsVolume.volumeCapacityGB && volumeId.equals(ebsVolume.volumeId) && Objects.equals(volumeAvailabilityZone, ebsVolume.volumeAvailabilityZone) && mountPath.equals(ebsVolume.mountPath) && mountPermissions == ebsVolume.mountPermissions && fsType.equals(ebsVolume.fsType); } @Override public int hashCode() { return Objects.hash(volumeId, volumeAvailabilityZone, volumeCapacityGB, mountPath, mountPermissions, fsType); } @Override public String toString() { return "EbsVolume{" + "volumeId='" + volumeId + '\'' + ", volumeAvailabilityZone='" + volumeAvailabilityZone + '\'' + ", volumeCapacityGB=" + volumeCapacityGB + ", mountPath='" + mountPath + '\'' + ", mountPermissions=" + mountPermissions + ", fsType='" + fsType + '\'' + '}'; } public static final class Builder { private String volumeId; private String volumeAvailabilityZone; private int volumeCapacityGB; private String mountPath; private MountPerm mountPermissions; private String fsType; private Builder() { } private Builder(EbsVolume ebsVolume) { this.volumeId = ebsVolume.getVolumeId(); this.volumeAvailabilityZone = ebsVolume.getVolumeAvailabilityZone(); this.volumeCapacityGB = ebsVolume.getVolumeCapacityGB(); this.mountPath = ebsVolume.getMountPath(); this.mountPermissions = ebsVolume.getMountPermissions(); this.fsType = ebsVolume.getFsType(); } public Builder withVolumeId(String val) { volumeId = val; return this; } public Builder withVolumeAvailabilityZone(String val) { volumeAvailabilityZone = val; return this; } public Builder withVolumeCapacityGB(int val) { volumeCapacityGB = val; return this; } public Builder withMountPath(String val) { mountPath = val; return this; } public Builder withMountPermissions(MountPerm val) { mountPermissions = val; return this; } public Builder withFsType(String val) { fsType = val; return this; } public EbsVolume build() { Preconditions.checkNotNull(volumeId, "Volume ID is null"); Preconditions.checkNotNull(mountPath, "Mount path is null"); Preconditions.checkNotNull(mountPermissions, "Mount permission is null"); Preconditions.checkNotNull(fsType, "File system type is null"); // Volume AZ and capacity may be set after object creation during object sanitization return new EbsVolume(volumeId, volumeAvailabilityZone, volumeCapacityGB, mountPath, mountPermissions, fsType); } } }
9,496
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/ebs/EbsVolumeUtils.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.titus.api.jobmanager.model.job.ebs; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.util.StringExt; import static com.netflix.titus.api.jobmanager.TaskAttributes.TASK_ATTRIBUTES_EBS_VOLUME_ID; /** * Helper utilities for processing EBS volume related info. */ public class EbsVolumeUtils { public static <E extends JobDescriptor.JobDescriptorExt> List<EbsVolume> getEbsVolumes(JobDescriptor<E> jobDescriptor) { List<String> volumeIds = getEbsVolumeIds(jobDescriptor); Optional<String> mountPointOptional = getEbsMountPoint(jobDescriptor); Optional<EbsVolume.MountPerm> mountPermOptional = getEbsMountPerm(jobDescriptor); Optional<String> fsTypeOptional = getEbsFsType(jobDescriptor); if (!(mountPointOptional.isPresent() && mountPermOptional.isPresent() && fsTypeOptional.isPresent())) { return Collections.emptyList(); } String mountPoint = mountPointOptional.get(); EbsVolume.MountPerm mountPerm = mountPermOptional.get(); String fsType = fsTypeOptional.get(); return volumeIds.stream() .map(volumeId -> EbsVolume.newBuilder() .withVolumeId(volumeId) .withMountPath(mountPoint) .withMountPermissions(mountPerm) .withFsType(fsType) .build()) .collect(Collectors.toList()); } public static <E extends JobDescriptor.JobDescriptorExt> List<String> getEbsVolumeIds(JobDescriptor<E> jobDescriptor) { String volumeIdsStr = StringExt.nonNull(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_EBS_VOLUME_IDS)); return StringExt.splitByComma(volumeIdsStr); } public static <E extends JobDescriptor.JobDescriptorExt> Optional<String> getEbsMountPoint(JobDescriptor<E> jobDescriptor) { return Optional.ofNullable(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_EBS_MOUNT_POINT)); } public static <E extends JobDescriptor.JobDescriptorExt> Optional<EbsVolume.MountPerm> getEbsMountPerm(JobDescriptor<E> jobDescriptor) throws IllegalArgumentException { String mountPermStr = StringExt.nonNull(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_EBS_MOUNT_PERM)).toUpperCase(); return mountPermStr.isEmpty() ? Optional.empty() : Optional.of(EbsVolume.MountPerm.valueOf(mountPermStr)); } public static <E extends JobDescriptor.JobDescriptorExt> Optional<String> getEbsFsType(JobDescriptor<E> jobDescriptor) { return Optional.ofNullable(jobDescriptor.getAttributes().get(JobAttributes.JOB_ATTRIBUTES_EBS_FS_TYPE)); } public static Optional<EbsVolume> getEbsVolumeForTask(Job<?> job, Task task) { String ebsVolumeId = task.getTaskContext().get(TASK_ATTRIBUTES_EBS_VOLUME_ID); if (null == ebsVolumeId) { return Optional.empty(); } return job.getJobDescriptor().getContainer().getContainerResources().getEbsVolumes() .stream() .filter(ebsVolume -> ebsVolume.getVolumeId().equals(ebsVolumeId)) .findFirst(); } }
9,497
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/vpc/IpAddressLocation.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.titus.api.jobmanager.model.job.vpc; import java.util.Objects; import javax.validation.constraints.Size; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; /** * Location within a cloud provider of an IP address */ @ClassFieldsNotNull public class IpAddressLocation { @Size(min = 1, message = "Empty value not allowed") private final String region; @Size(min = 1, message = "Empty value not allowed") private final String availabilityZone; @Size(min = 1, message = "Empty value not allowed") private final String subnetId; public String getRegion() { return region; } public String getAvailabilityZone() { return availabilityZone; } public String getSubnetId() { return subnetId; } public IpAddressLocation(String region, String availabilityZone, String subnetId) { this.region = region; this.availabilityZone = availabilityZone; this.subnetId = subnetId; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IpAddressLocation that = (IpAddressLocation) o; return Objects.equals(region, that.region) && Objects.equals(availabilityZone, that.availabilityZone) && Objects.equals(subnetId, that.subnetId); } @Override public int hashCode() { return Objects.hash(region, availabilityZone, subnetId); } @Override public String toString() { return "IpAddressLocation{" + "region='" + region + '\'' + ", availabilityZone='" + availabilityZone + '\'' + ", subnetId='" + subnetId + '\'' + '}'; } public static final class Builder { private String region; private String availabilityZone; private String subnetId; private Builder() { } private Builder(IpAddressLocation ipAddressLocation) { this.region = ipAddressLocation.getRegion(); this.availabilityZone = ipAddressLocation.getAvailabilityZone(); this.subnetId = ipAddressLocation.getSubnetId(); } public Builder withRegion(String val) { region = val; return this; } public Builder withAvailabilityZone(String val) { availabilityZone = val; return this; } public Builder withSubnetId(String val) { subnetId = val; return this; } public Builder but() { return newBuilder() .withRegion(region) .withAvailabilityZone(availabilityZone) .withSubnetId(subnetId); } public IpAddressLocation build() { return new IpAddressLocation(region, availabilityZone, subnetId); } } }
9,498
0
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job
Create_ds/titus-control-plane/titus-api/src/main/java/com/netflix/titus/api/jobmanager/model/job/vpc/SignedIpAddressAllocation.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.titus.api.jobmanager.model.job.vpc; import java.util.Arrays; import java.util.Objects; import javax.validation.Valid; import com.netflix.titus.common.model.sanitizer.ClassFieldsNotNull; @ClassFieldsNotNull public class SignedIpAddressAllocation { @Valid private final IpAddressAllocation ipAddressAllocation; private final byte[] authoritativePublicKey; private final byte[] hostPublicKey; private final byte[] hostPublicKeySignature; private final byte[] message; private final byte[] messageSignature; public SignedIpAddressAllocation(IpAddressAllocation ipAddressAllocation, byte[] authoritativePublicKey, byte[] hostPublicKey, byte[] hostPublicKeySignature, byte[] message, byte[] messageSignature) { this.ipAddressAllocation = ipAddressAllocation; this.authoritativePublicKey = authoritativePublicKey; this.hostPublicKey = hostPublicKey; this.hostPublicKeySignature = hostPublicKeySignature; this.message = message; this.messageSignature = messageSignature; } public IpAddressAllocation getIpAddressAllocation() { return ipAddressAllocation; } public byte[] getAuthoritativePublicKey() { return authoritativePublicKey; } public byte[] getHostPublicKey() { return hostPublicKey; } public byte[] getHostPublicKeySignature() { return hostPublicKeySignature; } public byte[] getMessage() { return message; } public byte[] getMessageSignature() { return messageSignature; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SignedIpAddressAllocation that = (SignedIpAddressAllocation) o; return ipAddressAllocation.equals(that.ipAddressAllocation) && Arrays.equals(authoritativePublicKey, that.authoritativePublicKey) && Arrays.equals(hostPublicKey, that.hostPublicKey) && Arrays.equals(hostPublicKeySignature, that.hostPublicKeySignature) && Arrays.equals(message, that.message) && Arrays.equals(messageSignature, that.messageSignature); } @Override public int hashCode() { int result = Objects.hash(ipAddressAllocation); result = 31 * result + Arrays.hashCode(authoritativePublicKey); result = 31 * result + Arrays.hashCode(hostPublicKey); result = 31 * result + Arrays.hashCode(hostPublicKeySignature); result = 31 * result + Arrays.hashCode(message); result = 31 * result + Arrays.hashCode(messageSignature); return result; } @Override public String toString() { return "SignedIpAddressAllocation{" + "ipAddressAllocation=" + ipAddressAllocation + ", authoritativePublicKey=" + Arrays.toString(authoritativePublicKey) + ", hostPublicKey=" + Arrays.toString(hostPublicKey) + ", hostPublicKeySignature=" + Arrays.toString(hostPublicKeySignature) + ", message=" + Arrays.toString(message) + ", messageSignature=" + Arrays.toString(messageSignature) + '}'; } public Builder toBuilder() { return newBuilder(this); } public static Builder newBuilder() { return new Builder(); } public static Builder newBuilder(SignedIpAddressAllocation copy) { Builder builder = new Builder(); builder.ipAddressAllocation = copy.getIpAddressAllocation(); builder.authoritativePublicKey = copy.getAuthoritativePublicKey(); builder.hostPublicKey = copy.getHostPublicKey(); builder.hostPublicKeySignature = copy.getHostPublicKeySignature(); builder.message = copy.getMessage(); builder.messageSignature = copy.getMessageSignature(); return builder; } public static final class Builder { private IpAddressAllocation ipAddressAllocation; private byte[] authoritativePublicKey; private byte[] hostPublicKey; private byte[] hostPublicKeySignature; private byte[] message; private byte[] messageSignature; private Builder() { } public Builder withIpAddressAllocation(IpAddressAllocation val) { ipAddressAllocation = val; return this; } public Builder withAuthoritativePublicKey(byte[] val) { authoritativePublicKey = val; return this; } public Builder withHostPublicKey(byte[] val) { hostPublicKey = val; return this; } public Builder withHostPublicKeySignature(byte[] val) { hostPublicKeySignature = val; return this; } public Builder withMessage(byte[] val) { message = val; return this; } public Builder withMessageSignature(byte[] val) { messageSignature = val; return this; } public SignedIpAddressAllocation build() { return new SignedIpAddressAllocation( ipAddressAllocation, authoritativePublicKey, hostPublicKey, hostPublicKeySignature, message, messageSignature); } } }
9,499