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-master/src/main/java/com/netflix/titus/master/scheduler/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/scheduler/endpoint/grpc/DefaultSchedulerServiceGrpc.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.master.scheduler.endpoint.grpc; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.Injector; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.grpc.protogen.SchedulerServiceGrpc; import com.netflix.titus.grpc.protogen.SchedulingResultEvent.Failure; import com.netflix.titus.grpc.protogen.SchedulingResultEvent.Failures; import com.netflix.titus.grpc.protogen.SchedulingResultEvent.Success; import com.netflix.titus.grpc.protogen.SchedulingResultRequest; import com.netflix.titus.master.kubernetes.client.DirectKubeApiServerIntegrator; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodCondition; @Singleton public class DefaultSchedulerServiceGrpc extends SchedulerServiceGrpc.SchedulerServiceImplBase { private final V3JobOperations v3JobOperations; private final Injector injector; @Inject public DefaultSchedulerServiceGrpc(V3JobOperations v3JobOperations, Injector injector) { this.v3JobOperations = v3JobOperations; this.injector = injector; } @Override public void getSchedulingResult(SchedulingResultRequest request, StreamObserver<com.netflix.titus.grpc.protogen.SchedulingResultEvent> responseObserver) { String taskId = request.getTaskId(); Pair<Job<?>, Task> jobAndTask = v3JobOperations.findTaskById(taskId).orElse(null); if (jobAndTask == null) { responseObserver.onError(new StatusRuntimeException(Status.NOT_FOUND.withDescription("Task not found: " + taskId))); return; } DirectKubeApiServerIntegrator directIntegrator = injector.getInstance(DirectKubeApiServerIntegrator.class); V1Pod pod = directIntegrator.findPod(taskId).orElse(null); if (pod != null) { responseObserver.onNext(toGrpcSchedulingResultEvent(pod)); responseObserver.onCompleted(); return; } responseObserver.onError(new StatusRuntimeException(Status.NOT_FOUND.withDescription("No scheduling result available for task: " + taskId))); } private com.netflix.titus.grpc.protogen.SchedulingResultEvent toGrpcSchedulingResultEvent(V1Pod pod) { if ("TASK_RUNNING".equalsIgnoreCase(pod.getStatus().getPhase())) { return com.netflix.titus.grpc.protogen.SchedulingResultEvent.newBuilder() .setSuccess(Success.newBuilder().setMessage("Running now")) .build(); } Failures.Builder failuresBuilder = Failures.newBuilder(); if (CollectionsExt.isNullOrEmpty(pod.getStatus().getConditions())) { failuresBuilder.addFailures(Failure.newBuilder() .setReason("Task not scheduled yet, but no placement issues found") .setFailureCount(1) ); } else { for (V1PodCondition v1PodCondition : pod.getStatus().getConditions()) { failuresBuilder.addFailures(Failure.newBuilder() .setReason(String.format("Pod scheduling failure: reason=%s, message=%s", v1PodCondition.getReason(), v1PodCondition.getMessage() )) .setFailureCount(1) ); } } return com.netflix.titus.grpc.protogen.SchedulingResultEvent.newBuilder().setFailures(failuresBuilder).build(); } }
100
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/LoadBalancerModule.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.master.loadbalancer; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.api.connector.cloud.LoadBalancerConnector; import com.netflix.titus.api.connector.cloud.noop.NoOpLoadBalancerConnector; import com.netflix.titus.api.loadbalancer.model.sanitizer.DefaultLoadBalancerJobValidator; import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerJobValidator; import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerValidationConfiguration; import com.netflix.titus.api.loadbalancer.service.LoadBalancerService; import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc; import com.netflix.titus.master.loadbalancer.endpoint.grpc.DefaultLoadBalancerServiceGrpc; import com.netflix.titus.master.loadbalancer.service.DefaultLoadBalancerService; import com.netflix.titus.master.loadbalancer.service.LoadBalancerConfiguration; public class LoadBalancerModule extends AbstractModule { @Override protected void configure() { bind(LoadBalancerServiceGrpc.LoadBalancerServiceImplBase.class).to(DefaultLoadBalancerServiceGrpc.class); bind(LoadBalancerService.class).to(DefaultLoadBalancerService.class); bind(LoadBalancerJobValidator.class).to(DefaultLoadBalancerJobValidator.class); bind(LoadBalancerConnector.class).to(NoOpLoadBalancerConnector.class); } @Provides @Singleton public LoadBalancerConfiguration getLoadBalancerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(LoadBalancerConfiguration.class); } @Provides @Singleton public LoadBalancerValidationConfiguration getLoadBalancerValidationConfiguration(ConfigProxyFactory factory) { return factory.newProxy(LoadBalancerValidationConfiguration.class); } }
101
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/endpoint/grpc/DefaultLoadBalancerServiceGrpc.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.master.loadbalancer.endpoint.grpc; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import com.google.protobuf.Empty; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.service.LoadBalancerService; import com.netflix.titus.api.model.Pagination; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.grpc.protogen.AddLoadBalancerRequest; import com.netflix.titus.grpc.protogen.GetAllLoadBalancersRequest; import com.netflix.titus.grpc.protogen.GetAllLoadBalancersResult; import com.netflix.titus.grpc.protogen.GetJobLoadBalancersResult; import com.netflix.titus.grpc.protogen.JobId; import com.netflix.titus.grpc.protogen.LoadBalancerId; import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc; import com.netflix.titus.grpc.protogen.Page; import com.netflix.titus.grpc.protogen.RemoveLoadBalancerRequest; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError; import static com.netflix.titus.runtime.loadbalancer.GrpcModelConverters.toGetAllLoadBalancersResult; import static com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobQueryModelConverters.toPage; import static com.netflix.titus.runtime.endpoint.v3.grpc.TitusPaginationUtils.checkPageIsValid; @Singleton public class DefaultLoadBalancerServiceGrpc extends LoadBalancerServiceGrpc.LoadBalancerServiceImplBase { private static Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerServiceGrpc.class); private final LoadBalancerService loadBalancerService; @Inject public DefaultLoadBalancerServiceGrpc(LoadBalancerService loadBalancerService) { this.loadBalancerService = loadBalancerService; } @Override public void getJobLoadBalancers(JobId request, StreamObserver<GetJobLoadBalancersResult> responseObserver) { logger.debug("Received get load balancer request {}", request); GetJobLoadBalancersResult.Builder resultBuilder = GetJobLoadBalancersResult.newBuilder() .setJobId(request.getId()); loadBalancerService.getJobLoadBalancers(request.getId()).subscribe( loadBalancerId -> resultBuilder.addLoadBalancers(LoadBalancerId.newBuilder().setId(loadBalancerId).build()), e -> safeOnError(logger, e, responseObserver), () -> { responseObserver.onNext(resultBuilder.build()); responseObserver.onCompleted(); } ); } @Override public void getAllLoadBalancers(GetAllLoadBalancersRequest request, StreamObserver<GetAllLoadBalancersResult> responseObserver) { logger.debug("Received get all load balancer request {}", request); Page grpcPage = request.getPage(); if (!checkPageIsValid(grpcPage, responseObserver)) { return; } try { Pair<List<JobLoadBalancer>, Pagination> pageResult = loadBalancerService.getAllLoadBalancers(toPage(grpcPage)); responseObserver.onNext(toGetAllLoadBalancersResult(pageResult.getLeft(), pageResult.getRight())); responseObserver.onCompleted(); } catch (Exception e) { safeOnError(logger, e, responseObserver); } } @Override public void addLoadBalancer(AddLoadBalancerRequest request, StreamObserver<Empty> responseObserver) { logger.debug("Received add load balancer request {}", request); loadBalancerService.addLoadBalancer(request.getJobId(), request.getLoadBalancerId().getId()).subscribe( () -> { responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); }, e -> safeOnError(logger, e, responseObserver) ); } @Override public void removeLoadBalancer(RemoveLoadBalancerRequest request, StreamObserver<Empty> responseObserver) { logger.debug("Received remove load balancer request {}", request); loadBalancerService.removeLoadBalancer(request.getJobId(), request.getLoadBalancerId().getId()).subscribe( () -> { responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); }, e -> safeOnError(logger, e, responseObserver) ); } }
102
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/LoadBalancerReconciler.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.master.loadbalancer.service; import java.util.concurrent.TimeUnit; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import rx.Observable; public interface LoadBalancerReconciler { /** * Stop reconciliation internal processes. Reconciliation is not guaranteed to continue after it is called. */ void shutdown(); /** * Periodically emit events for targets that need to be updated based on what the state they should be in. */ Observable<TargetStateBatchable> events(); /** * Mark a target to be ignored for a while, so reconciliation does not try to undo (or re-do) an update for it that * is currently in-flight. This is necessary since reconciliation often runs off of stale data (cached snapshots) * and there are propagation delays until updates can be detected by the reconciliation loop. * * @param target to be ignored * @param period to ignore it for */ void activateCooldownFor(LoadBalancerTarget target, long period, TimeUnit unit); }
103
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/LoadBalancerConfiguration.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.master.loadbalancer.service; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.master.loadBalancer") public interface LoadBalancerConfiguration { @DefaultValue("true") boolean isEngineEnabled(); @DefaultValue("4") long getRateLimitBurst(); @DefaultValue("20") long getRateLimitRefillPerSec(); /** * How long the reconciliation logic will ignore a particular target after an update has been enqueued for it. * This should be higher than the expected max propagation delay for updates, so the reconciliation loop is able * to detect changes made to loadbalancers. */ @DefaultValue("120000") long getCooldownPeriodMs(); /** * Max execution time for a full reconciliation. */ @DefaultValue("90000") long getReconciliationTimeoutMs(); /** * Delay between full reconciliation runs. */ @DefaultValue("30000") long getReconciliationDelayMs(); /** * Minimum time that items are held in a buffer for batching. */ @DefaultValue("1000") long getMinTimeMs(); /** * Maximum time that items are held in a buffer for batching (times are increased with exponential backoff). */ @DefaultValue("60000") long getMaxTimeMs(); /** * Size of the time bucket to group batches when sorting them by timestamp, so bigger batches in the same bucket * are picked first. * <p> * This provides a knob to control how to favor larger batches vs older batches first. */ @DefaultValue("5000") long getBucketSizeMs(); /** * Since state for load balancer targets has not always been stored, backfill needs to run at least once on every * deployment that managed one or more load balancers. Backfill should be disabled after being executed once (e.g.: * by enabling this flag once during a deploy and making sure backfill completes successfully). */ @DefaultValue("false") boolean isTargetsToStoreBackfillEnabled(); /** * Max execution time for backfilling */ @DefaultValue("60000") long getStoreBackfillTimeoutMs(); /** * How many load balancers to fetch in parallel when backfilling targets to the store. The max number of concurrent * store write operations will be this times concurrency configured for write operations on the Store. */ @DefaultValue("10") int getStoreBackfillConcurrencyLimit(); }
104
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/TaskHelpers.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.master.loadbalancer.service; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class TaskHelpers { private static final Logger logger = LoggerFactory.getLogger(TaskHelpers.class); static boolean isStateTransition(TaskUpdateEvent event) { final Task currentTask = event.getCurrentTask(); final Optional<Task> previousTask = event.getPreviousTask(); boolean identical = previousTask.map(previous -> previous == currentTask).orElse(false); return !identical && previousTask .map(previous -> !previous.getStatus().getState().equals(currentTask.getStatus().getState())) .orElse(false); } static boolean isStartedWithIp(Task task) { return hasIpAndStateMatches(task, TaskState.Started::equals); } static boolean isTerminalWithIp(Task task) { return hasIpAndStateMatches(task, state -> { switch (task.getStatus().getState()) { case KillInitiated: case Finished: case Disconnected: return true; default: return false; } }); } private static boolean hasIpAndStateMatches(Task task, Function<TaskState, Boolean> predicate) { final TaskState state = task.getStatus().getState(); if (!predicate.apply(state)) { return false; } return task.getTaskContext().containsKey(TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP); } static Set<String> ipAddresses(Collection<TargetStateBatchable> from) { return from.stream().map(TargetStateBatchable::getIpAddress).collect(Collectors.toSet()); } }
105
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/DefaultLoadBalancerService.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.master.loadbalancer.service; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.connector.cloud.LoadBalancer; import com.netflix.titus.api.connector.cloud.LoadBalancerConnector; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancerState; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.api.loadbalancer.model.sanitizer.LoadBalancerJobValidator; import com.netflix.titus.api.loadbalancer.service.LoadBalancerService; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.api.model.Page; import com.netflix.titus.api.model.Pagination; import com.netflix.titus.api.model.PaginationUtil; import com.netflix.titus.api.service.TitusServiceException; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.Deactivator; import com.netflix.titus.common.util.limiter.Limiters; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.rx.RetryHandlerBuilder; import com.netflix.titus.common.util.rx.batch.Batch; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.runtime.loadbalancer.LoadBalancerCursors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; import rx.Scheduler; import rx.Single; import rx.Subscription; import rx.schedulers.Schedulers; @Singleton public class DefaultLoadBalancerService implements LoadBalancerService { private static final Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerService.class); private final TitusRuntime runtime; private final LoadBalancerConfiguration configuration; private final LoadBalancerConnector loadBalancerConnector; private final LoadBalancerStore loadBalancerStore; private final LoadBalancerJobValidator validator; private final LoadBalancerReconciler reconciler; private final LoadBalancerEngine engine; private final Scheduler scheduler; private Subscription loadBalancerBatches; @Inject public DefaultLoadBalancerService(TitusRuntime runtime, LoadBalancerConfiguration configuration, LoadBalancerConnector loadBalancerConnector, LoadBalancerStore loadBalancerStore, V3JobOperations v3JobOperations, LoadBalancerJobValidator validator) { this(runtime, configuration, loadBalancerConnector, loadBalancerStore, new LoadBalancerJobOperations(v3JobOperations), new DefaultLoadBalancerReconciler( configuration, loadBalancerStore, loadBalancerConnector, new LoadBalancerJobOperations(v3JobOperations), runtime.getRegistry(), Schedulers.computation() ), validator, Schedulers.computation() ); } @VisibleForTesting DefaultLoadBalancerService(TitusRuntime runtime, LoadBalancerConfiguration configuration, LoadBalancerConnector loadBalancerConnector, LoadBalancerStore loadBalancerStore, LoadBalancerJobOperations loadBalancerJobOperations, LoadBalancerReconciler reconciler, LoadBalancerJobValidator validator, Scheduler scheduler) { this.runtime = runtime; this.configuration = configuration; this.loadBalancerConnector = loadBalancerConnector; this.loadBalancerStore = loadBalancerStore; this.reconciler = reconciler; this.validator = validator; this.scheduler = scheduler; final long burst = configuration.getRateLimitBurst(); final long refillPerSec = configuration.getRateLimitRefillPerSec(); final TokenBucket connectorTokenBucket = Limiters.createFixedIntervalTokenBucket("loadBalancerConnector", burst, burst, refillPerSec, 1, TimeUnit.SECONDS, runtime.getClock()); this.engine = new LoadBalancerEngine(runtime, configuration, loadBalancerJobOperations, reconciler, loadBalancerConnector, loadBalancerStore, connectorTokenBucket, scheduler); } @Override public Observable<String> getJobLoadBalancers(String jobId) { return loadBalancerStore.getAssociatedLoadBalancersForJob(jobId) .map(JobLoadBalancer::getLoadBalancerId); } @Override public Pair<List<JobLoadBalancer>, Pagination> getAllLoadBalancers(Page page) { if (StringExt.isNotEmpty(page.getCursor())) { final List<JobLoadBalancer> allLoadBalancers = loadBalancerStore.getAssociations().stream() .map(JobLoadBalancerState::getJobLoadBalancer) .sorted(LoadBalancerCursors.loadBalancerComparator()) .collect(Collectors.toList()); return PaginationUtil.takePageWithCursor(Page.newBuilder().withPageSize(page.getPageSize()).withCursor(page.getCursor()).build(), allLoadBalancers, LoadBalancerCursors.loadBalancerComparator(), LoadBalancerCursors::loadBalancerIndexOf, LoadBalancerCursors::newCursorFrom); } // no cursor provided int offset = page.getPageSize() * page.getPageNumber(); // Grab an extra item so we can tell if there's more to read after offset+limit. int limit = page.getPageSize() + 1; List<JobLoadBalancer> jobLoadBalancerPageList = loadBalancerStore.getAssociationsPage(offset, limit); boolean hasMore = jobLoadBalancerPageList.size() > page.getPageSize(); jobLoadBalancerPageList = hasMore ? jobLoadBalancerPageList.subList(0, page.getPageSize()) : jobLoadBalancerPageList; final String cursor = jobLoadBalancerPageList.isEmpty() ? "" : LoadBalancerCursors.newCursorFrom(jobLoadBalancerPageList.get(jobLoadBalancerPageList.size() - 1)); return Pair.of(jobLoadBalancerPageList, new Pagination(page, hasMore, 1, jobLoadBalancerPageList.size(), cursor, 0)); } @Override public Completable addLoadBalancer(String jobId, String loadBalancerId) { try { validator.validateJobId(jobId); } catch (Exception e) { return Completable.error(TitusServiceException.invalidArgument(e.getMessage())); } JobLoadBalancer jobLoadBalancer = new JobLoadBalancer(jobId, loadBalancerId); return loadBalancerStore.addOrUpdateLoadBalancer(jobLoadBalancer, JobLoadBalancer.State.ASSOCIATED) .doOnCompleted(() -> engine.add(jobLoadBalancer)); } @Override public Completable removeLoadBalancer(String jobId, String loadBalancerId) { JobLoadBalancer jobLoadBalancer = new JobLoadBalancer(jobId, loadBalancerId); return loadBalancerStore.addOrUpdateLoadBalancer(jobLoadBalancer, JobLoadBalancer.State.DISSOCIATED) .doOnCompleted(() -> engine.remove(jobLoadBalancer)); } @Activator public void activate() { if (!configuration.isEngineEnabled()) { return; // noop } if (configuration.isTargetsToStoreBackfillEnabled()) { backfillTargetsToStore(); } loadBalancerBatches = runtime.persistentStream(events()) .subscribeOn(scheduler) .subscribe( this::logBatchInfo, e -> logger.error("Error while processing load balancer batch", e), () -> logger.info("Load balancer batch stream closed") ); } private void logBatchInfo(Batch<TargetStateBatchable, String> batch) { final String loadBalancerId = batch.getIndex(); final Map<LoadBalancerTarget.State, List<TargetStateBatchable>> byState = batch.getItems().stream() .collect(Collectors.groupingBy(TargetStateBatchable::getState)); final int registered = byState.getOrDefault(LoadBalancerTarget.State.REGISTERED, Collections.emptyList()).size(); final int deregistered = byState.getOrDefault(LoadBalancerTarget.State.DEREGISTERED, Collections.emptyList()).size(); logger.info("Load balancer {} batch completed. To be registered: {}, to be deregistered: {}", loadBalancerId, registered, deregistered); } @Deactivator public void deactivate() { ObservableExt.safeUnsubscribe(loadBalancerBatches); engine.shutdown(); reconciler.shutdown(); } @VisibleForTesting Observable<Batch<TargetStateBatchable, String>> events() { return engine.events(); } /** * Temporary utility to backfill all targets from registered load balancers to the store, since targets were not * being persisted before. * <p> * Once all current state has been backfilled (i.e.: this runs successfully at least once), this is not needed * anymore and can be disabled/removed. */ @VisibleForTesting void backfillTargetsToStore() { Observable<Single<LoadBalancer>> fetchLoadBalancerOperations = loadBalancerStore.getAssociations().stream() .map(a -> a.getJobLoadBalancer().getLoadBalancerId()) .map(loadBalancerId -> loadBalancerConnector.getLoadBalancer(loadBalancerId) // 404s will not error, and just return a LoadBalancer with state=REMOVED and no registered targets .retryWhen(RetryHandlerBuilder.retryHandler() .withRetryDelay(10, TimeUnit.MILLISECONDS) .withRetryCount(10) .buildExponentialBackoff() ) ) .collect(Collectors.collectingAndThen(Collectors.toList(), Observable::from)); try { int concurrency = configuration.getStoreBackfillConcurrencyLimit(); ReactorExt.toFlux(Single.mergeDelayError(fetchLoadBalancerOperations, concurrency)) .flatMap(this::backfillTargetsToStore) .ignoreElements() .block(Duration.ofMillis(configuration.getStoreBackfillTimeoutMs())); } catch (Exception e) { Registry registry = runtime.getRegistry(); registry.counter(registry.createId("titus.loadbalancer.service.backfillErrors", "error", e.getClass().getSimpleName() )).increment(); // swallow the error so we do not prevent activation of the leader // regular operations will not be affected by the incomplete backfill, but targets may leak until remaining // targets get backfilled during the next run logger.error("Backfill did not complete successfully, missing targets may be orphaned and leak on load balancers (i.e. never deregistered)", e); } } private Mono<Void> backfillTargetsToStore(LoadBalancer loadBalancer) { if (!loadBalancer.getState().equals(LoadBalancer.State.ACTIVE) || loadBalancer.getRegisteredIps().isEmpty()) { return Mono.empty(); } Set<LoadBalancerTargetState> targets = loadBalancer.getRegisteredIps().stream() .map(ip -> new LoadBalancerTargetState( new LoadBalancerTarget(loadBalancer.getId(), "BACKFILLED", ip), LoadBalancerTarget.State.REGISTERED )) .collect(Collectors.toSet()); return loadBalancerStore.addOrUpdateTargets(targets); } }
106
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/TargetStateBatchable.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.master.loadbalancer.service; import java.time.Instant; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.common.util.rx.batch.Batchable; import com.netflix.titus.common.util.rx.batch.Priority; class TargetStateBatchable implements Batchable<LoadBalancerTarget> { private final Priority priority; private final Instant timestamp; private final LoadBalancerTargetState targetState; TargetStateBatchable(Priority priority, Instant timestamp, LoadBalancerTargetState targetState) { this.priority = priority; this.timestamp = timestamp; this.targetState = targetState; } @Override public LoadBalancerTarget getIdentifier() { return targetState.getLoadBalancerTarget(); } @Override public Priority getPriority() { return priority; } @Override public Instant getTimestamp() { return timestamp; } String getLoadBalancerId() { return getIdentifier().getLoadBalancerId(); } String getIpAddress() { return getIdentifier().getIpAddress(); } LoadBalancerTarget.State getState() { return targetState.getState(); } LoadBalancerTargetState getTargetState() { return targetState; } @Override public boolean isEquivalent(Batchable<?> other) { if (!(other instanceof TargetStateBatchable)) { return false; } TargetStateBatchable o = (TargetStateBatchable) other; return targetState.equals(o.targetState); } @Override public String toString() { return "TargetStateBatchable{" + "priority=" + priority + ", timestamp=" + timestamp + ", targetState=" + targetState + '}'; } }
107
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/DefaultLoadBalancerReconciler.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.master.loadbalancer.service; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import com.google.common.collect.Sets; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.api.connector.cloud.LoadBalancer; import com.netflix.titus.api.connector.cloud.LoadBalancerConnector; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancerState; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget.State; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.rx.batch.Priority; import com.netflix.titus.common.util.spectator.ContinuousSubscriptionMetrics; import com.netflix.titus.common.util.spectator.SpectatorExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; import rx.Scheduler; import rx.schedulers.Schedulers; import static com.netflix.titus.api.jobmanager.service.JobManagerException.ErrorCode.JobNotFound; import static com.netflix.titus.master.MetricConstants.METRIC_LOADBALANCER; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.partitioningBy; public class DefaultLoadBalancerReconciler implements LoadBalancerReconciler { private static final Logger logger = LoggerFactory.getLogger(DefaultLoadBalancerReconciler.class); private static final String METRIC_RECONCILER = METRIC_LOADBALANCER + "reconciliation"; private static final Runnable NOOP = () -> { }; /** * how many store calls (both updates and deletes) are allowed concurrently during cleanup (GC) */ private static final int MAX_ORPHAN_CLEANUP_CONCURRENCY = 100; private final ConcurrentMap<LoadBalancerTarget, Instant> ignored = new ConcurrentHashMap<>(); // this is not being accessed by multiple threads at the same time, but we still use a ConcurrentMap to ensure // visibility across multiple reconciliation runs, which may run on different threads private final Set<JobLoadBalancer> markedAsOrphan = ConcurrentHashMap.newKeySet(); private final LoadBalancerStore store; private final LoadBalancerConnector connector; private final LoadBalancerJobOperations jobOperations; // TODO: make dynamic and switch to a Supplier<Long> private final long delayMs; private final Supplier<Long> timeoutMs; private final Runnable afterReconciliation; private final Registry registry; private final Scheduler scheduler; private final Counter registerCounter; private final Counter deregisterCounter; private final Counter removeCounter; private final ContinuousSubscriptionMetrics fullReconciliationMetrics; private final ContinuousSubscriptionMetrics orphanUpdateMetrics; private final ContinuousSubscriptionMetrics removeMetrics; private final ContinuousSubscriptionMetrics removeTargetsMetrics; private final ContinuousSubscriptionMetrics registeredIpsMetrics; private final Id ignoredMetricsId; private final Id orphanMetricsId; DefaultLoadBalancerReconciler(LoadBalancerConfiguration configuration, LoadBalancerStore store, LoadBalancerConnector connector, LoadBalancerJobOperations loadBalancerJobOperations, Registry registry, Scheduler scheduler) { this(configuration, store, connector, loadBalancerJobOperations, NOOP, registry, scheduler); } DefaultLoadBalancerReconciler(LoadBalancerConfiguration configuration, LoadBalancerStore store, LoadBalancerConnector connector, LoadBalancerJobOperations loadBalancerJobOperations, Runnable afterReconciliation, Registry registry, Scheduler scheduler) { this.store = store; this.connector = connector; this.jobOperations = loadBalancerJobOperations; this.delayMs = configuration.getReconciliationDelayMs(); this.timeoutMs = configuration::getReconciliationTimeoutMs; this.afterReconciliation = afterReconciliation; this.registry = registry; this.scheduler = scheduler; List<Tag> tags = Collections.singletonList(new BasicTag("class", DefaultLoadBalancerReconciler.class.getSimpleName())); final Id updatesCounterId = registry.createId(METRIC_RECONCILER + ".updates", tags); this.registerCounter = registry.counter(updatesCounterId.withTag("operation", "register")); this.deregisterCounter = registry.counter(updatesCounterId.withTag("operation", "deregister")); this.removeCounter = registry.counter(updatesCounterId.withTag("operation", "remove")); this.fullReconciliationMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".full", tags, registry); this.orphanUpdateMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".orphanUpdates", tags, registry); this.removeMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".remove", tags, registry); this.removeTargetsMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".removeTargets", tags, registry); this.registeredIpsMetrics = SpectatorExt.continuousSubscriptionMetrics(METRIC_RECONCILER + ".getRegisteredIps", tags, registry); this.ignoredMetricsId = registry.createId(METRIC_RECONCILER + ".ignored", tags); this.orphanMetricsId = registry.createId(METRIC_RECONCILER + ".orphan", tags); PolledMeter.using(registry).withId(ignoredMetricsId).monitorSize(ignored); PolledMeter.using(registry).withId(orphanMetricsId).monitorSize(markedAsOrphan); } @Override public void activateCooldownFor(LoadBalancerTarget target, long period, TimeUnit unit) { Duration periodDuration = Duration.ofMillis(unit.toMillis(period)); logger.debug("Setting a cooldown of {} for target {}", periodDuration, target); Instant untilWhen = Instant.ofEpochMilli(scheduler.now()).plus(periodDuration); ignored.put(target, untilWhen); } @Override public void shutdown() { orphanUpdateMetrics.remove(); removeMetrics.remove(); registeredIpsMetrics.remove(); PolledMeter.remove(registry, ignoredMetricsId); PolledMeter.remove(registry, orphanMetricsId); } @Override public Observable<TargetStateBatchable> events() { Observable<Map.Entry<String, List<JobLoadBalancerState>>> cleanupOrphansAndSnapshot = updateOrphanAssociations() .andThen(snapshotAssociationsByLoadBalancer()); // full reconciliation run Observable<TargetStateBatchable> updatesForAll = cleanupOrphansAndSnapshot .flatMap(entry -> reconcile(entry.getKey(), entry.getValue()), 1) .compose(ObservableExt.subscriptionTimeout(timeoutMs, TimeUnit.MILLISECONDS, scheduler)) .compose(fullReconciliationMetrics.asObservable()) .doOnError(e -> logger.error("reconciliation failed", e)) .onErrorResumeNext(Observable.empty()); // schedule periodic full reconciliations return ObservableExt.periodicGenerator(updatesForAll, delayMs, delayMs, TimeUnit.MILLISECONDS, scheduler) .compose(SpectatorExt.subscriptionMetrics(METRIC_RECONCILER, DefaultLoadBalancerReconciler.class, registry)) .flatMap(iterable -> Observable.from(iterable) .doOnTerminate(afterReconciliation::run), 1); } private Observable<TargetStateBatchable> reconcile(String loadBalancerId, List<JobLoadBalancerState> associations) { Observable<TargetStateBatchable> updatesForLoadBalancer = connector.getLoadBalancer(loadBalancerId) // merge known targets .flatMap(loadBalancer -> ReactorExt.toSingle( store.getLoadBalancerTargets(loadBalancer.getId()) .collect(Collectors.toSet()) .map(knownTargets -> new LoadBalancerWithKnownTargets(loadBalancer, knownTargets)) )) // the same metrics transformer can be used for all subscriptions only because they are all being // serialized with flatMap(maxConcurrent: 1) .compose(registeredIpsMetrics.asSingle()) .flatMapObservable(loadBalancerTargets -> updatesFor(loadBalancerTargets, associations)); return updatesForLoadBalancer .doOnError(e -> logger.error("Error while reconciling load balancer {}", loadBalancerId, e)) .onErrorResumeNext(Observable.empty()); } /** * Generates a stream of necessary updates based on what jobs are currently associated with a load balancer, the * ip addresses currently registered on it, and what ips were previously registered with the load balancer. * <p> * {@link JobLoadBalancer} associations in the <tt>Dissociated</tt> state will be removed when it is safe to do so, * i.e.: when there is no more stored state to be cleaned up, and nothing to be deregistered on the load balancer. * * @param loadBalancer tuple with ip addresses currently registered on the load balancer, and ip addresses * previously registered with the load balancer * @param associations jobs currently associated to the load balancer */ private Observable<TargetStateBatchable> updatesFor(LoadBalancerWithKnownTargets loadBalancer, List<JobLoadBalancerState> associations) { Instant now = now(); ReconciliationUpdates updates = (loadBalancer.current.getState().equals(LoadBalancer.State.ACTIVE)) ? updatesForActiveLoadBalancer(loadBalancer, associations) : updatesForRemovedLoadBalancer(loadBalancer, associations); Completable cleanupTargets = (!updates.toRemove.isEmpty()) ? ReactorExt.toCompletable(store.removeDeregisteredTargets(updates.toRemove)) // bring processing back the the Rx threads, otherwise it happens in the C* driver threadpool .observeOn(Schedulers.computation()) .doOnSubscribe(ignored -> logger.info("Cleaning up {} deregistered targets for load balancer {}", updates.toRemove.size(), loadBalancer.current.getId())) .compose(removeTargetsMetrics.asCompletable()) .doOnError(e -> logger.error("Error while cleaning up targets for " + loadBalancer.current.getId(), e)) .onErrorComplete() : Completable.complete(); // clean up dissociated entries only if it is safe: all targets have been deregistered and there is nothing to be removed Completable cleanupDissociated = (updates.toDeregister.isEmpty() && updates.toRemove.isEmpty()) ? Completable.mergeDelayError(removeAllDissociated(associations), MAX_ORPHAN_CLEANUP_CONCURRENCY) .doOnSubscribe(ignored -> logger.debug("Cleaning up dissociated jobs for load balancer {}", loadBalancer.current.getId())) .compose(removeMetrics.asCompletable()) .doOnError(e -> logger.error("Error while cleaning up associations for " + loadBalancer.current.getId(), e)) .onErrorComplete() : Completable.complete(); Observable<TargetStateBatchable> updatesForLoadBalancer = Observable.from(CollectionsExt.merge( withState(now, updates.toRegister, State.REGISTERED), withState(now, updates.toDeregister, State.DEREGISTERED) )).filter(this::isNotIgnored); return Completable.merge(cleanupTargets, cleanupDissociated) .andThen(updatesForLoadBalancer); } private ReconciliationUpdates updatesForActiveLoadBalancer(LoadBalancerWithKnownTargets loadBalancer, List<JobLoadBalancerState> associations) { Set<LoadBalancerTarget> shouldBeRegistered = associations.stream() .filter(JobLoadBalancerState::isStateAssociated) .flatMap(association -> targetsForJobSafe(association).stream()) .collect(Collectors.toSet()); Set<LoadBalancerTarget> toRegister = shouldBeRegistered.stream() .filter(target -> !loadBalancer.current.getRegisteredIps().contains(target.getIpAddress())) .collect(Collectors.toSet()); // we will force deregistration of inconsistent entries to force their state to be updated Set<LoadBalancerTarget> inconsistentStoredState = loadBalancer.knownTargets.stream() .filter(target -> target.getState().equals(State.REGISTERED) && !shouldBeRegistered.contains(target.getLoadBalancerTarget()) ) .map(LoadBalancerTargetState::getLoadBalancerTarget) .collect(Collectors.toSet()); Set<LoadBalancerTarget> shouldBeDeregisteredFromStoredState = loadBalancer.knownTargets.stream() .filter(target -> target.getState().equals(State.DEREGISTERED) && // filter out cases where job state hasn't fully propagated yet !shouldBeRegistered.contains(target.getLoadBalancerTarget()) ) .map(LoadBalancerTargetState::getLoadBalancerTarget) .collect(Collectors.toSet()); // Split what should be deregistered in: // 1. what needs to be deregistered (and is still registered in the loadbalancer) // 2. what state can be GCed because it has been already deregistered Map<Boolean, Set<LoadBalancerTarget>> toDeregisterCurrentInLoadBalancer = shouldBeDeregisteredFromStoredState.stream() .collect(partitioningBy( target -> loadBalancer.current.getRegisteredIps().contains(target.getIpAddress()), Collectors.toSet() )); Set<LoadBalancerTarget> toDeregister = Sets.union(toDeregisterCurrentInLoadBalancer.get(true), inconsistentStoredState); Set<LoadBalancerTarget> toRemove = toDeregisterCurrentInLoadBalancer.get(false); return new ReconciliationUpdates(loadBalancer.current.getId(), toRegister, toDeregister, toRemove); } private ReconciliationUpdates updatesForRemovedLoadBalancer(LoadBalancerWithKnownTargets loadBalancer, List<JobLoadBalancerState> associations) { logger.warn("Load balancer is gone, ignoring its associations (marking them to be GCed later), and removing known state for its targets: {}", loadBalancer.current.getId()); for (JobLoadBalancerState association : associations) { if (association.isStateAssociated()) { logger.info("Marking association as orphan: {}", association.getJobLoadBalancer()); markedAsOrphan.add(association.getJobLoadBalancer()); } } // we will force deregistration of everything that was marked as REGISTERED to force its state to be updated Map<Boolean, Set<LoadBalancerTarget>> registeredOrNot = loadBalancer.knownTargets.stream() .collect(partitioningBy( target -> target.getState().equals(State.REGISTERED), mapping(LoadBalancerTargetState::getLoadBalancerTarget, Collectors.toSet()) )); Set<LoadBalancerTarget> toDeregister = registeredOrNot.get(true); // all REGISTERED Set<LoadBalancerTarget> toRemove = registeredOrNot.get(false); // all DEREGISTERED return new ReconciliationUpdates(loadBalancer.current.getId(), Collections.emptySet(), toDeregister, toRemove); } private boolean isNotIgnored(TargetStateBatchable update) { return !ignored.containsKey(update.getIdentifier()); } private List<LoadBalancerTarget> targetsForJobSafe(JobLoadBalancerState association) { try { return jobOperations.targetsForJob(association.getJobLoadBalancer()); } catch (RuntimeException e) { if (JobManagerException.hasErrorCode(e, JobNotFound)) { logger.warn("Job is gone, ignoring its association and marking it to be GCed later {}", association); markedAsOrphan.add(association.getJobLoadBalancer()); } else { logger.error("Ignoring association, unable to fetch targets for {}", association, e); } return Collections.emptyList(); } } private Observable<Completable> removeAllDissociated(List<JobLoadBalancerState> associations) { final List<Completable> removeOperations = associations.stream() .filter(JobLoadBalancerState::isStateDissociated) .map(JobLoadBalancerState::getJobLoadBalancer) .map(association -> store.removeLoadBalancer(association) // bring processing back the the Rx threads, otherwise it happens in the C* driver threadpool .observeOn(Schedulers.computation()) .doOnSubscribe(ignored -> logger.info("Removing dissociated {}", association)) .doOnError(e -> logger.error("Failed to remove {}", association, e)) .onErrorComplete() ).collect(Collectors.toList()); return Observable.from(removeOperations); } private List<TargetStateBatchable> withState(Instant instant, Collection<LoadBalancerTarget> targets, State state) { return targets.stream() .map(target -> new TargetStateBatchable(Priority.LOW, instant, new LoadBalancerTargetState(target, state))) .collect(Collectors.toList()); } /** * @return emit loadBalancerId -> listOfAssociation pairs to subscribers */ private Observable<Map.Entry<String, List<JobLoadBalancerState>>> snapshotAssociationsByLoadBalancer() { return Observable.defer(() -> { cleanupExpiredIgnored(); logger.debug("Snapshotting current associations"); Set<Map.Entry<String, List<JobLoadBalancerState>>> pairs = store.getAssociations().stream() .collect(Collectors.groupingBy(JobLoadBalancerState::getLoadBalancerId)) .entrySet(); return Observable.from(pairs); }); } private void cleanupExpiredIgnored() { Instant now = Instant.ofEpochMilli(scheduler.now()); ignored.forEach((target, untilWhen) -> { if (untilWhen.isAfter(now)) { return; } if (ignored.remove(target, untilWhen) /* do not remove when changed */) { logger.debug("Cooldown expired for target {}", target); } }); } /** * set previously marked orphan associations (their jobs are gone) as <tt>Dissociated</tt>. */ private Completable updateOrphanAssociations() { Observable<Completable> updateOperations = Observable.from(markedAsOrphan).map(marked -> { if (jobOperations.getJob(marked.getJobId()).isPresent()) { logger.warn("Not updating an association that was previously marked as orphan, but now contains an existing job: {}", marked); return Completable.complete(); } return store.addOrUpdateLoadBalancer(marked, JobLoadBalancer.State.DISSOCIATED) // bring processing back the the Rx threads, otherwise it happens in the C* driver threadpool .observeOn(Schedulers.computation()) .doOnSubscribe(ignored -> logger.info("Setting orphan association as Dissociated: {}", marked)) .doOnError(e -> logger.error("Failed to update to Dissociated {}", marked, e)); }); // do as much as possible and swallow errors since future reconciliations will mark orphan associations again return Completable.mergeDelayError(updateOperations, MAX_ORPHAN_CLEANUP_CONCURRENCY) .doOnSubscribe(s -> logger.debug("Updating orphan associations")) .compose(orphanUpdateMetrics.asCompletable()) .onErrorComplete() .doOnTerminate(markedAsOrphan::clear); } private Instant now() { return Instant.ofEpochMilli(scheduler.now()); } private static class LoadBalancerWithKnownTargets { private final LoadBalancer current; /** * Targets that have been previously registered by us. */ private final Set<LoadBalancerTargetState> knownTargets; private LoadBalancerWithKnownTargets(LoadBalancer current, Set<LoadBalancerTargetState> knownTargets) { this.current = current; this.knownTargets = knownTargets; } } private class ReconciliationUpdates { private final String loadBalancerId; private final Set<LoadBalancerTarget> toRegister; private final Set<LoadBalancerTarget> toDeregister; private final Set<LoadBalancerTarget> toRemove; private ReconciliationUpdates(String loadBalancerId, Set<LoadBalancerTarget> toRegister, Set<LoadBalancerTarget> toDeregister, Set<LoadBalancerTarget> toRemove) { this.loadBalancerId = loadBalancerId; this.toRegister = toRegister; this.toDeregister = toDeregister; this.toRemove = toRemove; report(); } private void report() { boolean found = false; if (!toRegister.isEmpty()) { found = true; registerCounter.increment(toRegister.size()); } if (!toDeregister.isEmpty()) { found = true; deregisterCounter.increment(toDeregister.size()); } if (!toRemove.isEmpty()) { found = true; removeCounter.increment(toRemove.size()); } if (found) { logger.info("Reconciliation for load balancer {} found targets to to be registered: {}, to be deregistered: {}, to be removed: {}", loadBalancerId, toRegister.size(), toDeregister.size(), toRemove.size()); } } } }
108
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/LoadBalancerJobOperations.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.master.loadbalancer.service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent; 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.model.LoadBalancerTarget; import rx.Observable; /** * Wrapper for the V3 engines with some load balancer specific logic. */ class LoadBalancerJobOperations { private final V3JobOperations v3JobOperations; LoadBalancerJobOperations(V3JobOperations v3JobOperations) { this.v3JobOperations = v3JobOperations; } /** * Valid targets are tasks in the Started state that have ip addresses associated to them. * * @param jobLoadBalancer association * @throws JobManagerException when the job is not present anymore */ List<LoadBalancerTarget> targetsForJob(JobLoadBalancer jobLoadBalancer) { return v3JobOperations.getTasks(jobLoadBalancer.getJobId()).stream() .filter(TaskHelpers::isStartedWithIp) .map(task -> new LoadBalancerTarget( jobLoadBalancer.getLoadBalancerId(), task.getId(), task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP) )) .collect(Collectors.toList()); } Observable<JobManagerEvent<?>> observeJobs() { return v3JobOperations.observeJobs(); } Optional<Job<?>> getJob(String jobId) { return v3JobOperations.getJob(jobId); } }
109
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/loadbalancer/service/LoadBalancerEngine.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.master.loadbalancer.service; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import com.netflix.titus.api.connector.cloud.LoadBalancerConnector; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget.State; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.code.CodeInvariants; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.rx.batch.Batch; import com.netflix.titus.common.util.rx.batch.LargestPerTimeBucket; import com.netflix.titus.common.util.rx.batch.Priority; import com.netflix.titus.common.util.rx.batch.RateLimitedBatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import rx.Observable; import rx.Scheduler; import rx.subjects.PublishSubject; import rx.subjects.Subject; import static com.netflix.titus.master.MetricConstants.METRIC_LOADBALANCER; class LoadBalancerEngine { private static final Logger logger = LoggerFactory.getLogger(LoadBalancerEngine.class); private static final String METRIC_BATCHES = METRIC_LOADBALANCER + "batches"; private static final String METRIC_BATCHER = METRIC_LOADBALANCER + "batcher"; private final Subject<JobLoadBalancer, JobLoadBalancer> pendingAssociations = PublishSubject.<JobLoadBalancer>create().toSerialized(); private final Subject<JobLoadBalancer, JobLoadBalancer> pendingDissociations = PublishSubject.<JobLoadBalancer>create().toSerialized(); private final TitusRuntime titusRuntime; private final CodeInvariants invariants; private final LoadBalancerConfiguration configuration; private final LoadBalancerJobOperations jobOperations; private final TokenBucket connectorTokenBucket; private final LoadBalancerConnector connector; private final LoadBalancerStore store; private final LoadBalancerReconciler reconciler; private final Scheduler scheduler; LoadBalancerEngine(TitusRuntime titusRuntime, LoadBalancerConfiguration configuration, LoadBalancerJobOperations loadBalancerJobOperations, LoadBalancerReconciler reconciler, LoadBalancerConnector loadBalancerConnector, LoadBalancerStore loadBalancerStore, TokenBucket connectorTokenBucket, Scheduler scheduler) { this.titusRuntime = titusRuntime; this.invariants = titusRuntime.getCodeInvariants(); this.configuration = configuration; this.jobOperations = loadBalancerJobOperations; this.connector = loadBalancerConnector; this.store = loadBalancerStore; this.connectorTokenBucket = connectorTokenBucket; this.reconciler = reconciler; this.scheduler = scheduler; } public void add(JobLoadBalancer jobLoadBalancer) { pendingAssociations.onNext(jobLoadBalancer); } public void remove(JobLoadBalancer jobLoadBalancer) { pendingDissociations.onNext(jobLoadBalancer); } Observable<Batch<TargetStateBatchable, String>> events() { // the reconciliation loop must not stop the rest of the rx pipeline onErrors, so we retry Observable<TargetStateBatchable> reconcilerEvents = titusRuntime.persistentStream( reconciler.events().doOnError(e -> logger.error("Reconciliation error", e)) ); Observable<TaskUpdateEvent> taskEvents = jobOperations.observeJobs() .filter(TaskUpdateEvent.class::isInstance) .cast(TaskUpdateEvent.class); Observable<TaskUpdateEvent> stateTransitions = taskEvents.filter(TaskHelpers::isStateTransition); Observable<TaskUpdateEvent> tasksMoved = taskEvents.filter(TaskUpdateEvent::isMovedFromAnotherJob); final Observable<TargetStateBatchable> updates = Observable.merge( reconcilerEvents, pendingAssociations.compose(targetsForJobLoadBalancers(State.REGISTERED)), pendingDissociations.compose(targetsForJobLoadBalancers(State.DEREGISTERED)), registerFromEvents(stateTransitions), deregisterFromEvents(stateTransitions), moveFromEvents(tasksMoved) ).compose(disableReconciliationTemporarily()); return updates .compose(ObservableExt.batchWithRateLimit(buildBatcher(), METRIC_BATCHES, titusRuntime.getRegistry())) .filter(batch -> !batch.getItems().isEmpty()) .onBackpressureDrop(batch -> logger.warn("Backpressure! Dropping batch for {} size {}", batch.getIndex(), batch.size())) .doOnNext(batch -> logger.debug("Processing batch for {} size {}", batch.getIndex(), batch.size())) .flatMap(batch -> applyUpdates(batch).onErrorResumeNext(e -> { logger.error("Could not apply batch for load balancer " + batch.getIndex(), e); return Observable.empty(); })) .doOnNext(batch -> logger.info("Processed {} load balancer updates for {}", batch.size(), batch.getIndex())) .doOnError(e -> logger.error("Error batching load balancer calls", e)) .retry(); } /** * Prevent reconciliation from undoing in-flight updates, since it will be running off cached (and potentially * stale) state. */ private Observable.Transformer<TargetStateBatchable, TargetStateBatchable> disableReconciliationTemporarily() { return updates -> updates.doOnNext(update -> reconciler.activateCooldownFor(update.getIdentifier(), configuration.getCooldownPeriodMs(), TimeUnit.MILLISECONDS) ); } public void shutdown() { this.pendingAssociations.onCompleted(); this.pendingDissociations.onCompleted(); } private Observable<Batch<TargetStateBatchable, String>> applyUpdates(Batch<TargetStateBatchable, String> batch) { String loadBalancerId = batch.getIndex(); Map<State, List<TargetStateBatchable>> byState = batch.getItems().stream() .collect(Collectors.groupingBy(TargetStateBatchable::getState)); Mono<Void> registerAll = CollectionsExt.optionalOfNotEmpty(byState.get(State.REGISTERED)) .map(targets -> updateTargetsInStore(targets).then(ReactorExt.toMono( connector.registerAll(loadBalancerId, TaskHelpers.ipAddresses(targets)) ))) .orElse(Mono.empty()); Mono<Void> deregisterAll = CollectionsExt.optionalOfNotEmpty(byState.get(State.DEREGISTERED)) .map(targets -> updateTargetsInStore(targets).then(ReactorExt.toMono( connector.deregisterAll(loadBalancerId, TaskHelpers.ipAddresses(targets)) ))) .orElse(Mono.empty()); return ReactorExt.toObservable( Mono.whenDelayError(registerAll, deregisterAll) .thenReturn(batch) .onErrorContinue((e, problem) -> logger.error("Error processing batch {}", problem, e)) ); } private Mono<Void> updateTargetsInStore(Collection<TargetStateBatchable> targets) { List<LoadBalancerTargetState> targetStates = targets.stream() .map(TargetStateBatchable::getTargetState) .collect(Collectors.toList()); return store.addOrUpdateTargets(targetStates); } private Observable<TargetStateBatchable> registerFromEvents(Observable<TaskUpdateEvent> events) { return events.map(TaskUpdateEvent::getCurrentTask) .filter(TaskHelpers::isStartedWithIp) .flatMapIterable(task -> { Set<JobLoadBalancer> loadBalancers = store.getAssociatedLoadBalancersSetForJob(task.getJobId()); if (!loadBalancers.isEmpty()) { logger.info("Task update in job associated to one or more load balancers, registering {} load balancer targets: {}", loadBalancers.size(), task.getJobId()); } return updatesForLoadBalancers(loadBalancers, task, State.REGISTERED); }); } private Observable<TargetStateBatchable> deregisterFromEvents(Observable<TaskUpdateEvent> events) { return events.map(TaskUpdateEvent::getCurrentTask) .filter(TaskHelpers::isTerminalWithIp) .flatMapIterable(task -> { Set<JobLoadBalancer> loadBalancers = store.getAssociatedLoadBalancersSetForJob(task.getJobId()); if (!loadBalancers.isEmpty()) { logger.info("Task update in job associated to one or more load balancers, deregistering {} load balancer targets: {}", loadBalancers.size(), task.getJobId()); } return updatesForLoadBalancers(loadBalancers, task, State.DEREGISTERED); }); } private Observable<TargetStateBatchable> moveFromEvents(Observable<TaskUpdateEvent> taskMovedEvents) { return taskMovedEvents.flatMapIterable(taskMoved -> { ArrayList<TargetStateBatchable> changes = new ArrayList<>(); Task task = taskMoved.getCurrentTask(); String targetJobId = task.getJobId(); Set<JobLoadBalancer> targetJobLoadBalancers = store.getAssociatedLoadBalancersSetForJob(targetJobId); String sourceJobId = task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_MOVED_FROM_JOB); if (StringExt.isEmpty(sourceJobId)) { invariants.inconsistent("Task moved to %s does not include the source job id: %s", task.getJobId(), task.getId()); return Collections.emptyList(); } Set<JobLoadBalancer> sourceJobLoadBalancers = store.getAssociatedLoadBalancersSetForJob(sourceJobId); // operations below will dedup load balancers present in both source and target Sets, so we avoid // unnecessary churn by deregistering and registering the same targets on the same loadBalancerId // register on load balancers associated with the target job if (TaskHelpers.isStartedWithIp(task)) { Collection<JobLoadBalancer> toRegister = CollectionsExt.difference( targetJobLoadBalancers, sourceJobLoadBalancers, JobLoadBalancer::byLoadBalancerId ); changes.addAll(updatesForLoadBalancers(toRegister, task, State.REGISTERED)); } // deregister from load balancers associated with the source job Collection<JobLoadBalancer> toDeregister = CollectionsExt.difference( sourceJobLoadBalancers, targetJobLoadBalancers, JobLoadBalancer::byLoadBalancerId ); changes.addAll(updatesForLoadBalancers(toDeregister, task, State.DEREGISTERED)); if (!changes.isEmpty()) { logger.info("Task moved to {} from {}. Jobs are associated with one or more load balancers, generating {} load balancer updates", targetJobId, sourceJobId, changes.size()); } return changes; }); } private List<TargetStateBatchable> updatesForLoadBalancers(Collection<JobLoadBalancer> loadBalancers, Task task, State desired) { return loadBalancers.stream() .map(association -> toLoadBalancerTarget(association, task)) .map(target -> new TargetStateBatchable(Priority.HIGH, now(), new LoadBalancerTargetState(target, desired))) .collect(Collectors.toList()); } private Observable.Transformer<JobLoadBalancer, TargetStateBatchable> targetsForJobLoadBalancers(State state) { return jobLoadBalancers -> jobLoadBalancers .filter(jobLoadBalancer -> jobOperations.getJob(jobLoadBalancer.getJobId()).isPresent()) .flatMap(jobLoadBalancer -> Observable.from(jobOperations.targetsForJob(jobLoadBalancer)) .doOnError(e -> logger.error("Error loading targets for jobId {}", jobLoadBalancer.getJobId(), e)) .onErrorResumeNext(Observable.empty())) .map(target -> new TargetStateBatchable(Priority.HIGH, now(), new LoadBalancerTargetState(target, state))) .doOnError(e -> logger.error("Error fetching targets to {}", state, e)) .retry(); } private static LoadBalancerTarget toLoadBalancerTarget(JobLoadBalancer association, Task task) { return new LoadBalancerTarget(association.getLoadBalancerId(), task.getId(), task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_CONTAINER_IP)); } private RateLimitedBatcher<TargetStateBatchable, String> buildBatcher() { final long minTimeMs = configuration.getMinTimeMs(); final long maxTimeMs = configuration.getMaxTimeMs(); final long bucketSizeMs = configuration.getBucketSizeMs(); final LargestPerTimeBucket emissionStrategy = new LargestPerTimeBucket(minTimeMs, bucketSizeMs, scheduler); return RateLimitedBatcher.create(connectorTokenBucket, minTimeMs, maxTimeMs, TargetStateBatchable::getLoadBalancerId, emissionStrategy, METRIC_BATCHER, titusRuntime.getRegistry(), scheduler); } private Instant now() { return Instant.ofEpochMilli(scheduler.now()); } }
110
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit/service/AuditLogConfiguration.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.master.audit.service; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; /** * Configuration parameters for audit subsystem. */ @Configuration(prefix = "titus.master.audit") public interface AuditLogConfiguration { /** * A folder in which audit file is created. */ @DefaultValue("/logs/titus-master") String getAuditLogFolder(); }
111
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit/service/AuditEventLogger.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.master.audit.service; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.audit.model.AuditLogEvent; import com.netflix.titus.api.audit.service.AuditLogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Subscriber; /** * Writes audit events to a logger. */ @Singleton public class AuditEventLogger { private static final Logger logger = LoggerFactory.getLogger(AuditEventLogger.class); @Inject public AuditEventLogger(AuditLogService auditLogService) { auditLogService.auditLogEvents().subscribe( new Subscriber<AuditLogEvent>() { @Override public void onCompleted() { logger.warn("Audit log observable completed"); } @Override public void onError(Throwable e) { logger.error("Error in Audit long observable: {}", e.getMessage(), e); } @Override public void onNext(AuditLogEvent event) { logger.info("Audit log: event type: {}, operand: {}, data: {}", event.getType(), event.getOperand(), event.getData()); } } ); } }
112
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit/service/DefaultAuditLogService.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.master.audit.service; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.audit.model.AuditLogEvent; import com.netflix.titus.api.audit.service.AuditLogService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.BackpressureOverflow; import rx.Observable; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; @Singleton public class DefaultAuditLogService implements AuditLogService { private static final Logger logger = LoggerFactory.getLogger(DefaultAuditLogService.class); private static final int BACK_PRESSURE_BUFFER_SIZE = 10000; private final Subject<AuditLogEvent, AuditLogEvent> observer; private final Observable<AuditLogEvent> observable; @Inject public DefaultAuditLogService() { this.observer = new SerializedSubject<>(PublishSubject.create()); this.observable = observer .onBackpressureBuffer( BACK_PRESSURE_BUFFER_SIZE, () -> logger.warn("Exceeded back pressure buffer of " + BACK_PRESSURE_BUFFER_SIZE), BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST ) .observeOn(Schedulers.io()); } @Override public void submit(AuditLogEvent event) { observer.onNext(event); } @Override public Observable<AuditLogEvent> auditLogEvents() { return observable; } }
113
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit/service/AuditModule.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.master.audit.service; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.api.audit.service.AuditLogService; public final class AuditModule extends AbstractModule { @Override protected void configure() { bind(AuditLogService.class).to(DefaultAuditLogService.class); bind(AuditEventLogger.class).asEagerSingleton(); bind(AuditEventDiskWriter.class).asEagerSingleton(); } @Provides @Singleton public AuditLogConfiguration getAuditLogConfiguration(ConfigProxyFactory factory) { return factory.newProxy(AuditLogConfiguration.class); } }
114
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/audit/service/AuditEventDiskWriter.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.master.audit.service; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.audit.model.AuditLogEvent; import com.netflix.titus.api.audit.service.AuditLogService; import com.netflix.titus.api.model.event.UserRequestEvent; import com.netflix.titus.common.util.DateTimeExt; import com.netflix.titus.common.util.IOExt; import com.netflix.titus.common.util.rx.eventbus.RxEventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.schedulers.Schedulers; /** * Audit logging to a file. */ @Singleton public class AuditEventDiskWriter { private static final Logger logger = LoggerFactory.getLogger(AuditEventDiskWriter.class); static final String LOG_FILE_NAME = "titus-audit.log"; static final long WRITE_INTERVAL_MS = 1000; private final File auditLogFolder; private final RxEventBus rxEventBus; private final File auditLogFile; private final AuditLogService auditLogService; private final Scheduler ioScheduler; private final Subscription auditLogSubscription; private final Subscription rxEventsSubscription; private final Subscription logWriterSubscription; private final Queue<AuditLogEvent> eventQueue = new LinkedBlockingDeque<>(); private final Queue<UserRequestEvent> eventBusQueue = new LinkedBlockingQueue<>(); private volatile Writer logWriter; @Inject public AuditEventDiskWriter(AuditLogConfiguration config, AuditLogService auditLogService, RxEventBus rxEventBus) { this(config, auditLogService, rxEventBus, Schedulers.io()); } public AuditEventDiskWriter(AuditLogConfiguration config, AuditLogService auditLogService, RxEventBus rxEventBus, Scheduler ioScheduler) { this.auditLogFolder = createAuditLogFolder(new File(config.getAuditLogFolder())); this.rxEventBus = rxEventBus; this.auditLogFile = new File(auditLogFolder, LOG_FILE_NAME); this.auditLogService = auditLogService; this.ioScheduler = ioScheduler; this.auditLogSubscription = enableLogging(); this.rxEventsSubscription = enableRxEventBusLogging(); this.logWriterSubscription = enableLogWriter(); } @PreDestroy public void shutdown() { auditLogSubscription.unsubscribe(); rxEventsSubscription.unsubscribe(); logWriterSubscription.unsubscribe(); shutdownInternal(); } private void shutdownInternal() { writeLog(); IOExt.closeSilently(logWriter); } private Subscription enableLogging() { return auditLogService.auditLogEvents() .doOnTerminate(() -> logger.info("Terminating audit log subscription")) .subscribe(eventQueue::add); } private Subscription enableRxEventBusLogging() { return rxEventBus.listen(getClass().getSimpleName(), UserRequestEvent.class) .doOnTerminate(() -> logger.info("Terminating RxEventBus subscription")) .subscribe(eventBusQueue::add); } private Subscription enableLogWriter() { return Observable.interval(0, WRITE_INTERVAL_MS, TimeUnit.MILLISECONDS, ioScheduler) .doOnTerminate(() -> { logger.info("Terminating audit log writer"); shutdownInternal(); }) .subscribe(tick -> writeLog()); } private void writeLog() { try { if (logWriter == null) { createAuditLogFolder(auditLogFolder); logWriter = new BufferedWriter(new FileWriter(auditLogFile, true)); } for (AuditLogEvent event = eventQueue.poll(); event != null; event = eventQueue.poll()) { logWriter.write(formatEvent(event)); logWriter.write('\n'); } for (UserRequestEvent event = eventBusQueue.poll(); event != null; event = eventBusQueue.poll()) { logWriter.write(formatEvent(event)); logWriter.write('\n'); } logWriter.flush(); } catch (Exception e) { logger.warn("Audit log write to disk failure ({})", e.getMessage()); } } private static File createAuditLogFolder(File logFolder) { if (!logFolder.exists()) { if (!logFolder.mkdirs()) { throw new IllegalArgumentException("Cannot create an audit log folder " + logFolder); } } else { if (!logFolder.isDirectory()) { throw new IllegalArgumentException(logFolder + " is configured as an audit log folder, but it is not a directory"); } } return logFolder; } private String formatEvent(AuditLogEvent event) { StringBuilder sb = new StringBuilder(); sb.append(DateTimeExt.toUtcDateTimeString(event.getTime())); sb.append(",source=JobManager,"); sb.append(event.getType()); sb.append(','); sb.append(event.getOperand()); sb.append(','); sb.append(event.getData()); return sb.toString(); } private String formatEvent(UserRequestEvent event) { StringBuilder sb = new StringBuilder(); sb.append(DateTimeExt.toUtcDateTimeString(event.getTimestamp())); sb.append(",source=HTTP,"); sb.append(event.getOperation()); sb.append(",callerId="); sb.append(event.getCallerId()); sb.append(','); sb.append(event.getDetails()); return sb.toString(); } }
115
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/MasterEndpointModule.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.master.endpoint; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.api.Config; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.loadshedding.AdmissionController; import com.netflix.titus.common.util.loadshedding.AdmissionControllers; import com.netflix.titus.common.util.loadshedding.grpc.GrpcAdmissionControllerServerInterceptor; import com.netflix.titus.master.endpoint.grpc.GrpcMasterEndpointConfiguration; import com.netflix.titus.master.endpoint.grpc.TitusMasterGrpcServer; import com.netflix.titus.runtime.endpoint.authorization.AuthorizationServiceModule; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolveModule; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; public class MasterEndpointModule extends AbstractModule { public static final String GRPC_ADMISSION_CONTROLLER_CONFIGURATION_PREFIX = "titus.master.grpcServer.admissionController.buckets"; private static final String UNIDENTIFIED = "unidentified"; @Override protected void configure() { bind(TitusMasterGrpcServer.class).asEagerSingleton(); install(new CallMetadataResolveModule()); install(new AuthorizationServiceModule()); } @Provides @Singleton public GrpcMasterEndpointConfiguration getGrpcEndpointConfiguration(ConfigProxyFactory factory) { return factory.newProxy(GrpcMasterEndpointConfiguration.class); } @Provides @Singleton public GrpcAdmissionControllerServerInterceptor getGrpcAdmissionControllerServerInterceptor(Config config, GrpcMasterEndpointConfiguration configuration, CallMetadataResolver callMetadataResolver, TitusRuntime titusRuntime) { AdmissionController mainController = AdmissionControllers.tokenBucketsFromArchaius( config.getPrefixedView(GRPC_ADMISSION_CONTROLLER_CONFIGURATION_PREFIX), true, titusRuntime ); AdmissionController circuitBreaker = AdmissionControllers.circuitBreaker( mainController, configuration::isAdmissionControllerEnabled ); AdmissionController spectator = AdmissionControllers.spectator(circuitBreaker, titusRuntime); return new GrpcAdmissionControllerServerInterceptor( spectator, () -> callMetadataResolver.resolve().map(c -> { if (CollectionsExt.isNullOrEmpty(c.getCallers())) { return UNIDENTIFIED; } return c.getCallers().get(0).getId(); }).orElse(UNIDENTIFIED) ); } }
116
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/grpc/TitusMasterGrpcServer.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.master.endpoint.grpc; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.framework.fit.adapter.GrpcFitInterceptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.common.util.loadshedding.grpc.GrpcAdmissionControllerServerInterceptor; import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc; import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc.AutoScalingServiceImplBase; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc.EvictionServiceImplBase; import com.netflix.titus.grpc.protogen.HealthGrpc; import com.netflix.titus.grpc.protogen.HealthGrpc.HealthImplBase; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc; import com.netflix.titus.grpc.protogen.JobManagementServiceGrpc.JobManagementServiceImplBase; import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc; import com.netflix.titus.grpc.protogen.LoadBalancerServiceGrpc.LoadBalancerServiceImplBase; import com.netflix.titus.grpc.protogen.SchedulerServiceGrpc; import com.netflix.titus.grpc.protogen.SchedulerServiceGrpc.SchedulerServiceImplBase; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc.SupervisorServiceImplBase; import com.netflix.titus.master.endpoint.common.grpc.interceptor.LeaderServerInterceptor; import com.netflix.titus.runtime.endpoint.common.grpc.interceptor.ErrorCatchingServerInterceptor; import com.netflix.titus.runtime.endpoint.metadata.V3HeaderInterceptor; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; import io.grpc.ServiceDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * */ @Singleton public class TitusMasterGrpcServer { private static final Logger LOG = LoggerFactory.getLogger(TitusMasterGrpcServer.class); private final HealthImplBase healthService; private final SupervisorServiceImplBase titusSupervisorService; private final JobManagementServiceImplBase jobManagementService; private final EvictionServiceImplBase evictionService; private final AutoScalingServiceImplBase appAutoScalingService; private final SchedulerServiceImplBase schedulerService; private final GrpcMasterEndpointConfiguration config; private final LeaderServerInterceptor leaderServerInterceptor; private final LoadBalancerServiceImplBase loadBalancerService; private final GrpcAdmissionControllerServerInterceptor admissionControllerServerInterceptor; private final TitusRuntime titusRuntime; private final ExecutorService grpcCallbackExecutor; private final AtomicBoolean started = new AtomicBoolean(); private Server server; private int port; @Inject public TitusMasterGrpcServer( HealthImplBase healthService, SupervisorServiceImplBase titusSupervisorService, JobManagementServiceImplBase jobManagementService, EvictionServiceImplBase evictionService, AutoScalingServiceImplBase appAutoScalingService, LoadBalancerServiceImplBase loadBalancerService, SchedulerServiceImplBase schedulerService, GrpcMasterEndpointConfiguration config, LeaderServerInterceptor leaderServerInterceptor, GrpcAdmissionControllerServerInterceptor admissionControllerServerInterceptor, TitusRuntime titusRuntime ) { this.healthService = healthService; this.titusSupervisorService = titusSupervisorService; this.jobManagementService = jobManagementService; this.evictionService = evictionService; this.appAutoScalingService = appAutoScalingService; this.loadBalancerService = loadBalancerService; this.schedulerService = schedulerService; this.config = config; this.leaderServerInterceptor = leaderServerInterceptor; this.admissionControllerServerInterceptor = admissionControllerServerInterceptor; this.titusRuntime = titusRuntime; this.grpcCallbackExecutor = ExecutorsExt.instrumentedCachedThreadPool(titusRuntime.getRegistry(), "grpcCallbackExecutor"); } public int getGrpcPort() { return port; } @PostConstruct public void start() { if (started.getAndSet(true)) { return; } this.port = config.getPort(); this.server = configure(ServerBuilder.forPort(port).executor(grpcCallbackExecutor)) .addService(ServerInterceptors.intercept( healthService, createInterceptors(HealthGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( titusSupervisorService, createInterceptors(SupervisorServiceGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( jobManagementService, createInterceptors(JobManagementServiceGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( evictionService, createInterceptors(EvictionServiceGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( appAutoScalingService, createInterceptors(AutoScalingServiceGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( schedulerService, createInterceptors(SchedulerServiceGrpc.getServiceDescriptor()) )) .addService(ServerInterceptors.intercept( loadBalancerService, createInterceptors(LoadBalancerServiceGrpc.getServiceDescriptor()) )) .build(); LOG.info("Starting gRPC server on port {}.", port); try { this.server.start(); this.port = server.getPort(); } catch (final IOException e) { String errorMessage = "Cannot start TitusMaster GRPC server on port " + port; LOG.error(errorMessage, e); throw new RuntimeException(errorMessage, e); } LOG.info("Started gRPC server on port {}.", port); } @PreDestroy public void shutdown() { if (server.isShutdown()) { return; } long timeoutMs = config.getShutdownTimeoutMs(); try { if (timeoutMs <= 0) { server.shutdownNow(); } else { server.shutdown(); try { server.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } if (!server.isShutdown()) { server.shutdownNow(); } } } finally { grpcCallbackExecutor.shutdown(); if (timeoutMs > 0) { try { grpcCallbackExecutor.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } } } } /** * Override to change default server configuration. */ protected ServerBuilder configure(ServerBuilder serverBuilder) { return serverBuilder; } /** * Override to add server side interceptors. */ protected List<ServerInterceptor> createInterceptors(ServiceDescriptor serviceDescriptor) { List<ServerInterceptor> interceptors = new ArrayList<ServerInterceptor>(); interceptors.add(admissionControllerServerInterceptor); interceptors.add(new ErrorCatchingServerInterceptor()); interceptors.add(leaderServerInterceptor); interceptors.add(new V3HeaderInterceptor()); return GrpcFitInterceptor.appendIfFitEnabled(interceptors, titusRuntime); } }
117
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/grpc/GrpcMasterEndpointConfiguration.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.master.endpoint.grpc; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.master.grpcServer") public interface GrpcMasterEndpointConfiguration { @DefaultValue("7104") int getPort(); /** * Graceful shutdown time for GRPC server. If zero, shutdown happens immediately, and all client connections are * terminated abruptly. */ @DefaultValue("30000") long getShutdownTimeoutMs(); @DefaultValue("true") boolean isAdmissionControllerEnabled(); /** * Max number of threads used to handle expensive server streaming calls. 2 threads per available CPU is usually a * good start, tweak as necessary. */ @DefaultValue("256") int getServerStreamsThreadPoolSize(); }
118
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/admission/JobCoordinatorAdmissionModule.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.master.endpoint.admission; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.common.model.admission.AdmissionSanitizer; import com.netflix.titus.common.model.admission.AdmissionValidator; import com.netflix.titus.runtime.endpoint.admission.PassJobValidator; public class JobCoordinatorAdmissionModule extends AbstractModule { @Override protected void configure() { } @Provides @Singleton public AdmissionSanitizer<JobDescriptor> getJobSanitizer() { return new PassJobValidator(); } @Provides @Singleton public AdmissionValidator<JobDescriptor> getJobValidator() { return new PassJobValidator(); } }
119
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/Representation2ModelConvertions.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.master.endpoint.v2.rest; import com.netflix.titus.api.endpoint.v2.rest.representation.ApplicationSlaRepresentation; import com.netflix.titus.api.endpoint.v2.rest.representation.ReservationUsage; import com.netflix.titus.api.endpoint.v2.rest.representation.TierRepresentation; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.api.model.Tier; /** * Translate between REST representation and core entities. */ public final class Representation2ModelConvertions { private Representation2ModelConvertions() { } public static ApplicationSLA asCoreEntity(ApplicationSlaRepresentation representation) { ResourceDimension resourceDimension = ResourceDimension.newBuilder() .withCpus(representation.getInstanceCPU()) .withMemoryMB(representation.getInstanceMemoryMB()) .withDiskMB(representation.getInstanceDiskMB()) .withNetworkMbs(representation.getInstanceNetworkMbs()) .withGpu(representation.getInstanceGPU()) .build(); Tier tier; if (representation.getTier() != null) { tier = Tier.valueOf(representation.getTier().name()); } else { tier = Tier.Flex; } return ApplicationSLA.newBuilder() .withAppName(representation.getAppName()) .withTier(tier) .withResourceDimension(resourceDimension) .withInstanceCount(representation.getInstanceCount()) .withSchedulerName(representation.getSchedulerName()) .withResourcePool(representation.getResourcePool()) .build(); } public static ApplicationSlaRepresentation asRepresentation(ApplicationSLA coreEntity) { return asRepresentation(coreEntity, null, null); } public static ApplicationSlaRepresentation asRepresentation(ApplicationSLA coreEntity, String cellId, ReservationUsage reservationUsage) { ResourceDimension resourceDimension = coreEntity.getResourceDimension(); return new ApplicationSlaRepresentation( coreEntity.getAppName(), cellId, TierRepresentation.valueOf(coreEntity.getTier().name()), resourceDimension.getCpu(), resourceDimension.getMemoryMB(), resourceDimension.getDiskMB(), resourceDimension.getNetworkMbs(), resourceDimension.getGpu(), coreEntity.getInstanceCount(), reservationUsage, coreEntity.getSchedulerName(), coreEntity.getResourcePool() ); } }
120
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ReservationUsageCalculator.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.master.endpoint.v2.rest; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.endpoint.v2.rest.representation.ReservationUsage; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; @Singleton public class ReservationUsageCalculator { private final ReadOnlyJobOperations jobOperations; private final ApplicationSlaManagementService capacityManagementService; @Inject public ReservationUsageCalculator(ReadOnlyJobOperations jobOperations, ApplicationSlaManagementService capacityManagementService) { this.jobOperations = jobOperations; this.capacityManagementService = capacityManagementService; } public Map<String, ReservationUsage> buildUsage() { Map<String, ResourceAccumulator> accumulatorMap = new HashMap<>(); List<Pair<Job, List<Task>>> jobsAndTasks = jobOperations.getJobsAndTasks(); Set<String> capacityGroupNames = capacityManagementService.getApplicationSLAs().stream() .map(ApplicationSLA::getAppName) .collect(Collectors.toSet()); for (Pair<Job, List<Task>> jobAndTasks : jobsAndTasks) { Job job = jobAndTasks.getLeft(); String capacityGroup = capacityGroupNames.contains(job.getJobDescriptor().getCapacityGroup()) ? job.getJobDescriptor().getCapacityGroup() : ApplicationSlaManagementService.DEFAULT_APPLICATION; ResourceAccumulator accumulator = accumulatorMap.computeIfAbsent( capacityGroup, cp -> new ResourceAccumulator() ); processJob(accumulator, jobAndTasks); } Map<String, ReservationUsage> result = new HashMap<>(); accumulatorMap.forEach((capacityGroup, accumulator) -> result.put(capacityGroup, accumulator.toReservationUsage())); capacityManagementService.getApplicationSLAs().forEach(capacityGroup -> { if (!result.containsKey(capacityGroup.getAppName())) { result.put(capacityGroup.getAppName(), ReservationUsage.none()); } }); return result; } public ReservationUsage buildCapacityGroupUsage(String capacityGroupName) { ApplicationSLA capacityGroup = capacityManagementService.getApplicationSLA(capacityGroupName); if (capacityGroup == null) { return ReservationUsage.none(); } List<Pair<Job, List<Task>>> jobsAndTasks = jobOperations.getJobsAndTasks(); ResourceAccumulator accumulator = new ResourceAccumulator(); for (Pair<Job, List<Task>> jobAndTasks : jobsAndTasks) { Job job = jobAndTasks.getLeft(); if (capacityGroupName.equals(job.getJobDescriptor().getCapacityGroup())) { processJob(accumulator, jobAndTasks); } } return accumulator.toReservationUsage(); } private void processJob(ResourceAccumulator accumulator, Pair<Job, List<Task>> jobAndTasks) { Job job = jobAndTasks.getLeft(); List<Task> tasks = jobAndTasks.getRight(); int running = 0; for (Task task : tasks) { if (TaskState.isRunning(task.getStatus().getState())) { running++; } } accumulator.add(running, job.getJobDescriptor().getContainer().getContainerResources()); } private static class ResourceAccumulator { private double cpuSum = 0.0; private long memoryMbSum = 0; private long diskMbSum = 0; private long networkMbpsSum = 0; private void add(int count, ContainerResources containerResources) { if (count > 0) { cpuSum += count * containerResources.getCpu(); memoryMbSum += count * containerResources.getMemoryMB(); diskMbSum += count * containerResources.getDiskMB(); networkMbpsSum += count * containerResources.getNetworkMbps(); } } private ReservationUsage toReservationUsage() { return new ReservationUsage(cpuSum, memoryMbSum, diskMbSum, networkMbpsSum); } } }
121
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/Util.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.master.endpoint.v2.rest; import java.net.InetAddress; import java.net.UnknownHostException; import com.netflix.titus.api.supervisor.service.MasterDescription; public class Util { public static boolean isLocalHost(MasterDescription master) { if(master == null) { return false; } try { InetAddress localHost = InetAddress.getLocalHost(); for (InetAddress addr : InetAddress.getAllByName(master.getHostname())) { if (addr.equals(localHost)) { return true; } } } catch (UnknownHostException e) { //logger.warn("Failed to compare if given master {} is local host: {}", master, e); return false; } return false; } }
122
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ApplicationSlaManagementEndpoint.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.master.endpoint.v2.rest; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; 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.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.netflix.titus.api.endpoint.v2.rest.representation.ApplicationSlaRepresentation; /** * REST endpoint for application SLA management. See {@link ApplicationSlaRepresentation} for more information. * <p> * <h1>Application with no associated SLA</h1> * If an application has no associated SLA, created via this API, it will be assigned to the default group. * This group is associated with a virtual 'default' application. The 'default' application's SLA can be managed * as any other via this REST API. * <p> * <h1>Persistence guarantees</h1> */ @Path(ApplicationSlaManagementEndpoint.PATH_API_V2_MANAGEMENT_APPLICATIONS) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public interface ApplicationSlaManagementEndpoint { String PATH_API_V2_MANAGEMENT_APPLICATIONS = "/api/v2/management/applications"; String DEFAULT_APPLICATION = "DEFAULT"; /** * Returns all registered application SLAs. * * @return a collection of application SLAs or empty array if non present */ @GET List<ApplicationSlaRepresentation> getApplicationSLAs(@QueryParam("extended") boolean extended, @QueryParam("schedulerName") String schedulerName); /** * Returns application SLA data for a given application. * * @return HTTP 200, and application SLA in the response body or HTTP 404 if application SLA is not defined * for the given application */ @GET @Path("/{applicationName}") ApplicationSlaRepresentation getApplicationSLA(@PathParam("applicationName") String applicationName, @QueryParam("extended") boolean extended); /** * Adds a new SLA for an application. If SLA for the given application was already defined, it is overridden. * <p> * <h1>Input validation rules</h1> * <ul> * <li>an instance type is available for service jobs (for example must be m4.2xlarge only)</li> * <li>an instance count is within a configured limits: COUNT > 0 && COUNT < MAX_ALLOWED</li> * </ul> * * @return HTTP 204, and location to the newly created resource in 'Location' HTTP header. */ @POST Response addApplicationSLA(ApplicationSlaRepresentation applicationSLA); /** * Updates SLA for a given application. If SLA for the given application is not defined, returns 404. * * @return HTTP 204, and location to the update resource in 'Location' HTTP header. */ @PUT @Path("/{applicationName}") Response updateApplicationSLA(@PathParam("applicationName") String applicationName, ApplicationSlaRepresentation applicationSLA); /** * Removes existing application SLA. * * @return HTTP 200 or 404 if SLA for the given application was not defined */ @DELETE @Path("/{applicationName}") Response removeApplicationSLA(@PathParam("applicationName") String applicationName); }
123
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/LeaderResource.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.master.endpoint.v2.rest; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.netflix.titus.api.endpoint.v2.rest.representation.LeaderRepresentation; import com.netflix.titus.api.supervisor.service.MasterDescription; import com.netflix.titus.api.supervisor.service.MasterMonitor; /** * */ @Path(LeaderEndpoint.PATH_API_V2_LEADER) @Produces(MediaType.APPLICATION_JSON) @Singleton public class LeaderResource implements LeaderEndpoint { private final MasterMonitor masterMonitor; @Inject public LeaderResource(MasterMonitor masterMonitor) { this.masterMonitor = masterMonitor; } @GET public LeaderRepresentation getLeader() { MasterDescription masterDescription = masterMonitor.getLatestLeader(); LeaderRepresentation.Builder builder = LeaderRepresentation.newBuilder() .withHostname(masterDescription.getHostname()) .withHostIP(masterDescription.getHostIP()) .withApiPort(masterDescription.getApiPort()) .withApiStatusUri(masterDescription.getApiStatusUri()) .withCreateTime(masterDescription.getCreateTime()); return builder.build(); } }
124
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ResourceConsumptionEndpoint.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.master.endpoint.v2.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Internal REST API for exposing resource consumption information. */ @Path(ResourceConsumptionEndpoint.PATH_API_V2_RESOURCE_CONSUMPTION) @Produces(MediaType.APPLICATION_JSON) public interface ResourceConsumptionEndpoint { String PATH_API_V2_RESOURCE_CONSUMPTION = "/api/v2/resource/consumption"; @GET Response getSystemConsumption(); }
125
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/HealthCheckResource.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.master.endpoint.v2.rest; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.netflix.runtime.health.api.HealthCheckAggregator; import com.netflix.runtime.health.api.HealthCheckStatus; @Path("/health") @Singleton public class HealthCheckResource { private final HealthCheckAggregator healthCheck; @Inject public HealthCheckResource(HealthCheckAggregator healthCheck) { this.healthCheck = healthCheck; } @GET public Response doCheck() throws Exception { HealthCheckStatus healthCheckStatus = healthCheck.check().get(2, TimeUnit.SECONDS); if (healthCheckStatus.isHealthy()) { return Response.ok(healthCheckStatus).build(); } else { return Response.serverError().entity(healthCheckStatus).build(); } } }
126
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ResourceConsumptionResource.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.master.endpoint.v2.rest; import java.util.Optional; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.netflix.titus.master.service.management.CompositeResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumptionService; @Path(ResourceConsumptionEndpoint.PATH_API_V2_RESOURCE_CONSUMPTION) @Produces(MediaType.APPLICATION_JSON) @Singleton public class ResourceConsumptionResource implements ResourceConsumptionEndpoint { private final ResourceConsumptionService service; @Inject public ResourceConsumptionResource(ResourceConsumptionService service) { this.service = service; } @Override public Response getSystemConsumption() { Optional<CompositeResourceConsumption> systemConsumption = service.getSystemConsumption(); if (systemConsumption.isPresent()) { return Response.ok(systemConsumption.get()).build(); } return Response.status(Status.SERVICE_UNAVAILABLE).build(); } }
127
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/JerseyModule.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.master.endpoint.v2.rest; import java.util.function.UnaryOperator; import javax.inject.Named; import javax.inject.Singleton; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.governator.guice.jersey.GovernatorServletContainer; import com.netflix.governator.providers.Advises; import com.netflix.titus.common.framework.scheduler.endpoint.LocalSchedulerResource; import com.netflix.titus.master.endpoint.v2.rest.filter.LeaderRedirectingFilter; import com.netflix.titus.master.supervisor.endpoint.http.SupervisorResource; import com.netflix.titus.runtime.endpoint.common.rest.JsonMessageReaderWriter; import com.netflix.titus.runtime.endpoint.common.rest.RestServerConfiguration; import com.netflix.titus.runtime.endpoint.common.rest.TitusExceptionMapper; import com.netflix.titus.runtime.endpoint.common.rest.metric.ResettableInputStreamFilter; import com.netflix.titus.runtime.endpoint.common.rest.provider.InstrumentedResourceMethodDispatchAdapter; import com.netflix.titus.runtime.endpoint.fit.FitResource; import com.netflix.titus.runtime.endpoint.metadata.SimpleHttpCallMetadataResolver; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.guice.JerseyServletModule; /** * We use this module to wire up our endpoints. */ public class JerseyModule extends JerseyServletModule { @Override protected void configureServlets() { // Call metadata interceptor (see CallMetadataHeaders). filter("/api/v3/*").through(SimpleHttpCallMetadataResolver.CallMetadataInterceptorFilter.class); filter("/*").through(LeaderRedirectingFilter.class); filter("/*").through(ResettableInputStreamFilter.class); // This sets up Jersey to serve any found resources that start with the base path of "/*" serve("/*").with(GovernatorServletContainer.class); } @Provides @Singleton public RestServerConfiguration getRestServerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(RestServerConfiguration.class); } @Advises @Singleton @Named("governator") public UnaryOperator<DefaultResourceConfig> getConfig() { return config -> { // Providers config.getClasses().add(JsonMessageReaderWriter.class); config.getClasses().add(TitusExceptionMapper.class); config.getClasses().add(InstrumentedResourceMethodDispatchAdapter.class); // Runtime (diagnostic) resources config.getClasses().add(HealthCheckResource.class); config.getClasses().add(LeaderResource.class); config.getClasses().add(FitResource.class); config.getClasses().add(LocalSchedulerResource.class); config.getClasses().add(ServerStatusResource.class); config.getClasses().add(SupervisorResource.class); // V2 resources config.getClasses().add(ApplicationSlaManagementResource.class); config.getClasses().add(ResourceConsumptionResource.class); return config; }; } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } }
128
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ApplicationSlaManagementResource.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.master.endpoint.v2.rest; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.google.common.base.Strings; import com.netflix.titus.api.endpoint.v2.rest.representation.ApplicationSlaRepresentation; import com.netflix.titus.api.endpoint.v2.rest.representation.ReservationUsage; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.master.config.MasterConfiguration; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import io.swagger.annotations.Api; import static com.netflix.titus.master.endpoint.v2.rest.Representation2ModelConvertions.asCoreEntity; import static com.netflix.titus.master.endpoint.v2.rest.Representation2ModelConvertions.asRepresentation; @Api(tags = "SLA") @Path(ApplicationSlaManagementEndpoint.PATH_API_V2_MANAGEMENT_APPLICATIONS) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Singleton public class ApplicationSlaManagementResource implements ApplicationSlaManagementEndpoint { private final MasterConfiguration configuration; private final ApplicationSlaManagementService applicationSlaManagementService; private final ReservationUsageCalculator reservationUsageCalculator; @Context private HttpServletRequest httpServletRequest; @Inject public ApplicationSlaManagementResource(MasterConfiguration configuration, ApplicationSlaManagementService applicationSlaManagementService, ReservationUsageCalculator reservationUsageCalculator) { this.configuration = configuration; this.applicationSlaManagementService = applicationSlaManagementService; this.reservationUsageCalculator = reservationUsageCalculator; } @GET @Override public List<ApplicationSlaRepresentation> getApplicationSLAs(@QueryParam("extended") boolean extended, @QueryParam("schedulerName") String schedulerName) { List<ApplicationSlaRepresentation> result = new ArrayList<>(); String cellId = extended ? configuration.getCellName() : null; Map<String, ReservationUsage> usageMap = extended ? reservationUsageCalculator.buildUsage() : Collections.emptyMap(); Collection<ApplicationSLA> applicationSLAs; if (Strings.isNullOrEmpty(schedulerName)) { applicationSLAs = applicationSlaManagementService.getApplicationSLAs(); } else { applicationSLAs = applicationSlaManagementService.getApplicationSLAsForScheduler(schedulerName); } applicationSLAs.forEach(a -> result.add(asRepresentation(a, cellId, usageMap.get(a.getAppName())))); return result; } @GET @Path("/{applicationName}") @Override public ApplicationSlaRepresentation getApplicationSLA(@PathParam("applicationName") String applicationName, @QueryParam("extended") boolean extended) { ApplicationSLA applicationSLA = applicationSlaManagementService.getApplicationSLA(applicationName); if (applicationSLA == null) { throw new WebApplicationException(new IllegalArgumentException("SLA not defined for " + applicationName), Status.NOT_FOUND); } String cellId = extended ? configuration.getCellName() : null; ReservationUsage reservationUsage = extended ? reservationUsageCalculator.buildCapacityGroupUsage(applicationName) : null; return asRepresentation(applicationSLA, cellId, reservationUsage); } @POST @Override public Response addApplicationSLA(ApplicationSlaRepresentation applicationSLA) { ApplicationSLA existing = applicationSlaManagementService.getApplicationSLA(applicationSLA.getAppName()); if (existing != null) { throw new WebApplicationException( new IllegalStateException("Application SLA for " + applicationSLA.getAppName() + " already exist"), Status.CONFLICT ); } applicationSlaManagementService.addApplicationSLA(asCoreEntity(applicationSLA)).timeout(1, TimeUnit.MINUTES).toBlocking().firstOrDefault(null); return Response.created(URI.create(applicationSLA.getAppName())).build(); } @PUT @Path("/{applicationName}") @Override public Response updateApplicationSLA(@PathParam("applicationName") String applicationName, ApplicationSlaRepresentation applicationSLA) { if (!applicationName.equals(applicationSLA.getAppName())) { throw new IllegalArgumentException("application name in path different from appName in the request body"); } ApplicationSLA existing = applicationSlaManagementService.getApplicationSLA(applicationSLA.getAppName()); if (existing == null) { throw new WebApplicationException(new IllegalArgumentException("SLA not defined for " + applicationName), Status.NOT_FOUND); } applicationSlaManagementService.addApplicationSLA(asCoreEntity(applicationSLA)).timeout(1, TimeUnit.MINUTES).toBlocking().firstOrDefault(null); return Response.status(Status.NO_CONTENT).build(); } @DELETE @Path("/{applicationName}") @Override public Response removeApplicationSLA(@PathParam("applicationName") String applicationName) { if (DEFAULT_APPLICATION.equals(applicationName)) { throw new WebApplicationException(new IllegalArgumentException("DEFAULT application SLA cannot be removed"), Status.BAD_REQUEST); } ApplicationSLA existing = applicationSlaManagementService.getApplicationSLA(applicationName); if (existing == null) { throw new WebApplicationException(new IllegalArgumentException("SLA not defined for " + applicationName), Status.NOT_FOUND); } applicationSlaManagementService.removeApplicationSLA(applicationName).timeout(1, TimeUnit.MINUTES).toBlocking().firstOrDefault(null); return Response.status(Status.NO_CONTENT).location(URI.create(PATH_API_V2_MANAGEMENT_APPLICATIONS + '/' + applicationName)).build(); } }
129
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/LeaderEndpoint.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.master.endpoint.v2.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.netflix.titus.api.endpoint.v2.rest.representation.LeaderRepresentation; /** * Provides information about current TitusMaster leader. */ @Path(LeaderEndpoint.PATH_API_V2_LEADER) @Produces(MediaType.APPLICATION_JSON) public interface LeaderEndpoint { String PATH_API_V2_LEADER = "/api/v2/leader"; @GET LeaderRepresentation getLeader(); }
130
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/ServerStatusResource.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.master.endpoint.v2.rest; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.google.protobuf.util.Durations; import com.google.protobuf.util.Timestamps; import com.netflix.titus.api.endpoint.v2.rest.representation.ServerStatusRepresentation; import com.netflix.titus.common.util.DateTimeExt; import com.netflix.titus.grpc.protogen.HealthCheckResponse.Details; import com.netflix.titus.grpc.protogen.HealthCheckResponse.ServingStatus; import com.netflix.titus.grpc.protogen.ServiceActivation; import com.netflix.titus.master.health.service.HealthService; /** * Provides local server status information. */ @Path(ServerStatusResource.PATH_API_V2_STATUS) @Produces(MediaType.APPLICATION_JSON) @Singleton public class ServerStatusResource { public static final String PATH_API_V2_STATUS = "/api/v2/status"; public static final String NOT_APPLICABLE = "N/A"; private final HealthService healthService; @Inject public ServerStatusResource(HealthService healthService) { this.healthService = healthService; } @GET public ServerStatusRepresentation getServerStatus() { Details details = healthService.getServerStatus(); if (details.getStatus() != ServingStatus.SERVING) { return new ServerStatusRepresentation( false, false, DateTimeExt.toTimeUnitString(details.getUptime()), NOT_APPLICABLE, NOT_APPLICABLE, NOT_APPLICABLE, Collections.emptyList(), Collections.emptyList() ); } List<ServerStatusRepresentation.ServiceActivation> sortedByActivationTime = details.getServiceActivationTimesList().stream() .sorted(Comparator.comparing(ServiceActivation::getActivationTime, Durations.comparator())) .map(s -> new ServerStatusRepresentation.ServiceActivation(s.getName(), DateTimeExt.toTimeUnitString(s.getActivationTime()))) .collect(Collectors.toList()); List<String> namesSortedByActivationTimestamp = details.getServiceActivationTimesList().stream() .map(ServiceActivation::getName) .collect(Collectors.toList()); return new ServerStatusRepresentation( details.getLeader(), details.getActive(), DateTimeExt.toTimeUnitString(details.getUptime()), Timestamps.toString(details.getElectionTimestamp()), Timestamps.toString(details.getActivationTimestamp()), details.getActive() ? DateTimeExt.toTimeUnitString(details.getActivationTime()) : NOT_APPLICABLE, sortedByActivationTime, namesSortedByActivationTimestamp ); } }
131
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/v2/rest/filter/LeaderRedirectingFilter.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.master.endpoint.v2.rest.filter; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.titus.api.supervisor.service.LeaderActivator; import com.netflix.titus.api.supervisor.service.MasterDescription; import com.netflix.titus.api.supervisor.service.MasterMonitor; import com.netflix.titus.master.config.MasterConfiguration; import com.netflix.titus.master.endpoint.v2.rest.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.common.util.CollectionsExt.asSet; @Singleton public class LeaderRedirectingFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(LeaderRedirectingFilter.class); private static final Set<String> ALWAYS_OPEN_PATHS = asSet( "/api/v2/leader", "/api/v2/status", "/api/v3/supervisor", "/health", "/api/diagnostic" ); private final MasterConfiguration config; private final MasterMonitor masterMonitor; private final LeaderActivator leaderActivator; @Inject public LeaderRedirectingFilter(MasterConfiguration config, MasterMonitor masterMonitor, LeaderActivator leaderActivator) { this.config = config; this.masterMonitor = masterMonitor; this.leaderActivator = leaderActivator; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; String requestURI = ((HttpServletRequest) request).getRequestURI(); boolean alwaysOpen = ALWAYS_OPEN_PATHS.stream().anyMatch(requestURI::contains); if (alwaysOpen) { chain.doFilter(request, response); } else if (isLocal() || leaderActivator.isLeader()) { if (leaderActivator.isActivated()) { chain.doFilter(request, response); } else { httpResponse.setStatus(503); } } else { URI redirectUri = getRedirectUri((HttpServletRequest) request, masterMonitor.getLatestLeader()); logger.info("Redirecting to {}", redirectUri.toURL()); httpResponse.sendRedirect(redirectUri.toURL().toString()); } } private URI getRedirectUri(HttpServletRequest request, MasterDescription leaderInfo) { URI requestUri; try { requestUri = new URI(request.getRequestURL().toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("The request has invalid URI: " + e.getMessage(), e); } try { return new URI( requestUri.getScheme(), requestUri.getUserInfo(), leaderInfo.getHostname(), leaderInfo.getApiPort(), requestUri.getPath(), requestUri.getQuery(), requestUri.getFragment() ); } catch (URISyntaxException e) { throw new IllegalArgumentException("Failed to construct redirect URI: " + e.getMessage(), e); } } @Override public void destroy() { } private boolean isLocal() { return config.isLocalMode() || Util.isLocalHost(masterMonitor.getLatestLeader()); } }
132
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/common/ContextResolver.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.master.endpoint.common; import java.util.Map; /** * Provides supplementary information about job execution context. */ public interface ContextResolver { Map<String, Object> resolveContext(String jobId); }
133
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/common/EmptyContextResolver.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.master.endpoint.common; import java.util.Collections; import java.util.Map; import javax.inject.Singleton; @Singleton public class EmptyContextResolver implements ContextResolver { public static final ContextResolver INSTANCE = new EmptyContextResolver(); @Override public Map<String, Object> resolveContext(String jobId) { return Collections.emptyMap(); } }
134
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/common/CellDecorator.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.master.endpoint.common; import java.util.function.Supplier; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.grpc.protogen.JobDescriptor; public class CellDecorator { private final Supplier<String> cellNameSupplier; public CellDecorator(Supplier<String> cellNameSupplier) { this.cellNameSupplier = cellNameSupplier; } /** * Adds a {@link JobAttributes#JOB_ATTRIBUTES_CELL "titus.cell"} attribute to a {@link JobDescriptor V3 job spec}, * replacing the existing value if it is already present. */ public JobDescriptor ensureCellInfo(JobDescriptor jobDescriptor) { final String cellName = cellNameSupplier.get(); return jobDescriptor.toBuilder() .putAttributes(JobAttributes.JOB_ATTRIBUTES_CELL, cellName) .build(); } }
135
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/common/grpc
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/endpoint/common/grpc/interceptor/LeaderServerInterceptor.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.master.endpoint.common.grpc.interceptor; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc; import com.netflix.titus.api.supervisor.service.LeaderActivator; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; /** * Interceptor that that blocks all grpc calls until the system is ready. */ @Singleton public final class LeaderServerInterceptor implements ServerInterceptor { private final LeaderActivator leaderActivator; @Inject public LeaderServerInterceptor(LeaderActivator leaderActivator) { this.leaderActivator = leaderActivator; } @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { if (SupervisorServiceGrpc.getServiceDescriptor().getMethods().contains(call.getMethodDescriptor())) { // Supervisor API calls are not restricted to the active leader. return next.startCall(call, headers); } if (leaderActivator.isLeader()) { if (leaderActivator.isActivated()) { return next.startCall(call, headers); } else { call.close(Status.UNAVAILABLE.withDescription("Titus Master is initializing and not yet available."), new Metadata()); return new ServerCall.Listener<ReqT>() { }; } } else { call.close(Status.UNAVAILABLE.withDescription("Titus Master is not leader."), new Metadata()); return new ServerCall.Listener<ReqT>() { }; } } }
136
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/model/ResourceDimensions.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.master.model; import java.util.Collection; import com.google.common.base.Preconditions; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.common.aws.AwsInstanceDescriptor; import com.netflix.titus.common.aws.AwsInstanceType; import com.netflix.titus.common.util.tuple.Pair; import static com.netflix.titus.common.util.CollectionsExt.isNullOrEmpty; /** * {@link ResourceDimension} related functions. */ public class ResourceDimensions { /** * Returns a new {@link ResourceDimension} instance with resources being some of all the provided. */ public static ResourceDimension add(ResourceDimension... parts) { if (isNullOrEmpty(parts)) { return ResourceDimension.empty(); } double cpuSum = 0; long memorySum = 0; long diskSum = 0; long networkSum = 0; long gpuSum = 0; long opportunisticCpuSum = 0; for (ResourceDimension part : parts) { cpuSum += part.getCpu(); memorySum += part.getMemoryMB(); diskSum += part.getDiskMB(); networkSum += part.getNetworkMbs(); gpuSum += part.getGpu(); opportunisticCpuSum += part.getOpportunisticCpu(); } return ResourceDimension.newBuilder() .withCpus(cpuSum) .withMemoryMB(memorySum) .withDiskMB(diskSum) .withNetworkMbs(networkSum) .withGpu(gpuSum) .withOpportunisticCpus(opportunisticCpuSum) .build(); } /** * Returns a new {@link ResourceDimension} instance with resources being some of all the provided. */ public static ResourceDimension add(Collection<ResourceDimension> parts) { return isNullOrEmpty(parts) ? ResourceDimension.empty() : add(parts.toArray(new ResourceDimension[parts.size()])); } /** * Subtract resources. If right side resource value (CPU, memory, etc) is greater than the left side, set it to 0. * * @throws IllegalArgumentException if left side resources are smaller then the right side */ public static ResourceDimension subtractPositive(ResourceDimension left, ResourceDimension right) { return ResourceDimension.newBuilder() .withCpus(Math.max(0, left.getCpu() - right.getCpu())) .withMemoryMB(Math.max(0, left.getMemoryMB() - right.getMemoryMB())) .withDiskMB(Math.max(0, left.getDiskMB() - right.getDiskMB())) .withNetworkMbs(Math.max(0, left.getNetworkMbs() - right.getNetworkMbs())) .withGpu(Math.max(0, left.getGpu() - right.getGpu())) .withOpportunisticCpus(Math.max(0, left.getOpportunisticCpu() - right.getOpportunisticCpu())) .build(); } /** * Multiple all resources of the {@link ResourceDimension} instance by the given number. */ public static ResourceDimension multiply(ResourceDimension base, double multiplier) { return ResourceDimension.newBuilder() .withCpus(base.getCpu() * multiplier) .withMemoryMB((long) Math.ceil(base.getMemoryMB() * multiplier)) .withDiskMB((long) Math.ceil(base.getDiskMB() * multiplier)) .withNetworkMbs((long) Math.ceil(base.getNetworkMbs() * multiplier)) .withGpu((long) Math.ceil(base.getGpu() * multiplier)) .withOpportunisticCpus((long) Math.ceil(base.getOpportunisticCpu() * multiplier)) .build(); } public static Pair<Long, ResourceDimension> divide(ResourceDimension left, ResourceDimension right) { double multiplier = 0; if (left.getCpu() != 0) { Preconditions.checkArgument(right.getCpu() != 0, "CPU: division by 0"); multiplier = left.getCpu() / right.getCpu(); } if (left.getMemoryMB() != 0) { Preconditions.checkArgument(right.getMemoryMB() != 0, "MemoryMB: division by 0"); multiplier = Math.max(multiplier, left.getMemoryMB() / right.getMemoryMB()); } if (left.getDiskMB() != 0) { Preconditions.checkArgument(right.getDiskMB() != 0, "DiskMB: division by 0"); multiplier = Math.max(multiplier, left.getDiskMB() / right.getDiskMB()); } if (left.getNetworkMbs() != 0) { Preconditions.checkArgument(right.getNetworkMbs() != 0, "NetworkMbs: division by 0"); multiplier = Math.max(multiplier, left.getNetworkMbs() / right.getNetworkMbs()); } if (left.getGpu() != 0) { Preconditions.checkArgument(right.getGpu() != 0, "GPU: division by 0"); multiplier = Math.max(multiplier, left.getGpu() / right.getGpu()); } if (left.getOpportunisticCpu() != 0) { Preconditions.checkArgument(right.getOpportunisticCpu() != 0, "Opportunistic CPU: division by 0"); multiplier = Math.max(multiplier, left.getOpportunisticCpu() / right.getOpportunisticCpu()); } if (multiplier == 0) { // left is empty return Pair.of(0L, ResourceDimension.empty()); } if (multiplier < 1) { // left < right return Pair.of(0L, left); } if (multiplier == 1) { return Pair.of(1L, ResourceDimension.empty()); } long full = (long) multiplier; return Pair.of(full, ResourceDimension.newBuilder() .withCpus(Math.max(0, left.getCpu() - right.getCpu() * full)) .withMemoryMB(Math.max(0, left.getMemoryMB() - right.getMemoryMB() * full)) .withDiskMB(Math.max(0, left.getDiskMB() - right.getDiskMB() * full)) .withNetworkMbs(Math.max(0, left.getNetworkMbs() - right.getNetworkMbs() * full)) .withGpu(Math.max(0, left.getGpu() - right.getGpu() * full)) .withOpportunisticCpus(Math.max(0, left.getOpportunisticCpu() - right.getOpportunisticCpu() * full)) .build() ); } public static long divideAndRoundUp(ResourceDimension left, ResourceDimension right) { Pair<Long, ResourceDimension> result = divide(left, right); return result.getRight().equals(ResourceDimension.empty()) ? result.getLeft() : result.getLeft() + 1; } /** * Align source {@link ResourceDimension} resources, to match resource ratios (cpu and memory) from the reference * entity, by adding additional allocations where needed. */ public static ResourceDimension alignUp(ResourceDimension source, ResourceDimension reference) { double cpuRatio = source.getCpu() / reference.getCpu(); double memoryRatio = source.getMemoryMB() / reference.getMemoryMB(); if (cpuRatio == memoryRatio) { return source; } if (cpuRatio > memoryRatio) { return ResourceDimension.newBuilder() .withCpus(source.getCpu()) .withMemoryMB((long) (reference.getMemoryMB() * cpuRatio)) .withDiskMB((long) (reference.getDiskMB() * cpuRatio)) .withNetworkMbs((long) (reference.getNetworkMbs() * cpuRatio)) .withGpu((long) (reference.getGpu() * cpuRatio)) .withOpportunisticCpus((long) (reference.getOpportunisticCpu() * cpuRatio)) .build(); } // memoryRatio > cpuRatio return ResourceDimension.newBuilder() .withCpus(reference.getCpu() * memoryRatio) .withMemoryMB(source.getMemoryMB()) .withDiskMB((long) (reference.getDiskMB() * memoryRatio)) .withNetworkMbs((long) (reference.getNetworkMbs() * memoryRatio)) .withGpu((long) (reference.getGpu() * memoryRatio)) .withOpportunisticCpus((long) (reference.getOpportunisticCpu() * memoryRatio)) .build(); } /** * Check if all resources from the second argument are below or equal to resources from the first argument. */ public static boolean isBigger(ResourceDimension dimension, ResourceDimension subDimension) { return dimension.getCpu() >= subDimension.getCpu() && dimension.getMemoryMB() >= subDimension.getMemoryMB() && dimension.getDiskMB() >= subDimension.getDiskMB() && dimension.getNetworkMbs() >= subDimension.getNetworkMbs() && dimension.getGpu() >= subDimension.getGpu() && dimension.getOpportunisticCpu() >= subDimension.getOpportunisticCpu(); } public static StringBuilder format(ResourceDimension input, StringBuilder output) { output.append("[cpu=").append(input.getCpu()); output.append(", memoryMB=").append(input.getMemoryMB()); output.append(", diskMB=").append(input.getDiskMB()); output.append(", networkMbs=").append(input.getNetworkMbs()); output.append(", gpu=").append(input.getGpu()); output.append(", opportunisticCpu=").append(input.getOpportunisticCpu()); output.append(']'); return output; } public static String format(ResourceDimension input) { return format(input, new StringBuilder()).toString(); } public static ResourceDimension fromAwsInstanceType(AwsInstanceType instanceType) { AwsInstanceDescriptor descriptor = instanceType.getDescriptor(); return ResourceDimension.newBuilder() .withCpus(descriptor.getvCPUs()) .withGpu(descriptor.getvGPUs()) .withMemoryMB(descriptor.getMemoryGB() * 1024) .withDiskMB(descriptor.getStorageGB() * 1024) .withNetworkMbs(descriptor.getNetworkMbs()) .build(); } }
137
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/CapacityManagementAttributes.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.master.service.management; /** * Collection of capacity management related attributes that can be associated with agent instance groups and agent instances. */ public final class CapacityManagementAttributes { /** * Mark an instance group such that capacity management will ignore the instance group when doing its operations. */ public static final String IGNORE = "titus.capacityManagement.ignore"; }
138
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ResourceConsumption.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.master.service.management; import java.util.Map; import com.netflix.titus.api.model.ResourceDimension; /** * Hierarchical resource consumption, which is system / tiers / capacity groups / applications. */ public class ResourceConsumption { public static final String SYSTEM_CONSUMER = "system"; public enum ConsumptionLevel {System, Tier, CapacityGroup, Application, InstanceType} private final String consumerName; private final ConsumptionLevel consumptionLevel; private final ResourceDimension currentConsumption; private final ResourceDimension maxConsumption; private final Map<String, Object> attributes; public ResourceConsumption(String consumerName, ConsumptionLevel consumptionLevel, ResourceDimension currentConsumption, ResourceDimension maxConsumption, Map<String, Object> attributes) { this.consumerName = consumerName; this.consumptionLevel = consumptionLevel; this.currentConsumption = currentConsumption; this.maxConsumption = maxConsumption; this.attributes = attributes; } public String getConsumerName() { return consumerName; } public ConsumptionLevel getConsumptionLevel() { return consumptionLevel; } public ResourceDimension getCurrentConsumption() { return currentConsumption; } public ResourceDimension getMaxConsumption() { return maxConsumption; } public Map<String, Object> getAttributes() { return attributes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceConsumption that = (ResourceConsumption) o; if (consumerName != null ? !consumerName.equals(that.consumerName) : that.consumerName != null) { return false; } if (consumptionLevel != that.consumptionLevel) { return false; } if (currentConsumption != null ? !currentConsumption.equals(that.currentConsumption) : that.currentConsumption != null) { return false; } if (maxConsumption != null ? !maxConsumption.equals(that.maxConsumption) : that.maxConsumption != null) { return false; } return attributes != null ? attributes.equals(that.attributes) : that.attributes == null; } @Override public int hashCode() { int result = consumerName != null ? consumerName.hashCode() : 0; result = 31 * result + (consumptionLevel != null ? consumptionLevel.hashCode() : 0); result = 31 * result + (currentConsumption != null ? currentConsumption.hashCode() : 0); result = 31 * result + (maxConsumption != null ? maxConsumption.hashCode() : 0); result = 31 * result + (attributes != null ? attributes.hashCode() : 0); return result; } @Override public String toString() { return "ResourceConsumption{" + "consumerName='" + consumerName + '\'' + ", consumptionLevel=" + consumptionLevel + ", currentConsumption=" + currentConsumption + ", maxConsumption=" + maxConsumption + ", attributes=" + attributes + '}'; } }
139
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ManagementModule.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.master.service.management; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.master.service.management.internal.DefaultResourceConsumptionService; import com.netflix.titus.master.service.management.internal.ResourceConsumptionLog; import com.netflix.titus.master.service.management.kube.KubeApplicationSlaManagementService; public class ManagementModule extends AbstractModule { @Override protected void configure() { bind(ApplicationSlaManagementService.class).to(KubeApplicationSlaManagementService.class); // Resource consumption monitoring bind(ResourceConsumptionService.class).to(DefaultResourceConsumptionService.class).asEagerSingleton(); bind(ResourceConsumptionLog.class).asEagerSingleton(); } @Provides @Singleton public CapacityManagementConfiguration getCapacityManagementConfiguration(ConfigProxyFactory factory) { return factory.newProxy(CapacityManagementConfiguration.class); } }
140
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ApplicationSlaManagementService.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.master.service.management; import java.util.Collection; import java.util.Optional; import com.netflix.titus.api.model.ApplicationSLA; import rx.Observable; /** * Application SLA management service. This interface is the primary interaction point between server endpoints * (REST, GRPC), and the core subsystem. */ public interface ApplicationSlaManagementService { String DEFAULT_APPLICATION = "DEFAULT"; Collection<ApplicationSLA> getApplicationSLAs(); Collection<ApplicationSLA> getApplicationSLAsForScheduler(String schedulerName); Optional<ApplicationSLA> findApplicationSLA(String applicationName); ApplicationSLA getApplicationSLA(String applicationName); Observable<Void> addApplicationSLA(ApplicationSLA applicationSLA); Observable<Void> removeApplicationSLA(String applicationName); }
141
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/CompositeResourceConsumption.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.master.service.management; import java.util.Collections; import java.util.Map; import com.netflix.titus.api.model.ResourceDimension; /** */ public class CompositeResourceConsumption extends ResourceConsumption { private final Map<String, ResourceConsumption> contributors; private final ResourceDimension allowedConsumption; private final boolean aboveLimit; public CompositeResourceConsumption(String consumerName, ConsumptionLevel consumptionLevel, ResourceDimension currentConsumption, ResourceDimension maxConsumption, ResourceDimension allowedConsumption, Map<String, Object> attributes, Map<String, ResourceConsumption> contributors, boolean aboveLimit) { super(consumerName, consumptionLevel, currentConsumption, maxConsumption, attributes); this.contributors = contributors; this.allowedConsumption = allowedConsumption; this.aboveLimit = aboveLimit; } public Map<String, ResourceConsumption> getContributors() { return contributors; } public ResourceDimension getAllowedConsumption() { return allowedConsumption; } public boolean isAboveLimit() { return aboveLimit; } @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; } CompositeResourceConsumption that = (CompositeResourceConsumption) o; if (aboveLimit != that.aboveLimit) { return false; } if (contributors != null ? !contributors.equals(that.contributors) : that.contributors != null) { return false; } return allowedConsumption != null ? allowedConsumption.equals(that.allowedConsumption) : that.allowedConsumption == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (contributors != null ? contributors.hashCode() : 0); result = 31 * result + (allowedConsumption != null ? allowedConsumption.hashCode() : 0); result = 31 * result + (aboveLimit ? 1 : 0); return result; } @Override public String toString() { return "CompositeResourceConsumption{" + "consumerName='" + getConsumerName() + '\'' + ", consumptionLevel=" + getConsumptionLevel() + ", currentConsumption=" + getCurrentConsumption() + ", maxConsumption=" + getMaxConsumption() + ", attributes=" + getAttributes() + "contributors=" + contributors + ", allowedConsumption=" + allowedConsumption + ", aboveLimit=" + aboveLimit + '}'; } public static CompositeResourceConsumption unused(String consumerName, ConsumptionLevel consumptionLevel, ResourceDimension allowedConsumption) { return new CompositeResourceConsumption( consumerName, consumptionLevel, ResourceDimension.empty(), ResourceDimension.empty(), allowedConsumption, Collections.emptyMap(), Collections.emptyMap(), false ); } }
142
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ResourceConsumptionService.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.master.service.management; import java.util.Optional; import rx.Observable; /** * A service that observers resource utilization by jobs, and checks if configured SLAs are not violated. */ public interface ResourceConsumptionService { /** * Returns current system-level resource consumption. The return object is a composite, that provides * further details at tier, capacity group and application levels. * * @return non-null value if system consumption data are available */ Optional<CompositeResourceConsumption> getSystemConsumption(); /** * Returns an observable that emits an item for each capacity category with its current resource utilization. * On subscribe emits a single item for each known category, followed by updates caused by either resource * consumption change or SLA update. */ Observable<ResourceConsumptionEvents.ResourceConsumptionEvent> resourceConsumptionEvents(); }
143
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ResourceConsumptions.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.master.service.management; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.base.Preconditions; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.master.model.ResourceDimensions; import static java.util.Arrays.asList; public final class ResourceConsumptions { private ResourceConsumptions() { } /** * Find {@link ResourceConsumption} instance in the consumption hierarchy. */ public static Optional<ResourceConsumption> findConsumption(ResourceConsumption parent, String... path) { ResourceConsumption current = parent; for (String segment : path) { if (!(current instanceof CompositeResourceConsumption)) { return Optional.empty(); } current = ((CompositeResourceConsumption) current).getContributors().get(segment); if (current == null) { return Optional.empty(); } } return Optional.of(current); } /** * Find all {@link ResourceConsumption} instances at a specific consumption level. */ public static Map<String, ResourceConsumption> groupBy(CompositeResourceConsumption parent, ResourceConsumption.ConsumptionLevel level) { Preconditions.checkArgument(parent.getConsumptionLevel().ordinal() <= level.ordinal()); if (parent.getConsumptionLevel() == level) { return Collections.singletonMap(parent.getConsumerName(), parent); } // If this is the Application level, the next one needs to be the InstanceType level, which is the last one if (parent.getConsumptionLevel() == ResourceConsumption.ConsumptionLevel.Application) { Preconditions.checkArgument(level == ResourceConsumption.ConsumptionLevel.InstanceType); return parent.getContributors(); } Map<String, ResourceConsumption> result = new HashMap<>(); for (ResourceConsumption nested : parent.getContributors().values()) { result.putAll(groupBy((CompositeResourceConsumption) nested, level)); } return result; } /** * Add a collection of {@link ResourceConsumption} values of the same kind (the same consumption name and level). * * @return aggregated value of the same type as the input */ public static <C extends ResourceConsumption> C add(Collection<C> consumptions) { verifySameKind(consumptions); List<C> consumptionList = new ArrayList<>(consumptions); if (consumptionList.size() == 1) { return consumptionList.get(0); } ResourceDimension currentUsage = addCurrentConsumptions(consumptionList); ResourceDimension maxUsage = addMaxConsumptions(consumptionList); Map<String, Object> mergedAttrs = mergeAttributesOf(consumptions); C first = consumptionList.get(0); if (first instanceof CompositeResourceConsumption) { Map<String, ResourceConsumption> mergedContributors = new HashMap<>(); consumptionList.stream() .map(CompositeResourceConsumption.class::cast) .flatMap(c -> c.getContributors().entrySet().stream()) .forEach(entry -> mergedContributors.compute(entry.getKey(), (name, current) -> current == null ? entry.getValue() : ResourceConsumptions.add(current, entry.getValue()) )); ResourceDimension allowedUsage = addAllowedConsumptions((Collection<CompositeResourceConsumption>) consumptionList); return (C) new CompositeResourceConsumption( first.getConsumerName(), first.getConsumptionLevel(), currentUsage, maxUsage, allowedUsage, mergedAttrs, mergedContributors, !ResourceDimensions.isBigger(allowedUsage, maxUsage) ); } return (C) new ResourceConsumption( first.getConsumerName(), first.getConsumptionLevel(), currentUsage, maxUsage, mergedAttrs ); } /** * See {@link #add(Collection)} for description. */ public static ResourceConsumption add(ResourceConsumption... consumptions) { return add(asList(consumptions)); } /** * Create a parent {@link CompositeResourceConsumption} instance from the provided consumption collection. */ public static CompositeResourceConsumption aggregate(String parentName, ResourceConsumption.ConsumptionLevel parentLevel, Collection<? extends ResourceConsumption> consumptions, ResourceDimension allowedUsage) { Map<String, ResourceConsumption> contributors = new HashMap<>(); consumptions.forEach(c -> contributors.put(c.getConsumerName(), c)); ResourceDimension currentUsage = addCurrentConsumptions(consumptions); ResourceDimension maxUsage = addMaxConsumptions(consumptions); Map<String, Object> mergedAttrs = mergeAttributesOf(consumptions); return new CompositeResourceConsumption( parentName, parentLevel, currentUsage, maxUsage, allowedUsage, mergedAttrs, contributors, !ResourceDimensions.isBigger(allowedUsage, maxUsage) ); } public static CompositeResourceConsumption aggregate(String parentName, ResourceConsumption.ConsumptionLevel parentLevel, Collection<CompositeResourceConsumption> consumptions) { ResourceDimension allowedUsage = addAllowedConsumptions(consumptions); return aggregate(parentName, parentLevel, consumptions, allowedUsage); } public static <C extends ResourceConsumption> ResourceDimension addCurrentConsumptions(Collection<C> consumptions) { List<ResourceDimension> all = consumptions.stream().map(ResourceConsumption::getCurrentConsumption).collect(Collectors.toList()); return ResourceDimensions.add(all); } public static <C extends ResourceConsumption> ResourceDimension addMaxConsumptions(Collection<C> consumptions) { List<ResourceDimension> all = consumptions.stream().map(ResourceConsumption::getMaxConsumption).collect(Collectors.toList()); return ResourceDimensions.add(all); } public static ResourceDimension addAllowedConsumptions(Collection<CompositeResourceConsumption> consumptions) { List<ResourceDimension> all = consumptions.stream().map(CompositeResourceConsumption::getAllowedConsumption).collect(Collectors.toList()); return ResourceDimensions.add(all); } public static Map<String, Object> mergeAttributes(Collection<Map<String, Object>> attrCollection) { Map<String, Object> result = new HashMap<>(); attrCollection.stream().flatMap(ac -> ac.entrySet().stream()).forEach(entry -> { Object effectiveValue = entry.getValue(); if (result.containsKey(entry.getKey()) && effectiveValue instanceof Integer) { try { effectiveValue = ((Integer) effectiveValue).intValue() + ((Integer) result.get(entry.getKey())).intValue(); } catch (Exception ignore) { // This is best effort only } } result.put(entry.getKey(), effectiveValue); }); return result; } public static Map<String, Object> mergeAttributesOf(Collection<? extends ResourceConsumption> attrCollection) { return mergeAttributes(attrCollection.stream().map(ResourceConsumption::getAttributes).collect(Collectors.toList())); } private static <C extends ResourceConsumption> void verifySameKind(Collection<C> consumptions) { Preconditions.checkArgument(!consumptions.isEmpty(), "Empty argument list"); Iterator<C> it = consumptions.iterator(); C ref = it.next(); if (!it.hasNext()) { return; } while (it.hasNext()) { C second = it.next(); Preconditions.checkArgument(ref.getConsumerName().equals(second.getConsumerName()), "Consumer names different %s != %s", ref.getConsumerName(), second.getConsumerName()); Preconditions.checkArgument(ref.getConsumptionLevel().equals(second.getConsumptionLevel()), "Consumption levels different %s != %s", ref.getConsumptionLevel(), second.getConsumptionLevel()); } } }
144
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/InMemoryApplicationSlaManagementService.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.api.model.Tier; import com.netflix.titus.api.service.TitusServiceException; import rx.Observable; @Singleton public class InMemoryApplicationSlaManagementService implements ApplicationSlaManagementService { private final ConcurrentMap<String, ApplicationSLA> capacityGroups = new ConcurrentHashMap<>(); @Inject public InMemoryApplicationSlaManagementService(CapacityManagementConfiguration configuration) { ApplicationSLA defaultCapacityGroup = buildDefaultApplicationSLA(configuration); capacityGroups.put(defaultCapacityGroup.getAppName(), defaultCapacityGroup); } private ApplicationSLA buildDefaultApplicationSLA(CapacityManagementConfiguration configuration) { CapacityManagementConfiguration.ResourceDimensionConfiguration rdConf = configuration.getDefaultApplicationResourceDimension(); return ApplicationSLA.newBuilder() .withAppName(ApplicationSlaManagementService.DEFAULT_APPLICATION) .withTier(Tier.Flex) .withSchedulerName(configuration.getDefaultSchedulerName()) .withResourcePool("") .withInstanceCount(configuration.getDefaultApplicationInstanceCount()) .withResourceDimension(ResourceDimension.newBuilder() .withCpus(rdConf.getCPU()) .withMemoryMB(rdConf.getMemoryMB()) .withDiskMB(rdConf.getDiskMB()) .withNetworkMbs(rdConf.getNetworkMbs()) .build() ) .build(); } @Override public Collection<ApplicationSLA> getApplicationSLAs() { return new ArrayList<>(capacityGroups.values()); } @Override public Collection<ApplicationSLA> getApplicationSLAsForScheduler(String schedulerName) { return capacityGroups.values().stream() .filter(c -> schedulerName.equals(c.getSchedulerName())) .collect(Collectors.toList()); } @Override public Optional<ApplicationSLA> findApplicationSLA(String applicationName) { return Optional.ofNullable(capacityGroups.get(applicationName)); } @Override public ApplicationSLA getApplicationSLA(String applicationName) { return findApplicationSLA(applicationName).orElse(null); } @Override public Observable<Void> addApplicationSLA(ApplicationSLA applicationSLA) { return Observable.defer(() -> { capacityGroups.put(applicationSLA.getAppName(), applicationSLA); return Observable.empty(); }); } @Override public Observable<Void> removeApplicationSLA(String applicationName) { return Observable.defer(() -> { capacityGroups.remove(applicationName); return Observable.empty(); }); } }
145
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/ResourceConsumptionEvents.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.master.service.management; /** */ public class ResourceConsumptionEvents { public abstract static class ResourceConsumptionEvent { private final String capacityGroup; private final long timestamp; public ResourceConsumptionEvent(String capacityGroup, long timestamp) { this.capacityGroup = capacityGroup; this.timestamp = timestamp; } public String getCapacityGroup() { return capacityGroup; } public long getTimestamp() { return timestamp; } } /** * Objects of this class represent a resource utilization for a capacity category at a point in time. */ public static class CapacityGroupAllocationEvent extends ResourceConsumptionEvent { private final CompositeResourceConsumption capacityGroupConsumption; public CapacityGroupAllocationEvent(String capacityGroup, long timestamp, CompositeResourceConsumption capacityGroupConsumption) { super(capacityGroup, timestamp); this.capacityGroupConsumption = capacityGroupConsumption; } public CompositeResourceConsumption getCapacityGroupConsumption() { return capacityGroupConsumption; } } public static class CapacityGroupUndefinedEvent extends ResourceConsumptionEvent { public CapacityGroupUndefinedEvent(String capacityGroup, long timestamp) { super(capacityGroup, timestamp); } } public static class CapacityGroupRemovedEvent extends ResourceConsumptionEvent { public CapacityGroupRemovedEvent(String capacityGroup, long timestamp) { super(capacityGroup, timestamp); } } }
146
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/CapacityManagementConfiguration.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.master.service.management; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.master.capacityManagement") public interface CapacityManagementConfiguration { interface ResourceDimensionConfiguration { @DefaultValue("2") double getCPU(); @DefaultValue("4096") int getMemoryMB(); @DefaultValue("10000") int getDiskMB(); @DefaultValue("128") int getNetworkMbs(); } /** * If 'default' application is not defined, it will be transparently created with the configured resource * dimensions. */ ResourceDimensionConfiguration getDefaultApplicationResourceDimension(); /** * If 'DEFAULT' application is not defined, it will be transparently created with the configured instance count. */ @DefaultValue("10") int getDefaultApplicationInstanceCount(); @DefaultValue("fenzo") String getDefaultSchedulerName(); }
147
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/internal/DefaultResourceConsumptionService.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.master.service.management.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.common.util.guice.ProxyType; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.ProxyConfiguration; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.master.MetricConstants; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import com.netflix.titus.master.service.management.CompositeResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption.ConsumptionLevel; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupAllocationEvent; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupRemovedEvent; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupUndefinedEvent; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.ResourceConsumptionEvent; import com.netflix.titus.master.service.management.ResourceConsumptionService; import com.netflix.titus.master.service.management.ResourceConsumptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import static com.netflix.titus.common.util.CollectionsExt.copyAndRemove; /** * Periodically checks for SLA violations, and a pre-configured interval. * * @TODO Improve this implementation by immediately reacting to state changes in the system. */ @Singleton @ProxyConfiguration(types = ProxyType.ActiveGuard) public class DefaultResourceConsumptionService implements ResourceConsumptionService { private static final Logger logger = LoggerFactory.getLogger(DefaultResourceConsumptionService.class); private static final String METRIC_CONSUMPTION = MetricConstants.METRIC_CAPACITY_MANAGEMENT + "consumption."; static final long UPDATE_INTERVAL_MS = 5000; private final Supplier<ConsumptionEvaluationResult> evaluator; private final Registry registry; private final Scheduler.Worker worker; private ResourceConsumptionServiceMetrics metrics; private Subscription subscription; private final PublishSubject<ResourceConsumptionEvent> eventsSubject = PublishSubject.create(); private volatile ConsumptionEvaluationResult latestEvaluation; @Inject public DefaultResourceConsumptionService(ApplicationSlaManagementService applicationSlaManagementService, V3JobOperations v3JobOperations, Registry registry) { this(ResourceConsumptionEvaluator.newEvaluator(applicationSlaManagementService, v3JobOperations), registry, Schedulers.computation()); } @VisibleForTesting DefaultResourceConsumptionService(Supplier<ConsumptionEvaluationResult> evaluator, Registry registry, Scheduler scheduler) { this.evaluator = evaluator; this.registry = registry; this.worker = scheduler.createWorker(); } @Activator public Observable<Void> enterActiveMode() { logger.info("Entering active mode"); this.metrics = new ResourceConsumptionServiceMetrics(registry.createId(METRIC_CONSUMPTION), registry); this.subscription = worker.schedulePeriodically(this::updateInfo, 0, UPDATE_INTERVAL_MS, TimeUnit.MILLISECONDS); return Observable.empty(); } @PreDestroy public void shutdown() { if (subscription != null) { subscription.unsubscribe(); } worker.unsubscribe(); eventsSubject.onCompleted(); } @Override public Optional<CompositeResourceConsumption> getSystemConsumption() { return latestEvaluation == null ? Optional.empty() : Optional.of(latestEvaluation.getSystemConsumption()); } @Override public Observable<ResourceConsumptionEvent> resourceConsumptionEvents() { return eventsSubject.compose(ObservableExt.head(() -> { if (latestEvaluation == null) { return Collections.emptyList(); } long now = worker.now(); List<ResourceConsumptionEvent> allEvents = new ArrayList<>(); // Capacity group consumptions Collection<ResourceConsumption> groupConsumptions = ResourceConsumptions.groupBy( latestEvaluation.getSystemConsumption(), ConsumptionLevel.CapacityGroup ).values(); groupConsumptions .forEach(consumption -> allEvents.add(new CapacityGroupAllocationEvent(consumption.getConsumerName(), now, (CompositeResourceConsumption) consumption)) ); // Undefined capacity groups latestEvaluation.getUndefinedCapacityGroups() .forEach(capacityGroup -> allEvents.add(new CapacityGroupUndefinedEvent(capacityGroup, now)) ); return allEvents; })); } private void updateInfo() { try { ConsumptionEvaluationResult evaluationResult = evaluator.get(); metrics.update(evaluationResult); ConsumptionEvaluationResult oldEvaluation = latestEvaluation; this.latestEvaluation = evaluationResult; if (eventsSubject.hasObservers()) { notifyAboutRemovedCapacityGroups(oldEvaluation); notifyAboutUndefinedCapacityGroups(oldEvaluation); notifyAboutResourceConsumptionChange(oldEvaluation); } } catch (Exception e) { logger.warn("Resource consumption update failure", e); } logger.debug("Resource consumption update finished"); } private void notifyAboutRemovedCapacityGroups(ConsumptionEvaluationResult oldEvaluation) { if (oldEvaluation != null) { Set<String> removed = copyAndRemove(oldEvaluation.getDefinedCapacityGroups(), latestEvaluation.getDefinedCapacityGroups()); removed.forEach(category -> publishEvent(new CapacityGroupRemovedEvent(category, worker.now()))); } } private void notifyAboutResourceConsumptionChange(ConsumptionEvaluationResult oldEvaluation) { Map<String, ResourceConsumption> newCapacityGroupConsumptions = ResourceConsumptions.groupBy( latestEvaluation.getSystemConsumption(), ConsumptionLevel.CapacityGroup ); Map<String, ResourceConsumption> oldCapacityGroupConsumptions = oldEvaluation == null ? Collections.emptyMap() : ResourceConsumptions.groupBy(oldEvaluation.getSystemConsumption(), ConsumptionLevel.CapacityGroup); long now = worker.now(); newCapacityGroupConsumptions.values().forEach(newConsumption -> { ResourceConsumption previous = oldCapacityGroupConsumptions.get(newConsumption.getConsumerName()); if (previous == null || !previous.equals(newConsumption)) { publishEvent(new CapacityGroupAllocationEvent(newConsumption.getConsumerName(), now, (CompositeResourceConsumption) newConsumption)); } }); } private void notifyAboutUndefinedCapacityGroups(ConsumptionEvaluationResult oldEvaluation) { long now = worker.now(); Set<String> toNotify = oldEvaluation == null ? latestEvaluation.getUndefinedCapacityGroups() : copyAndRemove(latestEvaluation.getUndefinedCapacityGroups(), oldEvaluation.getUndefinedCapacityGroups()); toNotify.forEach(capacityGroup -> publishEvent(new CapacityGroupUndefinedEvent(capacityGroup, now))); } private void publishEvent(ResourceConsumptionEvent event) { eventsSubject.onNext(event); } static class ConsumptionEvaluationResult { private final Set<String> definedCapacityGroups; private final Set<String> undefinedCapacityGroups; private final CompositeResourceConsumption systemConsumption; ConsumptionEvaluationResult(Set<String> definedCapacityGroups, Set<String> undefinedCapacityGroups, CompositeResourceConsumption systemConsumption) { this.definedCapacityGroups = definedCapacityGroups; this.undefinedCapacityGroups = undefinedCapacityGroups; this.systemConsumption = systemConsumption; } public Set<String> getDefinedCapacityGroups() { return definedCapacityGroups; } public Set<String> getUndefinedCapacityGroups() { return undefinedCapacityGroups; } public CompositeResourceConsumption getSystemConsumption() { return systemConsumption; } } }
148
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/internal/ResourceConsumptionEvaluator.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.master.service.management.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.jobmanager.TaskAttributes; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; 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.V3JobOperations; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.api.model.Tier; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.model.ResourceDimensions; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import com.netflix.titus.master.service.management.CompositeResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption.ConsumptionLevel; import com.netflix.titus.master.service.management.ResourceConsumptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.common.util.CollectionsExt.copyAndRemove; import static com.netflix.titus.master.service.management.ApplicationSlaManagementService.DEFAULT_APPLICATION; import static com.netflix.titus.master.service.management.ResourceConsumption.SYSTEM_CONSUMER; import static java.util.stream.Collectors.groupingBy; /** * Computes current resource consumption. */ class ResourceConsumptionEvaluator { private static final Logger logger = LoggerFactory.getLogger(ResourceConsumptionEvaluator.class); private final V3JobOperations v3JobOperations; private final Set<String> definedCapacityGroups; private final Map<String, ApplicationSLA> applicationSlaMap; private CompositeResourceConsumption systemConsumption; private Set<String> undefinedCapacityGroups; ResourceConsumptionEvaluator(ApplicationSlaManagementService applicationSlaManagementService, V3JobOperations v3JobOperations) { this.v3JobOperations = v3JobOperations; Collection<ApplicationSLA> applicationSLAs = applicationSlaManagementService.getApplicationSLAs(); this.definedCapacityGroups = applicationSLAs.stream().map(ApplicationSLA::getAppName).collect(Collectors.toSet()); this.applicationSlaMap = applicationSLAs.stream().collect(Collectors.toMap(ApplicationSLA::getAppName, Function.identity())); Pair<Map<String, Map<String, ResourceConsumption>>, Set<String>> allocationsByCapacityGroupPair = computeAllocationsByCapacityGroupAndAppName(); this.systemConsumption = buildSystemConsumption(allocationsByCapacityGroupPair.getLeft()); this.undefinedCapacityGroups = allocationsByCapacityGroupPair.getRight(); } Set<String> getDefinedCapacityGroups() { return definedCapacityGroups; } Set<String> getUndefinedCapacityGroups() { return undefinedCapacityGroups; } public CompositeResourceConsumption getSystemConsumption() { return systemConsumption; } private CompositeResourceConsumption buildSystemConsumption(Map<String, Map<String, ResourceConsumption>> capacityGroupConsumptionMap) { // Capacity group level Map<Tier, List<CompositeResourceConsumption>> tierConsumptions = new HashMap<>(); capacityGroupConsumptionMap.forEach((capacityGroup, appConsumptions) -> { ApplicationSLA sla = applicationSlaMap.get(capacityGroup); ResourceDimension allowedConsumption = ResourceDimensions.multiply(sla.getResourceDimension(), sla.getInstanceCount()); ResourceDimension maxConsumption = ResourceConsumptions.addMaxConsumptions(appConsumptions.values()); List<Map<String, Object>> attrsList = appConsumptions.values().stream().map(ResourceConsumption::getAttributes).collect(Collectors.toList()); CompositeResourceConsumption capacityGroupConsumption = new CompositeResourceConsumption( capacityGroup, ConsumptionLevel.CapacityGroup, ResourceConsumptions.addCurrentConsumptions(appConsumptions.values()), maxConsumption, allowedConsumption, ResourceConsumptions.mergeAttributes(attrsList), appConsumptions, !ResourceDimensions.isBigger(allowedConsumption, maxConsumption) ); tierConsumptions.computeIfAbsent(sla.getTier(), t -> new ArrayList<>()).add(capacityGroupConsumption); }); // Tier level List<CompositeResourceConsumption> aggregatedTierConsumptions = new ArrayList<>(); tierConsumptions.forEach((tier, consumptions) -> aggregatedTierConsumptions.add(ResourceConsumptions.aggregate(tier.name(), ConsumptionLevel.Tier, consumptions)) ); // System level return ResourceConsumptions.aggregate(SYSTEM_CONSUMER, ConsumptionLevel.System, aggregatedTierConsumptions); } /** * @return capacityGroups -> apps -> instanceTypes -> consumption */ private Pair<Map<String, Map<String, ResourceConsumption>>, Set<String>> computeAllocationsByCapacityGroupAndAppName() { Map<String, Map<String, ResourceConsumption>> consumptionMap = new HashMap<>(); Set<String> undefinedCapacityGroups = new HashSet<>(); v3JobOperations.getJobsAndTasks().forEach(jobsAndTasks -> { Job job = jobsAndTasks.getLeft(); List<Task> tasks = jobsAndTasks.getRight(); List<Task> runningTasks = getRunningWorkers(tasks); ResourceDimension taskResources = perTaskResourceDimension(job); String appName = Evaluators.getOrDefault(job.getJobDescriptor().getApplicationName(), DEFAULT_APPLICATION); ResourceDimension currentConsumption = ResourceDimensions.multiply(taskResources, runningTasks.size()); ResourceDimension maxConsumption = ResourceDimensions.multiply(taskResources, getMaxJobSize(job)); Map<String, List<Task>> tasksByInstanceType = tasks.stream().collect( groupingBy(task -> task.getTaskContext() .getOrDefault(TaskAttributes.TASK_ATTRIBUTES_AGENT_ITYPE, "unknown")) ); Map<String, ResourceConsumption> consumptionByInstanceType = CollectionsExt.mapValuesWithKeys( tasksByInstanceType, (instanceType, instanceTypeTasks) -> { List<Task> runningInstanceTypeTasks = getRunningWorkers(instanceTypeTasks); ResourceDimension instanceTypeConsumption = ResourceDimensions.multiply( taskResources, runningInstanceTypeTasks.size() ); return new ResourceConsumption( instanceType, ConsumptionLevel.InstanceType, instanceTypeConsumption, instanceTypeConsumption, // maxConsumption is not relevant at ConsumptionLevel.InstanceType getWorkerStateMap(instanceTypeTasks) ); }, HashMap::new ); ResourceConsumption jobConsumption = new CompositeResourceConsumption( appName, ConsumptionLevel.Application, currentConsumption, maxConsumption, maxConsumption, // allowedConsumption is not relevant at ConsumptionLevel.Application getWorkerStateMap(tasks), consumptionByInstanceType, false // we consider a job is always within its allowed usage since it can't go over its max ); String capacityGroup = resolveCapacityGroup(undefinedCapacityGroups, job, appName); updateConsumptionMap(appName, capacityGroup, jobConsumption, consumptionMap); }); // Add unused capacity groups copyAndRemove(definedCapacityGroups, consumptionMap.keySet()).forEach(capacityGroup -> consumptionMap.put(capacityGroup, Collections.emptyMap()) ); return Pair.of(consumptionMap, undefinedCapacityGroups); } private void updateConsumptionMap(String applicationName, String capacityGroup, ResourceConsumption jobConsumption, Map<String, Map<String, ResourceConsumption>> consumptionMap) { Map<String, ResourceConsumption> capacityGroupAllocation = consumptionMap.computeIfAbsent(capacityGroup, k -> new HashMap<>()); String effectiveAppName = applicationName == null ? DEFAULT_APPLICATION : applicationName; ResourceConsumption appAllocation = capacityGroupAllocation.get(effectiveAppName); if (appAllocation == null) { capacityGroupAllocation.put(effectiveAppName, jobConsumption); } else { capacityGroupAllocation.put(effectiveAppName, ResourceConsumptions.add(appAllocation, jobConsumption)); } } private int getMaxJobSize(Job<?> job) { return JobFunctions.isServiceJob(job) ? ((Job<ServiceJobExt>) job).getJobDescriptor().getExtensions().getCapacity().getMax() : ((Job<BatchJobExt>) job).getJobDescriptor().getExtensions().getSize(); } private Map<String, Object> getWorkerStateMap(List<Task> tasks) { Map<String, Object> tasksStates = newTaskStateMap(); tasks.stream().map(task -> task.getStatus().getState()).forEach(taskState -> tasksStates.put(taskState.name(), (int) tasksStates.get(taskState.name()) + 1) ); return tasksStates; } private Map<String, Object> newTaskStateMap() { Map<String, Object> tasksStates = new HashMap<>(); for (TaskState state : TaskState.values()) { tasksStates.put(state.name(), 0); } return tasksStates; } private String resolveCapacityGroup(Set<String> undefinedCapacityGroups, Job job, String appName) { String capacityGroup = job.getJobDescriptor().getCapacityGroup(); if (capacityGroup == null) { if (appName != null && definedCapacityGroups.contains(appName)) { capacityGroup = appName; } } if (capacityGroup == null) { capacityGroup = DEFAULT_APPLICATION; } else if (!definedCapacityGroups.contains(capacityGroup)) { undefinedCapacityGroups.add(capacityGroup); capacityGroup = DEFAULT_APPLICATION; } return capacityGroup; } static Supplier<DefaultResourceConsumptionService.ConsumptionEvaluationResult> newEvaluator(ApplicationSlaManagementService applicationSlaManagementService, V3JobOperations v3JobOperations) { return () -> { ResourceConsumptionEvaluator evaluator = new ResourceConsumptionEvaluator(applicationSlaManagementService, v3JobOperations); return new DefaultResourceConsumptionService.ConsumptionEvaluationResult( evaluator.getDefinedCapacityGroups(), evaluator.getUndefinedCapacityGroups(), evaluator.getSystemConsumption() ); }; } /** * @return resource dimensions per task as defined in the job descriptor. */ @VisibleForTesting static ResourceDimension perTaskResourceDimension(Job<?> job) { ContainerResources containerResources = job.getJobDescriptor().getContainer().getContainerResources(); return new ResourceDimension( containerResources.getCpu(), containerResources.getGpu(), containerResources.getMemoryMB(), containerResources.getDiskMB(), containerResources.getNetworkMbps(), 0); } private List<Task> getRunningWorkers(List<Task> tasks) { return tasks.stream().filter(t -> TaskState.isRunning(t.getStatus().getState())).collect(Collectors.toList()); } }
149
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/internal/ResourceConsumptionLog.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.master.service.management.internal; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.master.model.ResourceDimensions; import com.netflix.titus.master.service.management.CompositeResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumptionEvents; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupAllocationEvent; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupRemovedEvent; import com.netflix.titus.master.service.management.ResourceConsumptionEvents.CapacityGroupUndefinedEvent; import com.netflix.titus.master.service.management.ResourceConsumptionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; /** * A resource consumption state change event log. */ @Singleton public class ResourceConsumptionLog { private static final Logger logger = LoggerFactory.getLogger(ResourceConsumptionLog.class); private final ResourceConsumptionService resourceConsumptionService; private Subscription subscription; @Inject public ResourceConsumptionLog(ResourceConsumptionService resourceConsumptionService) { this.resourceConsumptionService = resourceConsumptionService; } @Activator public Observable<Void> enterActiveMode() { logger.info("Activating resource consumption logging..."); this.subscription = resourceConsumptionService.resourceConsumptionEvents().subscribe( ResourceConsumptionLog::doLog, e -> logger.error("Resource consumption log terminated with an error", e), () -> logger.warn("Resource consumption log completed") ); return Observable.empty(); } @PreDestroy public void shutdown() { if (subscription != null) { subscription.unsubscribe(); } } /* Visible for testing */ static String doLog(ResourceConsumptionEvents.ResourceConsumptionEvent event) { if (event instanceof CapacityGroupAllocationEvent) { CapacityGroupAllocationEvent changeEvent = (CapacityGroupAllocationEvent) event; CompositeResourceConsumption consumption = changeEvent.getCapacityGroupConsumption(); StringBuilder sb = new StringBuilder("Resource consumption change: group="); sb.append(consumption.getConsumerName()); if (consumption.isAboveLimit()) { sb.append(" [above limit] "); } else { sb.append(" [below limit] "); } sb.append("actual="); ResourceDimensions.format(consumption.getCurrentConsumption(), sb); sb.append(", max="); ResourceDimensions.format(consumption.getMaxConsumption(), sb); sb.append(", limit="); ResourceDimensions.format(consumption.getAllowedConsumption(), sb); if (consumption.getAttributes().isEmpty()) { sb.append(", attrs={}"); } else { sb.append(", attrs={"); consumption.getAttributes().forEach((k, v) -> sb.append(k).append('=').append(v).append(',')); sb.setCharAt(sb.length() - 1, '}'); } String message = sb.toString(); if (consumption.isAboveLimit()) { logger.warn(message); } else { logger.info(message); } return message; } if (event instanceof CapacityGroupUndefinedEvent) { String message = "Capacity group not defined: group=" + event.getCapacityGroup(); logger.warn(message); return message; } if (event instanceof CapacityGroupRemovedEvent) { String message = "Capacity group no longer defined: group=" + event.getCapacityGroup(); logger.info(message); return message; } String message = "Unrecognized resource consumption event type " + event.getClass(); logger.error(message); return message; } }
150
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/internal/ResourceConsumptionServiceMetrics.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.master.service.management.internal; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import com.google.common.base.Preconditions; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.service.management.CompositeResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption; import com.netflix.titus.master.service.management.ResourceConsumption.ConsumptionLevel; import static com.netflix.titus.common.util.CollectionsExt.copyAndRemove; class ResourceConsumptionServiceMetrics { private final Id rootId; private final Registry registry; private final Map<Pair<String, String>, ApplicationMetrics> metricsByCapacityGroupAndApp = new HashMap<>(); private final Map<String, ResourceMetrics> capacityGroupLimits = new HashMap<>(); private volatile long updateTimestamp; ResourceConsumptionServiceMetrics(Id rootId, Registry registry) { this.rootId = rootId; this.registry = registry; this.updateTimestamp = registry.clock().wallTime(); registry.gauge( registry.createId(rootId.name() + "updateDelay", rootId.tags()), this, self -> (registry.clock().wallTime() - updateTimestamp) ); } public void update(DefaultResourceConsumptionService.ConsumptionEvaluationResult evaluationResult) { CompositeResourceConsumption systemConsumption = evaluationResult.getSystemConsumption(); Set<Pair<String, String>> touchedApps = new HashSet<>(); Set<String> touchedGroups = new HashSet<>(); systemConsumption.getContributors().values().forEach(tierConsumption -> updateTier((CompositeResourceConsumption) tierConsumption, touchedApps, touchedGroups) ); // Remove no longer referenced items copyAndRemove(metricsByCapacityGroupAndApp.keySet(), touchedApps).forEach(removed -> metricsByCapacityGroupAndApp.remove(removed).reset() ); copyAndRemove(capacityGroupLimits.keySet(), touchedGroups).forEach(removed -> capacityGroupLimits.remove(removed).reset() ); updateTimestamp = registry.clock().wallTime(); } private void updateTier(CompositeResourceConsumption tierConsumption, Set<Pair<String, String>> touchedApps, Set<String> touchedGroups) { String tierName = tierConsumption.getConsumerName(); Set<String> capacityGroupNames = tierConsumption.getContributors().keySet(); Collection<ResourceConsumption> capacityGroupConsumption = tierConsumption.getContributors().values(); // Process application level metrics capacityGroupConsumption .forEach(groupConsumption -> { ((CompositeResourceConsumption) groupConsumption).getContributors().values() .forEach(appConsumption -> { touchedApps.add(updateApp(tierName, groupConsumption, appConsumption)); }); } ); // Process capacity group level metrics capacityGroupConsumption.forEach((groupConsumption) -> updateCapacityGroupLimit(tierName, (CompositeResourceConsumption) groupConsumption)); touchedGroups.addAll(capacityGroupNames); } private Pair<String, String> updateApp(String tierName, ResourceConsumption groupConsumption, ResourceConsumption appConsumption) { Pair<String, String> key = Pair.of(groupConsumption.getConsumerName(), appConsumption.getConsumerName()); ApplicationMetrics metrics = metricsByCapacityGroupAndApp.get(key); if (metrics == null) { metrics = new ApplicationMetrics(tierName, groupConsumption.getConsumerName(), appConsumption.getConsumerName()); metricsByCapacityGroupAndApp.put(key, metrics); } metrics.update(appConsumption); return key; } private void updateCapacityGroupLimit(String tierName, CompositeResourceConsumption groupConsumption) { String name = groupConsumption.getConsumerName(); ResourceMetrics metrics = capacityGroupLimits.get(name); if (metrics == null) { metrics = new ResourceMetrics(registry.createId(rootId.name() + "limit", rootId.tags()) .withTag("tier", tierName) .withTag("capacityGroup", name)); capacityGroupLimits.put(name, metrics); } metrics.update(groupConsumption.getAllowedConsumption()); } private enum ResourceType {Cpu, Memory, Disk, Network, Gpu, OpportunisticCpu} private class ResourceMetrics { private final Map<ResourceType, AtomicLong> usage; private ResourceMetrics(Id id) { this.usage = initialize(id); } private Map<ResourceType, AtomicLong> initialize(Id id) { Map<ResourceType, AtomicLong> result = new EnumMap<>(ResourceType.class); for (ResourceType rt : ResourceType.values()) { result.put(rt, PolledMeter.using(registry) .withId(id.withTag("resourceType", rt.name())) .monitorValue(new AtomicLong())); } return result; } private void update(ResourceDimension consumption) { usage.get(ResourceType.Cpu).set((int) consumption.getCpu()); usage.get(ResourceType.Memory).set(consumption.getMemoryMB()); usage.get(ResourceType.Disk).set(consumption.getDiskMB()); usage.get(ResourceType.Network).set(consumption.getNetworkMbs()); usage.get(ResourceType.Gpu).set(consumption.getGpu()); usage.get(ResourceType.OpportunisticCpu).set(consumption.getOpportunisticCpu()); } private void reset() { usage.values().forEach(g -> g.set(0)); } } private class ApplicationMetrics { private final String tierName; private final String capacityGroup; private final String appName; private final ResourceMetrics maxUsage; private final Map<String, ResourceMetrics> actualUsageByInstanceType = new HashMap<>(); private ApplicationMetrics(String tierName, String capacityGroup, String appName) { this.tierName = tierName; this.capacityGroup = capacityGroup; this.appName = appName; this.maxUsage = new ResourceMetrics( registry.createId(rootId.name() + "maxUsage", rootId.tags()) .withTag("tier", tierName) .withTag("capacityGroup", capacityGroup) .withTag("applicationName", appName) ); } private ResourceMetrics buildInstanceTypeMetrics(String instanceType) { return new ResourceMetrics( registry.createId(rootId.name() + "actualUsage", rootId.tags()) .withTag("tier", tierName) .withTag("capacityGroup", capacityGroup) .withTag("applicationName", appName) .withTag("instanceType", instanceType) ); } private void update(ResourceConsumption appConsumption) { Preconditions.checkArgument(ConsumptionLevel.Application.equals(appConsumption.getConsumptionLevel())); maxUsage.update(appConsumption.getMaxConsumption()); Set<String> instanceTypesInUse = new HashSet<>(); Map<String, ResourceConsumption> consumptionByInstanceType = ((CompositeResourceConsumption) appConsumption).getContributors(); consumptionByInstanceType.forEach((instanceType, consumption) -> { instanceTypesInUse.add(instanceType); actualUsageByInstanceType.computeIfAbsent(instanceType, this::buildInstanceTypeMetrics) .update(consumption.getCurrentConsumption()); }); // clean up instance types not being used anymore, create a copy to avoid ConcurrentModificationException List<String> trackedInstanceTypes = new ArrayList<>(actualUsageByInstanceType.keySet()); trackedInstanceTypes.stream() .filter(i -> !instanceTypesInUse.contains(i)) .forEach(toRemove -> actualUsageByInstanceType.remove(toRemove).reset()); } private void reset() { maxUsage.reset(); actualUsageByInstanceType.values().forEach(ResourceMetrics::reset); actualUsageByInstanceType.clear(); } } }
151
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/CapacityGroupInformerWrapper.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.service.management.kube.crd.F8IOCapacityGroup; import com.netflix.titus.runtime.connector.kubernetes.fabric8io.Fabric8IOInformerMetrics; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.fabric8.kubernetes.client.informers.SharedIndexInformer; import io.fabric8.kubernetes.client.informers.SharedInformerFactory; class CapacityGroupInformerWrapper { private final SharedInformerFactory sharedInformerFactory; private final SharedIndexInformer<F8IOCapacityGroup> informer; private final Fabric8IOInformerMetrics<F8IOCapacityGroup> metrics; CapacityGroupInformerWrapper(NamespacedKubernetesClient kubeApiClient, TitusRuntime titusRuntime) { this.sharedInformerFactory = kubeApiClient.informers(); this.informer = sharedInformerFactory.sharedIndexInformerFor( F8IOCapacityGroup.class, 3000 ); this.sharedInformerFactory.startAllRegisteredInformers(); this.metrics = new Fabric8IOInformerMetrics<>("capacityGroupInformer", informer, titusRuntime); } void shutdown() { metrics.close(); sharedInformerFactory.stopAllRegisteredInformers(); } SharedIndexInformer<F8IOCapacityGroup> getInformer() { return informer; } }
152
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/KubeApplicationSlaManagementService.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.service.TitusServiceException; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import com.netflix.titus.master.service.management.kube.crd.F8IOCapacityGroup; import com.netflix.titus.master.service.management.kube.crd.F8IOCapacityGroupSpec; import com.netflix.titus.master.service.management.kube.crd.Fabric8IOModelConverters; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import rx.Observable; @Singleton public class KubeApplicationSlaManagementService implements ApplicationSlaManagementService { private static final Logger logger = LoggerFactory.getLogger(KubeApplicationSlaManagementService.class); private final CapacityGroupInformerWrapper capacityGroupInformer; private final NonNamespaceOperation<F8IOCapacityGroup, KubernetesResourceList<F8IOCapacityGroup>, Resource<F8IOCapacityGroup>> crdClient; private final Scheduler scheduler; private volatile Map<String, ApplicationSLA> capacityGroups = Collections.emptyMap(); @Inject public KubeApplicationSlaManagementService(NamespacedKubernetesClient kubeApiClient, TitusRuntime titusRuntime) { this.crdClient = kubeApiClient.resources(F8IOCapacityGroup.class).inNamespace("default"); this.capacityGroupInformer = new CapacityGroupInformerWrapper(kubeApiClient, titusRuntime); this.scheduler = Schedulers.boundedElastic(); capacityGroupInformer.getInformer().addEventHandler(new ResourceEventHandler<F8IOCapacityGroup>() { @Override public void onAdd(F8IOCapacityGroup obj) { ApplicationSLA mapped = Fabric8IOModelConverters.toApplicationSLA(obj); String name = mapped.getAppName(); if (!StringExt.isEmpty(name)) { ApplicationSLA existing = capacityGroups.get(name); if (existing == null || !existing.equals(mapped)) { capacityGroups = CollectionsExt.copyAndAdd(capacityGroups, name, mapped); logger.info("Added/Updated capacity group cache: {}", mapped); } } } @Override public void onUpdate(F8IOCapacityGroup oldObj, F8IOCapacityGroup newObj) { onAdd(newObj); } @Override public void onDelete(F8IOCapacityGroup obj, boolean deletedFinalStateUnknown) { String name = obj.getMetadata().getName(); if (!StringExt.isEmpty(name)) { String originalName = Fabric8IOModelConverters.toApplicationSlaName(obj); if (capacityGroups.containsKey(originalName)) { capacityGroups = CollectionsExt.copyAndRemove(capacityGroups, originalName); logger.info("Removed capacity group from cache: {}", originalName); } else { logger.warn("Request to remove unknown capacity group from cache: {}", originalName); } } } }); } @PreDestroy public void shutdown() { capacityGroupInformer.shutdown(); scheduler.dispose(); } @Override public Collection<ApplicationSLA> getApplicationSLAs() { return capacityGroups.values(); } @Override public Collection<ApplicationSLA> getApplicationSLAsForScheduler(String schedulerName) { List<ApplicationSLA> filtered = new ArrayList<>(); capacityGroups.forEach((name, capacityGroup) -> { if (capacityGroup.getSchedulerName().equals(schedulerName)) { filtered.add(capacityGroup); } }); return filtered; } @Override public Optional<ApplicationSLA> findApplicationSLA(String applicationName) { return Optional.ofNullable(capacityGroups.get(applicationName)); } @Override public ApplicationSLA getApplicationSLA(String applicationName) { return capacityGroups.get(applicationName); } @Override public Observable<Void> addApplicationSLA(ApplicationSLA applicationSLA) { ObjectMeta meta = Fabric8IOModelConverters.toF8IOMetadata(applicationSLA); F8IOCapacityGroupSpec spec = Fabric8IOModelConverters.toF8IOCapacityGroupSpec(applicationSLA); Mono<Void> action = Mono.<Void>fromRunnable(() -> { // First try update in case the CRD exists F8IOCapacityGroup newCrd = new F8IOCapacityGroup(); newCrd.setMetadata(meta); newCrd.setSpec(spec); try { crdClient.create(newCrd); logger.info("Created new capacity group: {}", applicationSLA); return; } catch (Exception error) { if (error instanceof KubernetesClientException) { KubernetesClientException kerror = (KubernetesClientException) error; if (kerror.getCode() != 409) { throw TitusServiceException.internal(error, "Cannot create/update capacity group: %s", applicationSLA); } } } // We failed, so try again and create it. try { String name = meta.getName(); F8IOCapacityGroup existingCrd = crdClient.withName(name).get(); existingCrd.setSpec(spec); crdClient.withName(name).replace(existingCrd); logger.info("Updated an existing capacity group: {}", applicationSLA); } catch (Exception error) { throw TitusServiceException.internal(error, "Cannot create/update capacity group: %s", applicationSLA); } }).subscribeOn(scheduler); return ReactorExt.toObservable(action); } @Override public Observable<Void> removeApplicationSLA(String originalName) { String name = Fabric8IOModelConverters.toValidKubeCrdName(originalName); Mono<Void> action = Mono.<Void>fromRunnable(() -> { try { crdClient.withName(name).delete(); logger.info("Removed a capacity group: {}", originalName); } catch (Exception error) { throw TitusServiceException.internal(error, "Cannot remove capacity group: %s", originalName); } }).subscribeOn(scheduler); return ReactorExt.toObservable(action); } }
153
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/crd/F8IOCapacityGroupStatus.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube.crd; public class F8IOCapacityGroupStatus { }
154
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/crd/F8IOCapacityGroup.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube.crd; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Kind; import io.fabric8.kubernetes.model.annotation.Plural; import io.fabric8.kubernetes.model.annotation.Singular; import io.fabric8.kubernetes.model.annotation.Version; @Group("config.com.netflix.titus") @Version("v1") @Kind("CapacityGroup") @Singular("capacitygroup") @Plural("capacitygroups") public class F8IOCapacityGroup extends CustomResource<F8IOCapacityGroupSpec, F8IOCapacityGroupStatus> implements Namespaced { }
155
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/crd/Fabric8IOModelConverters.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube.crd; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.ResourceDimension; import com.netflix.titus.api.model.Tier; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import io.fabric8.kubernetes.api.model.ObjectMeta; public class Fabric8IOModelConverters { /** * TODO Get rid of it once all capacity group names follow the Kubernetes naming convention. */ private static final String LABEL_ORIGINAL_NAME = "capacitygroup.com.netflix.titus/original-name"; public static ApplicationSLA toApplicationSLA(F8IOCapacityGroup f8IOCapacityGroup) { String name = toApplicationSlaName(f8IOCapacityGroup); String tierAnnotation = f8IOCapacityGroup.getMetadata().getAnnotations().get("tier"); Tier tier = "Critical".equalsIgnoreCase(tierAnnotation) ? Tier.Critical : Tier.Flex; return ApplicationSLA.newBuilder() .withAppName(name) .withResourcePool(f8IOCapacityGroup.getSpec().getResourcePoolName()) .withInstanceCount(f8IOCapacityGroup.getSpec().getInstanceCount()) .withResourceDimension(toCoreResourceDimensions(f8IOCapacityGroup.getSpec().getResourceDimensions())) .withSchedulerName(f8IOCapacityGroup.getSpec().getSchedulerName()) .withTier(tier) .build(); } public static ObjectMeta toF8IOMetadata(ApplicationSLA applicationSLA) { String original = applicationSLA.getAppName(); String name = "default".equalsIgnoreCase(original) ? "default" : toValidKubeCrdName(original); ObjectMeta objectMeta = new ObjectMeta(); objectMeta.setName(name); objectMeta.setAnnotations(CollectionsExt.asMap( "tier", applicationSLA.getTier().name(), LABEL_ORIGINAL_NAME, original )); return objectMeta; } public static String toApplicationSlaName(F8IOCapacityGroup f8IOCapacityGroup) { String name = f8IOCapacityGroup.getMetadata().getName(); if ("default".equalsIgnoreCase(name)) { name = "DEFAULT"; } else { String original = f8IOCapacityGroup.getMetadata().getAnnotations().get(LABEL_ORIGINAL_NAME); if (!StringExt.isEmpty(original)) { name = original; } } return name; } public static String toValidKubeCrdName(String originalName) { return originalName.replaceAll("_", "-").toLowerCase(); } public static F8IOCapacityGroupSpec toF8IOCapacityGroupSpec(ApplicationSLA applicationSLA) { F8IOCapacityGroupSpec spec = new F8IOCapacityGroupSpec(); spec.setCapacityGroupName(applicationSLA.getAppName()); spec.setResourcePoolName(applicationSLA.getResourcePool()); spec.setCreatedBy("capacity-group-reconciler"); spec.setInstanceCount(applicationSLA.getInstanceCount()); spec.setSchedulerName(applicationSLA.getSchedulerName()); spec.setResourceDimensions(toF8IOResourceDimension(applicationSLA.getResourceDimension())); return spec; } private static ResourceDimension toCoreResourceDimensions(F8IOResourceDimension resourceDimensions) { return ResourceDimension.newBuilder() .withCpus(resourceDimensions.getCpu()) .withGpu(resourceDimensions.getGpu()) .withMemoryMB(resourceDimensions.getMemoryMB()) .withDiskMB(resourceDimensions.getDiskMB()) .withNetworkMbs(resourceDimensions.getNetworkMBPS()) .build(); } private static F8IOResourceDimension toF8IOResourceDimension(ResourceDimension resourceDimension) { F8IOResourceDimension f8IOResourceDimension = new F8IOResourceDimension(); f8IOResourceDimension.setCpu((int) resourceDimension.getCpu()); f8IOResourceDimension.setGpu((int) resourceDimension.getGpu()); f8IOResourceDimension.setMemoryMB((int) resourceDimension.getMemoryMB()); f8IOResourceDimension.setDiskMB((int) resourceDimension.getDiskMB()); f8IOResourceDimension.setNetworkMBPS((int) resourceDimension.getNetworkMbs()); return f8IOResourceDimension; } }
156
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/crd/F8IOCapacityGroupSpec.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube.crd; public class F8IOCapacityGroupSpec { private String resourcePoolName; private String createdBy; private String schedulerName; private String capacityGroupName; private int instanceCount; private F8IOResourceDimension resourceDimensions; public String getResourcePoolName() { return resourcePoolName; } public void setResourcePoolName(String resourcePoolName) { this.resourcePoolName = resourcePoolName; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getSchedulerName() { return schedulerName; } public void setSchedulerName(String schedulerName) { this.schedulerName = schedulerName; } public String getCapacityGroupName() { return capacityGroupName; } public void setCapacityGroupName(String capacityGroupName) { this.capacityGroupName = capacityGroupName; } public int getInstanceCount() { return instanceCount; } public void setInstanceCount(int instanceCount) { this.instanceCount = instanceCount; } public F8IOResourceDimension getResourceDimensions() { return resourceDimensions; } public void setResourceDimensions(F8IOResourceDimension resourceDimensions) { this.resourceDimensions = resourceDimensions; } }
157
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/service/management/kube/crd/F8IOResourceDimension.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.service.management.kube.crd; public class F8IOResourceDimension { private long cpu; private long gpu; private long memoryMB; private long diskMB; private long networkMBPS; public long getCpu() { return cpu; } public void setCpu(long cpu) { this.cpu = cpu; } public long getGpu() { return gpu; } public void setGpu(long gpu) { this.gpu = gpu; } public long getMemoryMB() { return memoryMB; } public void setMemoryMB(long memoryMB) { this.memoryMB = memoryMB; } public long getDiskMB() { return diskMB; } public void setDiskMB(long diskMB) { this.diskMB = diskMB; } public long getNetworkMBPS() { return networkMBPS; } public void setNetworkMBPS(long networkMBPS) { this.networkMBPS = networkMBPS; } }
158
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/KubeModule.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.master.kubernetes; import com.google.inject.AbstractModule; import com.netflix.titus.master.kubernetes.client.KubeClientModule; import com.netflix.titus.master.kubernetes.controller.KubeControllerModule; import com.netflix.titus.master.kubernetes.pod.KubePodModule; public class KubeModule extends AbstractModule { @Override protected void configure() { install(new KubeClientModule()); install(new KubeControllerModule()); install(new KubePodModule()); } }
159
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/ContainerResultCodeResolver.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.master.kubernetes; import java.util.Optional; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.master.kubernetes.client.model.PodWrapper; public interface ContainerResultCodeResolver { Optional<String> resolve(TaskState nextTaskState, Task task, PodWrapper podWrapper); }
160
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/KubeUtil.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.master.kubernetes; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import com.google.common.base.Strings; import com.google.gson.Gson; import com.google.protobuf.util.JsonFormat; import com.netflix.titus.api.jobmanager.JobConstraints; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.NetworkExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.models.V1ContainerState; import io.kubernetes.client.openapi.models.V1ContainerStateRunning; import io.kubernetes.client.openapi.models.V1ContainerStateTerminated; import io.kubernetes.client.openapi.models.V1ContainerStateWaiting; import io.kubernetes.client.openapi.models.V1ContainerStatus; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1NodeAddress; import io.kubernetes.client.openapi.models.V1NodeCondition; import io.kubernetes.client.openapi.models.V1NodeStatus; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1Toleration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KubeUtil { private static final Logger logger = LoggerFactory.getLogger(KubeUtil.class); private static final String SUCCEEDED = "Succeeded"; private static final String FAILED = "Failed"; private static final String BOUND = "Bound"; public static final String TYPE_INTERNAL_IP = "InternalIP"; private static final JsonFormat.Printer grpcJsonPrinter = JsonFormat.printer().includingDefaultValueFields(); private static final Gson GSON = new Gson(); /** * As it is not possible to capture pod size at the transport level, we try to estimate it directly using the same * JSON serializer as the Kube client (gson). */ public static int estimatePodSize(V1Pod v1Pod) { try { String json = GSON.toJson(v1Pod); return json == null ? 0 : json.length(); } catch (Exception e) { return 0; } } public static boolean isPodPhaseTerminal(String phase) { return SUCCEEDED.equals(phase) || FAILED.equals(phase); } public static boolean isPersistentVolumeBound(String phase) { return BOUND.equals(phase); } public static Optional<Long> findFinishedTimestamp(V1Pod pod) { if (pod.getStatus() == null || pod.getStatus().getContainerStatuses() == null) { return Optional.empty(); } return pod.getStatus().getContainerStatuses().stream() .filter(status -> status.getState() != null && status.getState().getTerminated() != null && status.getState().getTerminated().getFinishedAt() != null) .findFirst() .map(terminatedState -> terminatedState.getState().getTerminated().getFinishedAt().toInstant().toEpochMilli()); } public static Optional<V1ContainerState> findContainerState(V1Pod pod) { if (pod.getStatus() == null) { return Optional.empty(); } List<V1ContainerStatus> containerStatuses = pod.getStatus().getContainerStatuses(); if (containerStatuses != null) { for (V1ContainerStatus status : containerStatuses) { V1ContainerState state = status.getState(); if (state != null) { return Optional.of(state); } } } return Optional.empty(); } public static Optional<V1ContainerStateTerminated> findTerminatedContainerStatus(V1Pod pod) { return findContainerState(pod).flatMap(state -> Optional.ofNullable(state.getTerminated())); } public static String formatV1ContainerState(V1ContainerState containerState) { if (containerState.getWaiting() != null) { V1ContainerStateWaiting waiting = containerState.getWaiting(); return String.format("{state=waiting, reason=%s, message=%s}", waiting.getReason(), waiting.getMessage()); } if (containerState.getRunning() != null) { V1ContainerStateRunning running = containerState.getRunning(); return String.format("{state=running, startedAt=%s}", running.getStartedAt()); } if (containerState.getTerminated() != null) { V1ContainerStateTerminated terminated = containerState.getTerminated(); return String.format("{state=terminated, startedAt=%s, finishedAt=%s, reason=%s, message=%s}", terminated.getStartedAt(), terminated.getFinishedAt(), terminated.getReason(), terminated.getMessage()); } return "{state=<not set>}"; } /** * If a job has an availability zone hard constraint with a farzone id, return this farzone id. */ public static Optional<String> findFarzoneId(KubePodConfiguration configuration, Job<?> job) { List<String> farzones = configuration.getFarzones(); if (CollectionsExt.isNullOrEmpty(farzones)) { return Optional.empty(); } String zone = JobFunctions.findHardConstraint(job, JobConstraints.AVAILABILITY_ZONE).orElse(""); if (StringExt.isEmpty(zone)) { return Optional.empty(); } for (String farzone : farzones) { if (zone.equalsIgnoreCase(farzone)) { return Optional.of(farzone); } } return Optional.empty(); } public static boolean isOwnedByKubeScheduler(V1Pod v1Pod) { List<V1Toleration> tolerations = v1Pod.getSpec().getTolerations(); if (CollectionsExt.isNullOrEmpty(tolerations)) { return false; } for (V1Toleration toleration : tolerations) { if (KubeConstants.TAINT_SCHEDULER.equals(toleration.getKey()) && KubeConstants.TAINT_SCHEDULER_VALUE_KUBE.equals(toleration.getValue())) { return true; } } return false; } public static Optional<String> getNodeIpV4Address(V1Node node) { return Optional.ofNullable(node.getStatus().getAddresses()) .map(Collection::stream) .orElseGet(Stream::empty) .filter(a -> a.getType().equalsIgnoreCase(TYPE_INTERNAL_IP) && NetworkExt.isIpV4(a.getAddress())) .findFirst() .map(V1NodeAddress::getAddress); } public static boolean isFarzoneNode(List<String> farzones, V1Node node) { Map<String, String> labels = node.getMetadata().getLabels(); if (CollectionsExt.isNullOrEmpty(labels)) { return false; } String nodeZone = labels.get(KubeConstants.NODE_LABEL_ZONE); if (StringExt.isEmpty(nodeZone)) { logger.debug("Node without zone label: {}", node.getMetadata().getName()); return false; } for (String farzone : farzones) { if (farzone.equalsIgnoreCase(nodeZone)) { logger.debug("Farzone node: nodeId={}, zoneId={}", node.getMetadata().getName(), nodeZone); return true; } } logger.debug("Non-farzone node: nodeId={}, zoneId={}", node.getMetadata().getName(), nodeZone); return false; } public static String toErrorDetails(Throwable e) { if (!(e instanceof ApiException)) { return ExceptionExt.toMessageChain(e); } ApiException apiException = (ApiException) e; return String.format("{message=%s, httpCode=%d, responseBody=%s", Evaluators.getOrDefault(apiException.getMessage(), "<not set>"), apiException.getCode(), Evaluators.getOrDefault(apiException.getResponseBody(), "<not set>") ); } /** * Get Kube object name */ @Deprecated public static String getMetadataName(V1ObjectMeta metadata) { return com.netflix.titus.runtime.connector.kubernetes.KubeUtil.getMetadataName(metadata); } public static Optional<V1NodeCondition> findNodeCondition(V1Node node, String type) { V1NodeStatus status = node.getStatus(); if (status == null) { return Optional.empty(); } List<V1NodeCondition> conditions = status.getConditions(); if (conditions != null) { for (V1NodeCondition condition : conditions) { if (condition.getType().equals(type)) { return Optional.of(condition); } } } return Optional.empty(); } public static boolean hasUninitializedTaint(V1Node node) { if (node.getSpec() != null && node.getSpec().getTaints() != null) { return node.getSpec().getTaints().stream() .anyMatch(t -> KubeConstants.TAINT_NODE_UNINITIALIZED.equals(t.getKey())); } return false; } }
161
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/PerformanceToolUtil.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.master.kubernetes; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.unit.TimeUnitExt; import static com.netflix.titus.api.jobmanager.JobAttributes.TITUS_PARAMETER_ATTRIBUTE_PREFIX; public class PerformanceToolUtil { private static final Pattern TASK_STATE_RULES_RE = Pattern.compile("(launched|startInitiated|started|killInitiated)\\s*:\\s*delay=(\\d+(ms|s|m|h|d))"); // Mock VK titus job parameters static final String MOCK_VK_PROPERTY_PREFIX = TITUS_PARAMETER_ATTRIBUTE_PREFIX + "mockVK."; static final String MOCK_VK_PROPERTY_PREPARE_TIME = MOCK_VK_PROPERTY_PREFIX + "prepareTime"; static final String MOCK_VK_PROPERTY_RUN_TIME = MOCK_VK_PROPERTY_PREFIX + "runTime"; static final String MOCK_VK_PROPERTY_KILL_TIME = MOCK_VK_PROPERTY_PREFIX + "killTime"; static final String PREPARE_TIME = "github.com.netflix.titus.executor/prepareTime"; static final String RUN_TIME = "github.com.netflix.titus.executor/runTime"; static final String KILL_TIME = "github.com.netflix.titus.executor/killTime"; public static Map<String, String> toAnnotations(Job job) { Map<String, String> attributes = job.getJobDescriptor().getAttributes(); if (attributes.containsKey(MOCK_VK_PROPERTY_PREPARE_TIME) || attributes.containsKey(MOCK_VK_PROPERTY_RUN_TIME) || attributes.containsKey(MOCK_VK_PROPERTY_KILL_TIME)) { Map<String, String> annotations = new HashMap<>(); Evaluators.acceptNotNull(attributes.get(MOCK_VK_PROPERTY_PREPARE_TIME), value -> annotations.put(PREPARE_TIME, value)); Evaluators.acceptNotNull(attributes.get(MOCK_VK_PROPERTY_RUN_TIME), value -> annotations.put(RUN_TIME, value)); Evaluators.acceptNotNull(attributes.get(MOCK_VK_PROPERTY_KILL_TIME), value -> annotations.put(KILL_TIME, value)); return annotations; } // Legacy return findLegacyTaskLifecycleEnv(job.getJobDescriptor().getContainer().getEnv()) .map(PerformanceToolUtil::toLegacyAnnotations) .orElse(Collections.emptyMap()); } private static Optional<String> findLegacyTaskLifecycleEnv(Map<String, String> env) { return env.keySet().stream().filter(k -> k.startsWith("TASK_LIFECYCLE")).map(env::get).findFirst(); } private static Map<String, String> toLegacyAnnotations(String envValue) { Map<String, String> annotations = new HashMap<>(); Matcher matcher = TASK_STATE_RULES_RE.matcher(envValue); while (matcher.find()) { String state = matcher.group(1); String delayWithUnits = matcher.group(2); long delayMs = TimeUnitExt.toMillis(delayWithUnits).orElse(-1L); if (delayMs > 0) { switch (state) { case "startInitiated": annotations.put(PREPARE_TIME, delayWithUnits); break; case "started": annotations.put(RUN_TIME, delayWithUnits); break; case "killInitiated": annotations.put(KILL_TIME, delayWithUnits); break; } } } return annotations; } }
162
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/PodToTaskMapper.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.master.kubernetes; import java.util.Optional; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.DateTimeExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.tuple.Either; import com.netflix.titus.master.kubernetes.client.model.PodPhase; import com.netflix.titus.master.kubernetes.client.model.PodWrapper; import io.kubernetes.client.openapi.models.V1Node; import static com.netflix.titus.api.jobmanager.model.job.TaskState.Finished; import static com.netflix.titus.api.jobmanager.model.job.TaskState.KillInitiated; import static com.netflix.titus.api.jobmanager.model.job.TaskState.Launched; import static com.netflix.titus.api.jobmanager.model.job.TaskState.StartInitiated; import static com.netflix.titus.api.jobmanager.model.job.TaskState.Started; import static com.netflix.titus.api.jobmanager.model.job.TaskState.isBefore; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_FAILED; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_NORMAL; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_POD_SCHEDULED; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_STUCK_IN_STATE; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_TASK_KILLED; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_TASK_LOST; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_TRANSIENT_SYSTEM_ERROR; import static com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_UNKNOWN; import static com.netflix.titus.runtime.kubernetes.KubeConstants.NODE_LOST; /** * Evaluates pod phase, pod condition and container state to determine best fitting Titus task state. */ public class PodToTaskMapper { @VisibleForTesting static final String TASK_STARTING = "TASK_STARTING"; private final KubernetesConfiguration configuration; private final PodWrapper podWrapper; private final Optional<V1Node> node; private final Task task; private final ContainerResultCodeResolver containerResultCodeResolver; private final TitusRuntime titusRuntime; private final Either<TaskStatus, String> newTaskStatus; public PodToTaskMapper(KubernetesConfiguration configuration, PodWrapper podWrapper, Optional<V1Node> node, Task task, boolean podDeleted, ContainerResultCodeResolver containerResultCodeResolver, TitusRuntime titusRuntime) { this.configuration = configuration; this.podWrapper = podWrapper; this.node = node; this.task = task; this.containerResultCodeResolver = containerResultCodeResolver; this.titusRuntime = titusRuntime; if (TaskState.isTerminalState(task.getStatus().getState())) { this.newTaskStatus = irrelevant("task already marked as finished"); } else if (podDeleted) { this.newTaskStatus = handlePodDeleted(); } else { switch (podWrapper.getPodPhase()) { case PENDING: this.newTaskStatus = handlePodPending(); break; case RUNNING: this.newTaskStatus = handlePodRunning(); break; case SUCCEEDED: case FAILED: this.newTaskStatus = handlePodFinished(); break; case UNKNOWN: default: this.newTaskStatus = unexpected("unknown pod phase"); } } } /** * Handle pod object deleted event. */ private Either<TaskStatus, String> handlePodDeleted() { TaskState taskState = task.getStatus().getState(); boolean hasKillInitiatedState = JobFunctions.findTaskStatus(task, KillInitiated).isPresent(); String reason = podWrapper.getReason(); long now = titusRuntime.getClock().wallTime(); if (!hasKillInitiatedState) { if (NODE_LOST.equals(reason)) { return Either.ofValue(TaskStatus.newBuilder() .withState(Finished) .withReasonCode(effectiveFinalReasonCode(REASON_TASK_KILLED)) .withReasonMessage("The host running the container was unexpectedly terminated") .withTimestamp(now) .build() ); } else { return Either.ofValue(TaskStatus.newBuilder() .withState(Finished) .withReasonCode(effectiveFinalReasonCode(REASON_TASK_KILLED)) .withReasonMessage("Container was terminated without going through the Titus API") .withTimestamp(now) .build() ); } } String reasonCode; if (podWrapper.getPodPhase() == PodPhase.PENDING || podWrapper.getPodPhase() == PodPhase.RUNNING) { // Pod in pending phase which is being deleted must have been terminated, as it was never run. // Pod in running state that did not complete must have been terminated as well. if (taskState == KillInitiated && task.getStatus().getReasonCode().equals(REASON_STUCK_IN_STATE)) { reasonCode = REASON_TRANSIENT_SYSTEM_ERROR; } else { reasonCode = REASON_TASK_KILLED; } } else if (podWrapper.getPodPhase() == PodPhase.SUCCEEDED) { reasonCode = resolveFinalTaskState(REASON_NORMAL); } else if (podWrapper.getPodPhase() == PodPhase.FAILED) { reasonCode = resolveFinalTaskState(REASON_FAILED); } else { titusRuntime.getCodeInvariants().inconsistent("Pod: %s has unknown phase mapping: %s", podWrapper.getName(), podWrapper.getPodPhase()); reasonCode = REASON_UNKNOWN; } return Either.ofValue(TaskStatus.newBuilder() .withState(Finished) .withReasonCode(effectiveFinalReasonCode(reasonCode)) .withReasonMessage(podWrapper.getMessage()) .withTimestamp(now) .build() ); } private String resolveFinalTaskState(String currentReasonCode) { TaskState taskState = task.getStatus().getState(); if (taskState == KillInitiated && task.getStatus().getReasonCode().equals(REASON_STUCK_IN_STATE)) { return REASON_TRANSIENT_SYSTEM_ERROR; } else if (podWrapper.hasDeletionTimestamp() || taskState == KillInitiated) { return REASON_TASK_KILLED; } return currentReasonCode; } /** * Handle pod 'Pending' phase. In this phase we have to distinguish cases: * <ul> * <li>pod is waiting in the queue</li> * <li>pod is assigned to a node but not running yet</li> * </ul> */ private Either<TaskStatus, String> handlePodPending() { if (!podWrapper.isScheduled()) { return handlePodPendingQueued(); } return handlePodPendingInitializingInContainerWaitingState(podWrapper); } /** * Handle pod is waiting in the queue (is not scheduled yet). This event does not cause any task state * transition. We only verify consistency. */ private Either<TaskStatus, String> handlePodPendingQueued() { if (task.getStatus().getState() != TaskState.Accepted) { return unexpected("expected queued task in the Accepted state"); } return irrelevant("pod is waiting in the queue to be scheduled"); } /** * Handle pod is assigned to a node but not running yet. The following pre-conditions must exist: * <ul> * <li>pod condition 'PodScheduled' is set</li> * <li>nodeName is not empty</li> * </ul> * Based on container state and reason message the state is classified as 'Launched' or 'StartInitiated': * <ul> * <li>if reason != 'TASK_STARTING' set 'Launched'</li> * <li>if reason == 'TASK_STARTING' set 'StartInitiated'</li> * </ul> * The state update happens only forward. Backward changes (StartInitiated -> Launched) are ignored. */ private Either<TaskStatus, String> handlePodPendingInitializingInContainerWaitingState(PodWrapper podWrapper) { TaskState newState; // Pod that is being setup should be in 'Waiting' state. if (!podWrapper.hasContainerStateWaiting()) { newState = Launched; } else { String reason = podWrapper.getReason(); // inspect pod status reason to differentiate between Launched and StartInitiated (this is not standard Kubernetes) if (reason.equalsIgnoreCase(TASK_STARTING)) { newState = StartInitiated; } else { newState = Launched; } } // Check for races. Do not allow setting back task state. if (isBefore(newState, task.getStatus().getState())) { return unexpected(String.format("pod in state not consistent with the task state (newState=%s)", newState)); } String reason = podWrapper.getReason(); return Either.ofValue(TaskStatus.newBuilder() .withState(newState) .withReasonCode(StringExt.isEmpty(reason) ? REASON_POD_SCHEDULED : reason) .withReasonMessage(podWrapper.getMessage()) .withTimestamp(titusRuntime.getClock().wallTime()) .build() ); } /** * Handle pod 'Running. */ private Either<TaskStatus, String> handlePodRunning() { TaskState taskState = task.getStatus().getState(); // Check for races. Do not allow setting back task state. if (isBefore(Started, taskState)) { return unexpected("pod state (Running) not consistent with the task state"); } long now = titusRuntime.getClock().wallTime(); if ("NodeLost".equals(podWrapper.getReason())) { // If task is still in the Accepted state, move it first, as we know it was scheduled. if (taskState == TaskState.Accepted) { return Either.ofValue(TaskStatus.newBuilder() .withState(Launched) .withReasonCode(REASON_NORMAL) .withReasonMessage(String.format( "The pod is scheduled but the communication with its node is lost. If not recovered in %s, the task will be marked as failed", DateTimeExt.toTimeUnitString(configuration.getNodeLostTimeoutMs()) )) .withTimestamp(now) .build() ); } // Give it a chance to recover from the `NodeLost` state. long lastUpdateTime = task.getStatus().getTimestamp(); long deadline = lastUpdateTime + configuration.getNodeLostTimeoutMs(); if (deadline > now) { // Keep the existing state return Either.ofValue(task.getStatus()); } // We waited long enough. Time to mark this task as failed. return Either.ofValue(TaskStatus.newBuilder() .withState(Finished) .withReasonCode(REASON_TASK_LOST) .withReasonMessage("The node where task was scheduled is lost") .withTimestamp(now) .build() ); } return Either.ofValue(TaskStatus.newBuilder() .withState(Started) .withReasonCode(REASON_NORMAL) .withReasonMessage(podWrapper.getMessage()) .withTimestamp(now) .build() ); } /** * Handle pod 'Succeeded' or 'Failed'. Possible scenarios: * <ul> * <li>pod terminated while sitting in a queue</li> * <li>pod failure during container setup process (bad image, stuck in state, etc)</li> * <li>pod terminated during container setup</li> * <li>container ran to completion</li> * <li>container terminated by a user</li> * </ul> */ private Either<TaskStatus, String> handlePodFinished() { TaskState taskState = task.getStatus().getState(); String reasonCode; if (podWrapper.getPodPhase() == PodPhase.SUCCEEDED) { reasonCode = resolveFinalTaskState(REASON_NORMAL); } else { // PodPhase.FAILED reasonCode = resolveFinalTaskState(REASON_FAILED); } return Either.ofValue(TaskStatus.newBuilder() .withState(Finished) .withReasonCode(effectiveFinalReasonCode(reasonCode)) .withReasonMessage(podWrapper.getMessage()) .withTimestamp(titusRuntime.getClock().wallTime()) .build() ); } public Either<TaskStatus, String> getNewTaskStatus() { return newTaskStatus; } /** * Pod notification irrelevant to the current task state. */ private Either<TaskStatus, String> irrelevant(String message) { return Either.ofError(String.format("pod notification does not change task state (%s): digest=%s", message, digest())); } /** * Unexpected pod state. */ private Either<TaskStatus, String> unexpected(String cause) { return Either.ofError(String.format("unexpected (%s); digest=%s", cause, digest())); } private String digest() { StringBuilder builder = new StringBuilder("{"); // Task builder.append("taskId=").append(task.getId()).append(", "); builder.append("taskState=").append(task.getStatus().getState()).append(", "); // Pod builder.append("podPhase=").append(podWrapper.getPodPhase()).append(", "); builder.append("podReason=").append(podWrapper.getReason()).append(", "); builder.append("podMessage=").append(podWrapper.getMessage()).append(", "); builder.append("scheduled=").append(podWrapper.isScheduled()).append(", "); builder.append("deletionTimestamp=").append(podWrapper.hasDeletionTimestamp()).append(", "); // Node node.ifPresent(n -> builder.append("nodeId=").append(KubeUtil.getMetadataName(n.getMetadata()))); return builder.append("}").toString(); } private String effectiveFinalReasonCode(String reasonCode) { return containerResultCodeResolver.resolve(Finished, task, podWrapper).orElse(reasonCode); } }
163
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/DefaultContainerResultCodeResolver.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.master.kubernetes; import java.util.Optional; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.common.util.RegExpExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.kubernetes.client.model.PodWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class DefaultContainerResultCodeResolver implements ContainerResultCodeResolver { private static final Logger logger = LoggerFactory.getLogger(DefaultContainerResultCodeResolver.class); private final Function<String, Matcher> invalidRequestMessageMatcherFactory; private final Function<String, Matcher> crashedMessageMatcherFactory; private final Function<String, Matcher> transientSystemErrorMessageMatcherFactory; private final Function<String, Matcher> localSystemErrorMessageMatcherFactory; private final Function<String, Matcher> unknownSystemErrorMessageMatcherFactory; @Inject public DefaultContainerResultCodeResolver(KubernetesConfiguration kubernetesConfiguration) { this.invalidRequestMessageMatcherFactory = RegExpExt.dynamicMatcher(kubernetesConfiguration::getInvalidRequestMessagePattern, "invalidRequestMessagePattern", Pattern.DOTALL, logger); this.crashedMessageMatcherFactory = RegExpExt.dynamicMatcher(kubernetesConfiguration::getCrashedMessagePattern, "crashedMessagePattern", Pattern.DOTALL, logger); this.transientSystemErrorMessageMatcherFactory = RegExpExt.dynamicMatcher(kubernetesConfiguration::getTransientSystemErrorMessagePattern, "transientSystemErrorMessagePattern", Pattern.DOTALL, logger); this.localSystemErrorMessageMatcherFactory = RegExpExt.dynamicMatcher(kubernetesConfiguration::getLocalSystemErrorMessagePattern, "localSystemErrorMessagePattern", Pattern.DOTALL, logger); this.unknownSystemErrorMessageMatcherFactory = RegExpExt.dynamicMatcher(kubernetesConfiguration::getUnknownSystemErrorMessagePattern, "unknownSystemErrorMessagePattern", Pattern.DOTALL, logger); } @Override public Optional<String> resolve(TaskState nextTaskState, Task task, PodWrapper podWrapper) { if (nextTaskState != TaskState.Finished) { return Optional.empty(); } String reasonMessage = podWrapper.getMessage(); // If a pod crashed, this could be during the container setup (for example disk full) or while the container // is running. The former case we should classify as a transient system error, the latter a user error. if ("TASK_CRASHED".equals(podWrapper.getReason())) { // System error if (TaskState.isBefore(task.getStatus().getState(), TaskState.Started)) { return Optional.of(processReasonMessage(reasonMessage).orElse(TaskStatus.REASON_LOCAL_SYSTEM_ERROR)); } // User error return Optional.of(processReasonMessage(reasonMessage).orElse(TaskStatus.REASON_FAILED)); } return processReasonMessage(reasonMessage); } private Optional<String> processReasonMessage(String reasonMessage) { if (StringExt.isEmpty(reasonMessage)) { return Optional.empty(); } if (invalidRequestMessageMatcherFactory.apply(reasonMessage).matches()) { return Optional.of(TaskStatus.REASON_INVALID_REQUEST); } if (crashedMessageMatcherFactory.apply(reasonMessage).matches()) { return Optional.of(TaskStatus.REASON_CRASHED); } if (transientSystemErrorMessageMatcherFactory.apply(reasonMessage).matches()) { return Optional.of(TaskStatus.REASON_TRANSIENT_SYSTEM_ERROR); } if (localSystemErrorMessageMatcherFactory.apply(reasonMessage).matches()) { return Optional.of(TaskStatus.REASON_LOCAL_SYSTEM_ERROR); } if (unknownSystemErrorMessageMatcherFactory.apply(reasonMessage).matches()) { return Optional.of(TaskStatus.REASON_UNKNOWN_SYSTEM_ERROR); } return Optional.empty(); } }
164
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/KubernetesConfiguration.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.kubernetes; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.kubernetes") public interface KubernetesConfiguration { @DefaultValue(".*invalidRequest.*") String getInvalidRequestMessagePattern(); @DefaultValue(".*crashed.*") String getCrashedMessagePattern(); @DefaultValue(".*transientSystemError.*") String getTransientSystemErrorMessagePattern(); @DefaultValue(".*localSystemError.*") String getLocalSystemErrorMessagePattern(); @DefaultValue(".*unknownSystemError.*") String getUnknownSystemErrorMessagePattern(); @DefaultValue("true") boolean isReconcilerEnabled(); @DefaultValue("10000") long getReconcilerInitialDelayMs(); @DefaultValue("30000") long getReconcilerIntervalMs(); @DefaultValue("60000") long getOrphanedPodTimeoutMs(); @DefaultValue("600000") long getNodeLostTimeoutMs(); /** * @return the kube api server url to use. If this is empty, use the kube config path instead. */ @DefaultValue("") String getKubeApiServerUrl(); /** * @return the path to the kubeconfig file */ @DefaultValue("/run/kubernetes/config") String getKubeConfigPath(); /** * @return whether to enable or disable compression when LISTing pods using kubernetes java client */ @DefaultValue("false") boolean isCompressionEnabledForKubeApiClient(); }
165
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/KubeObjectFormatter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.kubernetes; import java.util.List; import java.util.Map; import io.kubernetes.client.custom.Quantity; import io.kubernetes.client.openapi.models.V1CSIPersistentVolumeSource; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1NodeSpec; import io.kubernetes.client.openapi.models.V1NodeStatus; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1ObjectReference; import io.kubernetes.client.openapi.models.V1PersistentVolume; import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim; import io.kubernetes.client.openapi.models.V1PersistentVolumeClaimSpec; import io.kubernetes.client.openapi.models.V1PersistentVolumeClaimStatus; import io.kubernetes.client.openapi.models.V1PersistentVolumeSpec; import io.kubernetes.client.openapi.models.V1PersistentVolumeStatus; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodSpec; import io.kubernetes.client.openapi.models.V1PodStatus; import io.kubernetes.client.openapi.models.V1Taint; /** * Helper functions to build compact representations of Kube objects suitable for logging. */ public final class KubeObjectFormatter { public static String formatPodEssentials(V1Pod pod) { try { return formatPodEssentialsInternal(pod); } catch (Exception e) { return "pod formatting error: " + e.getMessage(); } } private static String formatPodEssentialsInternal(V1Pod pod) { StringBuilder builder = new StringBuilder("{"); appendMetadata(builder, pod.getMetadata()); V1PodSpec spec = pod.getSpec(); if (spec != null) { builder.append(", nodeName=").append(spec.getNodeName()); } V1PodStatus status = pod.getStatus(); if (status != null) { builder.append(", phase=").append(status.getPhase()); builder.append(", reason=").append(status.getReason()); } builder.append("}"); return builder.toString(); } public static String formatNodeEssentials(V1Node node) { try { return formatNodeEssentialsInternal(node); } catch (Exception e) { return "node formatting error: " + e.getMessage(); } } private static String formatNodeEssentialsInternal(V1Node node) { StringBuilder builder = new StringBuilder("{"); appendMetadata(builder, node.getMetadata()); V1NodeSpec spec = node.getSpec(); if (spec != null) { List<V1Taint> taints = spec.getTaints(); builder.append(", taints="); if (taints == null) { builder.append("[]"); } else { builder.append("["); taints.forEach(taint -> { builder.append("{"); builder.append("key=").append(taint.getKey()).append(", "); builder.append("value=").append(taint.getValue()).append(", "); builder.append("effect=").append(taint.getEffect()); }); builder.append("]"); } } V1NodeStatus status = node.getStatus(); if (status != null) { builder.append(", phase=").append(status.getPhase()); Map<String, Quantity> allocatable = status.getAllocatable(); if (allocatable != null) { builder.append(", allocatableResources={"); allocatable.forEach((key, value) -> builder.append(key).append("=").append(value.getNumber().toString()).append(", ")); builder.setLength(builder.length() - 2); builder.append("}"); } } builder.append("}"); return builder.toString(); } public static String formatPvEssentials(V1PersistentVolume pv) { try { return formatPvEssentialsInternal(pv); } catch (Exception e) { return "pv formatting error: " + e.getMessage(); } } private static String formatPvEssentialsInternal(V1PersistentVolume pv) { StringBuilder builder = new StringBuilder("{"); appendMetadata(builder, pv.getMetadata()); V1PersistentVolumeSpec spec = pv.getSpec(); if (spec != null) { V1CSIPersistentVolumeSource csi = spec.getCsi(); if (csi != null) { builder.append(", volume=").append(csi.getVolumeHandle()); builder.append(", driver=").append(csi.getDriver()); } V1ObjectReference claimRef = spec.getClaimRef(); if (claimRef != null) { builder.append(", claimRef=").append(claimRef.getName()); } } V1PersistentVolumeStatus status = pv.getStatus(); if (status != null) { builder.append(", phase=").append(status.getPhase()); builder.append("null"); } builder.append("}"); return builder.toString(); } public static String formatPvcEssentials(V1PersistentVolumeClaim pvc) { try { return formatPvcEssentialsInternal(pvc); } catch (Exception e) { return "pvc formatting error: " + e.getMessage(); } } private static String formatPvcEssentialsInternal(V1PersistentVolumeClaim pvc) { StringBuilder builder = new StringBuilder("{"); appendMetadata(builder, pvc.getMetadata()); V1PersistentVolumeClaimSpec spec = pvc.getSpec(); if (spec != null) { builder.append(", volume=").append(spec.getVolumeName()); } V1PersistentVolumeClaimStatus status =pvc.getStatus(); if (status != null) { builder.append(", phase=").append(status.getPhase()); } builder.append("}"); return builder.toString(); } private static void appendMetadata(StringBuilder builder, V1ObjectMeta metadata) { if (metadata != null) { builder.append("name=").append(metadata.getName()); builder.append(", labels=").append(metadata.getLabels()); } else { builder.append("name=").append("<no_metadata>"); } } }
166
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/KubePodUtil.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.master.kubernetes.pod; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import com.google.protobuf.util.JsonFormat; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.TaskAttributes; 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.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.PlatformSidecar; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.VolumeMount; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolumeUtils; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.model.job.volume.SaaSVolumeSource; import com.netflix.titus.api.jobmanager.model.job.volume.SharedContainerVolumeSource; import com.netflix.titus.api.jobmanager.model.job.volume.Volume; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.Tier; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.scheduler.SchedulerConfiguration; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.models.V1AWSElasticBlockStoreVolumeSource; import io.kubernetes.client.openapi.models.V1CephFSVolumeSource; import io.kubernetes.client.openapi.models.V1EnvVar; import io.kubernetes.client.openapi.models.V1FlexVolumeSource; import io.kubernetes.client.openapi.models.V1Volume; import io.kubernetes.client.openapi.models.V1VolumeMount; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyStorageEBSFSType; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyStorageEBSMountPath; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyStorageEBSMountPerm; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyStorageEBSVolumeID; import static com.netflix.titus.common.kube.Annotations.AnnotationKeySuffixSidecars; public class KubePodUtil { private static final String MOUNT_PROPAGATION_BIDIRECTIONAL = com.netflix.titus.grpc.protogen.VolumeMount.MountPropagation.MountPropagationBidirectional.toString(); private static final String MOUNT_PROPAGATION_HOST_TO_CONTAINER = com.netflix.titus.grpc.protogen.VolumeMount.MountPropagation.MountPropagationHostToContainer.toString(); private static final String MOUNT_PROPAGATION_NONE = com.netflix.titus.grpc.protogen.VolumeMount.MountPropagation.MountPropagationNone.toString(); private static final Logger logger = LoggerFactory.getLogger(KubePodUtil.class); private static final JsonFormat.Printer grpcJsonPrinter = JsonFormat.printer().includingDefaultValueFields(); public static Map<String, String> createPodAnnotationsFromJobParameters(Job<?> job) { Map<String, String> annotations = new HashMap<>(); Map<String, String> containerAttributes = job.getJobDescriptor().getContainer().getAttributes(); Evaluators.acceptNotNull( containerAttributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_ACCOUNT_ID), accountId -> annotations.put(KubeConstants.POD_LABEL_ACCOUNT_ID, accountId) ); Evaluators.acceptNotNull( containerAttributes.get(JobAttributes.JOB_CONTAINER_ATTRIBUTE_SUBNETS), accountId -> annotations.put(KubeConstants.POD_LABEL_SUBNETS, accountId) ); return annotations; } public static Map<String, String> createEbsPodAnnotations(Job<?> job, Task task) { Map<String, String> annotations = new HashMap<>(); List<EbsVolume> ebsVolumes = job.getJobDescriptor().getContainer().getContainerResources().getEbsVolumes(); if (ebsVolumes.isEmpty()) { return Collections.emptyMap(); } EbsVolume ebsVolume = job.getJobDescriptor().getContainer().getContainerResources().getEbsVolumes().get(0); String ebsVolumeId = task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_EBS_VOLUME_ID); if (ebsVolumeId == null) { logger.error("Expected to find assigned EBS volume ID to task {} from volumes {}", task.getId(), ebsVolumes); return Collections.emptyMap(); } annotations.put(AnnotationKeyStorageEBSVolumeID, ebsVolumeId); annotations.put(AnnotationKeyStorageEBSMountPerm, ebsVolume.getMountPermissions().toString()); annotations.put(AnnotationKeyStorageEBSMountPath, ebsVolume.getMountPath()); annotations.put(AnnotationKeyStorageEBSFSType, ebsVolume.getFsType()); return annotations; } /** * Looks at a job's PlatformSidecars and converts them to the correct annotations * for the platform sidecar mutator to use. */ public static Map<String, String> createPlatformSidecarAnnotations(Job<?> job) { Map<String, String> annotations = new HashMap<>(); for (PlatformSidecar ps : job.getJobDescriptor().getPlatformSidecars()) { annotations.putAll(createSinglePlatformSidecarAnnotations(ps)); } return annotations; } private static Map<String, String> createSinglePlatformSidecarAnnotations(PlatformSidecar ps) { Map<String, String> annotations = new HashMap<>(); String nameKey = ps.getName() + "." + AnnotationKeySuffixSidecars; annotations.put(nameKey, "true"); String channelKey = ps.getName() + "." + AnnotationKeySuffixSidecars + "/channel"; annotations.put(channelKey, ps.getChannel()); String argumentsKey = ps.getName() + "." + AnnotationKeySuffixSidecars + "/arguments"; annotations.put(argumentsKey, ps.getArguments()); return annotations; } /** * Returns a job descriptor with fields unnecessary for inclusion on the pod removed. */ public static com.netflix.titus.api.jobmanager.model.job.JobDescriptor<?> filterPodJobDescriptor(com.netflix.titus.api.jobmanager.model.job.JobDescriptor<?> jobDescriptor) { // Metatron auth context is not needed on the pod. return JobFunctions.deleteJobSecurityAttributes(jobDescriptor, Collections.singleton(JobAttributes.JOB_SECURITY_ATTRIBUTE_METATRON_AUTH_CONTEXT)); } /** * Builds the various objects needed to for Pod objects to use a volume. */ public static Optional<Pair<V1Volume, V1VolumeMount>> buildV1EBSObjects(Job<?> job, Task task) { return EbsVolumeUtils.getEbsVolumeForTask(job, task) .map(ebsVolume -> { boolean readOnly = ebsVolume.getMountPermissions().equals(EbsVolume.MountPerm.RO); V1AWSElasticBlockStoreVolumeSource ebsVolumeSource = new V1AWSElasticBlockStoreVolumeSource() .volumeID(ebsVolume.getVolumeId()) .fsType(ebsVolume.getFsType()) .readOnly(false); V1Volume v1Volume = new V1Volume() // The resource name matches the volume ID so that the resource is independent of the job. .name(ebsVolume.getVolumeId()) .awsElasticBlockStore(ebsVolumeSource); V1VolumeMount v1VolumeMount = new V1VolumeMount() // The mount refers to the V1Volume being mounted .name(ebsVolume.getVolumeId()) .mountPath(ebsVolume.getMountPath()) .readOnly(readOnly); return Pair.of(v1Volume, v1VolumeMount); }); } /** * Converts a list of VolumeMounts and converts them to the k8s VolumeMounts */ public static List<V1VolumeMount> buildV1VolumeMounts(List<VolumeMount> volumeMounts) { List<V1VolumeMount> v1VolumeMounts = new ArrayList<>(); if (volumeMounts == null) { return v1VolumeMounts; } for (VolumeMount vm : volumeMounts) { v1VolumeMounts.add(buildV1VolumeMount(vm)); } return v1VolumeMounts; } private static V1VolumeMount buildV1VolumeMount(VolumeMount vm) { return new V1VolumeMount() .name(vm.getVolumeName()) .mountPath(vm.getMountPath()) .mountPropagation(buildV1VolumeMountPropagation(vm.getMountPropagation())) .readOnly(vm.getReadOnly()) .subPath(vm.getSubPath()); } private static String buildV1VolumeMountPropagation(String mountPropagation) { if (mountPropagation.equals(MOUNT_PROPAGATION_BIDIRECTIONAL)) { return "Bidirectional"; } else if (mountPropagation.equals(MOUNT_PROPAGATION_HOST_TO_CONTAINER)) { return "HostToContainer"; } else if (mountPropagation.equals(MOUNT_PROPAGATION_NONE)) { return "None"; } else { return "None"; } } public static List<V1Volume> buildV1Volumes(List<Volume> volumes) { if (volumes == null) { return Collections.emptyList(); } List<V1Volume> v1Volumes = new ArrayList<>(); for (Volume v : volumes) { buildV1Volume(v).ifPresent(v1Volumes::add); } return v1Volumes; } private static Optional<V1Volume> buildV1Volume(Volume volume) { if (volume.getVolumeSource() instanceof SharedContainerVolumeSource) { V1FlexVolumeSource flexVolume = getV1FlexVolumeForSharedContainerVolumeSource(volume); return Optional.ofNullable(new V1Volume() .name(volume.getName()) .flexVolume(flexVolume)); } else if (volume.getVolumeSource() instanceof SaaSVolumeSource) { V1CephFSVolumeSource cephVolume = getV1CephVolumeSource(volume); return Optional.ofNullable(new V1Volume() .name(volume.getName()) .cephfs(cephVolume)); } else { return Optional.empty(); } } private static V1FlexVolumeSource getV1FlexVolumeForSharedContainerVolumeSource(Volume volume) { SharedContainerVolumeSource sharedContainerVolumeSource = (SharedContainerVolumeSource) volume.getVolumeSource(); Map<String, String> options = new HashMap<>(); options.put("sourceContainer", sharedContainerVolumeSource.getSourceContainer()); options.put("sourcePath", sharedContainerVolumeSource.getSourcePath()); return new V1FlexVolumeSource() .driver("SharedContainerVolumeSource") .options(options); } private static V1CephFSVolumeSource getV1CephVolumeSource(Volume volume) { SaaSVolumeSource saaSVolumeSource = (SaaSVolumeSource) volume.getVolumeSource(); // This Ceph volume source is not "truly" representative of all the data we will // need to mount a SaaS volume. The actual connection string is built just-in-time // by the executor. // `monitors` must be set, however, to pass KubeAPI validation. // The "path" is what we use to store the actual SaaS volume ID. return new V1CephFSVolumeSource() .monitors(Collections.singletonList("")) .path(saaSVolumeSource.getSaaSVolumeID()); } /** * Builds the image string for Kubernetes pod spec */ public static String buildImageString(String registryUrl, Image image) { return registryUrl + image.getName() + "@" + image.getDigest(); } /** * Convert map into list of Kubernetes env var objects. */ public static List<V1EnvVar> toV1EnvVar(Map<String, String> env) { return env.entrySet().stream() .map(entry -> new V1EnvVar().name(entry.getKey()).value(entry.getValue())) .collect(Collectors.toList()); } /** * Sanitize name based on Kubernetes regex: [a-z0-9]([-a-z0-9]*[a-z0-9])?. */ public static String sanitizeVolumeName(String name) { String replaced = name.toLowerCase().replaceAll("[^a-z0-9]([^-a-z0-9]*[^a-z0-9])?", "-"); // All volume names *must* end with a normal char, so we always append something to the end return replaced + "-vol"; } public static List<String> getVolumeNames(List<V1Volume> volumes) { return volumes.stream() .map(e -> e.getName()) .collect(Collectors.toList()); } public static String selectScheduler(SchedulerConfiguration schedulerConfiguration, ApplicationSLA capacityGroupDescriptor, KubePodConfiguration configuration) { if (configuration.isMixedSchedulingEnabled()) { return configuration.getMixedSchedulingSchedulerName(); } String schedulerName; if (capacityGroupDescriptor != null && capacityGroupDescriptor.getTier() == Tier.Critical) { if (schedulerConfiguration.isCriticalServiceJobSpreadingEnabled()) { schedulerName = configuration.getReservedCapacityKubeSchedulerName(); } else { schedulerName = configuration.getReservedCapacityKubeSchedulerNameForBinPacking(); } } else { schedulerName = configuration.getKubeSchedulerName(); } return schedulerName; } public static String selectPriorityClassName(ApplicationSLA capacityGroupDescriptor, Job<?> job, KubePodConfiguration configuration) { if (!configuration.isMixedSchedulingEnabled()) { // Returning null here means it will be unset when we create the pod, // but will in turn get the `globalDefault` of whatever the priority class is for the cluster return null; } if (capacityGroupDescriptor != null && capacityGroupDescriptor.getTier() == Tier.Critical) { // TODO: Put these in titus-kube-common return "sched-latency-fast"; } JobDescriptor.JobDescriptorExt jobDescriptorExt = job.getJobDescriptor().getExtensions(); if (jobDescriptorExt instanceof ServiceJobExt) { return "sched-latency-medium"; } return "sched-latency-delay"; } }
167
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/PodFactory.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.master.kubernetes.pod; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import io.kubernetes.client.openapi.models.V1Pod; public interface PodFactory { V1Pod buildV1Pod(Job<?> job, Task task); }
168
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/KubePodModule.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.master.kubernetes.pod; import java.util.Arrays; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.archaius.api.Config; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.kubernetes.ContainerResultCodeResolver; import com.netflix.titus.master.kubernetes.DefaultContainerResultCodeResolver; import com.netflix.titus.master.kubernetes.pod.affinity.DefaultPodAffinityFactory; import com.netflix.titus.master.kubernetes.pod.affinity.PodAffinityFactory; import com.netflix.titus.master.kubernetes.pod.legacy.ContainerEnvFactory; import com.netflix.titus.master.kubernetes.pod.legacy.DefaultAggregatingContainerEnvFactory; import com.netflix.titus.master.kubernetes.pod.legacy.TitusProvidedContainerEnvFactory; import com.netflix.titus.master.kubernetes.pod.legacy.UserProvidedContainerEnvFactory; import com.netflix.titus.master.kubernetes.pod.resourcepool.CapacityGroupPodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.ExplicitJobPodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.FarzonePodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.FixedResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.GpuPodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.KubeSchedulerPodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.MixedSchedulerResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.PodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.PodResourcePoolResolverChain; import com.netflix.titus.master.kubernetes.pod.resourcepool.PodResourcePoolResolverFeatureGuard; import com.netflix.titus.master.kubernetes.pod.resourcepool.PodResourcePoolResolvers; import com.netflix.titus.master.kubernetes.pod.taint.DefaultTaintTolerationFactory; import com.netflix.titus.master.kubernetes.pod.taint.TaintTolerationFactory; import com.netflix.titus.master.kubernetes.pod.topology.DefaultTopologyFactory; import com.netflix.titus.master.kubernetes.pod.topology.TopologyFactory; import com.netflix.titus.master.kubernetes.pod.v1.V1SpecPodFactory; import com.netflix.titus.master.kubernetes.KubernetesConfiguration; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; public class KubePodModule extends AbstractModule { private static final String RESOURCE_POOL_PROPERTIES_PREFIX = "titus.resourcePools"; @Override protected void configure() { bind(PodFactory.class).to(V1SpecPodFactory.class); bind(ContainerResultCodeResolver.class).to(DefaultContainerResultCodeResolver.class); bind(PodAffinityFactory.class).to(DefaultPodAffinityFactory.class); bind(TaintTolerationFactory.class).to(DefaultTaintTolerationFactory.class); bind(TopologyFactory.class).to(DefaultTopologyFactory.class); } /** * TODO Move properties from {@link KubernetesConfiguration} to other configuration classes. */ @Provides @Singleton public KubernetesConfiguration getBackendConfiguration(ConfigProxyFactory factory) { return factory.newProxy(KubernetesConfiguration.class); } @Provides @Singleton public KubePodConfiguration getKubePodConfiguration(ConfigProxyFactory factory) { return factory.newProxy(KubePodConfiguration.class); } @Provides @Singleton public PodResourcePoolResolver getPodResourcePoolResolver(KubePodConfiguration configuration, Config config, ApplicationSlaManagementService capacityGroupService, TitusRuntime titusRuntime) { return new PodResourcePoolResolverFeatureGuard( configuration, new PodResourcePoolResolverChain(Arrays.asList( new ExplicitJobPodResourcePoolResolver(), new FarzonePodResourcePoolResolver(configuration), new GpuPodResourcePoolResolver(configuration, capacityGroupService), new MixedSchedulerResourcePoolResolver(configuration), new KubeSchedulerPodResourcePoolResolver(capacityGroupService), new CapacityGroupPodResourcePoolResolver( configuration, config.getPrefixedView(RESOURCE_POOL_PROPERTIES_PREFIX), capacityGroupService, titusRuntime ), new FixedResourcePoolResolver(PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC) ), titusRuntime) ); } @Provides @Singleton public ContainerEnvFactory getContainerEnvFactory(TitusRuntime titusRuntime) { return new DefaultAggregatingContainerEnvFactory(titusRuntime, UserProvidedContainerEnvFactory.getInstance(), TitusProvidedContainerEnvFactory.getInstance()); } }
169
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/KubePodConstants.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.master.kubernetes.pod; public final class KubePodConstants { private KubePodConstants() { } public static final String DEFAULT_NAMESPACE = "default"; public static final String DEFAULT_IMAGE_PULL_POLICY = "IfNotPresent"; public static String NEVER_RESTART_POLICY = "Never"; public static final String DEFAULT_DNS_POLICY = "Default"; public static final String JOB_ID = "v3.job.titus.netflix.com/job-id"; public static final String TASK_ID = "v3.job.titus.netflix.com/task-id"; // Resources public static final String RESOURCE_CPU = "cpu"; public static final String RESOURCE_MEMORY = "memory"; public static final String RESOURCE_EPHERMERAL_STORAGE = "ephemeral-storage"; public static final String RESOURCE_NETWORK = "titus/network"; public static final String RESOURCE_GPU = "nvidia.com/gpu"; // Security public static final String IAM_ROLE = "iam.amazonaws.com/role"; public static final String SECURITY_GROUPS_LEGACY = "network.titus.netflix.com/securityGroups"; // https://kubernetes.io/docs/tutorials/clusters/apparmor/#securing-a-pod public static final String PREFIX_APP_ARMOR = "container.apparmor.security.beta.kubernetes.io"; public static final String POD_SCHEMA_VERSION = "pod.netflix.com/pod-schema-version"; public static final String POD_SYSTEM_ENV_VAR_NAMES = "pod.titus.netflix.com/system-env-var-names"; // Titus-specific fields public static final String JOB_ACCEPTED_TIMESTAMP_MS = "v3.job.titus.netflix.com/accepted-timestamp-ms"; public static final String JOB_TYPE = "v3.job.titus.netflix.com/type"; public static final String JOB_DESCRIPTOR = "v3.job.titus.netflix.com/descriptor"; public static final String ENTRYPOINT_SHELL_SPLITTING_ENABLED = "pod.titus.netflix.com/entrypoint-shell-splitting-enabled"; public static final String JOB_DISRUPTION_BUDGET_POLICY_NAME = "v3.job.titus.netflix.com/disruption-budget-policy"; // Security public static final String SECURITY_APP_METADATA = "security.netflix.com/workload-metadata"; public static final String SECURITY_APP_METADATA_SIG = "security.netflix.com/workload-metadata-sig"; // Pod Features public static final String POD_CPU_BURSTING_ENABLED = "pod.netflix.com/cpu-bursting-enabled"; public static final String POD_KVM_ENABLED = "pod.netflix.com/kvm-enabled"; public static final String POD_FUSE_ENABLED = "pod.netflix.com/fuse-enabled"; public static final String POD_HOSTNAME_STYLE = "pod.netflix.com/hostname-style"; public static final String POD_OOM_SCORE_ADJ = "pod.netflix.com/oom-score-adj"; public static final String POD_SCHED_POLICY = "pod.netflix.com/sched-policy"; public static final String POD_SECCOMP_AGENT_NET_ENABLED = "pod.netflix.com/seccomp-agent-net-enabled"; public static final String POD_SECCOMP_AGENT_PERF_ENABLED = "pod.netflix.com/seccomp-agent-perf-enabled"; public static final String POD_TRAFFIC_STEERING_ENABLED = "pod.netflix.com/traffic-steering-enabled"; public static final String POD_IMAGE_TAG_PREFIX = "pod.titus.netflix.com/image-tag-"; // Container Logging Config public static final String LOG_KEEP_LOCAL_FILE = "log.netflix.com/keep-local-file-after-upload"; public static final String LOG_S3_BUCKET_NAME = "log.netflix.com/s3-bucket-name"; public static final String LOG_S3_PATH_PREFIX = "log.netflix.com/s3-path-prefix"; public static final String LOG_S3_WRITER_IAM_ROLE = "log.netflix.com/s3-writer-iam-role"; public static final String LOG_STDIO_CHECK_INTERVAL = "log.netflix.com/stdio-check-interval"; public static final String LOG_UPLOAD_THRESHOLD_TIME = "log.netflix.com/upload-threshold-time"; public static final String LOG_UPLOAD_CHECK_INTERVAL = "log.netflix.com/upload-check-interval"; public static final String LOG_UPLOAD_REGEXP = "log.netflix.com/upload-regexp"; // Service Configuration public static final String SERVICE_PREFIX = "service.netflix.com"; }
170
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/KubePodConfiguration.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.master.kubernetes.pod; import java.util.List; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.titus.master.kubernetes.pod.resourcepool.CapacityGroupPodResourcePoolResolver; @Configuration(prefix = "titusMaster.kubernetes.pod") public interface KubePodConfiguration { /** * @return the registry URL that will be merged with the image name. */ @DefaultValue("") String getRegistryUrl(); /** * @return the min that can be set on the killWaitSeconds field. The default value will be used instead if the value specified * is lower than the min. */ @DefaultValue("10") int getMinKillWaitSeconds(); /** * @return the max that can be set on the killWaitSeconds field. The default value will be used instead if the value specified * is greater than the max. */ @DefaultValue("300") int getMaxKillWaitSeconds(); /** * @return maximum amount of seconds to wait before forcefully terminating a batch job container. */ @DefaultValue("10") int getBatchDefaultKillWaitSeconds(); /** * @return maximum amount of seconds to wait before forcefully terminating a service job container. */ @DefaultValue("120") int getServiceDefaultKillWaitSeconds(); /** * Get list of farzone names. A job associated with a zone hard constraint, where the zone id is one of the * farzone names has pods tainted with that zone id. */ List<String> getFarzones(); /** * A list of primary/default availability zones. */ List<String> getPrimaryZones(); /** * @return whether or not to add a json encoded job descriptor as a pod annotation */ @DefaultValue("true") boolean isJobDescriptorAnnotationEnabled(); /** * Default GPU instance types assigned to a pod requesting GPU resources, but not specifying directly which GPU * instance to use. If empty, no GPU instance type constraint is set. */ List<String> getDefaultGpuInstanceTypes(); @DefaultValue("default-scheduler") String getKubeSchedulerName(); @DefaultValue("titus-kube-scheduler-reserved") String getReservedCapacityKubeSchedulerName(); @DefaultValue("titus-kube-scheduler-mixed") String getMixedSchedulingSchedulerName(); /** * This string corresponds to a kube-scheduler profile name which implements exact same set of scheduler plugins as * the standard reserved capacity scheduler (titus-kube-scheduler-reserved) except * with bin-packing plugins enabled. */ @DefaultValue("titus-kube-scheduler-reserved-binpacking") String getReservedCapacityKubeSchedulerNameForBinPacking(); /** * This bool indicates that we are in "mixed scheduling" mode, which means that we will launch pods * on either elastic or reserved resource pools if they fit. */ @DefaultValue("false") boolean isMixedSchedulingEnabled(); /** * The grace period on the pod object to use when the pod is created. */ @DefaultValue("600") long getPodTerminationGracePeriodSeconds(); /** * Set to true to enable resource pool affinity placement constraints. */ @DefaultValue("true") boolean isResourcePoolAffinityEnabled(); /** * Comma separated list of GPU resource pool names. Set to empty string if no GPU resource pools are available. */ @DefaultValue("") String getGpuResourcePoolNames(); /** * Frequency at which {@link CapacityGroupPodResourcePoolResolver} resolve configuration is re-read. */ @DefaultValue("5000") long getCapacityGroupPodResourcePoolResolverUpdateIntervalMs(); /** * Set to true to enable S3 writer configuration. */ @DefaultValue("true") boolean isDefaultS3WriterRoleEnabled(); /** * Default IAM role that should be used to upload log files to S3 bucket. */ String getDefaultS3WriterRole(); /** * A regular expression pattern for capacity groups for which job spreading should be disabled. */ @DefaultValue("NONE") String getDisabledJobSpreadingPattern(); /** * Job spreading on nodes skew adjustment factor, with the max skew computed as job_size/alpha. * Setting value <= 1 effectively disables the spreading (max skew >= job size). */ @DefaultValue("3") double getJobSpreadingSkewAlpha(); /** * The maximum allowed skew. This is how many tasks from a job can land on the same node. */ @DefaultValue("48") int getJobSpreadingMaxSkew(); /** * @return the pod spec target region to use */ String getTargetRegion(); }
171
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/v1/V1SpecPodFactory.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.master.kubernetes.pod.v1; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.Inject; import javax.inject.Singleton; 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.BasicContainer; 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.Job; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.JobGroupInfo; 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.LogStorageInfo; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfos; import com.netflix.titus.api.jobmanager.model.job.SecurityProfile; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.EfsMount; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.kubernetes.PerformanceToolUtil; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.kubernetes.pod.KubePodUtil; import com.netflix.titus.master.kubernetes.pod.PodFactory; import com.netflix.titus.master.kubernetes.pod.affinity.PodAffinityFactory; import com.netflix.titus.master.kubernetes.pod.legacy.ContainerEnvFactory; import com.netflix.titus.master.kubernetes.pod.taint.TaintTolerationFactory; import com.netflix.titus.master.kubernetes.pod.topology.TopologyFactory; import com.netflix.titus.master.scheduler.SchedulerConfiguration; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.custom.Quantity; import io.kubernetes.client.openapi.models.V1Affinity; import io.kubernetes.client.openapi.models.V1Container; import io.kubernetes.client.openapi.models.V1EmptyDirVolumeSource; import io.kubernetes.client.openapi.models.V1EnvVar; import io.kubernetes.client.openapi.models.V1NFSVolumeSource; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodSpec; import io.kubernetes.client.openapi.models.V1ResourceRequirements; import io.kubernetes.client.openapi.models.V1Volume; import io.kubernetes.client.openapi.models.V1VolumeMount; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_ACCOUNT_ID; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_IMDS_REQUIRE_TOKEN; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_NET_ENABLED; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_PERF_ENABLED; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_TRAFFIC_STEERING_ENABLED; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_CONTAINER_ATTRIBUTE_SUBNETS; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_ALLOW_CPU_BURSTING; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_BURSTING; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_JUMBO; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_ASSIGN_IPV6_ADDRESS; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_FUSE_ENABLED; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_HOSTNAME_STYLE; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_KILL_WAIT_SECONDS; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_LOG_KEEP_LOCAL_FILE_AFTER_UPLOAD; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_LOG_STDIO_CHECK_INTERVAL; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_CHECK_INTERVAL; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_REGEXP; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_THRESHOLD_TIME; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTES_SCHED_BATCH; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTE_EIPS; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_ATTRIBUTE_EIP_POOL; import static com.netflix.titus.api.jobmanager.JobAttributes.TITUS_PARAMETER_AGENT_PREFIX; import static com.netflix.titus.api.jobmanager.model.job.Container.ATTRIBUTE_NETFLIX_APP_METADATA; import static com.netflix.titus.api.jobmanager.model.job.Container.ATTRIBUTE_NETFLIX_APP_METADATA_SIG; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.getJobType; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyEgressBandwidth; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyIngressBandwidth; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkAccountID; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkAssignIPv6Address; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkBurstingEnabled; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkElasticIPPool; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkElasticIPs; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkIMDSRequireToken; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkJumboFramesEnabled; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkMode; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkSecurityGroups; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkStaticIPAllocationUUID; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyNetworkSubnetIDs; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyWorkloadDetail; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyWorkloadName; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyWorkloadOwnerEmail; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyWorkloadSequence; import static com.netflix.titus.common.kube.Annotations.AnnotationKeyWorkloadStack; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.DEFAULT_DNS_POLICY; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.DEFAULT_IMAGE_PULL_POLICY; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.DEFAULT_NAMESPACE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.ENTRYPOINT_SHELL_SPLITTING_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.IAM_ROLE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.JOB_ACCEPTED_TIMESTAMP_MS; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.JOB_DISRUPTION_BUDGET_POLICY_NAME; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.JOB_ID; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.JOB_TYPE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_KEEP_LOCAL_FILE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_S3_BUCKET_NAME; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_S3_PATH_PREFIX; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_S3_WRITER_IAM_ROLE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_STDIO_CHECK_INTERVAL; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_UPLOAD_CHECK_INTERVAL; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_UPLOAD_REGEXP; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.LOG_UPLOAD_THRESHOLD_TIME; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.NEVER_RESTART_POLICY; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_CPU_BURSTING_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_FUSE_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_HOSTNAME_STYLE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_IMAGE_TAG_PREFIX; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_SCHED_POLICY; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_SCHEMA_VERSION; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_SECCOMP_AGENT_NET_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_SECCOMP_AGENT_PERF_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_TRAFFIC_STEERING_ENABLED; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.POD_SYSTEM_ENV_VAR_NAMES; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_CPU; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_EPHERMERAL_STORAGE; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_GPU; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_MEMORY; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.RESOURCE_NETWORK; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.SECURITY_APP_METADATA; import static com.netflix.titus.master.kubernetes.pod.KubePodConstants.SECURITY_APP_METADATA_SIG; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.buildV1EBSObjects; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.buildV1Volumes; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.createEbsPodAnnotations; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.createPlatformSidecarAnnotations; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.sanitizeVolumeName; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.selectPriorityClassName; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.selectScheduler; import static com.netflix.titus.master.kubernetes.pod.KubePodUtil.toV1EnvVar; @Singleton public class V1SpecPodFactory implements PodFactory { public static final String DEV_SHM = "dev-shm"; public static final String DEV_SHM_MOUNT_PATH = "/dev/shm"; private final KubePodConfiguration configuration; private final ApplicationSlaManagementService capacityGroupManagement; private final PodAffinityFactory podAffinityFactory; private final TaintTolerationFactory taintTolerationFactory; private final TopologyFactory topologyFactory; private final ContainerEnvFactory containerEnvFactory; private final LogStorageInfo<Task> logStorageInfo; private final SchedulerConfiguration schedulerConfiguration; @Inject public V1SpecPodFactory(KubePodConfiguration configuration, ApplicationSlaManagementService capacityGroupManagement, PodAffinityFactory podAffinityFactory, TaintTolerationFactory taintTolerationFactory, TopologyFactory topologyFactory, ContainerEnvFactory containerEnvFactory, LogStorageInfo<Task> logStorageInfo, SchedulerConfiguration schedulerConfiguration) { this.configuration = configuration; this.capacityGroupManagement = capacityGroupManagement; this.podAffinityFactory = podAffinityFactory; this.taintTolerationFactory = taintTolerationFactory; this.topologyFactory = topologyFactory; this.containerEnvFactory = containerEnvFactory; this.logStorageInfo = logStorageInfo; this.schedulerConfiguration = schedulerConfiguration; } @Override public V1Pod buildV1Pod(Job<?> job, Task task) { String taskId = task.getId(); Map<String, String> annotations = createV1SchemaPodAnnotations(job, task); Pair<V1Affinity, Map<String, String>> affinityWithMetadata = podAffinityFactory.buildV1Affinity(job, task); annotations.putAll(affinityWithMetadata.getRight()); Pair<List<String>, Map<String, String>> envVarsWithIndex = containerEnvFactory.buildContainerEnv(job, task); List<V1EnvVar> envVarsList = toV1EnvVar(envVarsWithIndex.getRight()); annotations.put(POD_SYSTEM_ENV_VAR_NAMES, String.join(",", envVarsWithIndex.getLeft())); Map<String, String> labels = new HashMap<>(); labels.put(KubeConstants.POD_LABEL_JOB_ID, job.getId()); labels.put(KubeConstants.POD_LABEL_TASK_ID, taskId); JobManagerUtil.getRelocationBinpackMode(job).ifPresent(mode -> labels.put(KubeConstants.POD_LABEL_RELOCATION_BINPACK, mode)); // A V1Container has no room to store the original tag that the Image came from, so we store it as an // annotation. Only saving the 'main' one for now. annotations.put(POD_IMAGE_TAG_PREFIX + "main", job.getJobDescriptor().getContainer().getImage().getTag()); JobDescriptor<?> jobDescriptor = job.getJobDescriptor(); String capacityGroup = JobManagerUtil.getCapacityGroupDescriptorName(job.getJobDescriptor(), capacityGroupManagement).toLowerCase(); labels.put(KubeConstants.LABEL_CAPACITY_GROUP, capacityGroup); V1ObjectMeta metadata = new V1ObjectMeta() .name(taskId) .namespace(DEFAULT_NAMESPACE) .annotations(annotations) .labels(labels); V1Container container = new V1Container() .name("main") .image(KubePodUtil.buildImageString(configuration.getRegistryUrl(), jobDescriptor.getContainer().getImage())) .env(envVarsList) .resources(buildV1ResourceRequirements(job.getJobDescriptor().getContainer().getContainerResources())) .imagePullPolicy(DEFAULT_IMAGE_PULL_POLICY) .volumeMounts(KubePodUtil.buildV1VolumeMounts(job.getJobDescriptor().getContainer().getVolumeMounts())); Container jobContainer = jobDescriptor.getContainer(); if (CollectionsExt.isNullOrEmpty(jobContainer.getCommand()) && !shouldSkipEntryPointJoin(jobDescriptor.getAttributes())) { // use the old behavior where the agent needs to do shell splitting String entrypointStr = StringExt.concatenate(jobContainer.getEntryPoint(), " "); container.setCommand(Collections.singletonList(entrypointStr)); annotations.put(ENTRYPOINT_SHELL_SPLITTING_ENABLED, "true"); } else { container.setCommand(jobContainer.getEntryPoint()); container.setArgs(jobContainer.getCommand()); } List<V1Container> extraContainers = buildV1ExtraContainers(job.getJobDescriptor().getExtraContainers()); List<V1Container> allContainers = Stream.concat(Stream.of(container), extraContainers.stream()).collect(Collectors.toList()); List<V1Volume> volumes = buildV1Volumes(job.getJobDescriptor().getVolumes()); ApplicationSLA capacityGroupDescriptor = JobManagerUtil.getCapacityGroupDescriptor(job.getJobDescriptor(), capacityGroupManagement); String schedulerName = selectScheduler(schedulerConfiguration, capacityGroupDescriptor, configuration); String priorityClassName = selectPriorityClassName(capacityGroupDescriptor, job, configuration); V1PodSpec spec = new V1PodSpec() .schedulerName(schedulerName) .containers(allContainers) .volumes(volumes) .terminationGracePeriodSeconds(getTerminationGracePeriodSeconds(job)) .restartPolicy(NEVER_RESTART_POLICY) .dnsPolicy(DEFAULT_DNS_POLICY) .affinity(affinityWithMetadata.getLeft()) .priorityClassName(priorityClassName) .tolerations(taintTolerationFactory.buildV1Toleration(job, task)) .topologySpreadConstraints(topologyFactory.buildTopologySpreadConstraints(job)); // volumes need to be correctly added to pod spec Optional<Pair<V1Volume, V1VolumeMount>> optionalEbsVolumeInfo = buildV1EBSObjects(job, task); if (optionalEbsVolumeInfo.isPresent()) { spec.addVolumesItem(optionalEbsVolumeInfo.get().getLeft()); container.addVolumeMountsItem(optionalEbsVolumeInfo.get().getRight()); } appendEfsMounts(spec, container, job); appendShmMount(spec, container, job); return new V1Pod().metadata(metadata).spec(spec); } private List<V1Container> buildV1ExtraContainers(List<BasicContainer> extraContainers) { if (extraContainers == null) { return Collections.emptyList(); } return extraContainers.stream().map(this::buildV1ExtraContainers).collect(Collectors.toList()); } private V1Container buildV1ExtraContainers(BasicContainer extraContainer) { return new V1Container() .name(extraContainer.getName()) .command(extraContainer.getEntryPoint()) .args(extraContainer.getCommand()) .image(KubePodUtil.buildImageString(configuration.getRegistryUrl(), extraContainer.getImage())) .env(toV1EnvVar(extraContainer.getEnv())) .imagePullPolicy(DEFAULT_IMAGE_PULL_POLICY) .volumeMounts(KubePodUtil.buildV1VolumeMounts(extraContainer.getVolumeMounts())); } private Long getTerminationGracePeriodSeconds(Job<?> job) { String jobKillWaitSeconds = job.getJobDescriptor().getAttributes().get(JOB_PARAMETER_ATTRIBUTES_KILL_WAIT_SECONDS); if (jobKillWaitSeconds != null) { try { return Long.valueOf(jobKillWaitSeconds); } catch (NumberFormatException e) { return configuration.getPodTerminationGracePeriodSeconds(); } } else { return configuration.getPodTerminationGracePeriodSeconds(); } } @VisibleForTesting V1ResourceRequirements buildV1ResourceRequirements(ContainerResources containerResources) { Map<String, Quantity> requests = new HashMap<>(); Map<String, Quantity> limits = new HashMap<>(); Quantity cpu = new Quantity(String.valueOf(containerResources.getCpu())); Quantity memory = new Quantity(containerResources.getMemoryMB() + "Mi"); Quantity disk = new Quantity(containerResources.getDiskMB() + "Mi"); Quantity network = new Quantity(containerResources.getNetworkMbps() + "M"); Quantity gpu = new Quantity(String.valueOf(containerResources.getGpu())); requests.put(RESOURCE_CPU, cpu); limits.put(RESOURCE_CPU, cpu); requests.put(RESOURCE_MEMORY, memory); limits.put(RESOURCE_MEMORY, memory); requests.put(RESOURCE_EPHERMERAL_STORAGE, disk); limits.put(RESOURCE_EPHERMERAL_STORAGE, disk); requests.put(RESOURCE_NETWORK, network); limits.put(RESOURCE_NETWORK, network); requests.put(RESOURCE_GPU, gpu); limits.put(RESOURCE_GPU, gpu); return new V1ResourceRequirements().requests(requests).limits(limits); } Map<String, String> createV1SchemaPodAnnotations( Job<?> job, Task task ) { com.netflix.titus.api.jobmanager.model.job.JobDescriptor<?> jobDescriptor = job.getJobDescriptor(); Container container = jobDescriptor.getContainer(); Map<String, String> annotations = new HashMap<>(); annotations.put(POD_SCHEMA_VERSION, "1"); annotations.put(JOB_ID, job.getId()); annotations.put(JOB_TYPE, getJobType(job).name()); if (jobDescriptor.getDisruptionBudget().getDisruptionBudgetPolicy() != null) { annotations.put(JOB_DISRUPTION_BUDGET_POLICY_NAME, jobDescriptor.getDisruptionBudget().getDisruptionBudgetPolicy().getClass().getSimpleName()); } JobGroupInfo jobGroupInfo = jobDescriptor.getJobGroupInfo(); annotations.put(AnnotationKeyWorkloadName, jobDescriptor.getApplicationName()); annotations.put(AnnotationKeyWorkloadStack, jobGroupInfo.getStack()); annotations.put(AnnotationKeyWorkloadDetail, jobGroupInfo.getDetail()); annotations.put(AnnotationKeyWorkloadSequence, jobGroupInfo.getSequence()); annotations.put(AnnotationKeyWorkloadOwnerEmail, jobDescriptor.getOwner().getTeamEmail()); Optional<JobStatus> jobStatus = JobFunctions.findJobStatus(job, JobState.Accepted); if (jobStatus.isPresent()) { String jobAcceptedTimestamp = String.valueOf(jobStatus.get().getTimestamp()); annotations.put(JOB_ACCEPTED_TIMESTAMP_MS, jobAcceptedTimestamp); } ContainerResources containerResources = container.getContainerResources(); String networkBandwidth = containerResources.getNetworkMbps() + "M"; annotations.put(AnnotationKeyEgressBandwidth, networkBandwidth); annotations.put(AnnotationKeyIngressBandwidth, networkBandwidth); SecurityProfile securityProfile = container.getSecurityProfile(); String securityGroups = StringExt.concatenate(securityProfile.getSecurityGroups(), ","); annotations.put(AnnotationKeyNetworkSecurityGroups, securityGroups); annotations.put(IAM_ROLE, securityProfile.getIamRole()); Evaluators.acceptNotNull( securityProfile.getAttributes().get(ATTRIBUTE_NETFLIX_APP_METADATA), appMetadata -> annotations.put(SECURITY_APP_METADATA, appMetadata) ); Evaluators.acceptNotNull( securityProfile.getAttributes().get(ATTRIBUTE_NETFLIX_APP_METADATA_SIG), appMetadataSignature -> annotations.put(SECURITY_APP_METADATA_SIG, appMetadataSignature) ); Evaluators.acceptNotNull( job.getJobDescriptor().getAttributes().get(JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC), runtimeInSec -> annotations.put(KubeConstants.JOB_RUNTIME_PREDICTION, runtimeInSec + "s") ); Evaluators.acceptNotNull( task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_IP_ALLOCATION_ID), id -> annotations.put(AnnotationKeyNetworkStaticIPAllocationUUID, id) ); Evaluators.acceptNotNull( job.getJobDescriptor().getNetworkConfiguration().getNetworkModeName(), modeName -> annotations.put(AnnotationKeyNetworkMode, modeName) ); // convert container attributes into annotations container.getAttributes().forEach((k, v) -> { if (StringExt.isEmpty(k) || StringExt.isEmpty(v) || !k.startsWith(TITUS_PARAMETER_AGENT_PREFIX)) { return; } switch (k) { case JOB_PARAMETER_ATTRIBUTES_ALLOW_CPU_BURSTING: annotations.put(POD_CPU_BURSTING_ENABLED, v); break; case JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_BURSTING: annotations.put(AnnotationKeyNetworkBurstingEnabled, v); break; case JOB_PARAMETER_ATTRIBUTE_EIP_POOL: annotations.put(AnnotationKeyNetworkElasticIPPool, v); break; case JOB_PARAMETER_ATTRIBUTE_EIPS: annotations.put(AnnotationKeyNetworkElasticIPs, v); break; case JOB_PARAMETER_ATTRIBUTES_SCHED_BATCH: annotations.put(POD_SCHED_POLICY, "batch"); break; case JOB_CONTAINER_ATTRIBUTE_SUBNETS: annotations.put(AnnotationKeyNetworkSubnetIDs, v); break; case JOB_CONTAINER_ATTRIBUTE_ACCOUNT_ID: annotations.put(AnnotationKeyNetworkAccountID, v); break; case JOB_PARAMETER_ATTRIBUTES_HOSTNAME_STYLE: annotations.put(POD_HOSTNAME_STYLE, v); break; case JOB_PARAMETER_ATTRIBUTES_ALLOW_NETWORK_JUMBO: annotations.put(AnnotationKeyNetworkJumboFramesEnabled, v); break; case JOB_PARAMETER_ATTRIBUTES_FUSE_ENABLED: annotations.put(POD_FUSE_ENABLED, v); break; case JOB_PARAMETER_ATTRIBUTES_ASSIGN_IPV6_ADDRESS: annotations.put(AnnotationKeyNetworkAssignIPv6Address, v); break; case JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_CHECK_INTERVAL: annotations.put(LOG_UPLOAD_CHECK_INTERVAL, v); break; case JOB_PARAMETER_ATTRIBUTES_LOG_STDIO_CHECK_INTERVAL: annotations.put(LOG_STDIO_CHECK_INTERVAL, v); break; case JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_THRESHOLD_TIME: annotations.put(LOG_UPLOAD_THRESHOLD_TIME, v); break; case JOB_PARAMETER_ATTRIBUTES_LOG_KEEP_LOCAL_FILE_AFTER_UPLOAD: annotations.put(LOG_KEEP_LOCAL_FILE, v); break; case JOB_PARAMETER_ATTRIBUTES_LOG_UPLOAD_REGEXP: annotations.put(LOG_UPLOAD_REGEXP, v); break; case JOB_CONTAINER_ATTRIBUTE_S3_PATH_PREFIX: annotations.put(LOG_S3_PATH_PREFIX, v); break; case JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_PERF_ENABLED: annotations.put(POD_SECCOMP_AGENT_PERF_ENABLED, v); break; case JOB_CONTAINER_ATTRIBUTE_SECCOMP_AGENT_NET_ENABLED: annotations.put(POD_SECCOMP_AGENT_NET_ENABLED, v); break; case JOB_CONTAINER_ATTRIBUTE_TRAFFIC_STEERING_ENABLED: annotations.put(POD_TRAFFIC_STEERING_ENABLED, v); break; case JOB_CONTAINER_ATTRIBUTE_IMDS_REQUIRE_TOKEN: annotations.put(AnnotationKeyNetworkIMDSRequireToken, v); break; default: annotations.put(k, v); break; } }); appendS3WriterRole(annotations, job, task); annotations.putAll(createEbsPodAnnotations(job, task)); annotations.putAll(PerformanceToolUtil.toAnnotations(job)); annotations.putAll(createPlatformSidecarAnnotations(job)); return annotations; } private boolean shouldSkipEntryPointJoin(Map<String, String> jobAttributes) { return Boolean.parseBoolean(jobAttributes.getOrDefault(JobAttributes.JOB_PARAMETER_ATTRIBUTES_ENTRY_POINT_SKIP_SHELL_PARSING, "false").trim()); } @VisibleForTesting void appendS3WriterRole(Map<String, String> annotations, Job<?> job, Task task) { if (LogStorageInfos.findCustomS3Bucket(job).isPresent()) { annotations.put( LOG_S3_WRITER_IAM_ROLE, job.getJobDescriptor().getContainer().getSecurityProfile().getIamRole() ); } else { Evaluators.applyNotNull( configuration.getDefaultS3WriterRole(), role -> annotations.put(LOG_S3_WRITER_IAM_ROLE, role) ); } logStorageInfo.getS3LogLocation(task, false).ifPresent(s3LogLocation -> Evaluators.applyNotNull( s3LogLocation.getBucket(), bucket -> annotations.put(LOG_S3_BUCKET_NAME, bucket) ) ); } void appendEfsMounts(V1PodSpec spec, V1Container container, Job<?> job) { List<EfsMount> efsMounts = job.getJobDescriptor().getContainer().getContainerResources().getEfsMounts(); if (efsMounts.isEmpty()) { return; } for (EfsMount efsMount : efsMounts) { boolean readOnly = efsMount.getMountPerm() == EfsMount.MountPerm.RO; String efsId = efsMount.getEfsId(); String efsMountPoint = efsMount.getMountPoint(); String efsRelativeMountPoint = StringExt.isEmpty(efsMount.getEfsRelativeMountPoint()) ? "/" : efsMount.getEfsRelativeMountPoint(); String name = sanitizeVolumeName(efsId + efsRelativeMountPoint); V1VolumeMount volumeMount = new V1VolumeMount() .name(name) .mountPath(efsMountPoint) .readOnly(readOnly); container.addVolumeMountsItem(volumeMount); // We can't have duplicate volumes in here. In theory there should be a many:one mapping between // EFS mounts and the volumes that back them. For example, there could be two mounts to the same // nfs server, but with different *mount points*, but there should only be 1 volumes behind them List<String> allNames = KubePodUtil.getVolumeNames(spec.getVolumes()); if (!allNames.contains(name)) { V1NFSVolumeSource nfsVolumeSource = new V1NFSVolumeSource() .server(efsIdToNFSServer(efsId)) .readOnly(false); // "path" here represents the server-side relative mount path, sometimes called // the "exported directory", and goes into the v1 Volume nfsVolumeSource.setPath(efsRelativeMountPoint); V1Volume volume = new V1Volume() .name(name) .nfs(nfsVolumeSource); spec.addVolumesItem(volume); } } } /** * efsIdToNFSHostname will "resolve" an EFS ID into a real * hostname for the pod spec to use if necessary. * <p> * We have to do this because the pod spec doesn't know about EFS, * it just has a field for NFS hostname. * <p> * Titus has EFSID as a real entry. This function bridges the * gap and converts an EFS ID into a hostname. */ private String efsIdToNFSServer(String efsId) { // Most of the time, the EFS ID passed into the control plane // is a real EFS if (isEFSID(efsId)) { return efsId + ".efs." + this.configuration.getTargetRegion() + ".amazonaws.com"; } // But sometimes it is not, and in that case we can just let it go through // as-is return efsId; } private boolean isEFSID(String s) { return s.matches("^fs-[0-9a-f]+$"); } void appendShmMount(V1PodSpec spec, V1Container container, Job<?> job) { int shmMB = job.getJobDescriptor().getContainer().getContainerResources().getShmMB(); V1VolumeMount v1VolumeMount = new V1VolumeMount() .name(DEV_SHM) .mountPath(DEV_SHM_MOUNT_PATH); container.addVolumeMountsItem(v1VolumeMount); V1EmptyDirVolumeSource emptyDirVolumeSource = new V1EmptyDirVolumeSource() .medium("Memory") .sizeLimit(Quantity.fromString(shmMB + "Mi")); V1Volume volume = new V1Volume() .name(V1SpecPodFactory.DEV_SHM) .emptyDir(emptyDirVolumeSource); spec.addVolumesItem(volume); } }
172
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/topology/DefaultTopologyFactory.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.master.kubernetes.pod.topology; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.FeatureActivationConfiguration; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.JobConstraints; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.AvailabilityPercentageLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudgetPolicy; import com.netflix.titus.common.util.RegExpExt; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.models.V1LabelSelector; import io.kubernetes.client.openapi.models.V1TopologySpreadConstraint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.getJobDesiredSize; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.isServiceJob; @Singleton public class DefaultTopologyFactory implements TopologyFactory { private static final Logger logger = LoggerFactory.getLogger(DefaultTopologyFactory.class); private final KubePodConfiguration configuration; private final FeatureActivationConfiguration features; private final Function<String, Matcher> jobsWithNoSpreadingMatcher; @Inject public DefaultTopologyFactory(KubePodConfiguration configuration, FeatureActivationConfiguration features) { this.configuration = configuration; this.features = features; this.jobsWithNoSpreadingMatcher = RegExpExt.dynamicMatcher(configuration::getDisabledJobSpreadingPattern, "disabledJobSpreadingPattern", Pattern.DOTALL, logger); } @Override @VisibleForTesting public List<V1TopologySpreadConstraint> buildTopologySpreadConstraints(Job<?> job) { List<V1TopologySpreadConstraint> constraints = new ArrayList<>(); buildZoneTopologySpreadConstraints(job).ifPresent(constraints::add); buildJobTopologySpreadConstraints(job).ifPresent(constraints::add); return constraints; } private Optional<V1TopologySpreadConstraint> buildZoneTopologySpreadConstraints(Job<?> job) { boolean zoneHard = Boolean.parseBoolean(JobFunctions.findHardConstraint(job, JobConstraints.ZONE_BALANCE).orElse("false")); boolean zoneSoft = Boolean.parseBoolean(JobFunctions.findSoftConstraint(job, JobConstraints.ZONE_BALANCE).orElse("false")); if (!zoneHard && !zoneSoft) { return Optional.empty(); } V1TopologySpreadConstraint zoneConstraint = new V1TopologySpreadConstraint() .topologyKey(KubeConstants.NODE_LABEL_ZONE) .labelSelector(new V1LabelSelector().matchLabels(Collections.singletonMap(KubeConstants.POD_LABEL_JOB_ID, job.getId()))) .maxSkew(1); if (zoneHard) { zoneConstraint.whenUnsatisfiable("DoNotSchedule"); } else { zoneConstraint.whenUnsatisfiable("ScheduleAnyway"); } return Optional.of(zoneConstraint); } private Optional<V1TopologySpreadConstraint> buildJobTopologySpreadConstraints(Job<?> job) { if (!isJobSpreadingEnabled(job)) { return Optional.empty(); } int maxSkew = getJobMaxSkew(job); if (maxSkew <= 0) { return Optional.empty(); } V1TopologySpreadConstraint nodeConstraint = new V1TopologySpreadConstraint() .topologyKey(KubeConstants.NODE_LABEL_MACHINE_ID) .labelSelector(new V1LabelSelector().matchLabels(Collections.singletonMap(KubeConstants.POD_LABEL_JOB_ID, job.getId()))) .maxSkew(maxSkew) .whenUnsatisfiable("ScheduleAnyway"); return Optional.of(nodeConstraint); } /** * Spreading is by default enabled for service jobs and disabled for batch jobs or jobs binpacked for relocation. */ private boolean isJobSpreadingEnabled(Job<?> job) { if (jobsWithNoSpreadingMatcher.apply(job.getJobDescriptor().getApplicationName()).matches()) { return false; } if (jobsWithNoSpreadingMatcher.apply(job.getJobDescriptor().getCapacityGroup()).matches()) { return false; } String spreadingEnabledAttr = job.getJobDescriptor().getAttributes().get(JobAttributes.JOB_ATTRIBUTES_SPREADING_ENABLED); if (spreadingEnabledAttr != null) { return Boolean.parseBoolean(spreadingEnabledAttr); } if (features.isRelocationBinpackingEnabled() && JobManagerUtil.getRelocationBinpackMode(job).isPresent()) { // by default do not spread jobs that are marked for binpacking due to relocation return false; } return isServiceJob(job); } /** * Get max skew from a job descriptor or compute a value based on the job type and its configured disruption budget. * * @return -1 if max skew not set or is invalid */ private int getJobMaxSkew(Job<?> job) { String maxSkewAttr = job.getJobDescriptor().getAttributes().get(JobAttributes.JOB_ATTRIBUTES_SPREADING_MAX_SKEW); if (maxSkewAttr != null) { try { int maxSkew = Integer.parseInt(maxSkewAttr); if (maxSkew > 0) { return maxSkew; } } catch (Exception ignore) { } } DisruptionBudgetPolicy policy = job.getJobDescriptor().getDisruptionBudget().getDisruptionBudgetPolicy(); // Job spreading is only relevant for jobs that care about the availability. if (!(policy instanceof AvailabilityPercentageLimitDisruptionBudgetPolicy)) { return -1; } int jobSize = getJobDesiredSize(job); if (jobSize <= 1) { return -1; } double alpha = configuration.getJobSpreadingSkewAlpha(); if (alpha <= 0) { return -1; } int skew = (int) (Math.floor(jobSize / alpha)); // The skew must be between 1 and the configured max skew. return Math.max(1, Math.min(skew, configuration.getJobSpreadingMaxSkew())); } }
173
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/topology/TopologyFactory.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.master.kubernetes.pod.topology; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import io.kubernetes.client.openapi.models.V1TopologySpreadConstraint; /** * {@link TopologyFactory} resolves topologies for a task that should be added when a pod is created. */ public interface TopologyFactory { List<V1TopologySpreadConstraint> buildTopologySpreadConstraints(Job<?> job); }
174
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/taint/TaintTolerationFactory.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.master.kubernetes.pod.taint; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import io.kubernetes.client.openapi.models.V1Toleration; /** * {@link TaintTolerationFactory} resolves taint tolerations for a task that should be added when a pod is created. */ public interface TaintTolerationFactory { List<V1Toleration> buildV1Toleration(Job<?> job, Task task); }
175
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/taint/Tolerations.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.master.kubernetes.pod.taint; import java.util.function.Function; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.models.V1Toleration; public final class Tolerations { public static final V1Toleration TOLERATION_VIRTUAL_KUBLET = new V1Toleration() .key(KubeConstants.TAINT_VIRTUAL_KUBLET) .value("titus") .operator("Equal") .effect("NoSchedule"); public static final V1Toleration TOLERATION_KUBE_SCHEDULER = new V1Toleration() .key(KubeConstants.TAINT_SCHEDULER) .value(KubeConstants.TAINT_SCHEDULER_VALUE_KUBE) .operator("Equal") .effect("NoSchedule"); public static final V1Toleration TOLERATION_TIER_FLEX = new V1Toleration() .key(KubeConstants.TAINT_TIER) .value("flex") .operator("Equal") .effect("NoSchedule"); public static final V1Toleration TOLERATION_TIER_CRITICAL = new V1Toleration() .key(KubeConstants.TAINT_TIER) .value("critical") .operator("Equal") .effect("NoSchedule"); public static final Function<String, V1Toleration> TOLERATION_FARZONE_FACTORY = farzoneId -> new V1Toleration() .key(KubeConstants.TAINT_FARZONE) .value(farzoneId) .operator("Equal") .effect("NoSchedule"); public static final V1Toleration TOLERATION_GPU_INSTANCE = new V1Toleration() .key(KubeConstants.TAINT_GPU_INSTANCE) .operator("Exists") .effect("NoSchedule"); public static final V1Toleration TOLERATION_DECOMMISSIONING = new V1Toleration() .key(KubeConstants.TAINT_NODE_DECOMMISSIONING) .operator("Exists") .effect("NoSchedule"); }
176
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/taint/DefaultTaintTolerationFactory.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.master.kubernetes.pod.taint; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.jobmanager.JobConstraints; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.api.model.Tier; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.models.V1Toleration; @Singleton public class DefaultTaintTolerationFactory implements TaintTolerationFactory { private final KubePodConfiguration configuration; private final ApplicationSlaManagementService capacityManagement; @Inject public DefaultTaintTolerationFactory(KubePodConfiguration configuration, ApplicationSlaManagementService capacityManagement) { this.configuration = configuration; this.capacityManagement = capacityManagement; } @Override public List<V1Toleration> buildV1Toleration(Job<?> job, Task task) { List<V1Toleration> tolerations = new ArrayList<>(); // Default taints. tolerations.add(Tolerations.TOLERATION_VIRTUAL_KUBLET); tolerations.add(Tolerations.TOLERATION_KUBE_SCHEDULER); resolveDecommissioningToleration(job).ifPresent(tolerations::add); tolerations.add(resolveTierToleration(job)); resolveAvailabilityZoneToleration(job).ifPresent(tolerations::add); resolveGpuInstanceTypeToleration(job).ifPresent(tolerations::add); resolveKubeBackendToleration(job).ifPresent(tolerations::add); return tolerations; } /** * All tasks by default tolerate nodes being decommissioned, unless their job has the {@link JobConstraints#ACTIVE_HOST} * hard constraint */ private Optional<V1Toleration> resolveDecommissioningToleration(Job<?> job) { if (JobFunctions.findHardConstraint(job, JobConstraints.ACTIVE_HOST).isPresent()) { return Optional.empty(); } return Optional.of(Tolerations.TOLERATION_DECOMMISSIONING); } private V1Toleration resolveTierToleration(Job<?> job) { String capacityGroupName = JobFunctions.getEffectiveCapacityGroup(job); ApplicationSLA capacityGroup = capacityManagement.findApplicationSLA(capacityGroupName).orElse(null); if (capacityGroup == null) { return Tolerations.TOLERATION_TIER_FLEX; } return capacityGroup.getTier() == Tier.Critical ? Tolerations.TOLERATION_TIER_CRITICAL : Tolerations.TOLERATION_TIER_FLEX; } private Optional<V1Toleration> resolveAvailabilityZoneToleration(Job<?> job) { return KubeUtil.findFarzoneId(configuration, job).map(Tolerations.TOLERATION_FARZONE_FACTORY); } private Optional<V1Toleration> resolveGpuInstanceTypeToleration(Job<?> job) { return job.getJobDescriptor().getContainer().getContainerResources().getGpu() <= 0 ? Optional.empty() : Optional.of(Tolerations.TOLERATION_GPU_INSTANCE); } private Optional<V1Toleration> resolveKubeBackendToleration(Job<?> job) { String backend = JobFunctions.findHardConstraint(job, JobConstraints.KUBE_BACKEND).orElse(""); if (StringExt.isEmpty(backend)) { return Optional.empty(); } return Optional.of(new V1Toleration() .key(KubeConstants.TAINT_KUBE_BACKEND) .operator("Equal") .value(backend) .effect("NoSchedule") ); } }
177
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/affinity/PodAffinityFactory.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.master.kubernetes.pod.affinity; import java.util.Map; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.util.tuple.Pair; import io.kubernetes.client.openapi.models.V1Affinity; /** * Builds pod affinity and ant-affinity rules for a job/task. This includes both the job level hard and soft * constraints, as well as Titus system level constraints. */ public interface PodAffinityFactory { /** * Returns Kubernetes {@link V1Affinity} rules for a task, and a map of key/value pairs that are added to * pod annotations. */ Pair<V1Affinity, Map<String, String>> buildV1Affinity(Job<?> job, Task task); }
178
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/affinity/DefaultPodAffinityFactory.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.master.kubernetes.pod.affinity; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.FeatureActivationConfiguration; import com.netflix.titus.api.jobmanager.JobConstraints; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobFunctions; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolumeUtils; import com.netflix.titus.api.jobmanager.model.job.vpc.IpAddressAllocationUtils; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.kubernetes.pod.resourcepool.PodResourcePoolResolver; import com.netflix.titus.master.kubernetes.pod.resourcepool.ResourcePoolAssignment; import com.netflix.titus.runtime.kubernetes.KubeConstants; import io.kubernetes.client.openapi.models.V1Affinity; import io.kubernetes.client.openapi.models.V1LabelSelector; import io.kubernetes.client.openapi.models.V1LabelSelectorRequirement; import io.kubernetes.client.openapi.models.V1NodeAffinity; import io.kubernetes.client.openapi.models.V1NodeSelector; import io.kubernetes.client.openapi.models.V1NodeSelectorRequirement; import io.kubernetes.client.openapi.models.V1NodeSelectorTerm; import io.kubernetes.client.openapi.models.V1PodAffinity; import io.kubernetes.client.openapi.models.V1PodAffinityTerm; import io.kubernetes.client.openapi.models.V1PodAntiAffinity; import io.kubernetes.client.openapi.models.V1PreferredSchedulingTerm; import io.kubernetes.client.openapi.models.V1WeightedPodAffinityTerm; import static com.netflix.titus.common.util.CollectionsExt.toLowerCaseKeys; @Singleton public class DefaultPodAffinityFactory implements PodAffinityFactory { private static final int EXCLUSIVE_HOST_WEIGHT = 100; private static final int UNIQUE_HOST_WEIGHT = 100; private static final int NODE_AFFINITY_WEIGHT = 100; private static final int RELOCATION_AFFINITY_WEIGHT = 50; private final KubePodConfiguration configuration; private final FeatureActivationConfiguration featureConfiguration; private final PodResourcePoolResolver podResourcePoolResolver; private final TitusRuntime titusRuntime; @Inject public DefaultPodAffinityFactory(KubePodConfiguration configuration, FeatureActivationConfiguration featureConfiguration, PodResourcePoolResolver podResourcePoolResolver, TitusRuntime titusRuntime) { this.configuration = configuration; this.featureConfiguration = featureConfiguration; this.podResourcePoolResolver = podResourcePoolResolver; this.titusRuntime = titusRuntime; } @Override public Pair<V1Affinity, Map<String, String>> buildV1Affinity(Job<?> job, Task task) { return new Processor(job, task).build(); } private class Processor { private final Job<?> job; private final Task task; private final V1Affinity v1Affinity; private final Map<String, String> annotations = new HashMap<>(); private Processor(Job<?> job, Task task) { this.job = job; this.task = task; this.v1Affinity = new V1Affinity(); processJobConstraints(toLowerCaseKeys(job.getJobDescriptor().getContainer().getHardConstraints()), true); processJobConstraints(toLowerCaseKeys(job.getJobDescriptor().getContainer().getSoftConstraints()), false); processResourcePoolConstraints(); processZoneConstraints(); processRelocationAffinity(); } private void processJobConstraints(Map<String, String> constraints, boolean hard) { if (Boolean.parseBoolean(constraints.get(JobConstraints.EXCLUSIVE_HOST))) { addExclusiveHostConstraint(hard); } if (Boolean.parseBoolean(constraints.get(JobConstraints.UNIQUE_HOST))) { addUniqueHostConstraint(hard); } if (constraints.containsKey(JobConstraints.AVAILABILITY_ZONE)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_ZONE, constraints.get(JobConstraints.AVAILABILITY_ZONE), hard); } if (constraints.containsKey(JobConstraints.MACHINE_GROUP)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_MACHINE_GROUP, constraints.get(JobConstraints.MACHINE_GROUP), hard); } if (constraints.containsKey(JobConstraints.MACHINE_ID)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_MACHINE_ID, constraints.get(JobConstraints.MACHINE_ID), hard); } if (constraints.containsKey(JobConstraints.KUBE_BACKEND)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_KUBE_BACKEND, constraints.get(JobConstraints.KUBE_BACKEND), hard); } if (constraints.containsKey(JobConstraints.CPU_MODEL)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_CPU_MODEL, constraints.get(JobConstraints.CPU_MODEL), hard); } String instanceType = constraints.get(JobConstraints.MACHINE_TYPE); boolean instanceTypeRequested = !StringExt.isEmpty(instanceType); if (instanceTypeRequested) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_INSTANCE_TYPE, instanceType, hard); } if (hard && !instanceTypeRequested) { boolean gpuRequested = job.getJobDescriptor().getContainer().getContainerResources().getGpu() > 0; List<String> defaultGpuInstanceTypes = configuration.getDefaultGpuInstanceTypes(); if (gpuRequested && !defaultGpuInstanceTypes.isEmpty()) { // If not explicit instance type requested, restrict GPU instance types to a default set. addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_INSTANCE_TYPE, defaultGpuInstanceTypes, true); } } } private void addExclusiveHostConstraint(boolean hard) { V1PodAffinityTerm term = new V1PodAffinityTerm() .labelSelector(new V1LabelSelector() .addMatchExpressionsItem(new V1LabelSelectorRequirement() .key(KubeConstants.POD_LABEL_TASK_ID) .operator(KubeConstants.SELECTOR_OPERATOR_EXISTS) )) .topologyKey(KubeConstants.NODE_LABEL_MACHINE_ID); if (hard) { getPodAntiAffinity().addRequiredDuringSchedulingIgnoredDuringExecutionItem(term); } else { getPodAntiAffinity().addPreferredDuringSchedulingIgnoredDuringExecutionItem( new V1WeightedPodAffinityTerm() .weight(EXCLUSIVE_HOST_WEIGHT) .podAffinityTerm(term) ); } } private void addUniqueHostConstraint(boolean hard) { V1PodAffinityTerm term = new V1PodAffinityTerm() .labelSelector(new V1LabelSelector() .addMatchExpressionsItem(new V1LabelSelectorRequirement() .key(KubeConstants.POD_LABEL_JOB_ID) .operator(KubeConstants.SELECTOR_OPERATOR_IN) .values(Collections.singletonList(job.getId())) )) .topologyKey(KubeConstants.NODE_LABEL_MACHINE_ID); if (hard) { getPodAntiAffinity().addRequiredDuringSchedulingIgnoredDuringExecutionItem(term); } else { getPodAntiAffinity().addPreferredDuringSchedulingIgnoredDuringExecutionItem( new V1WeightedPodAffinityTerm() .weight(UNIQUE_HOST_WEIGHT) .podAffinityTerm(term) ); } } private void addNodeAffinitySelectorConstraint(String key, String value, boolean hard) { addNodeAffinitySelectorConstraint(key, Collections.singletonList(value), hard); } private void addNodeAffinitySelectorConstraint(String key, List<String> values, boolean hard) { if (hard) { addNodeAffinityRequiredSelectorConstraint(key, values); } else { addNodeAffinityPreferredSelectorConstraint(key, values); } } private void addNodeAffinityRequiredSelectorConstraint(String key, List<String> values) { V1NodeSelectorRequirement requirement = new V1NodeSelectorRequirement() .key(key) .operator(KubeConstants.SELECTOR_OPERATOR_IN) .values(values); V1NodeSelector nodeSelector = getNodeAffinity().getRequiredDuringSchedulingIgnoredDuringExecution(); if (nodeSelector == null) { getNodeAffinity().requiredDuringSchedulingIgnoredDuringExecution(nodeSelector = new V1NodeSelector()); } if (nodeSelector.getNodeSelectorTerms().isEmpty()) { nodeSelector.addNodeSelectorTermsItem(new V1NodeSelectorTerm().addMatchExpressionsItem(requirement)); } else { nodeSelector.getNodeSelectorTerms().get(0).addMatchExpressionsItem(requirement); } } private void addNodeAffinityPreferredSelectorConstraint(String key, List<String> values) { List<V1PreferredSchedulingTerm> nodeSelector = getNodeAffinity().getPreferredDuringSchedulingIgnoredDuringExecution(); V1NodeSelectorTerm term; if (nodeSelector == null) { V1PreferredSchedulingTerm preferredTerm = new V1PreferredSchedulingTerm() .preference(term = new V1NodeSelectorTerm()) .weight(NODE_AFFINITY_WEIGHT); getNodeAffinity().addPreferredDuringSchedulingIgnoredDuringExecutionItem(preferredTerm); } else { term = getNodeAffinity().getPreferredDuringSchedulingIgnoredDuringExecution().get(0).getPreference(); } V1NodeSelectorRequirement requirement = new V1NodeSelectorRequirement() .key(key) .operator(KubeConstants.SELECTOR_OPERATOR_IN) .values(values); term.addMatchExpressionsItem(requirement); } private void processResourcePoolConstraints() { List<ResourcePoolAssignment> resourcePools = podResourcePoolResolver.resolve(job, task); if (resourcePools.isEmpty()) { return; } List<String> names = resourcePools.stream().map(ResourcePoolAssignment::getResourcePoolName).collect(Collectors.toList()); String rule = resourcePools.isEmpty() ? "none" : (resourcePools.size() == 1 ? resourcePools.get(0).getRule() : resourcePools.stream().map(ResourcePoolAssignment::getRule).collect(Collectors.joining(",")) ); addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_RESOURCE_POOL, names, true); for (ResourcePoolAssignment assignment : resourcePools) { if (assignment.preferred()) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_RESOURCE_POOL, assignment.getResourcePoolName(), false); } } annotations.put(KubeConstants.TITUS_SCALER_DOMAIN + "resource-pool-selection", rule); annotations.put(KubeConstants.NODE_LABEL_RESOURCE_POOL, String.join(",", names)); } private void processZoneConstraints() { // If we have a single zone hard constraint defined, there is no need to add anything on top of this. String zone = JobFunctions.findHardConstraint(job, JobConstraints.AVAILABILITY_ZONE).orElse(""); if (!StringExt.isEmpty(zone)) { return; } // If there is a Static IP allocation, get its zone Optional<String> optionalIpAllocationZone = IpAddressAllocationUtils.getIpAllocationZoneForTask(job.getJobDescriptor(), task, titusRuntime.getCodeInvariants()); // If there is an EBS volume, get its zone Optional<String> optionalEbsVolumeZone = EbsVolumeUtils.getEbsVolumeForTask(job, task) .map(EbsVolume::getVolumeAvailabilityZone); if (optionalIpAllocationZone.isPresent() && optionalEbsVolumeZone.isPresent()) { String ipAllocationZone = optionalIpAllocationZone.get(); String ebsVolumeZone = optionalEbsVolumeZone.get(); // If the zones for the two assigned resources do not match we do not assign either. if (ebsVolumeZone.equals(ipAllocationZone)) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_ZONE, ebsVolumeZone, true); } else { titusRuntime.getCodeInvariants().inconsistent("Task %s has assigned Static IP in zone %s but assigned EBS Volume in zone %s", task.getId(), ipAllocationZone, ebsVolumeZone); } } else if (optionalIpAllocationZone.isPresent()) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_ZONE, optionalIpAllocationZone.get(), true); } else { optionalEbsVolumeZone.ifPresent(ebsVolumeZone -> addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_ZONE, ebsVolumeZone, true)); } // If there is no zone hard constraint, it defaults to placement in the primary availability zones if (!configuration.getPrimaryZones().isEmpty()) { addNodeAffinitySelectorConstraint(KubeConstants.NODE_LABEL_ZONE, configuration.getPrimaryZones(), true); } } private void processRelocationAffinity() { if (!featureConfiguration.isRelocationBinpackingEnabled() || !JobManagerUtil.getRelocationBinpackMode(job).isPresent()) { return; } getPodAffinity().addPreferredDuringSchedulingIgnoredDuringExecutionItem( new V1WeightedPodAffinityTerm() .weight(RELOCATION_AFFINITY_WEIGHT) .podAffinityTerm(new V1PodAffinityTerm() .labelSelector(new V1LabelSelector() .addMatchExpressionsItem(new V1LabelSelectorRequirement() .key(KubeConstants.POD_LABEL_RELOCATION_BINPACK) .operator(KubeConstants.SELECTOR_OPERATOR_EXISTS) ) ) .topologyKey(KubeConstants.NODE_LABEL_MACHINE_ID) ) ); getPodAntiAffinity().addPreferredDuringSchedulingIgnoredDuringExecutionItem( new V1WeightedPodAffinityTerm() .weight(RELOCATION_AFFINITY_WEIGHT) .podAffinityTerm(new V1PodAffinityTerm() .labelSelector(new V1LabelSelector() .addMatchExpressionsItem(new V1LabelSelectorRequirement() .key(KubeConstants.POD_LABEL_RELOCATION_BINPACK) .operator(KubeConstants.SELECTOR_OPERATOR_DOES_NOT_EXIST) ) ) .topologyKey(KubeConstants.NODE_LABEL_MACHINE_ID) ) ); } private V1NodeAffinity getNodeAffinity() { if (v1Affinity.getNodeAffinity() == null) { v1Affinity.nodeAffinity(new V1NodeAffinity()); } return v1Affinity.getNodeAffinity(); } private V1PodAffinity getPodAffinity() { if (v1Affinity.getPodAffinity() == null) { v1Affinity.podAffinity(new V1PodAffinity()); } return v1Affinity.getPodAffinity(); } private V1PodAntiAffinity getPodAntiAffinity() { if (v1Affinity.getPodAntiAffinity() == null) { v1Affinity.podAntiAffinity(new V1PodAntiAffinity()); } return v1Affinity.getPodAntiAffinity(); } private Pair<V1Affinity, Map<String, String>> build() { return Pair.of(v1Affinity, annotations); } } }
179
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/PodResourcePoolResolverFeatureGuard.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; public class PodResourcePoolResolverFeatureGuard implements PodResourcePoolResolver { private final KubePodConfiguration configuration; private final PodResourcePoolResolver delegate; public PodResourcePoolResolverFeatureGuard(KubePodConfiguration configuration, PodResourcePoolResolver delegate) { this.configuration = configuration; this.delegate = delegate; } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { if (configuration.isResourcePoolAffinityEnabled()) { return delegate.resolve(job, task); } return Collections.emptyList(); } }
180
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/MixedSchedulerResourcePoolResolver.java
package com.netflix.titus.master.kubernetes.pod.resourcepool; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.ContainerResources; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; public class MixedSchedulerResourcePoolResolver implements PodResourcePoolResolver { private final KubePodConfiguration configuration; public MixedSchedulerResourcePoolResolver(KubePodConfiguration configuration) { this.configuration = configuration; } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { if (!configuration.isMixedSchedulingEnabled()) { return Collections.emptyList(); } String preferredPool = calculatePreferredPool(job); ResourcePoolAssignment elasticAssignment = ResourcePoolAssignment.newBuilder() .withResourcePoolName(PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC) .withPreferred(preferredPool.equals(PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC)) .withRule("Mixed scheduling pool assignment " + PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC) .build(); ResourcePoolAssignment reservedAssignment = ResourcePoolAssignment.newBuilder() .withResourcePoolName(PodResourcePoolResolvers.RESOURCE_POOL_RESERVED) .withPreferred(preferredPool.equals(PodResourcePoolResolvers.RESOURCE_POOL_RESERVED)) .withRule("Mixed scheduling pool assignment " + PodResourcePoolResolvers.RESOURCE_POOL_RESERVED) .build(); return Arrays.asList(elasticAssignment, reservedAssignment); } /** * calculatePreferredPool looks at a job and picks the "best" pool for the job, * which is a function of its resources, *not* its capacity group! * In a mixed scheduling world, we prefer to put jobs based on where they might fit best * based on their ratio, and not due to a policy. */ private String calculatePreferredPool(Job<?> job) { double ratio = getRamCPURatio(job); if (ratio > 12) { return PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC; } return PodResourcePoolResolvers.RESOURCE_POOL_RESERVED; } private double getRamCPURatio(Job<?> job) { ContainerResources resources = job.getJobDescriptor().getContainer().getContainerResources(); if (resources.getCpu() == 0) { return 100; } return (resources.getMemoryMB() / 1024.0) / resources.getCpu(); } }
181
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/PodResourcePoolResolvers.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.master.kubernetes.pod.resourcepool; public final class PodResourcePoolResolvers { public static final String RESOURCE_POOL_ELASTIC = "elastic"; public static final String RESOURCE_POOL_ELASTIC_FARZONE_PREFIX = "elastic-farzone-"; public static final String RESOURCE_POOL_RESERVED = "reserved"; public static final String RESOURCE_POOL_GPU_PREFIX = "elasticGpu"; public static final String RESOURCE_POOL_FENZO_FLEX = "fenzo-flex"; public static final String RESOURCE_POOL_FENZO_CRITICAL = "fenzo-critical"; }
182
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/PodResourcePoolResolverChain.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.runtime.TitusRuntime; public class PodResourcePoolResolverChain implements PodResourcePoolResolver { private static final String POD_RESOLVER_METRIC_NAME = "titus.pod.resourcepool.resolver"; private static final String RESOLVER_NAME = "resolver"; private static final String RESOURCE_POOL_ASSIGNMENT = "resourcepool"; private final List<PodResourcePoolResolver> delegates; private final Registry registry; private final Id resolverId; public PodResourcePoolResolverChain(List<PodResourcePoolResolver> delegates, TitusRuntime titusRuntime) { this.delegates = delegates; this.registry = titusRuntime.getRegistry(); this.resolverId = this.registry.createId(POD_RESOLVER_METRIC_NAME); } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { for (PodResourcePoolResolver delegate : delegates) { List<ResourcePoolAssignment> result = delegate.resolve(job, task); if (!result.isEmpty()) { this.registry .counter(this.resolverId .withTag(RESOLVER_NAME, delegate.getClass().getSimpleName()) .withTag(RESOURCE_POOL_ASSIGNMENT, result.stream().map(ResourcePoolAssignment::getResourcePoolName).collect(Collectors.joining(","))) ).increment(); return result; } } return Collections.emptyList(); } }
183
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/CapacityGroupPodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import com.google.common.collect.Iterators; import com.netflix.archaius.api.Config; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CapacityGroupPodResourcePoolResolver implements PodResourcePoolResolver { private static final Logger logger = LoggerFactory.getLogger(CapacityGroupPodResourcePoolResolver.class); private final KubePodConfiguration configuration; private final Config config; private final ApplicationSlaManagementService capacityGroupService; private final TitusRuntime titusRuntime; private final Lock lock = new ReentrantLock(); private volatile List<Pair<String, Pattern>> resourcePoolToCapacityGroupMappers; private volatile long lastUpdate; public CapacityGroupPodResourcePoolResolver(KubePodConfiguration configuration, Config config, ApplicationSlaManagementService capacityGroupService, TitusRuntime titusRuntime) { this.configuration = configuration; this.config = config; this.capacityGroupService = capacityGroupService; this.titusRuntime = titusRuntime; refreshResourcePoolToCapacityGroupMappers(); } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { ApplicationSLA capacityGroup = JobManagerUtil.getCapacityGroupDescriptor(job.getJobDescriptor(), capacityGroupService); if (capacityGroup == null) { return Collections.emptyList(); } List<Pair<String, Pattern>> currentMappers = getCurrentMappers(); for (Pair<String, Pattern> next : currentMappers) { Pattern pattern = next.getRight(); if (pattern.matcher(capacityGroup.getAppName()).matches()) { return Collections.singletonList(ResourcePoolAssignment.newBuilder() .withResourcePoolName(next.getLeft()) .withRule(String.format("Capacity group %s matches %s", capacityGroup.getAppName(), pattern.toString())) .build() ); } } return Collections.emptyList(); } private List<Pair<String, Pattern>> getCurrentMappers() { if (!titusRuntime.getClock().isPast(lastUpdate + configuration.getCapacityGroupPodResourcePoolResolverUpdateIntervalMs())) { return resourcePoolToCapacityGroupMappers; } if (!lock.tryLock()) { return resourcePoolToCapacityGroupMappers; } try { refreshResourcePoolToCapacityGroupMappers(); } finally { lock.unlock(); } return resourcePoolToCapacityGroupMappers; } private void refreshResourcePoolToCapacityGroupMappers() { List<Pair<String, Pattern>> result = new ArrayList<>(); String[] orderKeys = Iterators.toArray(config.getKeys(), String.class); Arrays.sort(orderKeys); for (String name : orderKeys) { String patternText = config.getString(name); try { result.add(Pair.of(name, Pattern.compile(patternText))); } catch (Exception e) { logger.warn("Cannot parse resource pool rule: name={}, pattern={}", name, patternText, e); } } this.resourcePoolToCapacityGroupMappers = result; this.lastUpdate = titusRuntime.getClock().wallTime(); } }
184
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/KubeSchedulerPodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; public class KubeSchedulerPodResourcePoolResolver implements PodResourcePoolResolver { private final ApplicationSlaManagementService capacityGroupService; public KubeSchedulerPodResourcePoolResolver(ApplicationSlaManagementService capacityGroupService) { this.capacityGroupService = capacityGroupService; } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { ApplicationSLA capacityGroup = JobManagerUtil.getCapacityGroupDescriptor(job.getJobDescriptor(), capacityGroupService); if (capacityGroup != null && StringExt.isNotEmpty(capacityGroup.getResourcePool())) { String resourcePoolName = capacityGroup.getResourcePool(); return Collections.singletonList(ResourcePoolAssignment.newBuilder() .withResourcePoolName(resourcePoolName) .withRule("Kube-Scheduler task assigned to application Capacity Group " + resourcePoolName) .build()); } return Collections.emptyList(); } }
185
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/GpuPodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.model.ApplicationSLA; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.jobmanager.service.JobManagerUtil; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.service.management.ApplicationSlaManagementService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GpuPodResourcePoolResolver implements PodResourcePoolResolver { private static final Logger logger = LoggerFactory.getLogger(GpuPodResourcePoolResolver.class); private final KubePodConfiguration configuration; private final Lock lock = new ReentrantLock(); private volatile String lastParsedValue; private volatile Set<String> gpuResourcePoolNames = Collections.emptySet(); private volatile List<ResourcePoolAssignment> gpuResourcePoolAssignments = Collections.emptyList(); private final ApplicationSlaManagementService capacityGroupService; public GpuPodResourcePoolResolver(KubePodConfiguration configuration, ApplicationSlaManagementService capacityGroupService) { this.configuration = configuration; this.capacityGroupService = capacityGroupService; // Call early to initialize before the first usage. getCurrent(); } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { if (job.getJobDescriptor().getContainer().getContainerResources().getGpu() <= 0) { return Collections.emptyList(); } // If capacity group is already configured with a GPU resource pool, use just that rather than a list of GPU resource pools // as defined in the GpuResourcePoolNames fast property ApplicationSLA capacityGroup = JobManagerUtil.getCapacityGroupDescriptor(job.getJobDescriptor(), capacityGroupService); if (capacityGroup != null && StringExt.isNotEmpty(capacityGroup.getResourcePool()) && this.gpuResourcePoolNames.contains(capacityGroup.getResourcePool())) { String resourcePoolName = capacityGroup.getResourcePool(); return Collections.singletonList(ResourcePoolAssignment.newBuilder() .withResourcePoolName(resourcePoolName) .withRule("GPU task assigned to application Capacity Group " + resourcePoolName) .build()); } return getCurrent(); } private List<ResourcePoolAssignment> getCurrent() { if (!lock.tryLock()) { return gpuResourcePoolAssignments; } try { String currentValue = configuration.getGpuResourcePoolNames(); if (!Objects.equals(lastParsedValue, currentValue)) { this.lastParsedValue = currentValue; this.gpuResourcePoolNames = StringExt.splitByCommaIntoSet(currentValue); List<ResourcePoolAssignment> assignments = new ArrayList<>(); for (String gpuResourcePoolName : this.gpuResourcePoolNames) { assignments.add(ResourcePoolAssignment.newBuilder() .withResourcePoolName(gpuResourcePoolName) .withRule("GPU resources pool assignment") .build()); } this.gpuResourcePoolAssignments = assignments; } } catch (Exception e) { logger.error("Cannot parse GPU resource pool", e); } finally { lock.unlock(); } return gpuResourcePoolAssignments; } }
186
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/ResourcePoolAssignment.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.master.kubernetes.pod.resourcepool; import java.util.Objects; import com.google.common.base.Preconditions; public class ResourcePoolAssignment { private final String resourcePoolName; private final boolean preferred; private final String rule; public boolean preferred() { return preferred; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourcePoolAssignment that = (ResourcePoolAssignment) o; return Objects.equals(resourcePoolName, that.resourcePoolName) && Objects.equals(preferred, that.preferred) && Objects.equals(rule, that.rule); } @Override public int hashCode() { return Objects.hash(resourcePoolName, preferred, rule); } @Override public String toString() { return "ResourcePoolAssignment{" + "resourcePoolName='" + resourcePoolName + '\'' + ", preferredPoolName='" + preferred + '\'' + ", rule='" + rule + '\'' + '}'; } public ResourcePoolAssignment(String resourcePoolName, boolean preferred, String rule) { this.resourcePoolName = resourcePoolName; this.preferred = preferred; this.rule = rule; } public String getResourcePoolName() { return resourcePoolName; } public String getRule() { return rule; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private String resourcePoolName; private boolean preferred; private String rule; private Builder() { } public Builder withResourcePoolName(String resourcePoolName) { this.resourcePoolName = resourcePoolName; return this; } public Builder withPreferred(Boolean preferred) { this.preferred = preferred; return this; } public Builder withRule(String rule) { this.rule = rule; return this; } public ResourcePoolAssignment build() { Preconditions.checkNotNull(resourcePoolName, "resource pool name is null"); Preconditions.checkNotNull(rule, "rule is null"); return new ResourcePoolAssignment(resourcePoolName, preferred, rule); } } }
187
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/FarzonePodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.master.kubernetes.KubeUtil; /** * Farzone resource pool resolver. */ public class FarzonePodResourcePoolResolver implements PodResourcePoolResolver { private final KubePodConfiguration configuration; public FarzonePodResourcePoolResolver(KubePodConfiguration configuration) { this.configuration = configuration; } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { return KubeUtil.findFarzoneId(configuration, job).map(farzone -> { String resourcePoolName = PodResourcePoolResolvers.RESOURCE_POOL_ELASTIC_FARZONE_PREFIX + farzone; return Collections.singletonList(ResourcePoolAssignment.newBuilder() .withResourcePoolName(resourcePoolName) .withRule(String.format("Farzone %s assigned to resource pool %s", farzone, resourcePoolName)) .build() ); } ).orElse(Collections.emptyList()); } }
188
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/FixedResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; public class FixedResourcePoolResolver implements PodResourcePoolResolver { private final List<ResourcePoolAssignment> assignment; public FixedResourcePoolResolver(String resourcePoolName) { this.assignment = Collections.singletonList(ResourcePoolAssignment.newBuilder() .withResourcePoolName(resourcePoolName) .withRule("Fixed resource pool assignment " + resourcePoolName) .build()); } @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { return assignment; } }
189
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/ExplicitJobPodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.Collections; import java.util.List; 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.Task; import com.netflix.titus.common.util.StringExt; /** * Pick a resource pool directly by setting a job parameter. */ public class ExplicitJobPodResourcePoolResolver implements PodResourcePoolResolver { @Override public List<ResourcePoolAssignment> resolve(Job<?> job, Task task) { List<String> resourcePoolNames = StringExt.splitByComma( job.getJobDescriptor().getAttributes().get(JobAttributes.JOB_PARAMETER_RESOURCE_POOLS) ); if (resourcePoolNames.isEmpty()) { return Collections.emptyList(); } String rule = "Job requested placement in resource pools: " + resourcePoolNames; return resourcePoolNames.stream().map(name -> ResourcePoolAssignment.newBuilder().withResourcePoolName(name).withRule(rule).build() ).collect(Collectors.toList()); } }
190
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/resourcepool/PodResourcePoolResolver.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.master.kubernetes.pod.resourcepool; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; /** * {@link PodResourcePoolResolver} is an abstraction for resolving a set of resource pools in which a pod can be placed. */ public interface PodResourcePoolResolver { List<ResourcePoolAssignment> resolve(Job<?> job, Task task); }
191
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/legacy/DefaultAggregatingContainerEnvFactory.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.master.kubernetes.pod.legacy; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Singleton; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation aggregating container environment variables from multiple sources. * Evaluation happens from left to right, with the next item overriding entries from * previous evaluations if there is a collision. */ @Singleton public class DefaultAggregatingContainerEnvFactory implements ContainerEnvFactory { private static final Logger logger = LoggerFactory.getLogger(DefaultAggregatingContainerEnvFactory.class); private static final String CONFLICT_COUNTER = "titus.aggregatingContainerEnv.conflict"; private final Registry registry; private final Id conflictId; private final List<ContainerEnvFactory> orderedFactoryList; public DefaultAggregatingContainerEnvFactory(TitusRuntime titusRuntime, ContainerEnvFactory... containerEnvFactories) { orderedFactoryList = Arrays.asList(containerEnvFactories); this.registry = titusRuntime.getRegistry(); this.conflictId = registry.createId(CONFLICT_COUNTER); } @Override public Pair<List<String>, Map<String, String>> buildContainerEnv(Job<?> job, Task task) { List<String> systemEnvNames = new ArrayList<>(); Map<String, String> env = new HashMap<>(); for (ContainerEnvFactory factory : orderedFactoryList) { Pair<List<String>, Map<String, String>> incomingContainerEnv = factory.buildContainerEnv(job, task); Map<String, String> incomingEnv = incomingContainerEnv.getRight(); List<String> incomingSystemEnv = incomingContainerEnv.getLeft(); // Tracking conflicting env var for any two given factories env.keySet() .stream() .filter(incomingEnv::containsKey) .forEach(envVarName -> incrementConflictCounter(envVarName, job.getId(), job.getJobDescriptor().getApplicationName())); env.putAll(incomingEnv); systemEnvNames.addAll(incomingSystemEnv); } return Pair.of(systemEnvNames, env); } private void incrementConflictCounter(String envVarName, String jobId, String applicationName) { logger.info("JobId {} applicationName {} has conflicting env variable {}", jobId, applicationName, envVarName); registry.counter(this.conflictId.withTags("var_name", envVarName)).increment(); } }
192
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/legacy/UserProvidedContainerEnvFactory.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.master.kubernetes.pod.legacy; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.util.tuple.Pair; public class UserProvidedContainerEnvFactory implements ContainerEnvFactory { private static final ContainerEnvFactory INSTANCE = new UserProvidedContainerEnvFactory(); @Override public Pair<List<String>,Map<String, String>> buildContainerEnv(Job<?> job, Task task) { // For UserProvided env vars, the SystemProvidedEnvVars list is naturally empty. List<String> systemEnvNames = Collections.emptyList(); Map<String, String> env = new HashMap<>(); job.getJobDescriptor().getContainer().getEnv().forEach((k, v) -> { if (v != null) { env.put(k, v); } }); return Pair.of(systemEnvNames, env); } public static ContainerEnvFactory getInstance() { return INSTANCE; } }
193
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/legacy/TitusProvidedContainerEnvFactory.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.master.kubernetes.pod.legacy; 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 com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.runtime.kubernetes.KubeConstants; public class TitusProvidedContainerEnvFactory implements ContainerEnvFactory { private static final ContainerEnvFactory INSTANCE = new TitusProvidedContainerEnvFactory(); private static final List<String> commonPodEnvVars = new ArrayList<>(Arrays.asList( KubeConstants.POD_ENV_TITUS_JOB_ID, KubeConstants.POD_ENV_TITUS_TASK_ID, KubeConstants.POD_ENV_NETFLIX_EXECUTOR, KubeConstants.POD_ENV_NETFLIX_INSTANCE_ID, KubeConstants.POD_ENV_TITUS_TASK_INSTANCE_ID, KubeConstants.POD_ENV_TITUS_TASK_ORIGINAL_ID )); private static final List<String> batchPodEnvVars = Collections.singletonList( KubeConstants.POD_ENV_TITUS_TASK_INDEX ); @Override public Pair<List<String>, Map<String, String>> buildContainerEnv(Job<?> job, Task task) { Map<String, String> env = new HashMap<>(); env.put(KubeConstants.POD_ENV_TITUS_JOB_ID, task.getJobId()); env.put(KubeConstants.POD_ENV_TITUS_TASK_ID, task.getId()); env.put(KubeConstants.POD_ENV_NETFLIX_EXECUTOR, "titus"); env.put(KubeConstants.POD_ENV_NETFLIX_INSTANCE_ID, task.getId()); env.put(KubeConstants.POD_ENV_TITUS_TASK_INSTANCE_ID, task.getId()); env.put(KubeConstants.POD_ENV_TITUS_TASK_ORIGINAL_ID, task.getOriginalId()); // In TitusProvidedContainerEnvFactory, systemEnvNames ends up having everything we add List<String> systemEnvNames = new ArrayList<>(commonPodEnvVars); if (task instanceof BatchJobTask) { BatchJobTask batchJobTask = (BatchJobTask) task; env.put(KubeConstants.POD_ENV_TITUS_TASK_INDEX, "" + batchJobTask.getIndex()); systemEnvNames.addAll(batchPodEnvVars); } return Pair.of(systemEnvNames, env); } public static ContainerEnvFactory getInstance() { return INSTANCE; } }
194
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/pod/legacy/ContainerEnvFactory.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.master.kubernetes.pod.legacy; import java.util.List; import java.util.Map; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.util.tuple.Pair; import io.kubernetes.client.openapi.models.V1EnvVar; /** * Build container environment that is added to pod env section. */ public interface ContainerEnvFactory { /** * A pair of two things: * Right -> Map of env vars * Left -> A list of strings representing which of those env vars were injected by Titus and not provided by the user * * @return none null environment variables map */ Pair<List<String>, Map<String, String>> buildContainerEnv(Job<?> job, Task task); }
195
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/watcher/KubeAndJobServiceSyncStatusWatcher.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.master.kubernetes.watcher; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations; import com.netflix.titus.common.framework.scheduler.ExecutionContext; import com.netflix.titus.common.framework.scheduler.ScheduleReference; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.Evaluators; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.guice.annotation.Deactivator; import com.netflix.titus.common.util.tuple.Either; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.kubernetes.ContainerResultCodeResolver; import com.netflix.titus.master.kubernetes.KubernetesConfiguration; import com.netflix.titus.master.kubernetes.PodToTaskMapper; import com.netflix.titus.master.kubernetes.client.model.PodWrapper; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.informer.ResourceEventHandler; import io.kubernetes.client.openapi.models.V1Pod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; /** * A helper service that periodically checks job service task states and its corresponding pods. * In perfect scenario where the data is not lost, and there are no processing latencies of Kube informer events, the * states should be very close by. This services measures how much is that true. */ @Singleton public class KubeAndJobServiceSyncStatusWatcher { private static final Logger logger = LoggerFactory.getLogger(KubeAndJobServiceSyncStatusWatcher.class); private final KubernetesConfiguration configuration; private final StdKubeApiFacade kubeApiFacade; private final ReadOnlyJobOperations jobService; private final ContainerResultCodeResolver containerResultCodeResolver; private final TitusRuntime titusRuntime; private ScheduleReference schedulerRef; private final ConcurrentMap<String, TaskHolder> capturedState = new ConcurrentHashMap<>(); @Inject public KubeAndJobServiceSyncStatusWatcher(KubernetesConfiguration configuration, StdKubeApiFacade kubeApiFacade, ReadOnlyJobOperations jobService, ContainerResultCodeResolver containerResultCodeResolver, TitusRuntime titusRuntime) { this.configuration = configuration; this.kubeApiFacade = kubeApiFacade; this.jobService = jobService; this.containerResultCodeResolver = containerResultCodeResolver; this.titusRuntime = titusRuntime; } @Activator public Observable<Void> enterActiveMode() { try { kubeApiFacade.getPodInformer().addEventHandler(new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod obj) { capturedState.put(obj.getMetadata().getName(), new TaskHolder(obj, false)); } @Override public void onUpdate(V1Pod oldObj, V1Pod newObj) { capturedState.put(newObj.getMetadata().getName(), new TaskHolder(newObj, false)); } @Override public void onDelete(V1Pod obj, boolean deletedFinalStateUnknown) { capturedState.put(obj.getMetadata().getName(), new TaskHolder(obj, true)); } }); ScheduleDescriptor scheduleDescriptor = ScheduleDescriptor.newBuilder() .withName(KubeAndJobServiceSyncStatusWatcher.class.getSimpleName()) .withDescription("Compare Kube pod state with Titus job service") .withInitialDelay(Duration.ofSeconds(60)) .withInterval(Duration.ofSeconds(10)) .withTimeout(Duration.ofSeconds((60))) .build(); this.schedulerRef = titusRuntime.getLocalScheduler().schedule( scheduleDescriptor, this::process, ExecutorsExt.namedSingleThreadExecutor(KubeAndJobServiceSyncStatusWatcher.class.getSimpleName()) ); } catch (Exception e) { return Observable.error(e); } return Observable.empty(); } @Deactivator @PreDestroy public void shutdown() { Evaluators.acceptNotNull(schedulerRef, ScheduleReference::cancel); } private void process(ExecutionContext context) { if (!kubeApiFacade.getPodInformer().hasSynced()) { logger.info("Not synced yet"); return; } try { if (!jobService.getJobsAndTasks().isEmpty()) { // Remove tasks not found in job service Set<String> taskIds = jobService.getJobsAndTasks().stream() .flatMap(jobAndTasks -> jobAndTasks.getRight().stream()) .map(Task::getId) .collect(Collectors.toSet()); capturedState.keySet().retainAll(taskIds); // Update job service task state jobService.getJobsAndTasks().forEach(jobAndTasks -> jobAndTasks.getRight().forEach(task -> { TaskHolder taskHolder = capturedState.get(task.getId()); if (taskHolder == null || taskHolder.getPod() == null) { capturedState.put(task.getId(), new TaskHolder(task)); } else { capturedState.put(task.getId(), new TaskHolder(taskHolder.getPod(), taskHolder.isPodDeleted())); } }) ); } logger.info("Captured state size: {}", (long) capturedState.values().size()); Map<String, Integer> stateCounts = new HashMap<>(); capturedState.forEach((id, h) -> { String state = h.getSyncState(); stateCounts.put(state, stateCounts.getOrDefault(state, 0) + 1); }); stateCounts.forEach((state, count) -> logger.info("{}: {}", state, count)); } catch (Exception e) { logger.error("Processing error", e); } } class TaskHolder { private final Task task; private final V1Pod pod; private final boolean podDeleted; private final long timestamp; private final String syncState; public TaskHolder(V1Pod pod, boolean podDeleted) { this.podDeleted = podDeleted; String id = pod.getMetadata().getName(); Pair<Job<?>, Task> jobAndTask = jobService.findTaskById(id).orElse(null); if (jobAndTask == null) { this.task = null; BatchJobTask fakeTask = BatchJobTask.newBuilder() .withId(pod.getMetadata().getName()) .withStatus(TaskStatus.newBuilder().withState(TaskState.Accepted).build()) .build(); Optional<TaskStatus> taskStatusInKubeOpt = extractedTaskStatus(fakeTask, pod, podDeleted); this.syncState = taskStatusInKubeOpt .map(taskStatusInKube -> "noTask:" + taskStatusInKube.getState().name()) .orElse("noTask:unknown"); } else { this.task = jobAndTask.getRight(); Optional<TaskStatus> taskStatusInKubeOpt = extractedTaskStatus(task, pod, podDeleted); this.syncState = taskStatusInKubeOpt .map(taskStatusInKube -> { if (task.getStatus().getState() == taskStatusInKube.getState()) { return "synced:" + taskStatusInKube.getState().name(); } else { return "notSynced:" + taskStatusInKube.getState().name() + "!=" + task.getStatus().getState(); } }) .orElseGet(() -> "notSynced:unknown!=" + task.getStatus().getState()); } this.pod = pod; this.timestamp = System.currentTimeMillis(); } public TaskHolder(Task task) { this.task = task; this.pod = null; this.podDeleted = TaskState.isTerminalState(task.getStatus().getState()); this.timestamp = System.currentTimeMillis(); this.syncState = "noPod:" + task.getStatus().getState(); } public Task getTask() { return task; } public V1Pod getPod() { return pod; } public boolean isPodDeleted() { return podDeleted; } public long getTimestamp() { return timestamp; } public String getSyncState() { return syncState; } private Optional<TaskStatus> extractedTaskStatus(Task task, V1Pod obj, boolean podDeleted) { PodToTaskMapper mapper = new PodToTaskMapper(configuration, new PodWrapper(obj), Optional.empty(), task, podDeleted, containerResultCodeResolver, titusRuntime); Either<TaskStatus, String> either = mapper.getNewTaskStatus(); if (either.hasValue()) { return Optional.of(either.getValue()); } return Optional.empty(); } } }
196
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/watcher/KubeAndJobServiceSyncStatusWatcherMain.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.master.kubernetes.watcher; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent; import com.netflix.titus.api.jobmanager.service.ReadOnlyJobOperations; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.archaius2.Archaius2Ext; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.kubernetes.DefaultContainerResultCodeResolver; import com.netflix.titus.master.kubernetes.KubernetesConfiguration; import com.netflix.titus.runtime.connector.kubernetes.KubeConnectorConfiguration; import com.netflix.titus.runtime.connector.kubernetes.std.DefaultStdStdKubeApiFacade; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiClients; import io.kubernetes.client.openapi.ApiClient; import rx.Observable; /** * Help CLI utility to watch informer event streams. */ public class KubeAndJobServiceSyncStatusWatcherMain { private static final TitusRuntime titusRuntime = TitusRuntimes.internal(); private static final KubeConnectorConfiguration kubeConnectorConfiguration = Archaius2Ext.newConfiguration(KubeConnectorConfiguration.class); private static final KubernetesConfiguration backendConfig = Archaius2Ext.newConfiguration(KubernetesConfiguration.class); private static final DefaultContainerResultCodeResolver containerResultCodeResolver = new DefaultContainerResultCodeResolver(backendConfig); private static final ReadOnlyJobOperations jobService = new ReadOnlyJobOperations() { @Override public List<Job> getJobs() { return null; } @Override public Optional<Job<?>> getJob(String jobId) { return Optional.empty(); } @Override public List<Task> getTasks() { return null; } @Override public List<Task> getTasks(String jobId) { return null; } @Override public List<Pair<Job, List<Task>>> getJobsAndTasks() { return Collections.emptyList(); } @Override public List<Job<?>> findJobs(Predicate<Pair<Job<?>, List<Task>>> queryPredicate, int offset, int limit) { return null; } @Override public List<Pair<Job<?>, Task>> findTasks(Predicate<Pair<Job<?>, Task>> queryPredicate, int offset, int limit) { return null; } @Override public Optional<Pair<Job<?>, Task>> findTaskById(String taskId) { return Optional.empty(); } @Override public Observable<JobManagerEvent<?>> observeJobs(Predicate<Pair<Job<?>, List<Task>>> jobsPredicate, Predicate<Pair<Job<?>, Task>> tasksPredicate, boolean withCheckpoints) { return null; } @Override public Observable<JobManagerEvent<?>> observeJob(String jobId) { return null; } }; public static void main(String[] args) { ApiClient kubeClient = StdKubeApiClients.createApiClient("cli", TitusRuntimes.internal(), 0L); DefaultStdStdKubeApiFacade facade = new DefaultStdStdKubeApiFacade(kubeConnectorConfiguration, kubeClient, titusRuntime); KubernetesConfiguration configuration = Archaius2Ext.newConfiguration(KubernetesConfiguration.class); KubeAndJobServiceSyncStatusWatcher watcher = new KubeAndJobServiceSyncStatusWatcher( configuration, facade, jobService, containerResultCodeResolver, titusRuntime ); watcher.enterActiveMode(); try { Thread.sleep(3600_1000); } catch (InterruptedException ignore) { } } }
197
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/watcher/KubeWatcherModule.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.master.kubernetes.watcher; import com.google.inject.AbstractModule; public class KubeWatcherModule extends AbstractModule { @Override protected void configure() { bind(KubeAndJobServiceSyncStatusWatcher.class).asEagerSingleton(); } }
198
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/controller/PersistentVolumeClaimGcController.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.master.kubernetes.controller; import java.util.List; import java.util.Optional; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.master.kubernetes.client.KubeModelConverters; import com.netflix.titus.runtime.connector.kubernetes.KubeApiException; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1PersistentVolumeClaim; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.api.jobmanager.model.job.TaskState.isTerminalState; import static com.netflix.titus.master.kubernetes.KubeObjectFormatter.formatPvcEssentials; import static com.netflix.titus.runtime.kubernetes.KubeConstants.DEFAULT_NAMESPACE; /** * Garbage collects persistent volume claims that are not associated with active/non-terminal tasks. */ @Singleton public class PersistentVolumeClaimGcController extends BaseGcController<V1PersistentVolumeClaim> { private static final Logger logger = LoggerFactory.getLogger(PersistentVolumeClaimGcController.class); public static final String PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER = "persistentVolumeClaimGcController"; public static final String PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER_DESCRIPTION = "GC persistent volume claims that are no longer associated with active tasks."; private final StdKubeApiFacade kubeApiFacade; private final V3JobOperations v3JobOperations; @Inject public PersistentVolumeClaimGcController(TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade, V3JobOperations v3JobOperations) { super( PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER, PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; this.v3JobOperations = v3JobOperations; } @Override public boolean shouldGc() { return kubeApiFacade.getPersistentVolumeInformer().hasSynced(); } @Override public List<V1PersistentVolumeClaim> getItemsToGc() { return kubeApiFacade.getPersistentVolumeClaimInformer().getIndexer().list(); } @Override public boolean gcItem(V1PersistentVolumeClaim pvc) { // Extract the task ID embedded in the PVC's name String taskId = KubeModelConverters.getTaskIdFromPvc(pvc); Optional<Pair<Job<?>, Task>> optionalJobTaskPair = v3JobOperations.findTaskById(taskId); if (!optionalJobTaskPair.isPresent()) { // If we could not find a task for the PVC, GC it. logger.info("Did not find task {} for pvc {}", taskId, formatPvcEssentials(pvc)); return gcPersistentVolumeClaim(pvc); } // If the task is terminal, GC it. return isTerminalState(optionalJobTaskPair.get().getRight().getStatus().getState()) && gcPersistentVolumeClaim(pvc); } private boolean gcPersistentVolumeClaim(V1PersistentVolumeClaim pvc) { String volumeClaimName = KubeUtil.getMetadataName(pvc.getMetadata()); try { // If the PVC is deleted while still in use by a pod (though that is not expected), the PVC // will not be removed until no pod is using it. // https://kubernetes.io/docs/concepts/storage/persistent-volumes/#storage-object-in-use-protection kubeApiFacade.deleteNamespacedPersistentVolumeClaim(DEFAULT_NAMESPACE, volumeClaimName); logger.info("Successfully deleted persistent volume claim {}", formatPvcEssentials(pvc)); return true; } catch (KubeApiException e) { if (e.getErrorCode() == KubeApiException.ErrorCode.NOT_FOUND) { // If we did not find the PVC return true as it is removed logger.info("Delete for persistent volume claim {} not found", formatPvcEssentials(pvc)); return true; } logger.error("Failed to delete persistent volume claim: {} with error: ", formatPvcEssentials(pvc), e); } catch (Exception e) { logger.error("Failed to delete persistent volume claim: {} with error: ", formatPvcEssentials(pvc), e); } return false; } }
199