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/kubernetes
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/controller/PersistentVolumeReclaimController.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.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; 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.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1PersistentVolume; import io.kubernetes.client.openapi.models.V1PersistentVolumeBuilder; import io.kubernetes.client.openapi.models.V1PersistentVolumeSpec; import io.kubernetes.client.openapi.models.V1PersistentVolumeSpecBuilder; import io.kubernetes.client.openapi.models.V1PersistentVolumeStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.master.kubernetes.KubeObjectFormatter.formatPvEssentials; /** * Reclaims persistent volumes that are released from persistent volume claims that no longer exist. */ @Singleton public class PersistentVolumeReclaimController extends BaseGcController<V1PersistentVolume> { private static final Logger logger = LoggerFactory.getLogger(PersistentVolumeReclaimController.class); public static final String PERSISTENT_VOLUME_RECLAIM_CONTROLLER = "persistentVolumeReclaimController"; public static final String PERSISTENT_VOLUME_RECLAIM_CONTROLLER_DESCRIPTION = "GC persistent volumes that are no longer associated with active jobs."; private final StdKubeApiFacade kubeApiFacade; @Inject public PersistentVolumeReclaimController(TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(PERSISTENT_VOLUME_RECLAIM_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(PERSISTENT_VOLUME_RECLAIM_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade) { super( PERSISTENT_VOLUME_RECLAIM_CONTROLLER, PERSISTENT_VOLUME_RECLAIM_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; } @Override public boolean shouldGc() { return kubeApiFacade.getPersistentVolumeInformer().hasSynced(); } @Override public List<V1PersistentVolume> getItemsToGc() { return kubeApiFacade.getPersistentVolumeInformer().getIndexer().list().stream() // Only consider PVs that have been Released (i.e., the PVC in its claimRef has been deleted). .filter(this::isPvReleased) .collect(Collectors.toList()); } @Override public boolean gcItem(V1PersistentVolume v1PersistentVolume) { logger.info("Reclaiming pv {}", formatPvEssentials(v1PersistentVolume)); V1PersistentVolumeSpec spec = v1PersistentVolume.getSpec() == null ? new V1PersistentVolumeSpec() : v1PersistentVolume.getSpec(); // Reclaim the pv by removing the claimRef. V1PersistentVolume updatedPv = new V1PersistentVolumeBuilder(v1PersistentVolume) .withSpec(new V1PersistentVolumeSpecBuilder(spec).build().claimRef(null)) .build(); try { kubeApiFacade.replacePersistentVolume(updatedPv); logger.info("Successfully reclaimed pv {}", formatPvEssentials(updatedPv)); } catch (Exception e) { logger.error("Failed to reclaim pv {} with error: ", formatPvEssentials(v1PersistentVolume), e); return false; } return true; } @VisibleForTesting boolean isPvReleased(V1PersistentVolume v1PersistentVolume) { V1PersistentVolumeStatus status = v1PersistentVolume.getStatus() == null ? new V1PersistentVolumeStatus() : v1PersistentVolume.getStatus(); return status.getPhase() == null || status.getPhase().equalsIgnoreCase("Released"); } }
200
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/PodOnUnknownNodeGcController.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.controller; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1Pod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class PodOnUnknownNodeGcController extends BaseGcController<V1Pod> { public static final String POD_ON_UNKNOWN_NODE_GC_CONTROLLER = "podOnUnknownNodeGcController"; public static final String POD_ON_UNKNOWN_NODE_GC_CONTROLLER_DESCRIPTION = "GC pods on unknown nodes."; private static final Logger logger = LoggerFactory.getLogger(PodOnUnknownNodeGcController.class); private final StdKubeApiFacade kubeApiFacade; @Inject public PodOnUnknownNodeGcController( TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(POD_ON_UNKNOWN_NODE_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(POD_ON_UNKNOWN_NODE_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade ) { super( POD_ON_UNKNOWN_NODE_GC_CONTROLLER, POD_ON_UNKNOWN_NODE_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; } @Override public boolean shouldGc() { return kubeApiFacade.getNodeInformer().hasSynced() && kubeApiFacade.getPodInformer().hasSynced(); } @Override public List<V1Pod> getItemsToGc() { Set<String> knownNodeNames = kubeApiFacade.getNodeInformer().getIndexer().list() .stream() .map(n -> KubeUtil.getMetadataName(n.getMetadata())) .collect(Collectors.toSet()); return kubeApiFacade.getPodInformer().getIndexer().list() .stream() .filter(p -> isPodOnUnknownNode(p, knownNodeNames)) .collect(Collectors.toList()); } @Override public boolean gcItem(V1Pod item) { return GcControllerUtil.deletePod(kubeApiFacade, logger, item); } @VisibleForTesting boolean isPodOnUnknownNode(V1Pod pod, Set<String> knownNodeNames) { if (pod == null || pod.getSpec() == null) { return false; } String nodeName = pod.getSpec().getNodeName(); return StringExt.isNotEmpty(nodeName) && !knownNodeNames.contains(nodeName); } }
201
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/PodUnknownGcController.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.controller; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; 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.time.Clock; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class PodUnknownGcController extends BaseGcController<V1Pod> { public static final String POD_UNKNOWN_GC_CONTROLLER = "podUnknownGcController"; public static final String POD_UNKNOWN_GC_CONTROLLER_DESCRIPTION = "GC pods that are unknown to Titus."; private static final Logger logger = LoggerFactory.getLogger(PodUnknownGcController.class); private final StdKubeApiFacade kubeApiFacade; private final Clock clock; private final KubeControllerConfiguration kubeControllerConfiguration; private final V3JobOperations v3JobOperations; @Inject public PodUnknownGcController( TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(POD_UNKNOWN_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(POD_UNKNOWN_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade, KubeControllerConfiguration kubeControllerConfiguration, V3JobOperations v3JobOperations ) { super( POD_UNKNOWN_GC_CONTROLLER, POD_UNKNOWN_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; this.kubeControllerConfiguration = kubeControllerConfiguration; this.clock = titusRuntime.getClock(); this.v3JobOperations = v3JobOperations; } @Override public boolean shouldGc() { return kubeApiFacade.getPodInformer().hasSynced(); } @Override public List<V1Pod> getItemsToGc() { Map<String, Task> currentTasks = v3JobOperations.getTasks().stream() .collect(Collectors.toMap(Task::getId, Function.identity())); return kubeApiFacade.getPodInformer().getIndexer().list().stream() .filter(p -> isPodUnknownToJobManagement(p, currentTasks)) .collect(Collectors.toList()); } @Override public boolean gcItem(V1Pod item) { return GcControllerUtil.deletePod(kubeApiFacade, logger, item); } @VisibleForTesting boolean isPodUnknownToJobManagement(V1Pod pod, Map<String, Task> currentTasks) { V1ObjectMeta metadata = pod.getMetadata(); V1PodStatus status = pod.getStatus(); if (metadata == null || status == null) { // this pod is missing data so GC it return true; } if (KubeUtil.isPodPhaseTerminal(status.getPhase()) || currentTasks.containsKey(metadata.getName())) { return false; } OffsetDateTime creationTimestamp = metadata.getCreationTimestamp(); return creationTimestamp != null && clock.isPast(creationTimestamp.toInstant().toEpochMilli() + kubeControllerConfiguration.getPodUnknownGracePeriodMs()); } }
202
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/KubeControllerConfiguration.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.controller; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.kubernetes.controller") public interface KubeControllerConfiguration { /** * @return the accountId to use for GC. */ @DefaultValue("") String getAccountId(); /** * @return whether or not the logic to verify that a node's accountId matches the control plane's accountId is enabled. */ @DefaultValue("true") boolean isVerifyNodeAccountIdEnabled(); /** * @return the grace period of how old the Ready condition's timestamp can be before attempting to GC a node. */ @DefaultValue("300000") long getNodeGcGracePeriodMs(); /** * Amount of time to wait before GC'ing a pod that is past its deletion timestamp. . */ @DefaultValue("1800000") long getPodsPastTerminationGracePeriodMs(); /** * Amount of time to wait after the pod creation timestamp for unknown pods before deleting the pod. */ @DefaultValue("300000") long getPodUnknownGracePeriodMs(); /** * Amount of time to wait after the pod finished timestamp for terminal pods before deleting the pod. */ @DefaultValue("300000") long getPodTerminalGracePeriodMs(); /** * Amount of time to wait for a persistent volume that has not been associated with any active job * before deleting the persistent volume. */ @DefaultValue("300000") long getPersistentVolumeUnassociatedGracePeriodMs(); }
203
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/PodTerminalGcController.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.controller; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; 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.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.time.Clock; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class PodTerminalGcController extends BaseGcController<V1Pod> { public static final String POD_TERMINAL_GC_CONTROLLER = "podTerminalGcController"; public static final String POD_TERMINAL_GC_CONTROLLER_DESCRIPTION = "GC pods that are terminal to Titus."; private static final Logger logger = LoggerFactory.getLogger(PodTerminalGcController.class); private final StdKubeApiFacade kubeApiFacade; private final Clock clock; private final KubeControllerConfiguration kubeControllerConfiguration; private final V3JobOperations v3JobOperations; @Inject public PodTerminalGcController( TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(POD_TERMINAL_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(POD_TERMINAL_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade, KubeControllerConfiguration kubeControllerConfiguration, V3JobOperations v3JobOperations ) { super( POD_TERMINAL_GC_CONTROLLER, POD_TERMINAL_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; this.kubeControllerConfiguration = kubeControllerConfiguration; this.clock = titusRuntime.getClock(); this.v3JobOperations = v3JobOperations; } @Override public boolean shouldGc() { return kubeApiFacade.getPodInformer().hasSynced(); } @Override public List<V1Pod> getItemsToGc() { Map<String, Task> currentTasks = v3JobOperations.getTasks().stream() .collect(Collectors.toMap(Task::getId, Function.identity())); return kubeApiFacade.getPodInformer().getIndexer().list().stream() .filter(p -> isPodTerminal(p, currentTasks)) .collect(Collectors.toList()); } @Override public boolean gcItem(V1Pod item) { return GcControllerUtil.deletePod(kubeApiFacade, logger, item); } @VisibleForTesting boolean isPodTerminal(V1Pod pod, Map<String, Task> currentTasks) { String podName = KubeUtil.getMetadataName(pod.getMetadata()); Task task = currentTasks.get(podName); if (task != null) { if (TaskState.isTerminalState(task.getStatus().getState())) { return clock.isPast(task.getStatus().getTimestamp() + kubeControllerConfiguration.getPodTerminalGracePeriodMs()); } return false; } V1PodStatus status = pod.getStatus(); if (status != null && KubeUtil.isPodPhaseTerminal(status.getPhase())) { return KubeUtil.findFinishedTimestamp(pod) .map(timestamp -> clock.isPast(timestamp + kubeControllerConfiguration.getPodTerminalGracePeriodMs())) .orElse(true); } return false; } }
204
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/GcControllerUtil.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.controller; import com.google.gson.JsonSyntaxException; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.KubeApiException; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; import org.slf4j.Logger; import static com.netflix.titus.runtime.kubernetes.KubeConstants.DEFAULT_NAMESPACE; public final class GcControllerUtil { public static boolean deleteNode(StdKubeApiFacade kubeApiFacade, Logger logger, V1Node node) { String nodeName = KubeUtil.getMetadataName(node.getMetadata()); try { kubeApiFacade.deleteNode(nodeName); return true; } catch (JsonSyntaxException e) { // this will be counted as successful as the response type mapping in the client is incorrect return true; } catch (KubeApiException e) { if (e.getErrorCode() != KubeApiException.ErrorCode.NOT_FOUND) { logger.error("Failed to delete node: {} with error: ", nodeName, e); } } catch (Exception e) { logger.error("Failed to delete node: {} with error: ", nodeName, e); } return false; } public static boolean deletePod(StdKubeApiFacade kubeApiFacade, Logger logger, V1Pod pod) { String podName = KubeUtil.getMetadataName(pod.getMetadata()); try { kubeApiFacade.deleteNamespacedPod(DEFAULT_NAMESPACE, podName); return true; } catch (JsonSyntaxException e) { // this will be counted as successful as the response type mapping in the client is incorrect return true; } catch (KubeApiException e) { if (e.getErrorCode() != KubeApiException.ErrorCode.NOT_FOUND) { logger.error("Failed to delete pod: {} with error: ", podName, e); } } catch (Exception e) { logger.error("Failed to delete pod: {} with error: ", podName, e); } return false; } }
205
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/PersistentVolumeUnassociatedGcController.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.controller; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; 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.StringExt; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.KubeApiException; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1PersistentVolume; import io.kubernetes.client.openapi.models.V1PersistentVolumeStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.master.kubernetes.KubeObjectFormatter.formatPvEssentials; /** * Garbage collects persistent volumes that are not associated with active/non-terminal jobs. */ @Singleton public class PersistentVolumeUnassociatedGcController extends BaseGcController<V1PersistentVolume> { private static final Logger logger = LoggerFactory.getLogger(PersistentVolumeUnassociatedGcController.class); public static final String PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER = "persistentVolumeUnassociatedGcController"; public static final String PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER_DESCRIPTION = "GC persistent volumes that are no longer associated with active jobs."; private final StdKubeApiFacade kubeApiFacade; private final KubeControllerConfiguration kubeControllerConfiguration; private final V3JobOperations v3JobOperations; // Contains the persistent volumes marked for GC with the timestamp of when it was marked. private final Map<String, Long> markedPersistentVolumes = new ConcurrentHashMap<>(); @Inject public PersistentVolumeUnassociatedGcController(TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade, KubeControllerConfiguration kubeControllerConfiguration, V3JobOperations v3JobOperations) { super( PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER, PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; this.kubeControllerConfiguration = kubeControllerConfiguration; this.v3JobOperations = v3JobOperations; } @Override public boolean shouldGc() { return kubeApiFacade.getPersistentVolumeInformer().hasSynced(); } @Override public List<V1PersistentVolume> getItemsToGc() { Set<String> currentEbsVolumes = v3JobOperations.getJobs().stream() .flatMap(job -> job.getJobDescriptor().getContainer().getContainerResources().getEbsVolumes().stream()) .map(EbsVolume::getVolumeId) .collect(Collectors.toSet()); return kubeApiFacade.getPersistentVolumeInformer().getIndexer().list().stream() // Only consider PVs that are available (i.e., not bound) .filter(pv -> (pv.getStatus() == null ? "" : pv.getStatus().getPhase()).equalsIgnoreCase("Available")) // Only consider PVs that are not associated with active jobs .filter(pv -> isPersistentVolumeUnassociated(pv, currentEbsVolumes)) .collect(Collectors.toList()); } @Override public boolean gcItem(V1PersistentVolume pv) { return gcPersistentVolume(pv); } private boolean gcPersistentVolume(V1PersistentVolume pv) { String volumeName = KubeUtil.getMetadataName(pv.getMetadata()); try { // If the PV is deleted while still associated with a PVC (though that is not expected), the PV // will not be removed until it is no longer bound to a PVC. // https://kubernetes.io/docs/concepts/storage/persistent-volumes/#storage-object-in-use-protection kubeApiFacade.deletePersistentVolume(volumeName); logger.info("Successfully deleted persistent volume {}", formatPvEssentials(pv)); return true; } catch (KubeApiException e) { if (e.getErrorCode() == KubeApiException.ErrorCode.NOT_FOUND) { // If we did not find the PV return true as it is removed logger.info("Delete for persistent volume {} not found", formatPvEssentials(pv)); return true; } logger.error("Failed to delete persistent volume: {} with error: ", formatPvEssentials(pv), e); } catch (Exception e) { logger.error("Failed to delete persistent volume: {} with error: ", formatPvEssentials(pv), e); } return false; } /** * Returns true if the persistent volume has not been associated with an active job for enough time. */ @VisibleForTesting boolean isPersistentVolumeUnassociated(V1PersistentVolume pv, Set<String> ebsVolumeIds) { V1ObjectMeta metadata = pv.getMetadata(); V1PersistentVolumeStatus status = pv.getStatus(); if (metadata == null || metadata.getName() == null || status == null) { // this persistent volume is missing data so GC it return true; } String volumeName = StringExt.nonNull(metadata.getName()); if (ebsVolumeIds.contains(volumeName)) { // this persistent volume is associated with an active job, so reset/remove // any marking and don't GC it. markedPersistentVolumes.remove(volumeName); return false; } // TODO Maybe skip terminating as these should be handled already? // TODO Find/emit where volumes are stuck in terminating for too long like orphan pod Long marked = markedPersistentVolumes.get(volumeName); if (marked == null) { // this persistent volume is not associated with an active job and is not marked, // so mark it. markedPersistentVolumes.put(volumeName, titusRuntime.getClock().wallTime()); return false; } // gc this persistent volume if it has been marked for long enough return titusRuntime.getClock().isPast(marked + kubeControllerConfiguration.getPersistentVolumeUnassociatedGracePeriodMs()); } }
206
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/NoOpJobManagementReconciler.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 javax.inject.Singleton; import com.netflix.titus.master.kubernetes.client.model.PodEvent; import reactor.core.publisher.Flux; @Singleton public class NoOpJobManagementReconciler implements KubeJobManagementReconciler { @Override public Flux<PodEvent> getPodEventSource() { return Flux.empty(); } }
207
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/PodDeletionGcController.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.controller; import java.time.OffsetDateTime; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; 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.time.Clock; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1PodSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.runtime.kubernetes.KubeConstants.PENDING; @Singleton public class PodDeletionGcController extends BaseGcController<V1Pod> { public static final String POD_DELETION_GC_CONTROLLER = "podDeletionGcController"; public static final String POD_DELETION_GC_CONTROLLER_DESCRIPTION = "GC pods with a deletion timestamp that needs to be cleaned up."; private static final Logger logger = LoggerFactory.getLogger(PodDeletionGcController.class); private final StdKubeApiFacade kubeApiFacade; private final Clock clock; private final KubeControllerConfiguration kubeControllerConfiguration; @Inject public PodDeletionGcController( TitusRuntime titusRuntime, @Named(GC_CONTROLLER) LocalScheduler scheduler, @Named(POD_DELETION_GC_CONTROLLER) FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, @Named(POD_DELETION_GC_CONTROLLER) ControllerConfiguration controllerConfiguration, StdKubeApiFacade kubeApiFacade, KubeControllerConfiguration kubeControllerConfiguration ) { super( POD_DELETION_GC_CONTROLLER, POD_DELETION_GC_CONTROLLER_DESCRIPTION, titusRuntime, scheduler, tokenBucketConfiguration, controllerConfiguration ); this.kubeApiFacade = kubeApiFacade; this.kubeControllerConfiguration = kubeControllerConfiguration; this.clock = titusRuntime.getClock(); } @Override public boolean shouldGc() { return kubeApiFacade.getNodeInformer().hasSynced() && kubeApiFacade.getPodInformer().hasSynced(); } @Override public List<V1Pod> getItemsToGc() { return kubeApiFacade.getPodInformer().getIndexer().list() .stream() .filter(p -> isPodInPendingPhaseWithDeletionTimestamp(p) || isPodPastDeletionTimestamp(p)) .collect(Collectors.toList()); } @Override public boolean gcItem(V1Pod item) { return GcControllerUtil.deletePod(kubeApiFacade, logger, item); } @VisibleForTesting boolean isPodInPendingPhaseWithDeletionTimestamp(V1Pod pod) { if (pod == null || pod.getMetadata() == null || pod.getStatus() == null) { return false; } OffsetDateTime deletionTimestamp = pod.getMetadata().getDeletionTimestamp(); return deletionTimestamp != null && PENDING.equalsIgnoreCase(pod.getStatus().getPhase()); } @VisibleForTesting boolean isPodPastDeletionTimestamp(V1Pod pod) { V1PodSpec spec = pod.getSpec(); V1ObjectMeta metadata = pod.getMetadata(); if (spec == null || metadata == null) { return false; } Long terminationGracePeriodSeconds = spec.getTerminationGracePeriodSeconds(); OffsetDateTime deletionTimestamp = metadata.getDeletionTimestamp(); if (terminationGracePeriodSeconds == null || deletionTimestamp == null) { return false; } long terminationGracePeriodMs = terminationGracePeriodSeconds * 1000L; return clock.isPast(deletionTimestamp.toInstant().toEpochMilli() + terminationGracePeriodMs + kubeControllerConfiguration.getPodsPastTerminationGracePeriodMs()); } }
208
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/KubeJobManagementReconciler.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 com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.master.kubernetes.client.model.PodEvent; import reactor.core.publisher.Flux; /** * {@link KubeJobManagementReconciler} checks that for each placed {@link Task} there exists a pod. If the pod does not * exist, and a task is in a running state, the task is moved to a finished state, an event is emitted. */ public interface KubeJobManagementReconciler { /** * Event stream for {@link com.netflix.titus.master.jobmanager.service.KubeNotificationProcessor}. */ Flux<PodEvent> getPodEventSource(); }
209
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/ControllerConfiguration.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.controller; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.kubernetes.controller") public interface ControllerConfiguration { /** * @return whether or not the controller is enabled */ @DefaultValue("true") boolean isControllerEnabled(); /** * @return the initial delay in milliseconds before the execution runs after process startup. */ @DefaultValue("10000") long getControllerInitialDelayMs(); /** * @return the interval in milliseconds of how often the controller runs. */ @DefaultValue("30000") long getControllerIntervalMs(); /** * @return the timeout of the controller's execution loop. */ @DefaultValue("60000") long getControllerTimeoutMs(); }
210
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/DefaultKubeJobManagementReconciler.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.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; 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.TaskStatus; import com.netflix.titus.api.jobmanager.service.V3JobOperations; 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.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.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.master.MetricConstants; import com.netflix.titus.master.kubernetes.client.DirectKubeConfiguration; import com.netflix.titus.master.kubernetes.client.model.PodEvent; import com.netflix.titus.master.kubernetes.client.model.PodNotFoundEvent; import com.netflix.titus.master.kubernetes.KubernetesConfiguration; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; @Singleton public class DefaultKubeJobManagementReconciler implements KubeJobManagementReconciler { private static final Logger logger = LoggerFactory.getLogger(DefaultKubeJobManagementReconciler.class); static final String GC_UNKNOWN_PODS = "gcUnknownPods"; private enum OrphanedKind { /** * If the last task status was KillInitiated and the system missed the last event then the assumption is that * the kubelet successfully terminated the pod and deleted the pod object. */ KILL_INITIATED, /** * If task is associated with an non-existing agent, assume the agent was terminated. */ NODE_TERMINATED, UNKNOWN } private final KubernetesConfiguration kubernetesConfiguration; private final DirectKubeConfiguration directKubeConfiguration; private final FixedIntervalTokenBucketConfiguration gcUnknownPodsTokenBucketConfiguration; private final StdKubeApiFacade kubeApiFacade; private final V3JobOperations v3JobOperations; private final Clock clock; private final TitusRuntime titusRuntime; private final DirectProcessor<PodEvent> podEventProcessor = DirectProcessor.create(); private final FluxSink<PodEvent> podEventSink = podEventProcessor.sink(FluxSink.OverflowStrategy.IGNORE); private final Map<OrphanedKind, Gauge> orphanedTaskGauges; private ScheduleReference schedulerRef; @Inject public DefaultKubeJobManagementReconciler(KubernetesConfiguration kubernetesConfiguration, DirectKubeConfiguration directKubeConfiguration, @Named(GC_UNKNOWN_PODS) FixedIntervalTokenBucketConfiguration gcUnknownPodsTokenBucketConfiguration, StdKubeApiFacade kubeApiFacade, V3JobOperations v3JobOperations, TitusRuntime titusRuntime) { this.kubernetesConfiguration = kubernetesConfiguration; this.directKubeConfiguration = directKubeConfiguration; this.gcUnknownPodsTokenBucketConfiguration = gcUnknownPodsTokenBucketConfiguration; this.kubeApiFacade = kubeApiFacade; this.v3JobOperations = v3JobOperations; this.clock = titusRuntime.getClock(); this.titusRuntime = titusRuntime; Registry registry = titusRuntime.getRegistry(); this.orphanedTaskGauges = Stream.of(OrphanedKind.values()).collect(Collectors.toMap( Function.identity(), kind -> registry.gauge(MetricConstants.METRIC_KUBERNETES + "orphanedTasks", "kind", kind.name()) )); } @Activator public void enterActiveMode() { ScheduleDescriptor scheduleDescriptor = ScheduleDescriptor.newBuilder() .withName("reconcileNodesAndPods") .withDescription("Reconcile nodes and pods") .withInitialDelay(Duration.ofMillis(kubernetesConfiguration.getReconcilerInitialDelayMs())) .withInterval(Duration.ofMillis(kubernetesConfiguration.getReconcilerIntervalMs())) .withTimeout(Duration.ofMinutes(5)) .build(); this.schedulerRef = titusRuntime.getLocalScheduler().schedule( scheduleDescriptor, e -> reconcile(), ExecutorsExt.namedSingleThreadExecutor(DefaultKubeJobManagementReconciler.class.getSimpleName()) ); } @Deactivator @PreDestroy public void shutdown() { Evaluators.acceptNotNull(schedulerRef, ScheduleReference::cancel); } @Override public Flux<PodEvent> getPodEventSource() { return podEventProcessor.transformDeferred(ReactorExt.badSubscriberHandler(logger)); } private void reconcile() { if (!kubernetesConfiguration.isReconcilerEnabled()) { logger.info("Skipping the job management / Kube reconciliation cycle: reconciler disabled"); return; } if (!kubeApiFacade.getNodeInformer().hasSynced() || !kubeApiFacade.getPodInformer().hasSynced()) { logger.info("Skipping the job management / Kube reconciliation cycle: Kube informers not ready (node={}, pod={})", kubeApiFacade.getNodeInformer().hasSynced(), kubeApiFacade.getPodInformer().hasSynced() ); return; } List<V1Node> nodes = kubeApiFacade.getNodeInformer().getIndexer().list() .stream() .filter(n -> StringExt.isNotEmpty(KubeUtil.getMetadataName(n.getMetadata()))) .collect(Collectors.toList()); List<V1Pod> pods = kubeApiFacade.getPodInformer().getIndexer().list() .stream() .filter(p -> StringExt.isNotEmpty(KubeUtil.getMetadataName(p.getMetadata()))) .collect(Collectors.toList()); List<Task> tasks = v3JobOperations.getTasks(); Map<String, V1Node> nodesById = nodes.stream().collect(Collectors.toMap( node -> KubeUtil.getMetadataName(node.getMetadata()), Function.identity() )); Map<String, Task> currentTasks = tasks.stream().collect(Collectors.toMap(Task::getId, Function.identity())); Set<String> currentPodNames = pods.stream().map(p -> KubeUtil.getMetadataName(p.getMetadata())).collect(Collectors.toSet()); transitionOrphanedTasks(currentTasks, currentPodNames, nodesById); } /** * Transition orphaned tasks to Finished that don't exist in Kubernetes. */ private void transitionOrphanedTasks(Map<String, Task> currentTasks, Set<String> currentPodNames, Map<String, V1Node> nodes) { List<Task> tasksNotInApiServer = currentTasks.values().stream() .filter(t -> shouldTaskBeInApiServer(t) && !currentPodNames.contains(t.getId())) .collect(Collectors.toList()); Map<OrphanedKind, List<Task>> orphanedTasksByKind = new HashMap<>(); for (Task task : tasksNotInApiServer) { if (task.getStatus().getState().equals(TaskState.KillInitiated)) { orphanedTasksByKind.computeIfAbsent(OrphanedKind.KILL_INITIATED, s -> new ArrayList<>()).add(task); } else { if (findNode(task, nodes).isPresent()) { orphanedTasksByKind.computeIfAbsent(OrphanedKind.UNKNOWN, s -> new ArrayList<>()).add(task); } else { orphanedTasksByKind.computeIfAbsent(OrphanedKind.NODE_TERMINATED, s -> new ArrayList<>()).add(task); } } } orphanedTasksByKind.forEach((kind, tasks) -> { logger.info("Attempting to transition {} orphaned tasks to finished ({}): {}", tasks.size(), kind, tasks); orphanedTaskGauges.get(kind).set(tasks.size()); for (Task task : tasks) { String reasonCode; String reasonMessage; switch (kind) { case KILL_INITIATED: reasonCode = TaskStatus.REASON_TASK_KILLED; reasonMessage = "Task killed"; break; case NODE_TERMINATED: reasonCode = TaskStatus.REASON_TASK_LOST; reasonMessage = "Terminated due to an issue with the underlying host machine"; break; case UNKNOWN: default: reasonCode = TaskStatus.REASON_TASK_LOST; reasonMessage = "Abandoned with unknown state due to lack of status updates from the host machine"; break; } publishEvent(task, TaskStatus.newBuilder() .withState(TaskState.Finished) .withReasonCode(reasonCode) .withReasonMessage(reasonMessage) .withTimestamp(clock.wallTime()) .build() ); } logger.info("Finished orphaned task transitions to finished ({})", kind); }); } private Optional<V1Node> findNode(Task task, Map<String, V1Node> nodes) { // Node name may be different from agent instance id. We use the instance id attribute only as a fallback. String nodeName = task.getTaskContext().getOrDefault( TaskAttributes.TASK_ATTRIBUTES_KUBE_NODE_NAME, task.getTaskContext().get(TaskAttributes.TASK_ATTRIBUTES_AGENT_INSTANCE_ID) ); if (nodeName == null) { return Optional.empty(); } return Optional.ofNullable(nodes.get(nodeName)); } private boolean shouldTaskBeInApiServer(Task task) { boolean isRunning = TaskState.isRunning(task.getStatus().getState()); if (isRunning) { return true; } if (task.getStatus().getState() == TaskState.Accepted && TaskStatus.hasPod(task)) { return clock.isPast(task.getStatus().getTimestamp() + kubernetesConfiguration.getOrphanedPodTimeoutMs()); } return false; } private void publishEvent(Task task, TaskStatus finalTaskStatus) { publishPodEvent(task, finalTaskStatus); } private void publishPodEvent(Task task, TaskStatus finalTaskStatus) { PodNotFoundEvent podEvent = PodEvent.onPodNotFound(task, finalTaskStatus); logger.debug("Publishing pod event: {}", podEvent); podEventSink.next(podEvent); } }
211
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/BaseGcController.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.controller; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import javax.annotation.PreDestroy; import javax.inject.Named; import com.netflix.spectator.api.Gauge; import com.netflix.titus.common.framework.scheduler.LocalScheduler; 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.limiter.Limiters; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import com.netflix.titus.master.MetricConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class BaseGcController<T> { private static final Logger logger = LoggerFactory.getLogger(BaseGcController.class); static final String GC_CONTROLLER = "gcController"; protected final String name; protected final String description; protected final TitusRuntime titusRuntime; protected final LocalScheduler scheduler; protected final FixedIntervalTokenBucketConfiguration tokenBucketConfiguration; protected final ControllerConfiguration controllerConfiguration; protected String metricRoot; protected ExecutorService executorService; protected ScheduleReference schedulerRef; protected TokenBucket tokenBucket; protected final Gauge skippedGauge; protected final Gauge successesGauge; protected final Gauge failuresGauge; public BaseGcController( String name, String description, @Named(GC_CONTROLLER) TitusRuntime titusRuntime, LocalScheduler scheduler, FixedIntervalTokenBucketConfiguration tokenBucketConfiguration, ControllerConfiguration controllerConfiguration ) { this.name = name; this.description = description; this.titusRuntime = titusRuntime; this.scheduler = scheduler; this.metricRoot = MetricConstants.METRIC_KUBERNETES_CONTROLLER + name; this.skippedGauge = titusRuntime.getRegistry().gauge(metricRoot, "type", "skipped"); this.successesGauge = titusRuntime.getRegistry().gauge(metricRoot, "type", "successes"); this.failuresGauge = titusRuntime.getRegistry().gauge(metricRoot, "type", "failures"); this.tokenBucketConfiguration = tokenBucketConfiguration; this.controllerConfiguration = controllerConfiguration; } @Activator public void enterActiveMode() { ScheduleDescriptor gcScheduleDescriptor = ScheduleDescriptor.newBuilder() .withName(name) .withDescription(description) .withInitialDelay(Duration.ofMillis(controllerConfiguration.getControllerInitialDelayMs())) .withInterval(Duration.ofMillis(controllerConfiguration.getControllerIntervalMs())) .withTimeout(Duration.ofMillis(controllerConfiguration.getControllerTimeoutMs())) .build(); executorService = ExecutorsExt.namedSingleThreadExecutor(name); schedulerRef = scheduler.schedule(gcScheduleDescriptor, e -> doGc(), executorService); tokenBucket = Limiters.createInstrumentedFixedIntervalTokenBucket( name + "TokenBucket", tokenBucketConfiguration, currentTokenBucket -> logger.info("Token bucket: {} configuration updated with: {}", name, currentTokenBucket), titusRuntime ); } @Deactivator @PreDestroy public void shutdown() { Evaluators.acceptNotNull(executorService, ExecutorService::shutdown); Evaluators.acceptNotNull(schedulerRef, ScheduleReference::cancel); resetGauges(); } public String getName() { return name; } public String getDescription() { return description; } public String getMetricRoot() { return metricRoot; } private void doGc() { if (!controllerConfiguration.isControllerEnabled() || !shouldGc()) { logger.info("Skipping gc execution for: {}", name); resetGauges(); return; } List<T> allItemsToGc = Collections.emptyList(); try { allItemsToGc = getItemsToGc(); } catch (Exception e) { logger.error("Unable to get items to GC due to:", e); } int total = allItemsToGc.size(); int limitedNumberOfItemsToGc = (int) Math.min(total, tokenBucket.getNumberOfTokens()); int skipped = total - limitedNumberOfItemsToGc; int successes = 0; int failures = 0; if (limitedNumberOfItemsToGc > 0 && tokenBucket.tryTake(limitedNumberOfItemsToGc)) { List<T> itemsToGc = allItemsToGc.subList(0, limitedNumberOfItemsToGc); logger.debug("Attempting to GC: {}", itemsToGc); for (T item : itemsToGc) { try { if (gcItem(item)) { successes++; } else { failures++; } } catch (Exception e) { failures++; logger.error("Unable to GC: {} due to:", item, e); } } } setGauges(skipped, successes, failures); logger.info("Finished GC iteration total:{}, skipped: {}, successes: {}, failures: {}", total, skipped, successes, failures); } public abstract boolean shouldGc(); public abstract List<T> getItemsToGc(); public abstract boolean gcItem(T item); private void setGauges(int skipped, int successes, int failures) { skippedGauge.set(skipped); successesGauge.set(successes); failuresGauge.set(failures); } private void resetGauges() { setGauges(0, 0, 0); } }
212
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/KubeControllerModule.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.controller; import java.time.Duration; import javax.inject.Named; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.common.framework.scheduler.LocalScheduler; import com.netflix.titus.common.framework.scheduler.internal.DefaultLocalScheduler; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.limiter.tokenbucket.FixedIntervalTokenBucketConfiguration; import reactor.core.scheduler.Schedulers; import static com.netflix.titus.master.kubernetes.controller.BaseGcController.GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.DefaultKubeJobManagementReconciler.GC_UNKNOWN_PODS; import static com.netflix.titus.master.kubernetes.controller.PersistentVolumeClaimGcController.PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PersistentVolumeReclaimController.PERSISTENT_VOLUME_RECLAIM_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PersistentVolumeUnassociatedGcController.PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PodDeletionGcController.POD_DELETION_GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PodOnUnknownNodeGcController.POD_ON_UNKNOWN_NODE_GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PodTerminalGcController.POD_TERMINAL_GC_CONTROLLER; import static com.netflix.titus.master.kubernetes.controller.PodUnknownGcController.POD_UNKNOWN_GC_CONTROLLER; public class KubeControllerModule extends AbstractModule { @Override protected void configure() { bind(KubeJobManagementReconciler.class).to(DefaultKubeJobManagementReconciler.class); bind(PodOnUnknownNodeGcController.class).asEagerSingleton(); bind(PodDeletionGcController.class).asEagerSingleton(); bind(PodTerminalGcController.class).asEagerSingleton(); bind(PodUnknownGcController.class).asEagerSingleton(); bind(PersistentVolumeUnassociatedGcController.class).asEagerSingleton(); bind(PersistentVolumeClaimGcController.class).asEagerSingleton(); bind(PersistentVolumeReclaimController.class).asEagerSingleton(); } @Provides @Singleton @Named(GC_CONTROLLER) public LocalScheduler getLocalScheduler(TitusRuntime titusRuntime) { return new DefaultLocalScheduler(Duration.ofMillis(100), Schedulers.elastic(), titusRuntime.getClock(), titusRuntime.getRegistry()); } @Provides @Singleton public KubeControllerConfiguration getKubeControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(KubeControllerConfiguration.class); } @Provides @Singleton @Named(GC_UNKNOWN_PODS) public FixedIntervalTokenBucketConfiguration getGcUnknownPodsTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titusMaster.kube.gcUnknownPodsTokenBucket"); } @Provides @Singleton @Named(POD_ON_UNKNOWN_NODE_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPodOnUnknownNodeGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + POD_ON_UNKNOWN_NODE_GC_CONTROLLER); } @Provides @Singleton @Named(POD_ON_UNKNOWN_NODE_GC_CONTROLLER) public ControllerConfiguration getPodOnUnknownNodeGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + POD_ON_UNKNOWN_NODE_GC_CONTROLLER); } @Provides @Singleton @Named(POD_DELETION_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPodDeletionGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + POD_DELETION_GC_CONTROLLER); } @Provides @Singleton @Named(POD_DELETION_GC_CONTROLLER) public ControllerConfiguration getPodDeletionGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + POD_DELETION_GC_CONTROLLER); } @Provides @Singleton @Named(POD_TERMINAL_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPodTerminalGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + POD_TERMINAL_GC_CONTROLLER); } @Provides @Singleton @Named(POD_TERMINAL_GC_CONTROLLER) public ControllerConfiguration getPodTerminalGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + POD_TERMINAL_GC_CONTROLLER); } @Provides @Singleton @Named(POD_UNKNOWN_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPodUnknownGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + POD_UNKNOWN_GC_CONTROLLER); } @Provides @Singleton @Named(POD_UNKNOWN_GC_CONTROLLER) public ControllerConfiguration getPodUnknownGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + POD_UNKNOWN_GC_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPersistentVolumeUnassociatedGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER) public ControllerConfiguration getPersistentVolumeUnassociatedGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_UNASSOCIATED_GC_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPersistentVolumeClaimGcControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER) public ControllerConfiguration getPersistentVolumeClaimGcControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_CLAIM_GC_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_RECLAIM_CONTROLLER) public FixedIntervalTokenBucketConfiguration getPersistentVolumeReclaimControllerTokenBucketConfiguration(ConfigProxyFactory factory) { return factory.newProxy(FixedIntervalTokenBucketConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_RECLAIM_CONTROLLER); } @Provides @Singleton @Named(PERSISTENT_VOLUME_RECLAIM_CONTROLLER) public ControllerConfiguration getPersistentVolumeReclaimControllerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(ControllerConfiguration.class, "titus.kubernetes.controller." + PERSISTENT_VOLUME_RECLAIM_CONTROLLER); } }
213
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/client/DirectKubeConfiguration.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.client; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; import com.netflix.titus.runtime.connector.kubernetes.KubeConnectorConfiguration; @Configuration(prefix = "titusMaster.directKube") public interface DirectKubeConfiguration extends KubeConnectorConfiguration { /** * Thread pool size for handling Kube apiClient calls. */ @DefaultValue("20") int getApiClientThreadPoolSize(); @DefaultValue("5000") long getKubeApiClientTimeoutMs(); @DefaultValue("true") boolean isAsyncApiEnabled(); /** * Regular expression to match pod create errors for rejected pods. */ @DefaultValue(".*") String getInvalidPodMessagePattern(); /** * Regular expression to match pod create errors there are recoverable. */ @DefaultValue("NONE") String getTransientSystemErrorMessagePattern(); /** * Amount of grace period to set when deleting a namespace pod. */ @DefaultValue("300") int getDeleteGracePeriodSeconds(); /** * Maximum number of concurrent pod create requests. */ @DefaultValue("200") int getPodCreateConcurrencyLimit(); }
214
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/client/FitSharedIndexInformer.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.client; import java.util.List; import java.util.Map; import java.util.function.Function; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.kubernetes.client.DirectKubeApiServerIntegrator; import com.netflix.titus.master.kubernetes.client.KubeFitAction; import io.kubernetes.client.common.KubernetesObject; import io.kubernetes.client.informer.ResourceEventHandler; import io.kubernetes.client.informer.SharedIndexInformer; import io.kubernetes.client.informer.cache.Indexer; public class FitSharedIndexInformer<T extends KubernetesObject> implements SharedIndexInformer<T> { private final SharedIndexInformer<T> source; private final FitInjection fitKubeInjection; public FitSharedIndexInformer(String id, SharedIndexInformer<T> source, TitusRuntime titusRuntime) { this.source = source; FitFramework fit = titusRuntime.getFitFramework(); this.fitKubeInjection = fit.newFitInjectionBuilder(id) .withDescription("SharedIndexInformer FIT injection for " + id) .build(); fit.getRootComponent().getChild(DirectKubeApiServerIntegrator.COMPONENT).addInjection(fitKubeInjection); } @Override public void addIndexers(Map<String, Function<T, List<String>>> indexers) { source.addIndexers(indexers); } @Override public Indexer<T> getIndexer() { return source.getIndexer(); } @Override public void addEventHandler(ResourceEventHandler<T> handler) { source.addEventHandler(handler); } @Override public void addEventHandlerWithResyncPeriod(ResourceEventHandler<T> handler, long resyncPeriod) { source.addEventHandlerWithResyncPeriod(handler, resyncPeriod); } @Override public void run() { source.run(); } @Override public void stop() { source.stop(); } @Override public boolean hasSynced() { try { fitKubeInjection.beforeImmediate(KubeFitAction.ErrorKind.INFORMER_NOT_SYNCED.name()); } catch (Exception e) { return false; } return source.hasSynced(); } @Override public String lastSyncResourceVersion() { return source.lastSyncResourceVersion(); } }
215
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/client/KubeClientModule.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.client; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.jobmanager.service.ComputeProvider; import com.netflix.titus.master.kubernetes.KubernetesConfiguration; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiClients; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.openapi.ApiClient; public class KubeClientModule extends AbstractModule { public static final String CLIENT_METRICS_PREFIX = "titusMaster.kubernetes.kubeApiServerIntegration"; @Override protected void configure() { bind(DirectKubeApiServerIntegrator.class).to(DefaultDirectKubeApiServerIntegrator.class); bind(StdKubeApiFacade.class).to(JobControllerStdKubeApiFacadeDefault.class); } @Provides @Singleton public DirectKubeConfiguration getDirectKubeConfiguration(ConfigProxyFactory factory) { return factory.newProxy(DirectKubeConfiguration.class); } @Provides @Singleton public ApiClient getKubeApiClient(KubernetesConfiguration configuration, TitusRuntime titusRuntime) { return StdKubeApiClients.createApiClient( configuration.getKubeApiServerUrl(), configuration.getKubeConfigPath(), CLIENT_METRICS_PREFIX, titusRuntime, 0L, configuration.isCompressionEnabledForKubeApiClient() ); } @Provides @Singleton public ComputeProvider getComputeProvider(DirectKubeApiServerIntegrator integrator) { return integrator; } }
216
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/client/KubeModelConverters.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.client; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import com.netflix.titus.api.jobmanager.model.job.ebs.EbsVolume; import com.netflix.titus.master.kubernetes.KubeUtil; import io.kubernetes.client.custom.Quantity; import io.kubernetes.client.openapi.models.V1CSIPersistentVolumeSource; import io.kubernetes.client.openapi.models.V1LabelSelector; import io.kubernetes.client.openapi.models.V1ObjectMeta; 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.V1PersistentVolumeSpec; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.openapi.models.V1ResourceRequirements; import static com.netflix.titus.common.util.StringExt.splitByDot; /** * A collection of helper functions to convert core and Kube objects to other Kube model objects. */ public class KubeModelConverters { public static final String KUBE_VOLUME_CSI_EBS_DRIVER = "ebs.csi.aws.com"; public static final String KUBE_VOLUME_CSI_EBS_VOLUME_KEY = "volumeHandle"; private static final String KUBE_VOLUME_API_VERSION = "v1"; private static final String KUBE_VOLUME_ACCESS_MODE = "ReadWriteOnce"; private static final String KUBE_VOLUME_VOLUME_MODE_FS = "Filesystem"; private static final String KUBE_VOLUME_RECLAIM_POLICY = "Retain"; private static final String KUBE_VOLUME_CAPACITY_KEY = "storage"; public static Map<String, String> toVolumeLabelMap(String volumeName) { return Collections.singletonMap(KUBE_VOLUME_CSI_EBS_VOLUME_KEY, volumeName); } public static V1LabelSelector toVolumeMatchSelector(String volumeName) { return new V1LabelSelector() .matchLabels(toVolumeLabelMap(volumeName)); } public static V1PersistentVolume toEbsV1PersistentVolume(EbsVolume ebsVolume) { V1ObjectMeta v1ObjectMeta = new V1ObjectMeta() .labels(toVolumeLabelMap(ebsVolume.getVolumeId())) .name(ebsVolume.getVolumeId()); V1PersistentVolumeSpec v1PersistentVolumeSpec = new V1PersistentVolumeSpec() .addAccessModesItem(KUBE_VOLUME_ACCESS_MODE) .volumeMode(KUBE_VOLUME_VOLUME_MODE_FS) .persistentVolumeReclaimPolicy(KUBE_VOLUME_RECLAIM_POLICY) .putCapacityItem(KUBE_VOLUME_CAPACITY_KEY, new Quantity(volumeCapacityGiBToString(ebsVolume.getVolumeCapacityGB()))) .csi(new V1CSIPersistentVolumeSource() .driver(KUBE_VOLUME_CSI_EBS_DRIVER) .volumeHandle(ebsVolume.getVolumeId()) .fsType(ebsVolume.getFsType())); return new V1PersistentVolume() .apiVersion(KUBE_VOLUME_API_VERSION) .metadata(v1ObjectMeta) .spec(v1PersistentVolumeSpec); } public static V1PersistentVolumeClaim toV1PersistentVolumeClaim(V1PersistentVolume v1PersistentVolume, V1Pod v1Pod) { String volumeName = Optional.ofNullable(v1PersistentVolume.getSpec().getCsi()) .orElseThrow(() -> new IllegalStateException(String.format("Expected CSI persistent volume for %s", v1PersistentVolume))) .getVolumeHandle(); // The claim name should be specific to this volume and task V1ObjectMeta v1ObjectMeta = new V1ObjectMeta() .name(KubeModelConverters.toPvcName(KubeUtil.getMetadataName(v1PersistentVolume.getMetadata()), KubeUtil.getMetadataName(v1Pod.getMetadata()))); // The claim spec should be scoped to this specific volume V1PersistentVolumeClaimSpec v1PersistentVolumeClaimSpec = new V1PersistentVolumeClaimSpec() .volumeName(volumeName) .addAccessModesItem(KUBE_VOLUME_ACCESS_MODE) .volumeMode(KUBE_VOLUME_VOLUME_MODE_FS) .resources(new V1ResourceRequirements().requests(v1PersistentVolume.getSpec().getCapacity())) .selector(KubeModelConverters.toVolumeMatchSelector(volumeName)); return new V1PersistentVolumeClaim() .apiVersion(KUBE_VOLUME_API_VERSION) .metadata(v1ObjectMeta) .spec(v1PersistentVolumeClaimSpec); } public static String toPvcName(String volumeName, String taskId) { // Combine PV and task ID to create a unique PVC name return volumeName + "." + taskId; } public static String getTaskIdFromPvc(V1PersistentVolumeClaim v1PersistentVolumeClaim) { // We expect the volume ID to precede task ID and to be separated via a '.' List<String> parts = splitByDot(KubeUtil.getMetadataName(v1PersistentVolumeClaim.getMetadata())); return parts.size() < 2 ? "" : parts.get(1); } private static String volumeCapacityGiBToString(int capacityGiB) { return String.format("%dGi", capacityGiB); } }
217
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/client/DefaultDirectKubeApiServerIntegrator.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.client; import java.time.Duration; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.base.Stopwatch; import com.google.gson.JsonSyntaxException; 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.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.master.kubernetes.KubeUtil; import com.netflix.titus.master.kubernetes.client.model.PodDeletedEvent; import com.netflix.titus.master.kubernetes.client.model.PodEvent; import com.netflix.titus.master.kubernetes.client.model.PodUpdatedEvent; import com.netflix.titus.master.kubernetes.pod.PodFactory; import com.netflix.titus.runtime.connector.kubernetes.KubeApiException; import com.netflix.titus.runtime.connector.kubernetes.std.StdKubeApiFacade; import io.kubernetes.client.informer.ResourceEventHandler; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import static com.netflix.titus.master.kubernetes.KubeObjectFormatter.formatPodEssentials; @Singleton public class DefaultDirectKubeApiServerIntegrator implements DirectKubeApiServerIntegrator { private static final Logger logger = LoggerFactory.getLogger(DefaultDirectKubeApiServerIntegrator.class); private static final String KUBERNETES_NAMESPACE = "default"; private final DirectKubeConfiguration configuration; private final StdKubeApiFacade kubeApiFacade; private final PodFactory podFactory; private final DefaultDirectKubeApiServerIntegratorMetrics metrics; private final PodCreateErrorToResultCodeResolver podCreateErrorToReasonCodeResolver; private final TitusRuntime titusRuntime; private final DirectProcessor<PodEvent> supplementaryPodEventProcessor = DirectProcessor.create(); /** * We use {@link FluxSink.OverflowStrategy#LATEST} with the assumption that the supplementary events created here, will * be re-crated later if needed (like pod not found event). */ private final FluxSink<PodEvent> supplementaryPodEventSink = supplementaryPodEventProcessor.sink(FluxSink.OverflowStrategy.LATEST); private final ConcurrentMap<String, V1Pod> pods = new ConcurrentHashMap<>(); private final ExecutorService apiClientExecutor; private final Scheduler apiClientScheduler; private final Optional<FitInjection> fitKubeInjection; @Inject public DefaultDirectKubeApiServerIntegrator(DirectKubeConfiguration configuration, StdKubeApiFacade kubeApiFacade, PodFactory podFactory, TitusRuntime titusRuntime) { this.configuration = configuration; this.kubeApiFacade = kubeApiFacade; this.podFactory = podFactory; this.podCreateErrorToReasonCodeResolver = new PodCreateErrorToResultCodeResolver(configuration); this.titusRuntime = titusRuntime; this.metrics = new DefaultDirectKubeApiServerIntegratorMetrics(titusRuntime); metrics.observePodsCollection(pods); this.apiClientExecutor = ExecutorsExt.instrumentedFixedSizeThreadPool(titusRuntime.getRegistry(), "kube-apiclient", configuration.getApiClientThreadPoolSize()); this.apiClientScheduler = Schedulers.fromExecutorService(apiClientExecutor); FitFramework fit = titusRuntime.getFitFramework(); if (fit.isActive()) { FitInjection fitKubeInjection = fit.newFitInjectionBuilder("directKubeIntegration") .withDescription("DefaultDirectKubeApiServerIntegrator injection") .build(); fit.getRootComponent().getChild(DirectKubeApiServerIntegrator.COMPONENT).addInjection(fitKubeInjection); this.fitKubeInjection = Optional.of(fitKubeInjection); } else { this.fitKubeInjection = Optional.empty(); } } @PreDestroy public void shutdown() { apiClientScheduler.dispose(); apiClientExecutor.shutdown(); metrics.shutdown(); } @Override public Optional<V1Pod> findPod(String taskId) { return Optional.ofNullable(pods.get(taskId)); } @Override public boolean isReadyForScheduling() { return kubeApiFacade.isReadyForScheduling(); } @Override public Mono<Void> launchTask(Job job, Task task) { return Mono.fromCallable(() -> { try { V1Pod v1Pod = podFactory.buildV1Pod(job, task); logger.info("creating pod: {}", formatPodEssentials(v1Pod)); logger.debug("complete pod data: {}", v1Pod); return v1Pod; } catch (Exception e) { logger.error("Unable to convert job {} and task {} to pod: {}", job, task, KubeUtil.toErrorDetails(e), e); throw new IllegalStateException("Unable to convert task to pod " + task.getId(), e); } }) .flatMap(v1Pod -> launchPod(task, v1Pod)) .subscribeOn(apiClientScheduler) .timeout(Duration.ofMillis(configuration.getKubeApiClientTimeoutMs())) .doOnError(TimeoutException.class, e -> metrics.launchTimeout(configuration.getKubeApiClientTimeoutMs())) .ignoreElement() .cast(Void.class); } @Override public Mono<Void> terminateTask(Task task) { String taskId = task.getId(); return Mono.<Void>fromRunnable(() -> { Stopwatch timer = Stopwatch.createStarted(); try { logger.info("Deleting pod: {}", taskId); kubeApiFacade.deleteNamespacedPod(KUBERNETES_NAMESPACE, taskId, configuration.getDeleteGracePeriodSeconds()); metrics.terminateSuccess(task, timer.elapsed(TimeUnit.MILLISECONDS)); } catch (JsonSyntaxException e) { // this is probably successful. the generated client has the wrong response type metrics.terminateSuccess(task, timer.elapsed(TimeUnit.MILLISECONDS)); } catch (KubeApiException e) { metrics.terminateError(task, e, timer.elapsed(TimeUnit.MILLISECONDS)); if (e.getErrorCode() == KubeApiException.ErrorCode.NOT_FOUND && task.getStatus().getState() == TaskState.Accepted) { sendEvent(PodEvent.onPodNotFound(task, TaskStatus.newBuilder() .withState(TaskState.Finished) .withReasonCode(TaskStatus.REASON_TASK_LOST) .withReasonMessage("Task terminate requested, but its container is not found") .withTimestamp(titusRuntime.getClock().wallTime()) .build() )); } else { logger.error("Failed to kill task: {} with error: {}", taskId, KubeUtil.toErrorDetails(e), e); } } catch (Exception e) { logger.error("Failed to kill task: {} with error: {}", taskId, KubeUtil.toErrorDetails(e), e); metrics.terminateError(task, e, timer.elapsed(TimeUnit.MILLISECONDS)); } }).subscribeOn(apiClientScheduler).timeout(Duration.ofMillis(configuration.getKubeApiClientTimeoutMs())); } @Override public Flux<PodEvent> events() { return kubeInformerEvents().mergeWith(supplementaryPodEventProcessor).transformDeferred(ReactorExt.badSubscriberHandler(logger)); } @Override public String resolveReasonCode(Throwable cause) { return podCreateErrorToReasonCodeResolver.resolveReasonCode(cause); } private Mono<V1Pod> launchPod(Task task, V1Pod v1Pod) { return Mono.fromCallable(() -> { Stopwatch timer = Stopwatch.createStarted(); try { fitKubeInjection.ifPresent(i -> i.beforeImmediate(KubeFitAction.ErrorKind.POD_CREATE_ERROR.name())); kubeApiFacade.createNamespacedPod(KUBERNETES_NAMESPACE, v1Pod); pods.putIfAbsent(task.getId(), v1Pod); metrics.launchSuccess(task, v1Pod, timer.elapsed(TimeUnit.MILLISECONDS)); return v1Pod; } catch (Exception e) { logger.error("Unable to create pod with error: {}", KubeUtil.toErrorDetails(e), e); metrics.launchError(task, e, timer.elapsed(TimeUnit.MILLISECONDS)); throw new IllegalStateException("Unable to launch a task " + task.getId(), e); } }); } private Flux<PodEvent> kubeInformerEvents() { return Flux.create(sink -> { ResourceEventHandler<V1Pod> handler = new ResourceEventHandler<V1Pod>() { @Override public void onAdd(V1Pod pod) { Stopwatch stopwatch = Stopwatch.createStarted(); String taskId = pod.getMetadata().getName(); try { if (!KubeUtil.isOwnedByKubeScheduler(pod)) { return; } V1Pod old = pods.get(taskId); pods.put(taskId, pod); PodEvent podEvent; if (old != null) { podEvent = PodEvent.onUpdate(old, pod, findNode(pod)); metrics.onUpdate(pod); } else { podEvent = PodEvent.onAdd(pod); metrics.onAdd(pod); } sink.next(podEvent); logger.info("Pod Added: pod={}, sequenceNumber={}", formatPodEssentials(pod), podEvent.getSequenceNumber()); logger.debug("complete pod data: {}", pod); } finally { logger.debug("Pod informer onAdd: pod={}, elapsedMs={}", taskId, stopwatch.elapsed().toMillis()); } } @Override public void onUpdate(V1Pod oldPod, V1Pod newPod) { Stopwatch stopwatch = Stopwatch.createStarted(); String taskId = newPod.getMetadata().getName(); try { if (!KubeUtil.isOwnedByKubeScheduler(newPod)) { return; } metrics.onUpdate(newPod); pods.put(taskId, newPod); PodUpdatedEvent podEvent = PodEvent.onUpdate(oldPod, newPod, findNode(newPod)); sink.next(podEvent); logger.info("Pod Updated: old={}, new={}, sequenceNumber={}", formatPodEssentials(oldPod), formatPodEssentials(newPod), podEvent.getSequenceNumber()); logger.debug("Complete pod data: old={}, new={}", oldPod, newPod); } finally { logger.debug("Pod informer onUpdate: pod={}, elapsedMs={}", taskId, stopwatch.elapsed().toMillis()); } } @Override public void onDelete(V1Pod pod, boolean deletedFinalStateUnknown) { Stopwatch stopwatch = Stopwatch.createStarted(); String taskId = pod.getMetadata().getName(); try { if (!KubeUtil.isOwnedByKubeScheduler(pod)) { return; } metrics.onDelete(pod); pods.remove(taskId); PodDeletedEvent podEvent = PodEvent.onDelete(pod, deletedFinalStateUnknown, findNode(pod)); sink.next(podEvent); logger.info("Pod Deleted: {}, deletedFinalStateUnknown={}, sequenceNumber={}", formatPodEssentials(pod), deletedFinalStateUnknown, podEvent.getSequenceNumber()); logger.debug("complete pod data: {}", pod); } finally { logger.debug("Pod informer onDelete: pod={}, elapsedMs={}", taskId, stopwatch.elapsed().toMillis()); } } }; kubeApiFacade.getPodInformer().addEventHandler(handler); // A listener cannot be removed from shared informer. // sink.onCancel(() -> ???); }); } private void sendEvent(PodEvent podEvent) { supplementaryPodEventSink.next(podEvent); } private Optional<V1Node> findNode(V1Pod pod) { String nodeName = pod.getSpec().getNodeName(); if (StringExt.isEmpty(nodeName)) { return Optional.empty(); } return Optional.ofNullable(kubeApiFacade.getNodeInformer().getIndexer().getByKey(nodeName)); } private static boolean isEbsVolumeConflictException(KubeApiException apiException) { return apiException.getErrorCode() == KubeApiException.ErrorCode.CONFLICT_ALREADY_EXISTS; } }
218
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/client/JobControllerStdKubeApiFacadeDefault.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.client; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.runtime.connector.kubernetes.std.DefaultStdStdKubeApiFacade; import io.kubernetes.client.common.KubernetesObject; import io.kubernetes.client.informer.SharedIndexInformer; import io.kubernetes.client.openapi.ApiClient; @Singleton public class JobControllerStdKubeApiFacadeDefault extends DefaultStdStdKubeApiFacade { private final TitusRuntime titusRuntime; @Inject public JobControllerStdKubeApiFacadeDefault(DirectKubeConfiguration configuration, ApiClient apiClient, TitusRuntime titusRuntime) { super(configuration, apiClient, titusRuntime); this.titusRuntime = titusRuntime; } @Override protected <T extends KubernetesObject> SharedIndexInformer<T> customizeInformer(String name, SharedIndexInformer<T> informer) { return titusRuntime.getFitFramework().isActive() ? new FitSharedIndexInformer<>(name, informer, titusRuntime) : informer; } }
219
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/client/KubeFitAction.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.client; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import com.google.common.base.Preconditions; import com.netflix.titus.common.framework.fit.AbstractFitAction; import com.netflix.titus.common.framework.fit.FitActionDescriptor; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.framework.fit.FitUtil; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; public class KubeFitAction extends AbstractFitAction { public static final FitActionDescriptor DESCRIPTOR = new FitActionDescriptor( "kubeIntegration", "Inject failures in Kube integration", CollectionsExt.copyAndAdd( FitUtil.PERIOD_ERROR_PROPERTIES, "errorKinds", "A list of: " + StringExt.concatenate(ErrorKind.values(), ",") ) ); private final Set<ErrorKind> failurePoints; private final Supplier<Boolean> shouldFailFunction; public KubeFitAction(String id, Map<String, String> properties, FitInjection injection) { super(id, DESCRIPTOR, properties, injection); String errorKindsValue = properties.get("errorKinds"); Preconditions.checkArgument(errorKindsValue != null, "Missing 'errorKinds' property"); this.failurePoints = new HashSet<>(StringExt.parseEnumListIgnoreCase(errorKindsValue, ErrorKind.class)); this.shouldFailFunction = FitUtil.periodicErrors(properties); } public enum ErrorKind { /** * Do not call KubeAPI, just fail the pod create request immediately. */ POD_CREATE_ERROR, /** * Report an informer data to be stale. */ INFORMER_NOT_SYNCED, } @Override public void beforeImmediate(String injectionPoint) { ErrorKind errorKind = ErrorKind.valueOf(injectionPoint); if (shouldFailFunction.get() && failurePoints.contains(errorKind)) { switch (errorKind) { case POD_CREATE_ERROR: throw new IllegalStateException("Simulating pod create error"); case INFORMER_NOT_SYNCED: throw new IllegalStateException("Simulating informer data staleness"); } } } }
220
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/client/DirectKubeApiServerIntegrator.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.client; import java.util.Optional; import com.netflix.titus.master.jobmanager.service.ComputeProvider; import com.netflix.titus.master.kubernetes.client.model.PodEvent; import io.kubernetes.client.openapi.models.V1Pod; import reactor.core.publisher.Flux; public interface DirectKubeApiServerIntegrator extends ComputeProvider { String COMPONENT = "kubernetesIntegrator"; Optional<V1Pod> findPod(String taskId); Flux<PodEvent> events(); }
221
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/client/DefaultDirectKubeApiServerIntegratorMetrics.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.client; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.histogram.BucketCounter; import com.netflix.spectator.api.histogram.BucketFunctions; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.MetricConstants; import com.netflix.titus.master.kubernetes.KubeUtil; import io.kubernetes.client.openapi.models.V1Pod; /** * Metrics companion class for {@link DefaultDirectKubeApiServerIntegrator}. */ class DefaultDirectKubeApiServerIntegratorMetrics { private static final String ROOT = MetricConstants.METRIC_KUBERNETES + "directKubeApiServerIntegrator."; private static final String PV_ROOT = ROOT + "persistentVolume."; private static final String PVC_ROOT = ROOT + "persistentVolumeClaim."; private final Registry registry; private final Id podGaugeId; private final Id launchCounterId; private final Id terminateCounterId; private final Id eventCounterId; private final Id persistentVolumeCreateCounterId; private final Id persistentVolumeClaimCreateCounterId; private final BucketCounter podSizeMetrics; DefaultDirectKubeApiServerIntegratorMetrics(TitusRuntime titusRuntime) { this.registry = titusRuntime.getRegistry(); this.podGaugeId = registry.createId(ROOT + "pods"); this.launchCounterId = registry.createId(ROOT + "launches"); this.terminateCounterId = registry.createId(ROOT + "terminates"); this.eventCounterId = registry.createId(ROOT + "events"); this.persistentVolumeCreateCounterId = registry.createId(PV_ROOT + "create"); this.persistentVolumeClaimCreateCounterId = registry.createId(PVC_ROOT + "create"); this.podSizeMetrics = BucketCounter.get( registry, registry.createId(ROOT + "podSize"), BucketFunctions.bytes(32768) ); } void shutdown() { PolledMeter.remove(registry, podGaugeId); } void observePodsCollection(ConcurrentMap<String, V1Pod> pods) { PolledMeter.using(registry).withId(podGaugeId).monitorSize(pods); } void persistentVolumeCreateSuccess(long elapsedMs) { registry.timer(persistentVolumeCreateCounterId.withTag("status", "success")).record(elapsedMs, TimeUnit.MILLISECONDS); } void persistentVolumeCreateError(Throwable error, long elapsedMs) { registry.timer(persistentVolumeCreateCounterId.withTags( "status", "error", "error", error.getClass().getSimpleName() )).record(elapsedMs, TimeUnit.MILLISECONDS); } void persistentVolumeClaimCreateSuccess(long elapsedMs) { registry.timer(persistentVolumeClaimCreateCounterId.withTag("status", "success")).record(elapsedMs, TimeUnit.MILLISECONDS); } void persistentVolumeClaimCreateError(Throwable error, long elapsedMs) { registry.timer(persistentVolumeClaimCreateCounterId.withTags( "status", "error", "error", error.getClass().getSimpleName() )).record(elapsedMs, TimeUnit.MILLISECONDS); } void launchSuccess(Task task, V1Pod v1Pod, long elapsedMs) { podSizeMetrics.record(KubeUtil.estimatePodSize(v1Pod)); registry.timer(launchCounterId.withTag("status", "success")).record(elapsedMs, TimeUnit.MILLISECONDS); } void launchError(Task task, Throwable error, long elapsedMs) { registry.timer(launchCounterId.withTags( "status", "error", "error", error.getClass().getSimpleName() )).record(elapsedMs, TimeUnit.MILLISECONDS); } void launchTimeout(long elapsedMs) { registry.timer(launchCounterId.withTag("status", "timeout")).record(elapsedMs, TimeUnit.MILLISECONDS); } void terminateSuccess(Task task, long elapsedMs) { registry.timer(terminateCounterId.withTag("status", "success")).record(elapsedMs, TimeUnit.MILLISECONDS); } void terminateError(Task task, Throwable error, long elapsedMs) { registry.timer(terminateCounterId.withTags( "status", "error", "error", error.getClass().getSimpleName() )).record(elapsedMs, TimeUnit.MILLISECONDS); } void onAdd(V1Pod pod) { registry.counter(eventCounterId.withTags( "kind", "add" )).increment(); } void onUpdate(V1Pod pod) { registry.counter(eventCounterId.withTags( "kind", "update" )).increment(); } void onDelete(V1Pod pod) { registry.counter(eventCounterId.withTags( "kind", "delete" )).increment(); } }
222
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/client/PodCreateErrorToResultCodeResolver.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.client; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.common.util.RegExpExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class PodCreateErrorToResultCodeResolver { private static final Logger logger = LoggerFactory.getLogger(PodCreateErrorToResultCodeResolver.class); private final Function<String, Matcher> invalidPodMatcherFactory; private final Function<String, Matcher> transientSystemErrorMatcherFactory; PodCreateErrorToResultCodeResolver(DirectKubeConfiguration configuration) { this.invalidPodMatcherFactory = RegExpExt.dynamicMatcher(configuration::getInvalidPodMessagePattern, "invalidPodMessagePattern", Pattern.DOTALL, logger); this.transientSystemErrorMatcherFactory = RegExpExt.dynamicMatcher(configuration::getTransientSystemErrorMessagePattern, "transientSystemErrorMessagePattern", Pattern.DOTALL, logger); } String resolveReasonCode(Throwable cause) { try { if (cause.getMessage() != null) { return resolveReasonCodeFromMessage(cause.getMessage()); } return TaskStatus.REASON_UNKNOWN_SYSTEM_ERROR; } catch (Exception e) { return TaskStatus.REASON_UNKNOWN_SYSTEM_ERROR; } } private String resolveReasonCodeFromMessage(String message) { if (invalidPodMatcherFactory.apply(message).matches()) { return TaskStatus.REASON_INVALID_REQUEST; } if (transientSystemErrorMatcherFactory.apply(message).matches()) { return TaskStatus.REASON_TRANSIENT_SYSTEM_ERROR; } return TaskStatus.REASON_UNKNOWN_SYSTEM_ERROR; } }
223
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodDeletedEvent.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.client.model; import java.util.Objects; import java.util.Optional; import com.netflix.titus.master.kubernetes.KubeObjectFormatter; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; public class PodDeletedEvent extends PodEvent { private final boolean deletedFinalStateUnknown; private final Optional<V1Node> node; PodDeletedEvent(V1Pod pod, boolean deletedFinalStateUnknown, Optional<V1Node> node) { super(pod); this.deletedFinalStateUnknown = deletedFinalStateUnknown; this.node = node; } public boolean isDeletedFinalStateUnknown() { return deletedFinalStateUnknown; } public Optional<V1Node> getNode() { return node; } @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; } PodDeletedEvent that = (PodDeletedEvent) o; return deletedFinalStateUnknown == that.deletedFinalStateUnknown && Objects.equals(node, that.node); } @Override public int hashCode() { return Objects.hash(super.hashCode(), deletedFinalStateUnknown, node); } @Override public String toString() { return "PodDeletedEvent{" + "taskId='" + taskId + '\'' + ", sequenceNumber=" + sequenceNumber + ", pod=" + KubeObjectFormatter.formatPodEssentials(pod) + ", deletedFinalStateUnknown=" + deletedFinalStateUnknown + ", node=" + node.map(n -> n.getMetadata().getName()).orElse("<not_assigned>") + '}'; } }
224
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodNotFoundEvent.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.client.model; import java.util.Objects; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; public class PodNotFoundEvent extends PodEvent { private final Task task; private final TaskStatus finalTaskStatus; PodNotFoundEvent(Task task, TaskStatus finalTaskStatus) { super(new V1Pod().metadata(new V1ObjectMeta().name(task.getId()))); this.task = task; this.finalTaskStatus = finalTaskStatus; } public Task getTask() { return task; } public TaskStatus getFinalTaskStatus() { return finalTaskStatus; } @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; } PodNotFoundEvent that = (PodNotFoundEvent) o; return Objects.equals(task, that.task) && Objects.equals(finalTaskStatus, that.finalTaskStatus); } @Override public int hashCode() { return Objects.hash(super.hashCode(), task, finalTaskStatus); } @Override public String toString() { return "PodNotFoundEvent{" + "taskId=" + task.getId() + ", sequenceNumber=" + sequenceNumber + ", finalTaskStatus=" + finalTaskStatus + '}'; } }
225
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodPhase.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.client.model; import com.netflix.titus.common.util.ExceptionExt; import com.netflix.titus.common.util.StringExt; public enum PodPhase { PENDING("Pending"), RUNNING("Running"), SUCCEEDED("Succeeded"), FAILED("Failed"), UNKNOWN("Unknown"); private final String phaseName; PodPhase(String phaseName) { this.phaseName = phaseName; } public String getPhaseName() { return phaseName; } public static PodPhase parse(String phaseName) { return ExceptionExt.doTry(() -> StringExt.parseEnumIgnoreCase(phaseName, PodPhase.class)).orElse(UNKNOWN); } }
226
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodUpdatedEvent.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.client.model; import java.util.Objects; import java.util.Optional; import com.netflix.titus.master.kubernetes.KubeObjectFormatter; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; public class PodUpdatedEvent extends PodEvent { private final V1Pod oldPod; private final Optional<V1Node> node; PodUpdatedEvent(V1Pod oldPod, V1Pod newPod, Optional<V1Node> node) { super(newPod); this.oldPod = oldPod; this.node = node; } public V1Pod getOldPod() { return oldPod; } public Optional<V1Node> getNode() { return node; } @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; } PodUpdatedEvent that = (PodUpdatedEvent) o; return Objects.equals(oldPod, that.oldPod) && Objects.equals(node, that.node); } @Override public int hashCode() { return Objects.hash(super.hashCode(), oldPod, node); } @Override public String toString() { return "PodUpdatedEvent{" + "taskId='" + taskId + '\'' + ", sequenceNumber=" + sequenceNumber + ", pod=" + KubeObjectFormatter.formatPodEssentials(pod) + ", oldPod=" + KubeObjectFormatter.formatPodEssentials(oldPod) + ", node=" + node.map(n -> n.getMetadata().getName()).orElse("<not_assigned>") + '}'; } }
227
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodWrapper.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.client.model; import java.util.Optional; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.StringExt; import com.netflix.titus.master.kubernetes.KubeUtil; import io.kubernetes.client.openapi.models.V1ContainerState; import io.kubernetes.client.openapi.models.V1ContainerStatus; import io.kubernetes.client.openapi.models.V1Pod; /** * A helper object for processing pod state. This implementation assumes that it is always at most one container * in a pod. */ public class PodWrapper { private final V1Pod v1Pod; private volatile PodPhase podPhase; public PodWrapper(V1Pod v1Pod) { this.v1Pod = v1Pod; } public V1Pod getV1Pod() { return v1Pod; } public String getName() { return v1Pod.getMetadata() == null ? "" : StringExt.nonNull(v1Pod.getMetadata().getName()); } public PodPhase getPodPhase() { if (podPhase == null) { podPhase = v1Pod.getStatus() != null && v1Pod.getStatus().getPhase() != null ? PodPhase.parse(v1Pod.getStatus().getPhase()) : PodPhase.UNKNOWN; } return podPhase; } public String getReason() { return v1Pod.getStatus() != null && v1Pod.getStatus().getReason() != null ? v1Pod.getStatus().getReason() : ""; } public String getMessage() { return v1Pod.getStatus() != null && v1Pod.getStatus().getMessage() != null ? v1Pod.getStatus().getMessage() : "<no message>"; } public Optional<V1ContainerState> findContainerState() { return KubeUtil.findContainerState(v1Pod); } public Optional<Long> findFinishedAt() { V1ContainerState containerState = findContainerState().orElse(null); if (containerState != null && containerState.getTerminated() != null && containerState.getTerminated().getFinishedAt() != null) { return Optional.of(containerState.getTerminated().getFinishedAt().toInstant().toEpochMilli()); } return Optional.empty(); } public Optional<String> findPodAnnotation(String key) { if (v1Pod.getMetadata() == null || v1Pod.getMetadata().getAnnotations() == null) { return Optional.empty(); } return Optional.ofNullable(v1Pod.getMetadata().getAnnotations().get(key)); } public boolean hasDeletionTimestamp() { return v1Pod.getMetadata() != null && v1Pod.getMetadata().getDeletionTimestamp() != null; } public boolean isScheduled() { return v1Pod.getSpec() != null && StringExt.isNotEmpty(v1Pod.getSpec().getNodeName()); } public boolean hasContainerStateWaiting() { if (v1Pod.getStatus() == null || CollectionsExt.isNullOrEmpty(v1Pod.getStatus().getContainerStatuses())) { return false; } for (V1ContainerStatus status : v1Pod.getStatus().getContainerStatuses()) { if (status.getState() != null && status.getState().getWaiting() != null) { return true; } } return false; } public boolean isTerminated() { PodPhase podPhase = getPodPhase(); return podPhase == PodPhase.FAILED || podPhase == PodPhase.SUCCEEDED; } }
228
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodEvent.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.client.model; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.master.kubernetes.KubeObjectFormatter; import io.kubernetes.client.openapi.models.V1Node; import io.kubernetes.client.openapi.models.V1Pod; public abstract class PodEvent { private static final AtomicLong SEQUENCE_NUMBER = new AtomicLong(); protected final String taskId; protected final V1Pod pod; protected final long sequenceNumber; protected PodEvent(V1Pod pod) { this.taskId = pod.getMetadata().getName(); this.pod = pod; this.sequenceNumber = SEQUENCE_NUMBER.getAndIncrement(); } public String getTaskId() { return taskId; } public V1Pod getPod() { return pod; } public long getSequenceNumber() { return sequenceNumber; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PodEvent podEvent = (PodEvent) o; return sequenceNumber == podEvent.sequenceNumber && Objects.equals(taskId, podEvent.taskId) && Objects.equals(pod, podEvent.pod); } @Override public int hashCode() { return Objects.hash(taskId, pod, sequenceNumber); } @Override public String toString() { return "PodEvent{" + "taskId='" + taskId + '\'' + ", sequenceNumber=" + sequenceNumber + ", pod=" + KubeObjectFormatter.formatPodEssentials(pod) + '}'; } public static long nextSequence() { return SEQUENCE_NUMBER.get(); } public static PodAddedEvent onAdd(V1Pod pod) { return new PodAddedEvent(pod); } public static PodUpdatedEvent onUpdate(V1Pod oldPod, V1Pod newPod, Optional<V1Node> node) { return new PodUpdatedEvent(oldPod, newPod, node); } public static PodDeletedEvent onDelete(V1Pod pod, boolean deletedFinalStateUnknown, Optional<V1Node> node) { return new PodDeletedEvent(pod, deletedFinalStateUnknown, node); } public static PodNotFoundEvent onPodNotFound(Task task, TaskStatus finalTaskStatus) { return new PodNotFoundEvent(task, finalTaskStatus); } }
229
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/kubernetes/client/model/PodAddedEvent.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.client.model; import com.netflix.titus.master.kubernetes.KubeObjectFormatter; import io.kubernetes.client.openapi.models.V1Pod; public class PodAddedEvent extends PodEvent { PodAddedEvent(V1Pod pod) { super(pod); } @Override public String toString() { return "PodAddedEvent{" + "taskId=" + taskId + ", sequenceNumber=" + sequenceNumber + ", pod=" + KubeObjectFormatter.formatPodEssentials(pod) + '}'; } }
230
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3/AutoScalingModule.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.appscale.endpoint.v3; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.api.appscale.service.AppScaleManager; import com.netflix.titus.api.connector.cloud.AppAutoScalingClient; import com.netflix.titus.api.connector.cloud.CloudAlarmClient; import com.netflix.titus.api.connector.cloud.noop.NoOpAppAutoScalingClient; import com.netflix.titus.api.connector.cloud.noop.NoOpCloudAlarmClient; import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc; import com.netflix.titus.master.appscale.endpoint.v3.grpc.DefaultAutoScalingServiceGrpc; import com.netflix.titus.master.appscale.service.AppScaleManagerConfiguration; import com.netflix.titus.master.appscale.service.DefaultAppScaleManager; public class AutoScalingModule extends AbstractModule { @Override protected void configure() { bind(AutoScalingServiceGrpc.AutoScalingServiceImplBase.class).to(DefaultAutoScalingServiceGrpc.class); bind(AppScaleManager.class).to(DefaultAppScaleManager.class); bind(CloudAlarmClient.class).to(NoOpCloudAlarmClient.class); bind(AppAutoScalingClient.class).to(NoOpAppAutoScalingClient.class); } @Provides @Singleton public AppScaleManagerConfiguration getAppScaleManagerConfiguration(ConfigProxyFactory factory) { return factory.newProxy(AppScaleManagerConfiguration.class); } }
231
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3/grpc/GrpcModelConverters.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.appscale.endpoint.v3.grpc; import java.util.ArrayList; import java.util.List; import com.google.protobuf.BoolValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.ComparisonOperator; import com.netflix.titus.api.appscale.model.MetricAggregationType; import com.netflix.titus.api.appscale.model.PolicyStatus; import com.netflix.titus.api.appscale.model.Statistic; import com.netflix.titus.api.appscale.model.StepAdjustment; import com.netflix.titus.api.appscale.model.StepAdjustmentType; import com.netflix.titus.api.appscale.model.StepScalingPolicyConfiguration; import com.netflix.titus.api.appscale.model.TargetTrackingPolicy; import com.netflix.titus.grpc.protogen.AlarmConfiguration; import com.netflix.titus.grpc.protogen.CustomizedMetricSpecification; import com.netflix.titus.grpc.protogen.MetricDimension; import com.netflix.titus.grpc.protogen.PredefinedMetricSpecification; import com.netflix.titus.grpc.protogen.ScalingPolicy; import com.netflix.titus.grpc.protogen.ScalingPolicyID; import com.netflix.titus.grpc.protogen.ScalingPolicyResult; import com.netflix.titus.grpc.protogen.ScalingPolicyStatus; import com.netflix.titus.grpc.protogen.StepAdjustments; import com.netflix.titus.grpc.protogen.StepScalingPolicy; import com.netflix.titus.grpc.protogen.StepScalingPolicyDescriptor; import com.netflix.titus.grpc.protogen.TargetTrackingPolicyDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.api.appscale.model.PolicyType.StepScaling; import static com.netflix.titus.api.appscale.model.PolicyType.TargetTrackingScaling; /** * Collection of functions to convert policy models from internal to gRPC formats. */ public final class GrpcModelConverters { private static Logger log = LoggerFactory.getLogger(GrpcModelConverters.class); public static ScalingPolicyID toScalingPolicyId(String policyId) { return ScalingPolicyID.newBuilder().setId(policyId).build(); } public static ScalingPolicyResult toScalingPolicyResult(AutoScalingPolicy autoScalingPolicy) { ScalingPolicy scalingPolicy = toScalingPolicy(autoScalingPolicy); ScalingPolicyStatus scalingPolicyStatus = toScalingPolicyStatus(autoScalingPolicy.getStatus(), autoScalingPolicy.getStatusMessage()); return ScalingPolicyResult.newBuilder() .setJobId(autoScalingPolicy.getJobId()) .setId(ScalingPolicyID.newBuilder().setId(autoScalingPolicy.getRefId()).build()) .setPolicyState(scalingPolicyStatus) .setScalingPolicy(scalingPolicy) .build(); } private static ScalingPolicy toScalingPolicy(AutoScalingPolicy autoScalingPolicy) { ScalingPolicy.Builder scalingPolicyBuilder = ScalingPolicy.newBuilder(); if (autoScalingPolicy.getPolicyConfiguration().getPolicyType() == StepScaling) { AlarmConfiguration alarmConfiguration = toAlarmConfiguration(autoScalingPolicy.getPolicyConfiguration().getAlarmConfiguration()); StepScalingPolicy stepScalingPolicy = toStepScalingPolicy(autoScalingPolicy.getPolicyConfiguration().getStepScalingPolicyConfiguration()); StepScalingPolicyDescriptor stepScalingPolicyDescriptor = StepScalingPolicyDescriptor.newBuilder() .setAlarmConfig(alarmConfiguration) .setScalingPolicy(stepScalingPolicy) .build(); scalingPolicyBuilder .setStepPolicyDescriptor(stepScalingPolicyDescriptor); } else if (autoScalingPolicy.getPolicyConfiguration().getPolicyType() == TargetTrackingScaling) { TargetTrackingPolicyDescriptor targetTrackingPolicyDesc = toTargetTrackingPolicyDescriptor(autoScalingPolicy.getPolicyConfiguration().getTargetTrackingPolicy()); scalingPolicyBuilder .setTargetPolicyDescriptor(targetTrackingPolicyDesc); } else { throw new IllegalArgumentException("Invalid AutoScalingPolicyType value " + autoScalingPolicy.getPolicyConfiguration().getPolicyType()); } return scalingPolicyBuilder.build(); } private static AlarmConfiguration toAlarmConfiguration(com.netflix.titus.api.appscale.model.AlarmConfiguration alarmConfiguration) { AlarmConfiguration.Builder alarmConfigBuilder = AlarmConfiguration.newBuilder(); alarmConfiguration.getActionsEnabled().ifPresent( actionsEnabled -> alarmConfigBuilder.setActionsEnabled(BoolValue.newBuilder() .setValue(actionsEnabled) .build()) ); AlarmConfiguration.ComparisonOperator comparisonOperator = toComparisonOperator(alarmConfiguration.getComparisonOperator()); AlarmConfiguration.Statistic statistic = toStatistic(alarmConfiguration.getStatistic()); return AlarmConfiguration.newBuilder() .setComparisonOperator(comparisonOperator) .setEvaluationPeriods(Int32Value.newBuilder() .setValue(alarmConfiguration.getEvaluationPeriods()) .build()) .setPeriodSec(Int32Value.newBuilder() .setValue(alarmConfiguration.getPeriodSec()) .build()) .setThreshold(DoubleValue.newBuilder() .setValue(alarmConfiguration.getThreshold()) .build()) .setMetricNamespace(alarmConfiguration.getMetricNamespace()) .setMetricName(alarmConfiguration.getMetricName()) .setStatistic(statistic) .build(); } private static StepScalingPolicy toStepScalingPolicy(StepScalingPolicyConfiguration stepScalingPolicyConfiguration) { StepScalingPolicy.Builder stepScalingPolicyBuilder = StepScalingPolicy.newBuilder(); stepScalingPolicyConfiguration.getCoolDownSec().ifPresent( coolDown -> stepScalingPolicyBuilder.setCooldownSec(Int32Value.newBuilder().setValue(coolDown).build()) ); stepScalingPolicyConfiguration.getMetricAggregationType().ifPresent( metricAggregationType -> stepScalingPolicyBuilder.setMetricAggregationType(toMetricAggregationType(metricAggregationType)) ); stepScalingPolicyConfiguration.getAdjustmentType().ifPresent( stepAdjustmentType -> stepScalingPolicyBuilder.setAdjustmentType(toAdjustmentType(stepAdjustmentType)) ); stepScalingPolicyConfiguration.getMinAdjustmentMagnitude().ifPresent( minAdjustmentMagnitude -> stepScalingPolicyBuilder.setMinAdjustmentMagnitude( Int64Value.newBuilder() .setValue(minAdjustmentMagnitude) .build()) ); stepScalingPolicyBuilder.addAllStepAdjustments(toStepAdjustmentsList(stepScalingPolicyConfiguration.getSteps())); return stepScalingPolicyBuilder .build(); } private static TargetTrackingPolicyDescriptor toTargetTrackingPolicyDescriptor(TargetTrackingPolicy targetTrackingPolicy) { TargetTrackingPolicyDescriptor.Builder targetTrackingPolicyDescBuilder = TargetTrackingPolicyDescriptor.newBuilder(); targetTrackingPolicyDescBuilder.setTargetValue(DoubleValue.newBuilder() .setValue(targetTrackingPolicy.getTargetValue()) .build()); targetTrackingPolicy.getScaleOutCooldownSec().ifPresent( scaleOutCoolDownSec -> targetTrackingPolicyDescBuilder.setScaleOutCooldownSec( Int32Value.newBuilder().setValue(scaleOutCoolDownSec).build()) ); targetTrackingPolicy.getScaleInCooldownSec().ifPresent( scaleInCoolDownSec -> targetTrackingPolicyDescBuilder.setScaleInCooldownSec( Int32Value.newBuilder().setValue(scaleInCoolDownSec).build()) ); targetTrackingPolicy.getDisableScaleIn().ifPresent( disableScaleIn -> targetTrackingPolicyDescBuilder.setDisableScaleIn( BoolValue.newBuilder().setValue(disableScaleIn).build()) ); targetTrackingPolicy.getPredefinedMetricSpecification().ifPresent( predefinedMetricSpecification -> targetTrackingPolicyDescBuilder.setPredefinedMetricSpecification( toPredefinedMetricSpecification(targetTrackingPolicy.getPredefinedMetricSpecification().get())) ); targetTrackingPolicy.getCustomizedMetricSpecification().ifPresent( customizedMetricSpecification -> targetTrackingPolicyDescBuilder.setCustomizedMetricSpecification( toCustomizedMetricSpecification(targetTrackingPolicy.getCustomizedMetricSpecification().get())) ); return targetTrackingPolicyDescBuilder.build(); } private static CustomizedMetricSpecification toCustomizedMetricSpecification(com.netflix.titus.api.appscale.model.CustomizedMetricSpecification customizedMetricSpec) { CustomizedMetricSpecification.Builder customizedMetricSpecBuilder = CustomizedMetricSpecification.newBuilder(); customizedMetricSpecBuilder .addAllDimensions(toMetricDimensionList(customizedMetricSpec.getMetricDimensionList())) .setMetricName(customizedMetricSpec.getMetricName()) .setNamespace(customizedMetricSpec.getNamespace()) .setStatistic(toStatistic(customizedMetricSpec.getStatistic())); customizedMetricSpec.getUnit().ifPresent( unit -> customizedMetricSpecBuilder.setUnit(customizedMetricSpec.getUnit().get()) ); return customizedMetricSpecBuilder.build(); } private static List<MetricDimension> toMetricDimensionList(List<com.netflix.titus.api.appscale.model.MetricDimension> metricDimensionList) { List<MetricDimension> metricDimensionGrpcList = new ArrayList<>(); metricDimensionList.forEach((metricDimension) -> { metricDimensionGrpcList.add(toMetricDimension(metricDimension)); }); return metricDimensionGrpcList; } private static MetricDimension toMetricDimension(com.netflix.titus.api.appscale.model.MetricDimension metricDimension) { return MetricDimension.newBuilder() .setName(metricDimension.getName()) .setValue(metricDimension.getValue()) .build(); } private static PredefinedMetricSpecification toPredefinedMetricSpecification(com.netflix.titus.api.appscale.model.PredefinedMetricSpecification predefinedMetricSpec) { PredefinedMetricSpecification.Builder predefinedMetricSpecBuilder = PredefinedMetricSpecification.newBuilder(); predefinedMetricSpecBuilder.setPredefinedMetricType(predefinedMetricSpec.getPredefinedMetricType()); predefinedMetricSpec.getResourceLabel().ifPresent( resourceLabel -> predefinedMetricSpecBuilder.setResourceLabel(predefinedMetricSpec.getResourceLabel().get()) ); return predefinedMetricSpecBuilder.build(); } private static ScalingPolicyStatus toScalingPolicyStatus(PolicyStatus policyStatus, String statusMessage) { ScalingPolicyStatus.ScalingPolicyState policyState; switch (policyStatus) { case Pending: policyState = ScalingPolicyStatus.ScalingPolicyState.Pending; break; case Applied: policyState = ScalingPolicyStatus.ScalingPolicyState.Applied; break; case Deleting: policyState = ScalingPolicyStatus.ScalingPolicyState.Deleting; break; case Deleted: policyState = ScalingPolicyStatus.ScalingPolicyState.Deleted; break; case Error: policyState = ScalingPolicyStatus.ScalingPolicyState.Error; break; default: throw new IllegalArgumentException("Invalid PolicyStatus value " + policyStatus); } if (statusMessage == null) { statusMessage = ""; } return ScalingPolicyStatus.newBuilder() .setState(policyState) .setPendingReason(statusMessage) .build(); } private static StepScalingPolicy.AdjustmentType toAdjustmentType(StepAdjustmentType stepAdjustmentType) { StepScalingPolicy.AdjustmentType adjustmentType; switch (stepAdjustmentType) { case ChangeInCapacity: adjustmentType = StepScalingPolicy.AdjustmentType.ChangeInCapacity; break; case PercentChangeInCapacity: adjustmentType = StepScalingPolicy.AdjustmentType.PercentChangeInCapacity; break; case ExactCapacity: adjustmentType = StepScalingPolicy.AdjustmentType.ExactCapacity; break; default: throw new IllegalArgumentException("Invalid StepAdjustmentType value " + stepAdjustmentType); } return adjustmentType; } private static StepScalingPolicy.MetricAggregationType toMetricAggregationType(MetricAggregationType metricAggregationType) { StepScalingPolicy.MetricAggregationType metricAggregationTypeGrpc; switch (metricAggregationType) { case Average: metricAggregationTypeGrpc = StepScalingPolicy.MetricAggregationType.Average; break; case Maximum: metricAggregationTypeGrpc = StepScalingPolicy.MetricAggregationType.Maximum; break; case Minimum: metricAggregationTypeGrpc = StepScalingPolicy.MetricAggregationType.Minimum; break; default: throw new IllegalArgumentException("Invalid MetricAggregationType value " + metricAggregationType); } return metricAggregationTypeGrpc; } private static StepAdjustments toStepAdjustments(StepAdjustment stepAdjustment) { StepAdjustments.Builder stepAdjustmentsBuilder = StepAdjustments.newBuilder() .setScalingAdjustment(Int32Value.newBuilder() .setValue(stepAdjustment.getScalingAdjustment()) .build()); stepAdjustment.getMetricIntervalLowerBound().ifPresent( metricIntervalLowerBound -> stepAdjustmentsBuilder.setMetricIntervalLowerBound(DoubleValue.newBuilder() .setValue(metricIntervalLowerBound) .build()) ); stepAdjustment.getMetricIntervalUpperBound().ifPresent( metricIntervalUpperBound -> stepAdjustmentsBuilder.setMetricIntervalUpperBound(DoubleValue.newBuilder() .setValue(metricIntervalUpperBound) .build()) ); return stepAdjustmentsBuilder.build(); } private static List<StepAdjustments> toStepAdjustmentsList(List<StepAdjustment> stepAdjustmentList) { List<StepAdjustments> stepAdjustmentGrpcList = new ArrayList<>(); stepAdjustmentList.forEach((stepAdjustment) -> { stepAdjustmentGrpcList.add(toStepAdjustments(stepAdjustment)); }); return stepAdjustmentGrpcList; } private static AlarmConfiguration.ComparisonOperator toComparisonOperator(ComparisonOperator comparisonOperator) { AlarmConfiguration.ComparisonOperator comparisonOperatorGrpc; switch (comparisonOperator) { case GreaterThanOrEqualToThreshold: comparisonOperatorGrpc = AlarmConfiguration.ComparisonOperator.GreaterThanOrEqualToThreshold; break; case GreaterThanThreshold: comparisonOperatorGrpc = AlarmConfiguration.ComparisonOperator.GreaterThanThreshold; break; case LessThanOrEqualToThreshold: comparisonOperatorGrpc = AlarmConfiguration.ComparisonOperator.LessThanOrEqualToThreshold; break; case LessThanThreshold: comparisonOperatorGrpc = AlarmConfiguration.ComparisonOperator.LessThanThreshold; break; default: throw new IllegalArgumentException("Invalid ComparisonOperator value " + comparisonOperator); } return comparisonOperatorGrpc; } private static AlarmConfiguration.Statistic toStatistic(Statistic statistic) { AlarmConfiguration.Statistic statisticGrpc; switch (statistic) { case SampleCount: statisticGrpc = AlarmConfiguration.Statistic.SampleCount; break; case Sum: statisticGrpc = AlarmConfiguration.Statistic.Sum; break; case Average: statisticGrpc = AlarmConfiguration.Statistic.Average; break; case Maximum: statisticGrpc = AlarmConfiguration.Statistic.Maximum; break; case Minimum: statisticGrpc = AlarmConfiguration.Statistic.Minimum; break; default: throw new IllegalArgumentException("Invalid Statistic value " + statistic); } return statisticGrpc; } }
232
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3/grpc/DefaultAutoScalingServiceGrpc.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.appscale.endpoint.v3.grpc; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.protobuf.Empty; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.sanitizer.ScalingPolicySanitizerBuilder; import com.netflix.titus.api.appscale.service.AppScaleManager; import com.netflix.titus.api.service.TitusServiceException; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.grpc.protogen.AlarmConfiguration; import com.netflix.titus.grpc.protogen.AutoScalingServiceGrpc; import com.netflix.titus.grpc.protogen.GetPolicyResult; import com.netflix.titus.grpc.protogen.PutPolicyRequest; import com.netflix.titus.grpc.protogen.ScalingPolicyResult; import com.netflix.titus.grpc.protogen.UpdatePolicyRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import rx.Observable; import static com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil.safeOnError; @Singleton public class DefaultAutoScalingServiceGrpc extends AutoScalingServiceGrpc.AutoScalingServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(DefaultAutoScalingServiceGrpc.class); private AppScaleManager appScaleManager; private EntitySanitizer entitySanitizer; @Inject public DefaultAutoScalingServiceGrpc(AppScaleManager appScaleManager, @Named(ScalingPolicySanitizerBuilder.SCALING_POLICY_SANITIZER) EntitySanitizer entitySanitizer) { this.appScaleManager = appScaleManager; this.entitySanitizer = entitySanitizer; } @Override public void setAutoScalingPolicy(com.netflix.titus.grpc.protogen.PutPolicyRequest request, io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.ScalingPolicyID> responseObserver) { validateAndConvertAutoScalingPolicyToCoreModel(request).flatMap( validatedRequest -> ReactorExt.toMono(appScaleManager.createAutoScalingPolicy(validatedRequest).toSingle())) .subscribe( id -> responseObserver.onNext(GrpcModelConverters.toScalingPolicyId(id)), e -> safeOnError(logger, e, responseObserver), () -> responseObserver.onCompleted()); } private Mono<AutoScalingPolicy> validateAndConvertAutoScalingPolicyToCoreModel(PutPolicyRequest request) { return Mono.defer(() -> { AutoScalingPolicy autoScalingPolicy; try { autoScalingPolicy = InternalModelConverters.toAutoScalingPolicy(request); } catch (Exception exe) { return Mono.error(TitusServiceException.invalidArgument("Error when converting GRPC object to internal representation: " + exe.getMessage())); } return Mono.fromCallable(() -> entitySanitizer.validate(autoScalingPolicy)) .flatMap(violations -> { if (!violations.isEmpty()) { return Mono.error(TitusServiceException.invalidArgument(violations)); } return Mono.just(autoScalingPolicy); }); }); } @Override public void getJobScalingPolicies(com.netflix.titus.grpc.protogen.JobId request, io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) { Observable<AutoScalingPolicy> policyObservable = appScaleManager.getScalingPoliciesForJob(request.getId()); completePolicyList(policyObservable, responseObserver); } @Override public void getScalingPolicy(com.netflix.titus.grpc.protogen.ScalingPolicyID request, io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) { // FIXME: make NOT_FOUND an explicit error condition // appScaleManager.getScalingPolicy(id) will return an empty Observable when the id is not found, which makes // the gRPC handler throw an exception (INTERNAL: Completed without a response). This error should be an // explicit condition of the API, and mapped to Status.NOT_FOUND appScaleManager.getScalingPolicy(request.getId()).subscribe( autoScalingPolicyInternal -> { ScalingPolicyResult scalingPolicyResult = GrpcModelConverters.toScalingPolicyResult(autoScalingPolicyInternal); responseObserver.onNext(GetPolicyResult.newBuilder().addItems(scalingPolicyResult).build()); }, e -> safeOnError(logger, e, responseObserver), responseObserver::onCompleted ); } @Override public void getAllScalingPolicies(com.google.protobuf.Empty request, io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) { Observable<AutoScalingPolicy> policyObservable = appScaleManager.getAllScalingPolicies(); completePolicyList(policyObservable, responseObserver); } @Override public void deleteAutoScalingPolicy(com.netflix.titus.grpc.protogen.DeletePolicyRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { appScaleManager.removeAutoScalingPolicy(request.getId().getId()).subscribe( () -> { responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); }, e -> safeOnError(logger, e, responseObserver)); } @Override public void updateAutoScalingPolicy(UpdatePolicyRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { appScaleManager.updateAutoScalingPolicy(InternalModelConverters.toAutoScalingPolicy(request)) .subscribe( () -> { responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); }, e -> safeOnError(logger, e, responseObserver) ); } private void completePolicyList(Observable<AutoScalingPolicy> policyObservable, io.grpc.stub.StreamObserver<com.netflix.titus.grpc.protogen.GetPolicyResult> responseObserver) { List<ScalingPolicyResult> scalingPolicyResultList = new ArrayList<>(); policyObservable.subscribe( autoScalingPolicyInternal -> { ScalingPolicyResult scalingPolicyResult = GrpcModelConverters.toScalingPolicyResult(autoScalingPolicyInternal); scalingPolicyResultList.add(scalingPolicyResult); }, e -> safeOnError(logger, e, responseObserver), () -> { responseObserver.onNext(GetPolicyResult.newBuilder().addAllItems(scalingPolicyResultList).build()); responseObserver.onCompleted(); } ); } }
233
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/endpoint/v3/grpc/InternalModelConverters.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.appscale.endpoint.v3.grpc; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.netflix.titus.api.appscale.model.AlarmConfiguration; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.ComparisonOperator; import com.netflix.titus.api.appscale.model.CustomizedMetricSpecification; import com.netflix.titus.api.appscale.model.MetricAggregationType; import com.netflix.titus.api.appscale.model.MetricDimension; import com.netflix.titus.api.appscale.model.PolicyConfiguration; import com.netflix.titus.api.appscale.model.PolicyType; import com.netflix.titus.api.appscale.model.PredefinedMetricSpecification; import com.netflix.titus.api.appscale.model.Statistic; import com.netflix.titus.api.appscale.model.StepAdjustment; import com.netflix.titus.api.appscale.model.StepAdjustmentType; import com.netflix.titus.api.appscale.model.StepScalingPolicyConfiguration; import com.netflix.titus.api.appscale.model.TargetTrackingPolicy; import com.netflix.titus.grpc.protogen.PutPolicyRequest; import com.netflix.titus.grpc.protogen.ScalingPolicy; import com.netflix.titus.grpc.protogen.StepAdjustments; import com.netflix.titus.grpc.protogen.StepScalingPolicy; import com.netflix.titus.grpc.protogen.StepScalingPolicyDescriptor; import com.netflix.titus.grpc.protogen.TargetTrackingPolicyDescriptor; import com.netflix.titus.grpc.protogen.UpdatePolicyRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.grpc.protogen.CustomizedMetricSpecification.StatisticOneofCase.STATISTICONEOF_NOT_SET; import static com.netflix.titus.grpc.protogen.ScalingPolicy.ScalingPolicyDescriptorCase.STEPPOLICYDESCRIPTOR; import static com.netflix.titus.grpc.protogen.ScalingPolicy.ScalingPolicyDescriptorCase.TARGETPOLICYDESCRIPTOR; /** * Collection of functions to convert policy models from gRPC to internal formats. * There is no semantic validation. Conversion just attempts to set whatever gRPC * values are set. */ public class InternalModelConverters { private static Logger log = LoggerFactory.getLogger(InternalModelConverters.class); public static AutoScalingPolicy toAutoScalingPolicy(PutPolicyRequest putPolicyRequestGrpc) { AutoScalingPolicy.Builder autoScalingPolicyBuilder = AutoScalingPolicy.newBuilder(); autoScalingPolicyBuilder.withJobId(putPolicyRequestGrpc.getJobId()); if (putPolicyRequestGrpc.hasScalingPolicy()) { autoScalingPolicyBuilder.withPolicyConfiguration( toPolicyConfiguration(putPolicyRequestGrpc.getScalingPolicy()) ); } return autoScalingPolicyBuilder.build(); } public static AutoScalingPolicy toAutoScalingPolicy(UpdatePolicyRequest updatePolicyRequest) { AutoScalingPolicy.Builder autoScalingPolicyBuilder = AutoScalingPolicy.newBuilder(); if (updatePolicyRequest.hasPolicyId()) { autoScalingPolicyBuilder.withRefId(updatePolicyRequest.getPolicyId().getId()); } if (updatePolicyRequest.hasScalingPolicy()) { autoScalingPolicyBuilder.withPolicyConfiguration( toPolicyConfiguration(updatePolicyRequest.getScalingPolicy()) ); } return autoScalingPolicyBuilder.build(); } private static PolicyConfiguration toPolicyConfiguration(ScalingPolicy scalingPolicyGrpc) { PolicyConfiguration.Builder policyConfigBuilder = PolicyConfiguration.newBuilder(); if (scalingPolicyGrpc.getScalingPolicyDescriptorCase() == STEPPOLICYDESCRIPTOR) { policyConfigBuilder.withPolicyType(PolicyType.StepScaling); StepScalingPolicyDescriptor stepScalingPolicyDesc = scalingPolicyGrpc.getStepPolicyDescriptor(); // Build alarm if (stepScalingPolicyDesc.hasAlarmConfig()) { policyConfigBuilder.withAlarmConfiguration(toAlarmConfiguration(stepScalingPolicyDesc.getAlarmConfig())); } // Build step policy if (stepScalingPolicyDesc.hasScalingPolicy()) { policyConfigBuilder.withStepScalingPolicyConfiguration(toStepScalingPolicyConfiguration(stepScalingPolicyDesc.getScalingPolicy())); } } else if (scalingPolicyGrpc.getScalingPolicyDescriptorCase() == TARGETPOLICYDESCRIPTOR) { policyConfigBuilder.withPolicyType(PolicyType.TargetTrackingScaling); TargetTrackingPolicy targetTrackingPolicy = toTargetTrackingPolicy(scalingPolicyGrpc.getTargetPolicyDescriptor()); policyConfigBuilder.withTargetTrackingPolicy(targetTrackingPolicy); } else { throw new IllegalArgumentException("Invalid ScalingPolicy Type provided " + scalingPolicyGrpc.getScalingPolicyDescriptorCase()); } return policyConfigBuilder.build(); } private static TargetTrackingPolicy toTargetTrackingPolicy(TargetTrackingPolicyDescriptor targetTrackingPolicyDesc) { TargetTrackingPolicy.Builder targetTrackingPolicyBuilder = TargetTrackingPolicy.newBuilder(); if (targetTrackingPolicyDesc.hasTargetValue()) { targetTrackingPolicyBuilder.withTargetValue(targetTrackingPolicyDesc.getTargetValue().getValue()); } if (targetTrackingPolicyDesc.hasScaleOutCooldownSec()) { targetTrackingPolicyBuilder.withScaleOutCooldownSec(targetTrackingPolicyDesc.getScaleOutCooldownSec().getValue()); } if (targetTrackingPolicyDesc.hasScaleInCooldownSec()) { targetTrackingPolicyBuilder.withScaleInCooldownSec(targetTrackingPolicyDesc.getScaleInCooldownSec().getValue()); } if (targetTrackingPolicyDesc.hasPredefinedMetricSpecification()) { targetTrackingPolicyBuilder.withPredefinedMetricSpecification(toPredefinedMetricSpec(targetTrackingPolicyDesc.getPredefinedMetricSpecification())); } if (targetTrackingPolicyDesc.hasDisableScaleIn()) { targetTrackingPolicyBuilder.withDisableScaleIn(targetTrackingPolicyDesc.getDisableScaleIn().getValue()); } if (targetTrackingPolicyDesc.hasCustomizedMetricSpecification()) { targetTrackingPolicyBuilder.withCustomizedMetricSpecification(toCustomizedMetricSpec(targetTrackingPolicyDesc.getCustomizedMetricSpecification())); } return targetTrackingPolicyBuilder.build(); } private static CustomizedMetricSpecification toCustomizedMetricSpec(com.netflix.titus.grpc.protogen.CustomizedMetricSpecification customizedMetricSpecGrpc) { CustomizedMetricSpecification.Builder customizedMetricSpecBuilder = CustomizedMetricSpecification.newBuilder(); customizedMetricSpecBuilder.withMetricDimensionList( toMetricDimensionList(customizedMetricSpecGrpc.getDimensionsList())); customizedMetricSpecBuilder .withMetricName(customizedMetricSpecGrpc.getMetricName()) .withNamespace(customizedMetricSpecGrpc.getNamespace()); if (customizedMetricSpecGrpc.getStatisticOneofCase() != STATISTICONEOF_NOT_SET) { customizedMetricSpecBuilder.withStatistic(toStatistic(customizedMetricSpecGrpc.getStatistic())); } if (!customizedMetricSpecGrpc.getUnit().equals("")) { customizedMetricSpecBuilder .withUnit(customizedMetricSpecGrpc.getUnit()); } return customizedMetricSpecBuilder.build(); } private static List<MetricDimension> toMetricDimensionList(List<com.netflix.titus.grpc.protogen.MetricDimension> metricDimensionListGrpc) { return metricDimensionListGrpc.stream() .map(InternalModelConverters::toMetricDimension) .collect(Collectors.toList()); } private static MetricDimension toMetricDimension(com.netflix.titus.grpc.protogen.MetricDimension metricDimension) { return MetricDimension.newBuilder() .withName(metricDimension.getName()) .withValue(metricDimension.getValue()) .build(); } private static PredefinedMetricSpecification toPredefinedMetricSpec(com.netflix.titus.grpc.protogen.PredefinedMetricSpecification predefinedMetricSpecification) { return PredefinedMetricSpecification.newBuilder() .withPredefinedMetricType(predefinedMetricSpecification.getPredefinedMetricType()) .withResourceLabel(predefinedMetricSpecification.getResourceLabel()) .build(); } private static AlarmConfiguration toAlarmConfiguration(com.netflix.titus.grpc.protogen.AlarmConfiguration alarmConfigGrpc) { AlarmConfiguration.Builder alarmConfigBuilder = AlarmConfiguration.newBuilder(); if (alarmConfigGrpc.hasActionsEnabled()) { alarmConfigBuilder.withActionsEnabled(alarmConfigGrpc.getActionsEnabled().getValue()); } if (alarmConfigGrpc.hasEvaluationPeriods()) { alarmConfigBuilder.withEvaluationPeriods(alarmConfigGrpc.getEvaluationPeriods().getValue()); } if (alarmConfigGrpc.hasPeriodSec()) { alarmConfigBuilder.withPeriodSec(alarmConfigGrpc.getPeriodSec().getValue()); } if (alarmConfigGrpc.hasThreshold()) { alarmConfigBuilder.withThreshold(alarmConfigGrpc.getThreshold().getValue()); } if (alarmConfigGrpc.getComparisonOpOneofCase() != com.netflix.titus.grpc.protogen.AlarmConfiguration.ComparisonOpOneofCase.COMPARISONOPONEOF_NOT_SET) { alarmConfigBuilder.withComparisonOperator(toComparisonOperator(alarmConfigGrpc.getComparisonOperator())); } if (alarmConfigGrpc.getStatisticOneofCase() != com.netflix.titus.grpc.protogen.AlarmConfiguration.StatisticOneofCase.STATISTICONEOF_NOT_SET) { alarmConfigBuilder.withStatistic(toStatistic(alarmConfigGrpc.getStatistic())); } alarmConfigBuilder.withDimensions(toMetricDimensionList(alarmConfigGrpc.getMetricDimensionsList())); // TODO(Andrew L): Do we want to just always set empty string, if unset? alarmConfigBuilder.withMetricNamespace(alarmConfigGrpc.getMetricNamespace()); alarmConfigBuilder.withMetricName(alarmConfigGrpc.getMetricName()); return alarmConfigBuilder.build(); } private static StepScalingPolicyConfiguration toStepScalingPolicyConfiguration(StepScalingPolicy stepScalingPolicyGrpc) { StepScalingPolicyConfiguration.Builder stepScalingPolicyConfigBuilder = StepScalingPolicyConfiguration.newBuilder(); if (stepScalingPolicyGrpc.getAdjustmentTypeOneofCase() != StepScalingPolicy.AdjustmentTypeOneofCase.ADJUSTMENTTYPEONEOF_NOT_SET) { stepScalingPolicyConfigBuilder.withAdjustmentType(toStepAdjustmentType(stepScalingPolicyGrpc.getAdjustmentType())); } if (stepScalingPolicyGrpc.getMetricAggOneofCase() != StepScalingPolicy.MetricAggOneofCase.METRICAGGONEOF_NOT_SET) { stepScalingPolicyConfigBuilder.withMetricAggregatorType(toMetricAggregationType(stepScalingPolicyGrpc.getMetricAggregationType())); } if (stepScalingPolicyGrpc.hasCooldownSec()) { stepScalingPolicyConfigBuilder.withCoolDownSec(stepScalingPolicyGrpc.getCooldownSec().getValue()); } if (stepScalingPolicyGrpc.hasMinAdjustmentMagnitude()) { stepScalingPolicyConfigBuilder.withMinAdjustmentMagnitude(stepScalingPolicyGrpc.getMinAdjustmentMagnitude().getValue()); } List<StepAdjustment> stepAdjustmentList = toStepAdjustmentList(stepScalingPolicyGrpc.getStepAdjustmentsList()); stepScalingPolicyConfigBuilder.withSteps(stepAdjustmentList); return stepScalingPolicyConfigBuilder.build(); } private static List<StepAdjustment> toStepAdjustmentList(List<StepAdjustments> stepAdjustmentsGrpcList) { List<StepAdjustment> stepAdjustmentList = new ArrayList<>(); stepAdjustmentsGrpcList.forEach((stepAdjustments) -> { stepAdjustmentList.add(toStepAdjustment(stepAdjustments)); }); return stepAdjustmentList; } private static StepAdjustment toStepAdjustment(StepAdjustments stepAdjustmentsGprc) { StepAdjustment.Builder stepAdjustmentBuilder = StepAdjustment.newBuilder(); if (stepAdjustmentsGprc.hasMetricIntervalLowerBound()) { stepAdjustmentBuilder.withMetricIntervalLowerBound(stepAdjustmentsGprc.getMetricIntervalLowerBound().getValue()); } if (stepAdjustmentsGprc.hasMetricIntervalUpperBound()) { stepAdjustmentBuilder.withMetricIntervalUpperBound(stepAdjustmentsGprc.getMetricIntervalUpperBound().getValue()); } if (stepAdjustmentsGprc.hasScalingAdjustment()) { stepAdjustmentBuilder.withScalingAdjustment(stepAdjustmentsGprc.getScalingAdjustment().getValue()); } return stepAdjustmentBuilder.build(); } private static MetricAggregationType toMetricAggregationType(StepScalingPolicy.MetricAggregationType metricAggregationTypeGrpc) { MetricAggregationType metricAggregationType; switch (metricAggregationTypeGrpc) { case Average: metricAggregationType = MetricAggregationType.Average; break; case Minimum: metricAggregationType = MetricAggregationType.Minimum; break; case Maximum: metricAggregationType = MetricAggregationType.Maximum; break; default: throw new IllegalArgumentException("Invalid StepScalingPolicy MetricAggregationType value " + metricAggregationTypeGrpc); } return metricAggregationType; } private static StepAdjustmentType toStepAdjustmentType(StepScalingPolicy.AdjustmentType adjustmentTypeGrpc) { StepAdjustmentType stepAdjustmentType; switch (adjustmentTypeGrpc) { case ExactCapacity: stepAdjustmentType = StepAdjustmentType.ExactCapacity; break; case ChangeInCapacity: stepAdjustmentType = StepAdjustmentType.ChangeInCapacity; break; case PercentChangeInCapacity: stepAdjustmentType = StepAdjustmentType.PercentChangeInCapacity; break; default: throw new IllegalArgumentException("Invalid StepScalingPolicy AdjustmentType value " + adjustmentTypeGrpc); } return stepAdjustmentType; } private static ComparisonOperator toComparisonOperator(com.netflix.titus.grpc.protogen.AlarmConfiguration.ComparisonOperator comparisonOperatorGrpc) { ComparisonOperator comparisonOperator; switch (comparisonOperatorGrpc) { case GreaterThanOrEqualToThreshold: comparisonOperator = ComparisonOperator.GreaterThanOrEqualToThreshold; break; case GreaterThanThreshold: comparisonOperator = ComparisonOperator.GreaterThanThreshold; break; case LessThanOrEqualToThreshold: comparisonOperator = ComparisonOperator.LessThanOrEqualToThreshold; break; case LessThanThreshold: comparisonOperator = ComparisonOperator.LessThanThreshold; break; default: throw new IllegalArgumentException("Invalid AlarmConfiguration ComparisonOperator value " + comparisonOperatorGrpc); } return comparisonOperator; } private static Statistic toStatistic(com.netflix.titus.grpc.protogen.AlarmConfiguration.Statistic statisticGrpc) { Statistic statistic; switch (statisticGrpc) { case SampleCount: statistic = Statistic.SampleCount; break; case Sum: statistic = Statistic.Sum; break; case Average: statistic = Statistic.Average; break; case Minimum: statistic = Statistic.Minimum; break; case Maximum: statistic = Statistic.Maximum; break; default: throw new IllegalArgumentException("Invalid AlarmConfiguration Statistic value " + statisticGrpc); } return statistic; } }
234
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/JobScalingConstraints.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.appscale.service; public class JobScalingConstraints { private int minCapacity; private int maxCapacity; public JobScalingConstraints(int minCapacity, int maxCapacity) { this.minCapacity = minCapacity; this.maxCapacity = maxCapacity; } public int getMinCapacity() { return minCapacity; } public int getMaxCapacity() { return maxCapacity; } }
235
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/DefaultAppScaleManager.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.appscale.service; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.frigga.autoscaling.AutoScalingGroupNameBuilder; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.appscale.model.AutoScalableTarget; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.PolicyStatus; import com.netflix.titus.api.appscale.model.PolicyType; import com.netflix.titus.api.appscale.service.AppScaleManager; import com.netflix.titus.api.appscale.service.AutoScalePolicyException; import com.netflix.titus.api.appscale.store.AppScalePolicyStore; import com.netflix.titus.api.connector.cloud.AppAutoScalingClient; import com.netflix.titus.api.connector.cloud.CloudAlarmClient; 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.JobGroupInfo; import com.netflix.titus.api.jobmanager.model.job.JobState; import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent; import com.netflix.titus.api.jobmanager.model.job.ext.ServiceJobExt; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.ExecutorsExt; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.rx.RetryHandlerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; @Singleton public class DefaultAppScaleManager implements AppScaleManager { public static final long INITIAL_RETRY_DELAY_SEC = 5; public static final long MAX_RETRY_DELAY_SEC = 30; private static Logger logger = LoggerFactory.getLogger(DefaultAppScaleManager.class); private static final long SHUTDOWN_TIMEOUT_MS = 5_000; private static final String DEFAULT_JOB_GROUP_SEQ = "v000"; private static final int ASYNC_HANDLER_BUFFER_CAPACITY = 10_000; private final AppScaleManagerMetrics metrics; private final SerializedSubject<AppScaleAction, AppScaleAction> appScaleActionsSubject; private final AppScalePolicyStore appScalePolicyStore; private final CloudAlarmClient cloudAlarmClient; private final AppAutoScalingClient appAutoScalingClient; private final V3JobOperations v3JobOperations; private final AppScaleManagerConfiguration appScaleManagerConfiguration; private TitusRuntime titusRuntime; private volatile Map<String, AutoScalableTarget> scalableTargets; private volatile Subscription reconcileFinishedJobsSub; private volatile Subscription reconcileAllPendingRequests; private volatile Subscription reconcileScalableTargetsSub; private volatile ExecutorService awsInteractionExecutor; private Subscription appScaleActionsSub; @Inject public DefaultAppScaleManager(AppScalePolicyStore appScalePolicyStore, CloudAlarmClient cloudAlarmClient, AppAutoScalingClient applicationAutoScalingClient, V3JobOperations v3JobOperations, Registry registry, AppScaleManagerConfiguration appScaleManagerConfiguration, TitusRuntime titusRuntime) { this(appScalePolicyStore, cloudAlarmClient, applicationAutoScalingClient, v3JobOperations, registry, appScaleManagerConfiguration, ExecutorsExt.namedSingleThreadExecutor("DefaultAppScaleManager"), titusRuntime); } private DefaultAppScaleManager(AppScalePolicyStore appScalePolicyStore, CloudAlarmClient cloudAlarmClient, AppAutoScalingClient applicationAutoScalingClient, V3JobOperations v3JobOperations, Registry registry, AppScaleManagerConfiguration appScaleManagerConfiguration, ExecutorService awsInteractionExecutor, TitusRuntime titusRuntime) { this(appScalePolicyStore, cloudAlarmClient, applicationAutoScalingClient, v3JobOperations, registry, appScaleManagerConfiguration, Schedulers.from(awsInteractionExecutor), titusRuntime); this.awsInteractionExecutor = awsInteractionExecutor; } @VisibleForTesting public DefaultAppScaleManager(AppScalePolicyStore appScalePolicyStore, CloudAlarmClient cloudAlarmClient, AppAutoScalingClient applicationAutoScalingClient, V3JobOperations v3JobOperations, Registry registry, AppScaleManagerConfiguration appScaleManagerConfiguration, Scheduler awsInteractionScheduler, TitusRuntime titusRuntime) { this.appScalePolicyStore = appScalePolicyStore; this.cloudAlarmClient = cloudAlarmClient; this.appAutoScalingClient = applicationAutoScalingClient; this.v3JobOperations = v3JobOperations; this.appScaleManagerConfiguration = appScaleManagerConfiguration; this.titusRuntime = titusRuntime; this.scalableTargets = new ConcurrentHashMap<>(); this.metrics = new AppScaleManagerMetrics(registry); this.appScaleActionsSubject = PublishSubject.<AppScaleAction>create().toSerialized(); this.appScaleActionsSub = appScaleActionsSubject .onBackpressureDrop(appScaleAction -> { logger.warn("Dropping {}", appScaleAction); metrics.reportDroppedRequest(); }) .observeOn(awsInteractionScheduler, ASYNC_HANDLER_BUFFER_CAPACITY) .doOnError(e -> logger.error("Exception in appScaleActionsSubject ", e)) .retryWhen(RetryHandlerBuilder.retryHandler() .withUnlimitedRetries() .withScheduler(awsInteractionScheduler) .withDelay(INITIAL_RETRY_DELAY_SEC, MAX_RETRY_DELAY_SEC, TimeUnit.SECONDS) .withTitle("Auto-retry for appScaleActionsSubject") .buildExponentialBackoff() ) .subscribe(new AppScaleActionHandler()); } @Activator public Completable enterActiveMode() { // DB load this.appScalePolicyStore.init().await(appScaleManagerConfiguration.getStoreInitTimeoutSeconds(), TimeUnit.SECONDS); // report metrics from initial DB state this.appScalePolicyStore.retrievePolicies(true) .map(autoScalingPolicy -> { addScalableTargetIfNew(autoScalingPolicy.getJobId()); metrics.reportPolicyStatusTransition(autoScalingPolicy, autoScalingPolicy.getStatus()); return autoScalingPolicy.getRefId(); }) .subscribe(policyRefId -> logger.debug("AutoScalingPolicy loaded - {}", policyRefId)); // pending policy creation/updates or deletes checkForScalingPolicyActions().toCompletable().await(appScaleManagerConfiguration.getStoreInitTimeoutSeconds(), TimeUnit.SECONDS); reconcileAllPendingRequests = Observable.interval( appScaleManagerConfiguration.getReconcileAllPendingAndDeletingRequestsIntervalMins(), TimeUnit.MINUTES, Schedulers.io()) .flatMap(ignored -> titusRuntime.persistentStream(checkForScalingPolicyActions())) .subscribe(policy -> logger.info("Reconciliation - policy request processed : {}.", policy.getPolicyId()), e -> logger.error("error in reconciliation (ReconcileAllPendingRequests) stream", e), () -> logger.info("reconciliation (ReconcileAllPendingRequests) stream closed")); reconcileFinishedJobsSub = Observable.interval(appScaleManagerConfiguration.getReconcileFinishedJobsIntervalMins(), TimeUnit.MINUTES) .observeOn(Schedulers.io()) .flatMap(ignored -> titusRuntime.persistentStream(reconcileFinishedJobs())) .subscribe(jobId -> logger.info("reconciliation for FinishedJob : {} policies cleaned up.", jobId), e -> logger.error("error in reconciliation (FinishedJob) stream", e), () -> logger.info("reconciliation (FinishedJob) stream closed")); reconcileScalableTargetsSub = Observable.interval(appScaleManagerConfiguration.getReconcileTargetsIntervalMins(), TimeUnit.MINUTES) .observeOn(Schedulers.io()) .flatMap(ignored -> titusRuntime.persistentStream(reconcileScalableTargets())) .subscribe(jobId -> logger.info("Reconciliation (TargetUpdated) : {} target updated", jobId), e -> logger.error("Error in reconciliation (TargetUpdated) stream", e), () -> logger.info("Reconciliation (TargetUpdated) stream closed")); titusRuntime.persistentStream(v3LiveStreamTargetUpdates()) .subscribe(jobId -> logger.info("(V3) Job {} scalable target updated.", jobId), e -> logger.error("Error in V3 job state change event stream", e), () -> logger.info("V3 job event stream closed")); titusRuntime.persistentStream(v3LiveStreamPolicyCleanup()) .subscribe(jobId -> logger.info("(V3) Job {} policies clean up.", jobId), e -> logger.error("Error in V3 job state change event stream", e), () -> logger.info("V3 job event stream closed")); return Completable.complete(); } @PreDestroy public void shutdown() { ObservableExt.safeUnsubscribe(reconcileFinishedJobsSub, reconcileScalableTargetsSub, reconcileAllPendingRequests, appScaleActionsSub); if (awsInteractionExecutor == null) { return; // nothing else to do } // cancel all pending and running tasks for (Runnable runnable : awsInteractionExecutor.shutdownNow()) { logger.warn("Pending task was halted during shutdown: {}", runnable); } try { boolean terminated = awsInteractionExecutor.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (!terminated) { logger.warn("Not all currently running tasks were terminated"); } } catch (Exception e) { logger.error("Shutdown process failed, some tasks may not have been terminated", e); } } private Observable<AutoScalingPolicy> checkForScalingPolicyActions() { return appScalePolicyStore.retrievePolicies(false) .map(autoScalingPolicy -> { if (autoScalingPolicy.getStatus() == PolicyStatus.Pending) { sendCreatePolicyAction(autoScalingPolicy); } else if (autoScalingPolicy.getStatus() == PolicyStatus.Deleting) { sendDeletePolicyAction(autoScalingPolicy); } return autoScalingPolicy; }); } private Observable<String> reconcileFinishedJobs() { return appScalePolicyStore.retrievePolicies(false) .map(AutoScalingPolicy::getJobId) .filter(jobId -> !isJobActive(jobId)) .flatMap(jobId -> removePoliciesForJob(jobId).andThen(Observable.just(jobId))) .doOnError(e -> logger.error("Exception in reconcileFinishedJobs -> ", e)) .onErrorResumeNext(e -> saveStatusOnError(e).andThen(Observable.empty())); } private Observable<String> reconcileScalableTargets() { return appScalePolicyStore.retrievePolicies(false) .filter(autoScalingPolicy -> isJobActive(autoScalingPolicy.getJobId())) .filter(autoScalingPolicy -> { String jobId = autoScalingPolicy.getJobId(); return shouldRefreshScalableTargetForJob(jobId, getJobScalingConstraints(autoScalingPolicy.getRefId(), jobId)); }) .map(this::sendUpdateTargetAction) .map(AppScaleAction::getJobId) .doOnError(e -> logger.error("Exception in reconcileScalableTargets -> ", e)) .onErrorResumeNext(e -> Observable.empty()); } Observable<String> v3LiveStreamTargetUpdates() { return v3JobOperations.observeJobs() .filter(event -> { if (event instanceof JobUpdateEvent) { JobUpdateEvent jobUpdateEvent = (JobUpdateEvent) event; return jobUpdateEvent.getCurrent().getStatus().getState() != JobState.Finished; } return false; }) .cast(JobUpdateEvent.class) .flatMap(event -> appScalePolicyStore.retrievePoliciesForJob(event.getCurrent().getId()) .filter(autoScalingPolicy -> shouldRefreshScalableTargetForJob(autoScalingPolicy.getJobId(), getJobScalingConstraints(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()))) .map(this::sendUpdateTargetAction) .map(AppScaleAction::getJobId) .doOnError(e -> logger.error("Exception in v3LiveStreamTargetUpdates -> ", e)) .onErrorResumeNext(e -> Observable.empty()) ); } private Observable<String> v3LiveStreamPolicyCleanup() { return v3JobOperations.observeJobs() .filter(event -> { if (event instanceof JobUpdateEvent) { JobUpdateEvent jobUpdateEvent = (JobUpdateEvent) event; return jobUpdateEvent.getCurrent().getStatus().getState() == JobState.Finished; } return false; }) .cast(JobUpdateEvent.class) .map(event -> event.getCurrent().getId()) // extract jobId from event .flatMap(jobId -> removePoliciesForJob(jobId).andThen(Observable.just(jobId))) .doOnError(e -> logger.error("Exception in v3LiveStreamPolicyCleanup -> ", e)) .onErrorResumeNext(e -> saveStatusOnError(e).andThen(Observable.empty())); } @Override public Observable<String> createAutoScalingPolicy(AutoScalingPolicy autoScalingPolicy) { logger.info("Adding new AutoScalingPolicy {}", autoScalingPolicy); if (autoScalingPolicy.getJobId() == null || autoScalingPolicy.getPolicyConfiguration() == null) { return Observable.error(AutoScalePolicyException.invalidScalingPolicy(autoScalingPolicy.getRefId(), String.format("JobID Or PolicyConfiguration missing for %s", autoScalingPolicy.getRefId()))); } return appScalePolicyStore.storePolicy(autoScalingPolicy) .map(policyRefId -> { addScalableTargetIfNew(autoScalingPolicy.getJobId()); AutoScalingPolicy newPolicy = AutoScalingPolicy.newBuilder().withAutoScalingPolicy(autoScalingPolicy).withRefId(policyRefId).build(); sendCreatePolicyAction(newPolicy); metrics.reportPolicyStatusTransition(newPolicy, PolicyStatus.Pending); return policyRefId; }); } @Override public Completable updateAutoScalingPolicy(AutoScalingPolicy autoScalingPolicy) { logger.info("Updating AutoScalingPolicy {}", autoScalingPolicy); return appScalePolicyStore.retrievePolicyForRefId(autoScalingPolicy.getRefId()) .map(existingPolicy -> AutoScalingPolicy.newBuilder().withAutoScalingPolicy(existingPolicy) .withPolicyConfiguration(autoScalingPolicy.getPolicyConfiguration()).build()) .filter(policyWithJobId -> PolicyStateTransitions.isAllowed(policyWithJobId.getStatus(), PolicyStatus.Pending)) .flatMap(policyWithJobId -> appScalePolicyStore.updatePolicyConfiguration(policyWithJobId).andThen(Observable.just(policyWithJobId))) .flatMap(updatedPolicy -> { metrics.reportPolicyStatusTransition(updatedPolicy, PolicyStatus.Pending); return appScalePolicyStore.updatePolicyStatus(updatedPolicy.getRefId(), PolicyStatus.Pending) .andThen(Observable.fromCallable(() -> sendCreatePolicyAction(updatedPolicy))); }).toCompletable(); } @Override public Observable<AutoScalingPolicy> getScalingPoliciesForJob(String jobId) { return appScalePolicyStore.retrievePoliciesForJob(jobId); } @Override public Observable<AutoScalingPolicy> getScalingPolicy(String policyRefId) { return appScalePolicyStore.retrievePolicyForRefId(policyRefId); } @Override public Observable<AutoScalingPolicy> getAllScalingPolicies() { return appScalePolicyStore.retrievePolicies(false); } @Override public Completable removeAutoScalingPolicy(String policyRefId) { return appScalePolicyStore.retrievePolicyForRefId(policyRefId) .flatMap(autoScalingPolicy -> { if (PolicyStateTransitions.isAllowed(autoScalingPolicy.getStatus(), PolicyStatus.Deleting)) { logger.info("Removing policy {} for job {}", autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()); metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Deleting); return appScalePolicyStore.updatePolicyStatus(autoScalingPolicy.getRefId(), PolicyStatus.Deleting) .andThen(Observable.fromCallable(() -> sendDeletePolicyAction(autoScalingPolicy))); } else { return Observable.empty(); } }) .toCompletable(); } private Completable removePoliciesForJob(String jobId) { return appScalePolicyStore.retrievePoliciesForJob(jobId) .flatMapCompletable(autoScalingPolicy -> removeAutoScalingPolicy(autoScalingPolicy.getRefId())).toCompletable(); } private boolean shouldRefreshScalableTargetForJob(String jobId, JobScalingConstraints jobScalingConstraints) { return !scalableTargets.containsKey(jobId) || scalableTargets.get(jobId).getMinCapacity() != jobScalingConstraints.getMinCapacity() || scalableTargets.get(jobId).getMaxCapacity() != jobScalingConstraints.getMaxCapacity(); } private boolean isJobActive(String jobId) { return v3JobOperations.getJob(jobId).isPresent(); } private Completable saveStatusOnError(Throwable e) { Optional<AutoScalePolicyException> autoScalePolicyExceptionOpt = extractAutoScalePolicyException(e); if (!autoScalePolicyExceptionOpt.isPresent()) { return Completable.complete(); } logger.info("Saving AutoScalePolicyException", autoScalePolicyExceptionOpt.get()); AutoScalePolicyException autoScalePolicyException = autoScalePolicyExceptionOpt.get(); if (autoScalePolicyException.getPolicyRefId() != null && !autoScalePolicyException.getPolicyRefId().isEmpty()) { metrics.reportErrorForException(autoScalePolicyException); String statusMessage = String.format("%s - %s", autoScalePolicyException.getErrorCode(), autoScalePolicyException.getMessage()); AutoScalingPolicy autoScalingPolicy = AutoScalingPolicy.newBuilder().withRefId(autoScalePolicyException.getPolicyRefId()).build(); if (autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.UnknownScalingPolicy) { metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Deleted); return appScalePolicyStore.updateStatusMessage(autoScalePolicyException.getPolicyRefId(), statusMessage) .andThen(appScalePolicyStore.updatePolicyStatus(autoScalePolicyException.getPolicyRefId(), PolicyStatus.Deleted)); } else if (isPolicyCreationError(autoScalePolicyException)) { metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Error); return appScalePolicyStore.updateStatusMessage(autoScalePolicyException.getPolicyRefId(), statusMessage) .andThen(appScalePolicyStore.updatePolicyStatus(autoScalePolicyException.getPolicyRefId(), PolicyStatus.Error)); } else { return appScalePolicyStore.updateStatusMessage(autoScalePolicyException.getPolicyRefId(), statusMessage); } } else { return Completable.complete(); } } private JobScalingConstraints getJobScalingConstraints(String policyRefId, String jobId) { // V3 API if (v3JobOperations == null) { return new JobScalingConstraints(0, 0); } Optional<Job<?>> job = v3JobOperations.getJob(jobId); if (job.isPresent()) { if (job.get().getJobDescriptor().getExtensions() instanceof ServiceJobExt) { ServiceJobExt serviceJobExt = (ServiceJobExt) job.get().getJobDescriptor().getExtensions(); int minCapacity = serviceJobExt.getCapacity().getMin(); int maxCapacity = serviceJobExt.getCapacity().getMax(); return new JobScalingConstraints(minCapacity, maxCapacity); } else { logger.info("Not a service job (V3) {}", jobId); throw AutoScalePolicyException.wrapJobManagerException(policyRefId, JobManagerException.notServiceJob(jobId)); } } else { throw AutoScalePolicyException.wrapJobManagerException(policyRefId, JobManagerException.jobNotFound(jobId)); } } private String buildAutoScalingGroup(String jobId) { if (v3JobOperations == null) { return jobId; } return v3JobOperations.getJob(jobId) .map(job -> buildAutoScalingGroupV3(job.getJobDescriptor())) .orElseThrow(() -> JobManagerException.jobNotFound(jobId)); } @VisibleForTesting static String buildAutoScalingGroupV3(JobDescriptor<?> jobDescriptor) { JobGroupInfo jobGroupInfo = jobDescriptor.getJobGroupInfo(); String jobGroupSequence = jobGroupInfo.getSequence() != null ? jobGroupInfo.getSequence() : DEFAULT_JOB_GROUP_SEQ; // Using frigga builder for auto scaling group name so that cloud watch alarm configuration // is compatible with spinnaker generated auto scaling group name that is tagged with cloud watch metrics AutoScalingGroupNameBuilder autoScalingGroupNameBuilder = new AutoScalingGroupNameBuilder(); String asgWithNoSequence = autoScalingGroupNameBuilder .withAppName(jobDescriptor.getApplicationName()) .withStack(jobGroupInfo.getStack()) .withDetail(jobGroupInfo.getDetail()) .buildGroupName(); return String.format("%s-%s", asgWithNoSequence, jobGroupSequence); } private void addScalableTargetIfNew(String jobId) { if (!scalableTargets.containsKey(jobId)) { metrics.reportNewScalableTarget(); AutoScalableTarget autoScalableTarget = AutoScalableTarget.newBuilder().build(); scalableTargets.put(jobId, autoScalableTarget); } } static Optional<AutoScalePolicyException> extractAutoScalePolicyException(Throwable exception) { Throwable e = exception; while (e != null) { if (AutoScalePolicyException.class.isAssignableFrom(e.getClass())) { return Optional.of((AutoScalePolicyException) e); } e = e.getCause(); } return Optional.empty(); } public class AppScaleActionHandler implements Action1<AppScaleAction> { @Override public void call(AppScaleAction appScaleAction) { try { switch (appScaleAction.getType()) { case CREATE_SCALING_POLICY: if (appScaleAction.getAutoScalingPolicy().isPresent()) { String policyId = createOrUpdateScalingPolicyWorkflow(appScaleAction.getAutoScalingPolicy().get()).toBlocking().first(); logger.info("AutoScalingPolicy {} created/updated", policyId); } break; case DELETE_SCALING_POLICY: if (appScaleAction.getAutoScalingPolicy().isPresent()) { String policyIdDeleted = deleteScalingPolicyWorkflow(appScaleAction.getAutoScalingPolicy().get()).toBlocking().first(); logger.info("Autoscaling policy {} deleted", policyIdDeleted); } break; case UPDATE_SCALABLE_TARGET: if (appScaleAction.getPolicyRefId().isPresent()) { logger.info("Asked to remove {}", appScaleAction.getPolicyRefId()); AutoScalableTarget updatedTarget = updateScalableTargetWorkflow(appScaleAction.getPolicyRefId().get(), appScaleAction.getJobId()).toBlocking().first(); logger.info("AutoScalableTarget updated {}", updatedTarget); } break; } } catch (Exception ex) { logger.error("Exception in processing appScaleAction {}", ex.getMessage()); } } } private Observable<AutoScalableTarget> updateScalableTargetWorkflow(String policyRefId, String jobId) { return Observable.fromCallable(() -> getJobScalingConstraints(policyRefId, jobId)) .flatMap(jobScalingConstraints -> appAutoScalingClient.createScalableTarget(jobId, jobScalingConstraints.getMinCapacity(), jobScalingConstraints.getMaxCapacity()) .andThen(appAutoScalingClient.getScalableTargetsForJob(jobId)) .map(autoScalableTarget -> { scalableTargets.put(jobId, autoScalableTarget); return autoScalableTarget; })); } private Observable<String> createOrUpdateScalingPolicyWorkflow(AutoScalingPolicy inputAutoScalingPolicy) { Observable<AutoScalingPolicy> cachedPolicyObservable = Observable.just(inputAutoScalingPolicy) .flatMap(autoScalingPolicy -> { JobScalingConstraints jobScalingConstraints = getJobScalingConstraints(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()); return appAutoScalingClient .createScalableTarget(autoScalingPolicy.getJobId(), jobScalingConstraints.getMinCapacity(), jobScalingConstraints.getMaxCapacity()) .doOnError(e -> saveStatusOnError( AutoScalePolicyException.errorCreatingTarget( autoScalingPolicy.getPolicyId(), autoScalingPolicy.getJobId(), e.getMessage()))) .andThen(Observable.just(autoScalingPolicy)); }) .flatMap(autoScalingPolicy -> appAutoScalingClient.createOrUpdateScalingPolicy(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId(), autoScalingPolicy.getPolicyConfiguration()) .flatMap(policyId -> { logger.debug("Storing policy ID {} for ref ID {} on Job {}", policyId, autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()); return appScalePolicyStore.updatePolicyId(autoScalingPolicy.getRefId(), policyId) // Return an observable of the newly update policy .andThen(Observable.fromCallable(() -> appScalePolicyStore.retrievePolicyForRefId(autoScalingPolicy.getRefId())) .flatMap(autoScalingPolicyObservable -> autoScalingPolicyObservable)); })) .cache(); // Apply TT policies Observable<String> targetPolicyObservable = cachedPolicyObservable .filter(autoScalingPolicy -> autoScalingPolicy.getPolicyConfiguration().getPolicyType() == PolicyType.TargetTrackingScaling) .flatMap(autoScalingPolicy -> { metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Applied); return appScalePolicyStore.updatePolicyStatus(autoScalingPolicy.getRefId(), PolicyStatus.Applied) .andThen(Observable.just(autoScalingPolicy.getRefId())); }); // Create alarm and apply SS policies Observable<String> stepPolicyObservable = cachedPolicyObservable .filter(autoScalingPolicy -> autoScalingPolicy.getPolicyConfiguration().getPolicyType() == PolicyType.StepScaling) .flatMap(autoScalingPolicy -> { logger.debug("Updating alarm for policy {} with Policy ID {}", autoScalingPolicy, autoScalingPolicy.getPolicyId()); return cloudAlarmClient.createOrUpdateAlarm(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId(), autoScalingPolicy.getPolicyConfiguration().getAlarmConfiguration(), buildAutoScalingGroup(autoScalingPolicy.getJobId()), Collections.singletonList(autoScalingPolicy.getPolicyId()) ).flatMap(alarmId -> appScalePolicyStore.updateAlarmId(autoScalingPolicy.getRefId(), alarmId) .andThen(Observable.just(autoScalingPolicy))); }).flatMap(autoScalingPolicy -> appScalePolicyStore.retrievePolicyForRefId(autoScalingPolicy.getRefId()) .flatMap(latestPolicy -> { if (PolicyStateTransitions.isAllowed(latestPolicy.getStatus(), PolicyStatus.Applied)) { metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Applied); return appScalePolicyStore.updatePolicyStatus(autoScalingPolicy.getRefId(), PolicyStatus.Applied) .andThen(Observable.just(autoScalingPolicy.getRefId())); } else { logger.error("Invalid AutoScaling Policy state - Updating a policy that is either Deleted or Deleting {}", latestPolicy); return Observable.just(autoScalingPolicy.getRefId()); } })); return Observable.mergeDelayError(targetPolicyObservable, stepPolicyObservable) .doOnError(e -> logger.error("Exception in createOrUpdateScalingPolicyImpl -> ", e)) .onErrorResumeNext(e -> saveStatusOnError(e).andThen(Observable.empty())); } private Observable<String> deleteScalingPolicyWorkflow(AutoScalingPolicy policyToBeDeleted) { Observable<AutoScalingPolicy> cachedPolicyObservable = Observable.just(policyToBeDeleted) .flatMap(autoScalingPolicy -> appAutoScalingClient.deleteScalingPolicy(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()) .andThen(Observable.just(autoScalingPolicy))) .cache(); Observable<AutoScalingPolicy> targetPolicyObservable = cachedPolicyObservable .filter(autoScalingPolicy -> autoScalingPolicy.getPolicyConfiguration().getPolicyType() == PolicyType.TargetTrackingScaling); Observable<AutoScalingPolicy> stepPolicyObservable = cachedPolicyObservable .filter(autoScalingPolicy -> autoScalingPolicy.getPolicyConfiguration().getPolicyType() == PolicyType.StepScaling) .flatMap(autoScalingPolicy -> cloudAlarmClient.deleteAlarm(autoScalingPolicy.getRefId(), autoScalingPolicy.getJobId()) .andThen(Observable.just(autoScalingPolicy))); return Observable.mergeDelayError(targetPolicyObservable, stepPolicyObservable) .flatMap(autoScalingPolicy -> appScalePolicyStore.retrievePoliciesForJob(autoScalingPolicy.getJobId()) .count() .flatMap(c -> { // Last policy - delete target if (c == 1) { return appAutoScalingClient.deleteScalableTarget(autoScalingPolicy.getJobId()) .doOnError(e -> saveStatusOnError(AutoScalePolicyException.errorDeletingTarget(autoScalingPolicy.getPolicyId(), autoScalingPolicy.getJobId(), e.getMessage()))) .andThen(Observable.just(autoScalingPolicy)); } else { return Observable.just(autoScalingPolicy); } })) .flatMap(autoScalingPolicy -> appScalePolicyStore.retrievePolicyForRefId(autoScalingPolicy.getRefId()) .flatMap(currentPolicy -> { if (PolicyStateTransitions.isAllowed(currentPolicy.getStatus(), PolicyStatus.Deleted)) { metrics.reportPolicyStatusTransition(autoScalingPolicy, PolicyStatus.Deleted); return appScalePolicyStore.updatePolicyStatus(autoScalingPolicy.getRefId(), PolicyStatus.Deleted) .andThen(Observable.just(autoScalingPolicy.getRefId())); } else { logger.error("Invalid AutoScaling Policy state - Trying to delete a policy {}", currentPolicy); return Observable.just(autoScalingPolicy.getRefId()); } })) .doOnError(e -> logger.error("Exception in processDeletingPolicyRequests -> ", e)) .onErrorResumeNext(e -> saveStatusOnError(e).andThen(Observable.empty())); } private AppScaleAction sendUpdateTargetAction(AutoScalingPolicy autoScalingPolicy) { AppScaleAction updateTargetAction = AppScaleAction.newBuilder().buildUpdateTargetAction(autoScalingPolicy.getJobId(), autoScalingPolicy.getRefId()); appScaleActionsSubject.onNext(updateTargetAction); return updateTargetAction; } private AppScaleAction sendCreatePolicyAction(AutoScalingPolicy autoScalingPolicy) { AppScaleAction createPolicyAction = AppScaleAction.newBuilder().buildCreatePolicyAction(autoScalingPolicy.getJobId(), autoScalingPolicy); appScaleActionsSubject.onNext(createPolicyAction); return createPolicyAction; } private AppScaleAction sendDeletePolicyAction(AutoScalingPolicy autoScalingPolicy) { AppScaleAction deletePolicyAction = AppScaleAction.newBuilder().buildDeletePolicyAction(autoScalingPolicy.getJobId(), autoScalingPolicy); appScaleActionsSubject.onNext(deletePolicyAction); return deletePolicyAction; } private Boolean isPolicyCreationError(AutoScalePolicyException autoScalePolicyException) { return autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.InvalidScalingPolicy || autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.ErrorCreatingTarget || autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.ErrorCreatingAlarm || autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.ErrorCreatingPolicy || autoScalePolicyException.getErrorCode() == AutoScalePolicyException.ErrorCode.JobManagerError; } }
236
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/AppScaleManagerConfiguration.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.appscale.service; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titusMaster.appScaleManager") public interface AppScaleManagerConfiguration { @DefaultValue("10") long getReconcileTargetsIntervalMins(); @DefaultValue("15") long getReconcileFinishedJobsIntervalMins(); @DefaultValue("120") long getStoreInitTimeoutSeconds(); @DefaultValue("30") long getReconcileAllPendingAndDeletingRequestsIntervalMins(); }
237
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/AppScaleAction.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.appscale.service; import java.util.Optional; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; public class AppScaleAction { public enum ActionType { CREATE_SCALING_POLICY, DELETE_SCALING_POLICY, UPDATE_SCALABLE_TARGET } private final ActionType actionType; private final String jobId; private Optional<AutoScalingPolicy> autoScalingPolicy; private Optional<String> policyRefId; private AppScaleAction(ActionType actionType, String jobId, AutoScalingPolicy autoScalingPolicy) { this.actionType = actionType; this.jobId = jobId; this.autoScalingPolicy = Optional.of(autoScalingPolicy); this.policyRefId = Optional.empty(); } private AppScaleAction(ActionType actionType, String jobId, String policyRefId) { this.actionType = actionType; this.jobId = jobId; this.autoScalingPolicy = Optional.empty(); this.policyRefId = Optional.of(policyRefId); } public ActionType getType() { return this.actionType; } public String getJobId() { return jobId; } public Optional<AutoScalingPolicy> getAutoScalingPolicy() { return autoScalingPolicy; } public Optional<String> getPolicyRefId() { return policyRefId; } public static AppScaleActionsBuilder newBuilder() { return new AppScaleActionsBuilder(); } public static class AppScaleActionsBuilder { private AppScaleActionsBuilder() { } public AppScaleAction buildCreatePolicyAction(String jobId, AutoScalingPolicy autoScalingPolicy) { return new AppScaleAction(ActionType.CREATE_SCALING_POLICY, jobId, autoScalingPolicy); } public AppScaleAction buildDeletePolicyAction(String jobId, AutoScalingPolicy autoScalingPolicy) { return new AppScaleAction(ActionType.DELETE_SCALING_POLICY, jobId, autoScalingPolicy); } public AppScaleAction buildUpdateTargetAction(String jobId, String policyRefId) { return new AppScaleAction(ActionType.UPDATE_SCALABLE_TARGET, jobId, policyRefId); } } }
238
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/PolicyStateTransitions.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.appscale.service; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.netflix.titus.api.appscale.model.PolicyStatus; public class PolicyStateTransitions { private static Map<PolicyStatus, List<PolicyStatus>> allowedTransitions = new HashMap<PolicyStatus, List<PolicyStatus>>() {{ put(PolicyStatus.Applied, new ArrayList<PolicyStatus>() {{ add(PolicyStatus.Pending); add(PolicyStatus.Deleting); }}); put(PolicyStatus.Pending, new ArrayList<PolicyStatus>() {{ add(PolicyStatus.Pending); add(PolicyStatus.Applied); add(PolicyStatus.Error); }}); put(PolicyStatus.Deleting, new ArrayList<PolicyStatus>() {{ add(PolicyStatus.Deleted); }}); put(PolicyStatus.Deleted, Collections.emptyList()); put(PolicyStatus.Error, new ArrayList<PolicyStatus>() {{ add(PolicyStatus.Deleting); add(PolicyStatus.Pending); }}); }}; public static boolean isAllowed(PolicyStatus from, PolicyStatus to) { return allowedTransitions.containsKey(from) && allowedTransitions.get(from).contains(to); } }
239
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/appscale/service/AppScaleManagerMetrics.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.appscale.service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.appscale.model.AutoScalingPolicy; import com.netflix.titus.api.appscale.model.PolicyStatus; import com.netflix.titus.api.appscale.service.AutoScalePolicyException; import com.netflix.titus.common.util.spectator.SpectatorExt; public class AppScaleManagerMetrics { private final Id errorMetricId; private Registry registry; private final AtomicInteger numTargets; private final Counter droppedRequestsCount; private volatile Map<String, SpectatorExt.FsmMetrics<PolicyStatus>> fsmMetricsMap; public AppScaleManagerMetrics(Registry registry) { errorMetricId = registry.createId(METRIC_APPSCALE_ERRORS); fsmMetricsMap = new ConcurrentHashMap<>(); numTargets = registry.gauge(METRIC_TITUS_APPSCALE_NUM_TARGETS, new AtomicInteger(0)); this.registry = registry; droppedRequestsCount = registry.counter(METRIC_BACK_PRESSURE_DROP_COUNT); } private static final String METRIC_APPSCALE_ERRORS = "titus.appScale.errors"; private static final String METRIC_TITUS_APPSCALE_NUM_TARGETS = "titus.appScale.numTargets"; private static final String METRIC_TITUS_APPSCALE_POLICY = "titus.appScale.policy."; private static final String METRIC_BACK_PRESSURE_DROP_COUNT = "titus.appScale.droppedRequests"; private Id stateIdOf(AutoScalingPolicy autoScalingPolicy) { return registry.createId(METRIC_TITUS_APPSCALE_POLICY, "t.jobId", autoScalingPolicy.getJobId()); } private SpectatorExt.FsmMetrics<PolicyStatus> getFsmMetricsForPolicy(AutoScalingPolicy autoScalingPolicy) { return fsmMetricsMap.computeIfAbsent(autoScalingPolicy.getRefId(), fsmMetrics -> { PolicyStatus initialStatus = autoScalingPolicy.getStatus(); // TODO Status is null when the scaling policy is created if (initialStatus == null) { initialStatus = PolicyStatus.Pending; } return SpectatorExt.fsmMetrics(stateIdOf(autoScalingPolicy), policyStatus -> false, initialStatus, registry); }); } public void reportPolicyStatusTransition(AutoScalingPolicy autoScalingPolicy, PolicyStatus targetStatus) { SpectatorExt.FsmMetrics<PolicyStatus> fsmMetricsForPolicy = getFsmMetricsForPolicy(autoScalingPolicy); fsmMetricsForPolicy.transition(targetStatus); } public void reportNewScalableTarget() { numTargets.incrementAndGet(); } public void reportErrorForException(AutoScalePolicyException autoScalePolicyException) { registry.counter(errorMetricId.withTag("errorCode", autoScalePolicyException.getErrorCode().name())).increment(); } public void reportDroppedRequest() { droppedRequestsCount.increment(); } }
240
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/supervisor/SupervisorConfiguration.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.supervisor; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titus.supervisor") public interface SupervisorConfiguration { @DefaultValue("TitusMasterInstanceId") String getTitusMasterInstanceId(); /** * @return whether or not the instance is forced to join into the leader election process instead of going through the * lifecycle states. This property is useful in case the system used to resolve the other instances is not functioning. */ @DefaultValue("false") boolean isForceLeaderElectionEnabled(); }
241
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint/SupervisorEndpointModule.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.supervisor.endpoint; import com.google.inject.AbstractModule; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc.SupervisorServiceImplBase; import com.netflix.titus.master.supervisor.endpoint.grpc.DefaultSupervisorServiceGrpc; public class SupervisorEndpointModule extends AbstractModule { @Override protected void configure() { bind(SupervisorServiceImplBase.class).to(DefaultSupervisorServiceGrpc.class); } }
242
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint/grpc/SupervisorGrpcModelConverters.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.supervisor.endpoint.grpc; import java.util.stream.Collectors; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.MasterStatus; import com.netflix.titus.api.supervisor.model.ServerPort; import com.netflix.titus.api.supervisor.model.event.MasterInstanceRemovedEvent; import com.netflix.titus.api.supervisor.model.event.MasterInstanceUpdateEvent; import com.netflix.titus.api.supervisor.model.event.SupervisorEvent; public class SupervisorGrpcModelConverters { public static MasterInstance toCoreMasterInstance(com.netflix.titus.grpc.protogen.MasterInstance grpcMasterInstance) { return MasterInstance.newBuilder() .withInstanceId(grpcMasterInstance.getInstanceId()) .withInstanceGroupId(grpcMasterInstance.getInstanceGroupId()) .withIpAddress(grpcMasterInstance.getIpAddress()) .withStatus(toCoreStatus(grpcMasterInstance.getStatus())) .withStatusHistory(grpcMasterInstance.getStatusHistoryList().stream().map(SupervisorGrpcModelConverters::toCoreStatus).collect(Collectors.toList())) .withServerPorts(grpcMasterInstance.getServerPortsList().stream().map(SupervisorGrpcModelConverters::toCoreServerPort).collect(Collectors.toList())) .withLabels(grpcMasterInstance.getLabelsMap()) .build(); } public static com.netflix.titus.grpc.protogen.MasterInstance toGrpcMasterInstance(MasterInstance masterInstance) { return com.netflix.titus.grpc.protogen.MasterInstance.newBuilder() .setInstanceId(masterInstance.getInstanceId()) .setInstanceGroupId(masterInstance.getInstanceGroupId()) .setIpAddress(masterInstance.getIpAddress()) .setStatus(toGrpcStatus(masterInstance.getStatus())) .addAllStatusHistory(masterInstance.getStatusHistory().stream().map(SupervisorGrpcModelConverters::toGrpcStatus).collect(Collectors.toList())) .addAllServerPorts(masterInstance.getServerPorts().stream().map(SupervisorGrpcModelConverters::toGrpcServerPort).collect(Collectors.toList())) .putAllLabels(masterInstance.getLabels()) .build(); } private static ServerPort toCoreServerPort(com.netflix.titus.grpc.protogen.ServerPort grpcServerPort) { return ServerPort.newBuilder() .withPortNumber(grpcServerPort.getPortNumber()) .withProtocol(grpcServerPort.getProtocol()) .withSecure(grpcServerPort.getSecure()) .withDescription(grpcServerPort.getDescription()) .build(); } private static com.netflix.titus.grpc.protogen.ServerPort toGrpcServerPort(ServerPort coreServerPort) { return com.netflix.titus.grpc.protogen.ServerPort.newBuilder() .setPortNumber(coreServerPort.getPortNumber()) .setProtocol(coreServerPort.getProtocol()) .setSecure(coreServerPort.isSecure()) .setDescription(coreServerPort.getDescription()) .build(); } public static MasterStatus toCoreStatus(com.netflix.titus.grpc.protogen.MasterStatus grpcStatus) { return MasterStatus.newBuilder() .withState(toCoreState(grpcStatus.getState())) .withMessage(grpcStatus.getReasonMessage()) .withTimestamp(grpcStatus.getTimestamp()) .build(); } public static com.netflix.titus.grpc.protogen.MasterStatus toGrpcStatus(MasterStatus masterStatus) { return com.netflix.titus.grpc.protogen.MasterStatus.newBuilder() .setState(toGrpcState(masterStatus.getState())) .setTimestamp(masterStatus.getTimestamp()) .setReasonCode("<deprecated>") .setReasonMessage(masterStatus.getMessage()) .build(); } public static MasterState toCoreState(com.netflix.titus.grpc.protogen.MasterStatus.MasterState grpcState) { switch (grpcState) { case Starting: return MasterState.Starting; case Inactive: return MasterState.Inactive; case NonLeader: return MasterState.NonLeader; case LeaderActivating: return MasterState.LeaderActivating; case LeaderActivated: return MasterState.LeaderActivated; } throw new IllegalArgumentException("Unrecognized GRPC MasterState state: " + grpcState); } public static com.netflix.titus.grpc.protogen.MasterStatus.MasterState toGrpcState(MasterState state) { switch (state) { case Starting: return com.netflix.titus.grpc.protogen.MasterStatus.MasterState.Starting; case Inactive: return com.netflix.titus.grpc.protogen.MasterStatus.MasterState.Inactive; case NonLeader: return com.netflix.titus.grpc.protogen.MasterStatus.MasterState.NonLeader; case LeaderActivating: return com.netflix.titus.grpc.protogen.MasterStatus.MasterState.LeaderActivating; case LeaderActivated: return com.netflix.titus.grpc.protogen.MasterStatus.MasterState.LeaderActivated; } throw new IllegalArgumentException("Unrecognized core MasterState state: " + state); } public static com.netflix.titus.grpc.protogen.SupervisorEvent toGrpcEvent(SupervisorEvent coreEvent) { if (coreEvent instanceof MasterInstanceUpdateEvent) { return com.netflix.titus.grpc.protogen.SupervisorEvent.newBuilder() .setMasterInstanceUpdate(com.netflix.titus.grpc.protogen.SupervisorEvent.MasterInstanceUpdate.newBuilder() .setInstance(toGrpcMasterInstance(((MasterInstanceUpdateEvent) coreEvent).getMasterInstance())) ) .build(); } if (coreEvent instanceof MasterInstanceRemovedEvent) { return com.netflix.titus.grpc.protogen.SupervisorEvent.newBuilder() .setMasterInstanceRemoved(com.netflix.titus.grpc.protogen.SupervisorEvent.MasterInstanceRemoved.newBuilder() .setInstanceId(((MasterInstanceRemovedEvent) coreEvent).getMasterInstance().getInstanceId()) ) .build(); } throw new IllegalArgumentException("Unrecognized supervisor event: " + coreEvent); } }
243
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint/grpc/DefaultSupervisorServiceGrpc.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.supervisor.endpoint.grpc; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import com.google.protobuf.Empty; import com.netflix.titus.grpc.protogen.MasterInstance; import com.netflix.titus.grpc.protogen.MasterInstanceId; import com.netflix.titus.grpc.protogen.MasterInstances; import com.netflix.titus.grpc.protogen.SupervisorEvent; import com.netflix.titus.grpc.protogen.SupervisorServiceGrpc; import com.netflix.titus.api.supervisor.service.SupervisorOperations; import com.netflix.titus.runtime.endpoint.common.grpc.GrpcUtil; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.ServerCallStreamObserver; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Subscription; import static com.netflix.titus.master.supervisor.endpoint.grpc.SupervisorGrpcModelConverters.toGrpcMasterInstance; import static com.netflix.titus.runtime.endpoint.metadata.CallMetadataUtils.execute; @Singleton public class DefaultSupervisorServiceGrpc extends SupervisorServiceGrpc.SupervisorServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(DefaultSupervisorServiceGrpc.class); private final SupervisorOperations supervisorOperations; private final CallMetadataResolver callMetadataResolver; @Inject public DefaultSupervisorServiceGrpc(SupervisorOperations supervisorOperations, CallMetadataResolver callMetadataResolver) { this.supervisorOperations = supervisorOperations; this.callMetadataResolver = callMetadataResolver; } @Override public void getMasterInstances(Empty request, StreamObserver<MasterInstances> responseObserver) { try { List<MasterInstance> instances = supervisorOperations.getMasterInstances().stream() .map(SupervisorGrpcModelConverters::toGrpcMasterInstance) .collect(Collectors.toList()); responseObserver.onNext(MasterInstances.newBuilder().addAllInstances(instances).build()); responseObserver.onCompleted(); } catch (Exception e) { GrpcUtil.safeOnError(logger, e, responseObserver); } } @Override public void getMasterInstance(MasterInstanceId request, StreamObserver<MasterInstance> responseObserver) { try { responseObserver.onNext(toGrpcMasterInstance(supervisorOperations.getMasterInstance(request.getInstanceId()))); responseObserver.onCompleted(); } catch (Exception e) { GrpcUtil.safeOnError(logger, e, responseObserver); } } @Override public void stopBeingLeader(Empty request, StreamObserver<Empty> responseObserver) { execute(callMetadataResolver, responseObserver, callMetadata -> { try { supervisorOperations.stopBeingLeader(callMetadata); responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(e); } }); } @Override public void observeEvents(Empty request, StreamObserver<SupervisorEvent> responseObserver) { Subscription subscription = supervisorOperations.events() .map(SupervisorGrpcModelConverters::toGrpcEvent) .subscribe( responseObserver::onNext, e -> responseObserver.onError( new StatusRuntimeException(Status.INTERNAL .withDescription("Supervisor event stream terminated with an error") .withCause(e)) ), responseObserver::onCompleted ); ServerCallStreamObserver<SupervisorEvent> serverObserver = (ServerCallStreamObserver<SupervisorEvent>) responseObserver; serverObserver.setOnCancelHandler(subscription::unsubscribe); } }
244
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/endpoint/http/SupervisorResource.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.supervisor.endpoint.http; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.netflix.titus.grpc.protogen.MasterInstance; import com.netflix.titus.master.supervisor.endpoint.grpc.SupervisorGrpcModelConverters; import com.netflix.titus.api.supervisor.service.SupervisorOperations; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api(tags = "Titus Supervisor") @Path("/api/v3/supervisor") @Singleton public class SupervisorResource { private final SupervisorOperations supervisorOperations; private final CallMetadataResolver callMetadataResolver; @Inject public SupervisorResource(SupervisorOperations supervisorOperations, CallMetadataResolver callMetadataResolver) { this.supervisorOperations = supervisorOperations; this.callMetadataResolver = callMetadataResolver; } @GET @ApiOperation("Get all TitusMaster instances") @Path("/instances") public List<MasterInstance> getAllMasterInstances() { return supervisorOperations.getMasterInstances().stream() .map(SupervisorGrpcModelConverters::toGrpcMasterInstance) .collect(Collectors.toList()); } @GET @ApiOperation("Find the TitusMaster instance with the specified id") @Path("/instances/{masterInstanceId}") public MasterInstance getMasterInstance(@PathParam("masterInstanceId") String masterInstanceId) { return supervisorOperations.findMasterInstance(masterInstanceId) .map(SupervisorGrpcModelConverters::toGrpcMasterInstance) .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); } @GET @ApiOperation("Return current leader") @Path("/instances/leader") public MasterInstance getLeader() { return supervisorOperations.findLeader() .map(SupervisorGrpcModelConverters::toGrpcMasterInstance) .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); } @DELETE @ApiOperation("If leader, give up the leadership") @Path("/self/stopBeingLeader") public Response stopBeingLeader() { Optional<CallMetadata> callMetadataOpt = callMetadataResolver.resolve(); boolean validUser = callMetadataOpt.map(cm -> !CallMetadataUtils.isUnknown(cm)).orElse(false); if (!validUser) { return Response.status(Response.Status.FORBIDDEN).entity("Unidentified request").build(); } supervisorOperations.stopBeingLeader(callMetadataOpt.get()); return Response.ok().build(); } }
245
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/DefaultSupervisorOperations.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.supervisor.service; 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.Set; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.governator.LifecycleManager; import com.netflix.titus.api.supervisor.service.LeaderActivator; import com.netflix.titus.api.supervisor.service.MasterMonitor; import com.netflix.titus.api.supervisor.service.SupervisorOperations; import com.netflix.titus.api.supervisor.service.SupervisorServiceException; import com.netflix.titus.common.runtime.SystemLogEvent; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.common.util.SystemExt; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterInstanceFunctions; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.event.MasterInstanceRemovedEvent; import com.netflix.titus.api.supervisor.model.event.MasterInstanceUpdateEvent; import com.netflix.titus.api.supervisor.model.event.SupervisorEvent; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; @Singleton public class DefaultSupervisorOperations implements SupervisorOperations { private static final Logger logger = LoggerFactory.getLogger(DefaultSupervisorOperations.class); private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 10_000; private final LifecycleManager lifecycleManager; private final MasterMonitor masterMonitor; private final LeaderActivator leaderActivator; private final TitusRuntime titusRuntime; @Inject public DefaultSupervisorOperations(LifecycleManager lifecycleManager, MasterMonitor masterMonitor, LeaderActivator leaderActivator, TitusRuntime titusRuntime) { this.lifecycleManager = lifecycleManager; this.masterMonitor = masterMonitor; this.leaderActivator = leaderActivator; this.titusRuntime = titusRuntime; } @Override public List<MasterInstance> getMasterInstances() { return masterMonitor.observeMasters().take(1).toBlocking().first(); } @Override public Optional<MasterInstance> findMasterInstance(String instanceId) { return getMasterInstances().stream() .filter(i -> i.getInstanceId().equals(instanceId)) .findFirst(); } @Override public MasterInstance getMasterInstance(String instanceId) { return findMasterInstance(instanceId).orElseThrow(() -> SupervisorServiceException.masterInstanceNotFound(instanceId)); } @Override public Optional<MasterInstance> findLeader() { return getMasterInstances().stream().filter(i -> MasterState.isLeader(i.getStatus().getState())).findFirst(); } @Override public Observable<SupervisorEvent> events() { return masterMonitor.observeMasters() .compose(ObservableExt.mapWithState(Collections.emptyMap(), this::buildEventList)) .flatMap(Observable::from); } @Override public void stopBeingLeader(CallMetadata callMetadata) { if (!leaderActivator.isLeader()) { logger.warn("System shutdown requested for non-leader node by: {}", callMetadata); throw SupervisorServiceException.notLeader(masterMonitor.getCurrentMasterInstance()); } logger.warn("System shutdown requested for the current leader by: {}", callMetadata); titusRuntime.getSystemLogService().submit(SystemLogEvent.newBuilder() .withPriority(SystemLogEvent.Priority.Warn) .withMessage("System shutdown requested for the leader node") .withComponent(COMPONENT) .withCategory(SystemLogEvent.Category.Transient) .withContext(CallMetadataUtils.asMap(callMetadata)) .build() ); // Make both threads non-daemon so they do not get terminated too early. Thread controllerThread = new Thread("ShutdownController") { @Override public void run() { Thread shutdownThread = new Thread("ShutdownExecutor") { @Override public void run() { lifecycleManager.notifyShutdown(); } }; shutdownThread.setDaemon(false); shutdownThread.start(); try { shutdownThread.join(GRACEFUL_SHUTDOWN_TIMEOUT_MS); } catch (InterruptedException e) { // IGNORE } SystemExt.forcedProcessExit(-1); } }; controllerThread.setDaemon(false); controllerThread.start(); } private Pair<List<SupervisorEvent>, Map<String, MasterInstance>> buildEventList(List<MasterInstance> current, Map<String, MasterInstance> state) { Map<String, MasterInstance> newState = new HashMap<>(); current.forEach(instance -> newState.put(instance.getInstanceId(), instance)); List<SupervisorEvent> events = new ArrayList<>(); // Removed Masters Set<String> removed = CollectionsExt.copyAndRemove(state.keySet(), newState.keySet()); removed.forEach(id -> events.add(new MasterInstanceRemovedEvent(state.get(id)))); // Added Masters Set<String> added = CollectionsExt.copyAndRemove(newState.keySet(), state.keySet()); added.forEach(id -> events.add(new MasterInstanceUpdateEvent(newState.get(id)))); // Compare with the previous state, and build the new one Set<String> changeCandidates = CollectionsExt.copyAndRemove(newState.keySet(), added); changeCandidates.forEach(id -> { if (MasterInstanceFunctions.areDifferent(newState.get(id), state.get(id))) { events.add(new MasterInstanceUpdateEvent(newState.get(id))); } }); logger.debug("Master instances updated: current={}", current); logger.debug("Master instances updated: previous={}", state.values()); logger.debug("Master instances updated: events={}", events); return Pair.of(events, newState); } }
246
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/SupervisorServiceModule.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.supervisor.service; import java.util.Collections; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.MasterStatus; import com.netflix.titus.api.supervisor.model.ServerPort; import com.netflix.titus.api.supervisor.service.LeaderActivator; import com.netflix.titus.api.supervisor.service.LeaderElector; import com.netflix.titus.api.supervisor.service.LocalMasterInstanceResolver; import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver; import com.netflix.titus.api.supervisor.service.MasterMonitor; import com.netflix.titus.api.supervisor.service.SupervisorOperations; import com.netflix.titus.api.supervisor.service.resolver.AlwaysEnabledLocalMasterReadinessResolver; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.NetworkExt; import com.netflix.titus.master.endpoint.grpc.GrpcMasterEndpointConfiguration; import com.netflix.titus.master.supervisor.SupervisorConfiguration; import com.netflix.titus.master.supervisor.service.leader.GuiceLeaderActivator; import com.netflix.titus.master.supervisor.service.leader.ImmediateLeaderElector; import com.netflix.titus.master.supervisor.service.leader.LeaderElectionOrchestrator; import com.netflix.titus.master.supervisor.service.leader.LocalMasterMonitor; import com.netflix.titus.master.supervisor.service.resolver.DefaultLocalMasterInstanceResolver; public class SupervisorServiceModule extends AbstractModule { @Override protected void configure() { bind(LocalMasterReadinessResolver.class).toInstance(AlwaysEnabledLocalMasterReadinessResolver.getInstance()); bind(MasterMonitor.class).to(LocalMasterMonitor.class); bind(LeaderElector.class).to(ImmediateLeaderElector.class).asEagerSingleton(); bind(LeaderActivator.class).to(GuiceLeaderActivator.class); bind(LeaderElectionOrchestrator.class).asEagerSingleton(); bind(SupervisorOperations.class).to(DefaultSupervisorOperations.class); } @Provides @Singleton public SupervisorConfiguration getSupervisorConfiguration(ConfigProxyFactory factory) { return factory.newProxy(SupervisorConfiguration.class); } /** * As MasterInstance data contain a lot of details that are deployment specific, this binding is provided here * for completeness/as an example only. It should be overridden by deployment specific configuration. */ @Provides @Singleton public LocalMasterInstanceResolver getLocalMasterInstanceResolver(SupervisorConfiguration configuration, GrpcMasterEndpointConfiguration grpcServerConfiguration, LocalMasterReadinessResolver localMasterReadinessResolver, TitusRuntime titusRuntime) { String ipAddress = NetworkExt.getLocalIPs().flatMap(ips -> ips.stream().filter(NetworkExt::isIpV4).findFirst()).orElse("127.0.0.1"); ServerPort grpcPort = ServerPort.newBuilder() .withPortNumber(grpcServerConfiguration.getPort()) .withSecure(false) .withProtocol("grpc") .withDescription("TitusMaster GRPC endpoint") .build(); MasterInstance initial = MasterInstance.newBuilder() .withInstanceId(configuration.getTitusMasterInstanceId()) .withInstanceGroupId(configuration.getTitusMasterInstanceId() + "Group") .withIpAddress(ipAddress) .withStatusHistory(Collections.emptyList()) .withStatus(MasterStatus.newBuilder() .withState(MasterState.Starting) .withMessage("Bootstrapping") .withTimestamp(titusRuntime.getClock().wallTime()) .build() ) .withServerPorts(Collections.singletonList(grpcPort)) .build(); return new DefaultLocalMasterInstanceResolver(localMasterReadinessResolver, initial); } }
247
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/leader/ImmediateLeaderElector.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.supervisor.service.leader; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.service.LeaderActivator; import com.netflix.titus.api.supervisor.service.LeaderElector; import rx.Observable; @Singleton public class ImmediateLeaderElector implements LeaderElector { private final LeaderActivator leaderActivator; @Inject public ImmediateLeaderElector(LeaderActivator leaderActivator) { this.leaderActivator = leaderActivator; leaderActivator.becomeLeader(); } @PreDestroy public void shutdown() { leaderActivator.stopBeingLeader(); } @Override public boolean join() { return false; } @Override public boolean leaveIfNotLeader() { return false; } @Override public Observable<MasterState> awaitElection() { return Observable.just(MasterState.LeaderActivated); } }
248
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/leader/GuiceLeaderActivator.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.supervisor.service.leader; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.Injector; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.titus.api.supervisor.service.LeaderActivator; import com.netflix.titus.common.framework.fit.FitFramework; import com.netflix.titus.common.framework.fit.FitInjection; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.SystemExt; import com.netflix.titus.common.util.guice.ActivationLifecycle; import com.netflix.titus.common.util.guice.ContainerEventBus; import com.netflix.titus.common.util.guice.ContainerEventBus.ContainerEventListener; import com.netflix.titus.common.util.guice.ContainerEventBus.ContainerStartedEvent; import com.netflix.titus.common.util.time.Clock; import com.netflix.titus.master.MetricConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * */ @Singleton public class GuiceLeaderActivator implements LeaderActivator, ContainerEventListener<ContainerStartedEvent> { /** * We need to account for situation where {@link #becomeLeader()} is called before container setup is finished. */ private enum State { Starting, Started, Leader, StartedLeader } private static final Logger logger = LoggerFactory.getLogger(GuiceLeaderActivator.class); private final AtomicReference<State> stateRef = new AtomicReference<>(State.Starting); private final Injector injector; private final Clock clock; private final TitusRuntime titusRuntime; private final ActivationLifecycle activationLifecycle; private volatile boolean leader; private volatile boolean activated; private volatile long electionTimestamp = -1; private volatile long activationStartTimestamp = -1; private volatile long activationEndTimestamp = -1; private volatile long activationTime = -1; private final Optional<FitInjection> beforeActivationFitInjection; @Inject public GuiceLeaderActivator(Injector injector, ContainerEventBus eventBus, ActivationLifecycle activationLifecycle, TitusRuntime titusRuntime) { this.injector = injector; this.activationLifecycle = activationLifecycle; this.clock = titusRuntime.getClock(); this.titusRuntime = titusRuntime; Registry registry = titusRuntime.getRegistry(); PolledMeter.using(registry) .withName(MetricConstants.METRIC_LEADER + "isLeaderGauge") .monitorValue(this, self -> self.leader ? 1 : 0); PolledMeter.using(registry) .withName(MetricConstants.METRIC_LEADER + "isActivatedGauge") .monitorValue(this, self -> self.activated ? 1 : 0); PolledMeter.using(registry) .withName(MetricConstants.METRIC_LEADER + "activationTime") .monitorValue(this, GuiceLeaderActivator::getActivationTime); PolledMeter.using(registry) .withName(MetricConstants.METRIC_LEADER + "inActiveStateTime") .monitorValue(this, self -> self.isActivated() ? clock.wallTime() - self.activationEndTimestamp : 0L); FitFramework fit = titusRuntime.getFitFramework(); if (fit.isActive()) { FitInjection beforeActivationFitInjection = fit.newFitInjectionBuilder("beforeActivation") .withDescription("Inject failures after the node becomes the leader, but before the activation process is started") .build(); fit.getRootComponent().getChild(COMPONENT).addInjection(beforeActivationFitInjection); this.beforeActivationFitInjection = Optional.of(beforeActivationFitInjection); } else { this.beforeActivationFitInjection = Optional.empty(); } eventBus.registerListener(this); } @Override public long getElectionTimestamp() { return electionTimestamp; } @Override public long getActivationEndTimestamp() { return activationEndTimestamp; } @Override public long getActivationTime() { if (isActivated()) { return activationTime; } if (!isLeader()) { return -1; } return clock.wallTime() - activationStartTimestamp; } @Override public boolean isLeader() { return leader; } @Override public boolean isActivated() { return activated; } @Override public void becomeLeader() { logger.info("Becoming leader now"); if (stateRef.compareAndSet(State.Starting, State.Leader)) { leader = true; electionTimestamp = clock.wallTime(); return; } if (stateRef.compareAndSet(State.Started, State.StartedLeader)) { leader = true; electionTimestamp = clock.wallTime(); activate(); return; } logger.warn("Unexpected to be told to enter leader mode more than once, ignoring."); } @Override public void stopBeingLeader() { logger.info("Asked to stop being leader now"); if (!leader) { logger.warn("Unexpected to be told to stop being leader when we haven't entered leader mode before, ignoring."); return; } leader = false; activated = false; if (titusRuntime.isSystemExitOnFailure()) { // Various services may have built in-memory state that is currently not easy to revert to initialization state. // Until we create such a lifecycle feature for each service and all of their references, best thing to do is to // exit the process and depend on a watcher process to restart us right away. Especially since restart isn't // very expensive. logger.error("Exiting due to losing leadership after running as leader"); SystemExt.forcedProcessExit(1); } else { deactivate(); } } @Override public void onEvent(ContainerStartedEvent event) { if (stateRef.compareAndSet(State.Starting, State.Started)) { return; } if (stateRef.compareAndSet(State.Leader, State.StartedLeader)) { activate(); return; } logger.warn("ContainerStartedEvent received while in state {}; ignoring", stateRef.get()); } private void activate() { this.activationStartTimestamp = clock.wallTime(); beforeActivationFitInjection.ifPresent(i -> i.beforeImmediate("beforeActivation")); try { try { activationLifecycle.activate(); } catch (Exception e) { stopBeingLeader(); if (titusRuntime.isSystemExitOnFailure()) { // As stopBeingLeader method not always terminates the process, lets make sure it does. SystemExt.forcedProcessExit(-1); } throw e; } } catch (Throwable e) { if (titusRuntime.isSystemExitOnFailure()) { SystemExt.forcedProcessExit(-1); } throw e; } this.activated = true; this.activationEndTimestamp = clock.wallTime(); this.activationTime = activationEndTimestamp - activationStartTimestamp; } private void deactivate() { try { activationLifecycle.deactivate(); } catch (Exception e) { e.printStackTrace(); } } }
249
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/leader/LocalMasterMonitor.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.supervisor.service.leader; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.MasterStatus; import com.netflix.titus.api.supervisor.service.MasterDescription; import com.netflix.titus.api.supervisor.service.MasterMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; import rx.subjects.BehaviorSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; /** * A {@code MasterMonitor} implementation that does not monitor anything. Use this * class for local testing. */ @Singleton public class LocalMasterMonitor implements MasterMonitor { private static final Logger logger = LoggerFactory.getLogger(LocalMasterMonitor.class); private final MasterDescription master; private volatile MasterInstance ownMasterInstance; private volatile List<MasterInstance> masterInstances; private final Subject<List<MasterInstance>, List<MasterInstance>> masterUpdates = new SerializedSubject<>( BehaviorSubject.create(Collections.emptyList()) ); private final Observable<List<MasterInstance>> masterUpdatesObserver = ObservableExt.protectFromMissingExceptionHandlers( masterUpdates.asObservable(), logger ); @Inject public LocalMasterMonitor(MasterDescription masterDescription) { this.master = masterDescription; this.ownMasterInstance = MasterInstance.newBuilder() .withInstanceId(masterDescription.getHostIP()) .withInstanceGroupId("embeddedGroupId") .withIpAddress(masterDescription.getHostIP()) .withStatus(MasterStatus.newBuilder() .withState(MasterState.LeaderActivated) .withMessage("Embedded TitusMaster activated") .build() ) .withStatusHistory(Collections.emptyList()) .build(); this.masterInstances = Collections.singletonList(ownMasterInstance); } @Override public Observable<MasterDescription> getLeaderObservable() { return Observable.just(master); } @Override public MasterDescription getLatestLeader() { return master; } @Override public MasterInstance getCurrentMasterInstance() { return ownMasterInstance; } @Override public Completable updateOwnMasterInstance(MasterInstance self) { return Completable.fromAction(() -> { this.masterInstances = Collections.singletonList(self); masterUpdates.onNext(masterInstances); this.ownMasterInstance = self; }); } @Override public Observable<List<MasterInstance>> observeMasters() { return masterUpdatesObserver; } }
250
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/leader/LeaderElectionOrchestrator.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.supervisor.service.leader; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; 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.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.MasterStatus; import com.netflix.titus.api.supervisor.service.LeaderElector; import com.netflix.titus.api.supervisor.service.LocalMasterInstanceResolver; import com.netflix.titus.api.supervisor.service.MasterMonitor; import com.netflix.titus.common.runtime.TitusRuntime; 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.spectator.SpectatorExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.MetricConstants; import com.netflix.titus.master.supervisor.SupervisorConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.schedulers.Schedulers; @Singleton public class LeaderElectionOrchestrator { private static final Logger logger = LoggerFactory.getLogger(LeaderElectionOrchestrator.class); private static final long MASTER_INITIAL_UPDATE_TIMEOUT_MS = 5_000; private static final long MASTER_STATE_UPDATE_TIMEOUT_MS = 5_000; private final LocalMasterInstanceResolver localMasterInstanceResolver; private final MasterMonitor masterMonitor; private final LeaderElector leaderElector; private final TitusRuntime titusRuntime; private final Scheduler scheduler; private Subscription localMasterUpdateSubscription; private SpectatorExt.FsmMetrics<MasterState> stateFsmMetrics; @Inject public LeaderElectionOrchestrator(SupervisorConfiguration configuration, LocalMasterInstanceResolver localMasterInstanceResolver, MasterMonitor masterMonitor, LeaderElector leaderElector, TitusRuntime titusRuntime) { this( configuration, localMasterInstanceResolver, masterMonitor, leaderElector, fetchInitialMasterInstance(localMasterInstanceResolver), titusRuntime, Schedulers.computation() ); } @VisibleForTesting LeaderElectionOrchestrator(SupervisorConfiguration configuration, LocalMasterInstanceResolver localMasterInstanceResolver, MasterMonitor masterMonitor, LeaderElector leaderElector, MasterInstance initial, TitusRuntime titusRuntime, Scheduler scheduler) { this.localMasterInstanceResolver = localMasterInstanceResolver; this.masterMonitor = masterMonitor; this.leaderElector = leaderElector; this.titusRuntime = titusRuntime; this.scheduler = scheduler; if (configuration.isForceLeaderElectionEnabled()) { if (leaderElector.join()) { logger.info("Joined leader election process due to ForceLeaderElectionEnabled property being true"); } } else { // Synchronously initialize first the local MasterInstance, next subscribe to the stream to react to future changes checkAndRecordInitialMasterInstance(initial); Registry registry = titusRuntime.getRegistry(); this.stateFsmMetrics = SpectatorExt.fsmMetrics( registry.createId(MetricConstants.METRIC_SUPERVISOR + "orchestrator.masterState"), s -> false, initial.getStatus().getState(), registry ); this.localMasterUpdateSubscription = subscribeToLocalMasterUpdateStream(); } } @PreDestroy public void shutdown() { ObservableExt.safeUnsubscribe(localMasterUpdateSubscription); } private static MasterInstance fetchInitialMasterInstance(LocalMasterInstanceResolver localMasterInstanceResolver) { MasterInstance masterInstance = ReactorExt.toObservable(localMasterInstanceResolver.observeLocalMasterInstanceUpdates()) .take(1) .timeout(MASTER_INITIAL_UPDATE_TIMEOUT_MS, TimeUnit.MILLISECONDS, Schedulers.computation()) .toBlocking() .firstOrDefault(null); if (masterInstance == null) { throw new IllegalStateException("Local MasterInstance record not resolved"); } return masterInstance; } private void checkAndRecordInitialMasterInstance(MasterInstance initial) { if (initial == null) { String message = "Couldn't resolve the local MasterInstance data. The result is null"; titusRuntime.getCodeInvariants().inconsistent(message); throw new IllegalStateException(message); } Throwable error = masterMonitor.updateOwnMasterInstance(initial).get(); if (error != null) { logger.error("Could not record local MasterInstance state update", error); throw new IllegalStateException(error); } } private Subscription subscribeToLocalMasterUpdateStream() { Observable<?> updateStream = Observable.merge( ReactorExt.toObservable(localMasterInstanceResolver.observeLocalMasterInstanceUpdates()), leaderElector.awaitElection() ).compose( ObservableExt.mapWithState( (Supplier<MasterInstance>) masterMonitor::getCurrentMasterInstance, (BiFunction<Object, MasterInstance, Pair<Optional<MasterInstance>, MasterInstance>>) (change, currentMaster) -> processChange(change, currentMaster) .map(newMasterInstance -> Pair.of(Optional.of(newMasterInstance), newMasterInstance)) .orElseGet(() -> Pair.of(Optional.empty(), currentMaster)) ) ).flatMapCompletable(this::updateOwnMasterInstanceIfChanged); return titusRuntime.persistentStream(updateStream).subscribe(); } private Optional<MasterInstance> processChange(Object change, MasterInstance currentMaster) { MasterState currentState = currentMaster.getStatus().getState(); // MasterInstance update if (change instanceof MasterInstance) { if (MasterState.isLeader(currentState)) { // If already a leader, ignore further updates return Optional.empty(); } return Optional.of((MasterInstance) change); } // Leader election event if (change instanceof MasterState) { MasterState newState = (MasterState) change; if (!MasterState.isLeader(newState)) { titusRuntime.getCodeInvariants().inconsistent("Expected leader election state, but got: %s", newState); return Optional.empty(); } if (!MasterState.isAfter(currentState, newState)) { titusRuntime.getCodeInvariants().inconsistent("Unexpected leader election state: current=%s, new=%s", currentState, newState); return Optional.empty(); } MasterInstance newMasterInstance = currentMaster.toBuilder() .withStatus(MasterStatus.newBuilder() .withState(newState) .withMessage("Leader activation status change") .withTimestamp(titusRuntime.getClock().wallTime()) .build() ) .withStatusHistory(CollectionsExt.copyAndAdd(currentMaster.getStatusHistory(), currentMaster.getStatus())) .build(); return Optional.of(newMasterInstance); } return Optional.empty(); } private void updateLeaderElectionState(MasterInstance newMasterInstance) { MasterState state = newMasterInstance.getStatus().getState(); stateFsmMetrics.transition(state); if (state == MasterState.NonLeader) { if (leaderElector.join()) { logger.info("Joined leader election process due to MasterInstance state update: {}", newMasterInstance); } } else if (state == MasterState.Inactive) { if (leaderElector.leaveIfNotLeader()) { logger.info("Left leader election process due to MasterInstance state update: {}", newMasterInstance); } } } private Completable updateOwnMasterInstanceIfChanged(Optional<MasterInstance> newMasterOpt) { if (!newMasterOpt.isPresent()) { return Completable.complete(); } MasterInstance newMasterInstance = newMasterOpt.get(); updateLeaderElectionState(newMasterInstance); return masterMonitor .updateOwnMasterInstance(newMasterInstance) .timeout(MASTER_STATE_UPDATE_TIMEOUT_MS, TimeUnit.MILLISECONDS, scheduler) .doOnCompleted(() -> logger.info("Recorded local MasterInstance update: {}", newMasterInstance)); } }
251
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/resolver/DefaultLocalMasterInstanceResolver.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.supervisor.service.resolver; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.MasterInstanceFunctions; import com.netflix.titus.api.supervisor.model.MasterState; import com.netflix.titus.api.supervisor.model.MasterStatus; import com.netflix.titus.api.supervisor.model.ReadinessStatus; import com.netflix.titus.api.supervisor.service.LocalMasterInstanceResolver; import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import static com.netflix.titus.api.supervisor.model.MasterInstanceFunctions.areDifferent; @Singleton public class DefaultLocalMasterInstanceResolver implements LocalMasterInstanceResolver { private static final Logger logger = LoggerFactory.getLogger(DefaultLocalMasterInstanceResolver.class); private final LocalMasterReadinessResolver localMasterReadinessResolver; private final MasterInstance initial; @Inject public DefaultLocalMasterInstanceResolver(LocalMasterReadinessResolver localMasterReadinessResolver, MasterInstance initial) { this.localMasterReadinessResolver = localMasterReadinessResolver; this.initial = initial; } @Override public Flux<MasterInstance> observeLocalMasterInstanceUpdates() { return Flux.defer(() -> { AtomicReference<MasterInstance> lastRef = new AtomicReference<>(initial); return localMasterReadinessResolver.observeLocalMasterReadinessUpdates() .flatMap(update -> { Optional<MasterInstance> refreshedOpt = refresh(lastRef.get(), update); if (refreshedOpt.isPresent()) { MasterInstance refreshed = refreshedOpt.get(); lastRef.set(refreshed); return Flux.just(refreshed); } return Flux.empty(); }); }); } private Optional<MasterInstance> refresh(@Nullable MasterInstance previousMasterInstance, ReadinessStatus currentReadinessStatus) { MasterState newState; switch (currentReadinessStatus.getState()) { case NotReady: newState = MasterState.Starting; break; case Disabled: newState = MasterState.Inactive; break; case Enabled: newState = MasterState.NonLeader; break; default: logger.warn("Unrecognized master readiness state; assuming inactive: {}", currentReadinessStatus.getState()); newState = MasterState.Inactive; } MasterStatus newStatus = MasterStatus.newBuilder() .withState(newState) .withMessage(currentReadinessStatus.getMessage()) .withTimestamp(currentReadinessStatus.getTimestamp()) .build(); if (areDifferent(previousMasterInstance.getStatus(), newStatus)) { MasterInstance newMasterInstance = MasterInstanceFunctions.moveTo(previousMasterInstance, newStatus); logger.info("MasterInstance status change: {}", newMasterInstance); return Optional.of(newMasterInstance); } logger.debug("Refreshed master instance status not changed: status={}", newStatus); return Optional.empty(); } }
252
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/resolver/HealthLocalMasterReadinessResolver.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.supervisor.service.resolver; import java.time.Duration; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.runtime.health.api.HealthCheckAggregator; import com.netflix.titus.api.supervisor.model.MasterInstance; import com.netflix.titus.api.supervisor.model.ReadinessState; import com.netflix.titus.api.supervisor.model.ReadinessStatus; import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver; import com.netflix.titus.api.supervisor.service.resolver.PollingLocalMasterReadinessResolver; import com.netflix.titus.common.framework.scheduler.model.ScheduleDescriptor; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.retry.Retryers; import com.netflix.titus.common.util.time.Clock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; /** * Alters {@link MasterInstance} state based on instance health status. */ @Singleton public class HealthLocalMasterReadinessResolver implements LocalMasterReadinessResolver { private static final Logger logger = LoggerFactory.getLogger(HealthLocalMasterReadinessResolver.class); static final ScheduleDescriptor REFRESH_SCHEDULER_DESCRIPTOR = ScheduleDescriptor.newBuilder() .withName(HealthLocalMasterReadinessResolver.class.getSimpleName()) .withDescription("Local Master state adapter") .withInitialDelay(Duration.ZERO) .withInterval(Duration.ofSeconds(5)) .withRetryerSupplier(() -> Retryers.exponentialBackoff(100, 1_000, TimeUnit.MILLISECONDS, 5)) .withTimeout(Duration.ofSeconds(5)) .withOnErrorHandler((action, error) -> { logger.warn("Cannot refresh health status: {}", error.getMessage()); logger.debug(error.getMessage(), error); }) .build(); private final HealthCheckAggregator healthCheckAggregator; private final Clock clock; private final PollingLocalMasterReadinessResolver poller; @Inject public HealthLocalMasterReadinessResolver(HealthCheckAggregator healthCheckAggregator, TitusRuntime titusRuntime) { this(healthCheckAggregator, REFRESH_SCHEDULER_DESCRIPTOR, titusRuntime, Schedulers.parallel()); } public HealthLocalMasterReadinessResolver(HealthCheckAggregator healthCheckAggregator, ScheduleDescriptor scheduleDescriptor, TitusRuntime titusRuntime, Scheduler scheduler) { this.healthCheckAggregator = healthCheckAggregator; this.clock = titusRuntime.getClock(); this.poller = PollingLocalMasterReadinessResolver.newPollingResolver( refresh(), scheduleDescriptor, titusRuntime, scheduler ); } @PreDestroy public void shutdown() { poller.shutdown(); } @Override public Flux<ReadinessStatus> observeLocalMasterReadinessUpdates() { return poller.observeLocalMasterReadinessUpdates(); } private Mono<ReadinessStatus> refresh() { return Mono.defer(() -> Mono.fromFuture(healthCheckAggregator.check())) .map(health -> { ReadinessStatus.Builder builder = ReadinessStatus.newBuilder().withTimestamp(clock.wallTime()); if (health.isHealthy()) { builder.withState(ReadinessState.Enabled).withMessage("Instance is healthy"); } else { builder.withState(ReadinessState.Disabled).withMessage("Instance is unhealthy: " + health.getHealthResults()); } return builder.build(); }); } }
253
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/supervisor/service/resolver/OnOffLocalMasterReadinessResolver.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.supervisor.service.resolver; import java.time.Duration; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import com.netflix.titus.api.supervisor.model.MasterInstanceFunctions; import com.netflix.titus.api.supervisor.model.ReadinessStatus; import com.netflix.titus.api.supervisor.service.LocalMasterReadinessResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.scheduler.Scheduler; /** * A wrapper to enforce lifecycle state of the wrapped delegate. */ public class OnOffLocalMasterReadinessResolver implements LocalMasterReadinessResolver { private static final Logger logger = LoggerFactory.getLogger(OnOffLocalMasterReadinessResolver.class); private final LocalMasterReadinessResolver delegate; private final Supplier<Boolean> isOn; private final Supplier<ReadinessStatus> enforcedStatusSupplier; private final Duration checkInterval; private final Scheduler scheduler; public OnOffLocalMasterReadinessResolver(LocalMasterReadinessResolver delegate, Supplier<Boolean> isOn, Supplier<ReadinessStatus> enforcedStatusSupplier, Duration checkInterval, Scheduler scheduler) { this.delegate = delegate; this.isOn = isOn; this.enforcedStatusSupplier = enforcedStatusSupplier; this.checkInterval = checkInterval; this.scheduler = scheduler; } @Override public Flux<ReadinessStatus> observeLocalMasterReadinessUpdates() { return Flux.defer(() -> { AtomicReference<ReadinessStatus> lastDelegateRef = new AtomicReference<>(); AtomicReference<ReadinessStatus> lastEmittedRef = new AtomicReference<>(); Flux<ReadinessStatus> onStream = delegate.observeLocalMasterReadinessUpdates() .doOnNext(lastDelegateRef::set) .filter(s -> isOn.get()); Flux<ReadinessStatus> offStream = Flux.interval(checkInterval, scheduler) .filter(s -> !isOn.get() || lastDelegateRef.get() != lastEmittedRef.get()) .map(tick -> isOn.get() ? lastDelegateRef.get() : enforcedStatusSupplier.get()); return Flux.merge(onStream, offStream).doOnNext(update -> { if (MasterInstanceFunctions.areDifferent(lastEmittedRef.get(), update)) { logger.info("Master readiness state change detected: {}", update); } else { logger.debug("Master readiness status not changed: current={}", lastEmittedRef.get()); } lastEmittedRef.set(update); }); }); } }
254
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/store/StoreModule.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.store; import com.google.inject.AbstractModule; import com.netflix.titus.api.appscale.store.AppScalePolicyStore; import com.netflix.titus.api.jobmanager.store.JobStore; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryJobStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryLoadBalancerStore; import com.netflix.titus.runtime.store.v3.memory.InMemoryPolicyStore; public class StoreModule extends AbstractModule { @Override protected void configure() { bind(JobStore.class).to(InMemoryJobStore.class); bind(AppScalePolicyStore.class).to(InMemoryPolicyStore.class); bind(LoadBalancerStore.class).to(InMemoryLoadBalancerStore.class); } }
255
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/endpoint/grpc/GrpcEvictionService.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.eviction.endpoint.grpc; import java.util.Optional; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.eviction.service.EvictionOperations; import com.netflix.titus.grpc.protogen.EvictionQuota; import com.netflix.titus.grpc.protogen.EvictionServiceEvent; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc; import com.netflix.titus.grpc.protogen.ObserverEventRequest; import com.netflix.titus.grpc.protogen.Reference; import com.netflix.titus.grpc.protogen.TaskTerminateRequest; import com.netflix.titus.grpc.protogen.TaskTerminateResponse; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataResolver; import com.netflix.titus.runtime.endpoint.metadata.CallMetadataUtils; import com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.ServerCallStreamObserver; import io.grpc.stub.StreamObserver; import reactor.core.Disposable; import static com.netflix.titus.runtime.endpoint.metadata.CallMetadataUtils.execute; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toCoreReference; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toGrpcEvent; import static com.netflix.titus.runtime.eviction.endpoint.grpc.GrpcEvictionModelConverters.toGrpcEvictionQuota; @Singleton public class GrpcEvictionService extends EvictionServiceGrpc.EvictionServiceImplBase { private final EvictionOperations evictionOperations; private final CallMetadataResolver callMetadataResolver; @Inject public GrpcEvictionService(EvictionOperations evictionOperations, CallMetadataResolver callMetadataResolver) { this.evictionOperations = evictionOperations; this.callMetadataResolver = callMetadataResolver; } @Override public void getEvictionQuota(Reference request, StreamObserver<EvictionQuota> responseObserver) { com.netflix.titus.api.model.reference.Reference coreReference = toCoreReference(request); EvictionQuota evictionQuota; switch (request.getReferenceCase()) { case SYSTEM: case TIER: case CAPACITYGROUP: evictionQuota = toGrpcEvictionQuota(evictionOperations.getEvictionQuota(coreReference)); break; case JOBID: Optional<EvictionQuota> jobQuotaOpt = evictionOperations.findEvictionQuota(coreReference).map(GrpcEvictionModelConverters::toGrpcEvictionQuota); if (!jobQuotaOpt.isPresent()) { responseObserver.onError(new StatusRuntimeException(Status.NOT_FOUND.withDescription("Job not found or no eviction quota associated with the job"))); return; } evictionQuota = jobQuotaOpt.get(); break; case TASKID: Optional<EvictionQuota> taskQuotaOpt = evictionOperations.findEvictionQuota(coreReference).map(GrpcEvictionModelConverters::toGrpcEvictionQuota); if (!taskQuotaOpt.isPresent()) { responseObserver.onError(new StatusRuntimeException(Status.NOT_FOUND.withDescription("Task not found or no eviction quota associated with the job"))); return; } evictionQuota = taskQuotaOpt.get(); break; default: responseObserver.onError(new IllegalArgumentException("Reference type not supported: " + request.getReferenceCase())); return; } responseObserver.onNext(evictionQuota); responseObserver.onCompleted(); } @Override public void terminateTask(TaskTerminateRequest request, StreamObserver<TaskTerminateResponse> responseObserver) { execute(callMetadataResolver, responseObserver, callMetadata -> { evictionOperations.terminateTask(request.getTaskId(), request.getReason(), CallMetadataUtils.toCallerId(callMetadata)).subscribe( next -> { }, responseObserver::onError, () -> { responseObserver.onNext(TaskTerminateResponse.newBuilder() .setAllowed(true) .setReasonCode("normal") .setReasonMessage("Terminating") .build() ); responseObserver.onCompleted(); } ); }); } @Override public void observeEvents(ObserverEventRequest request, StreamObserver<EvictionServiceEvent> responseObserver) { Disposable subscription = evictionOperations.events(request.getIncludeSnapshot()).subscribe( next -> toGrpcEvent(next).ifPresent(responseObserver::onNext), e -> responseObserver.onError( new StatusRuntimeException(Status.INTERNAL .withDescription("Eviction event stream terminated with an error") .withCause(e)) ), responseObserver::onCompleted ); ServerCallStreamObserver<EvictionServiceEvent> serverObserver = (ServerCallStreamObserver<EvictionServiceEvent>) responseObserver; serverObserver.setOnCancelHandler(subscription::dispose); } }
256
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/endpoint
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/endpoint/grpc/EvictionEndpointModule.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.eviction.endpoint.grpc; import com.google.inject.AbstractModule; import com.netflix.titus.grpc.protogen.EvictionServiceGrpc.EvictionServiceImplBase; public class EvictionEndpointModule extends AbstractModule { @Override protected void configure() { bind(EvictionServiceImplBase.class).to(GrpcEvictionService.class); } }
257
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/TaskTerminationExecutorMetrics.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.eviction.service; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.eviction.service.EvictionException; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.MetricConstants; class TaskTerminationExecutorMetrics { private static final String ROOT_NAME = MetricConstants.METRIC_SCHEDULING_EVICTION + "taskTerminationExecutor."; private static final String TERMINATE_TASK = ROOT_NAME + "terminateTask"; private final Registry registry; private final Counter terminatedCounter; private final Id unexpectedErrorId; TaskTerminationExecutorMetrics(TitusRuntime titusRuntime) { this.registry = titusRuntime.getRegistry(); this.terminatedCounter = registry.counter(TERMINATE_TASK, "status", "success"); this.unexpectedErrorId = registry.createId(TERMINATE_TASK, "status", "error"); } void terminated() { terminatedCounter.increment(); } void error(Throwable error) { String errorCode = error instanceof EvictionException ? "" + ((EvictionException) error).getErrorCode() : "unknown"; registry.counter(unexpectedErrorId.withTags("exception", error.getClass().getSimpleName(), "errorCode", errorCode)); } }
258
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/DefaultEvictionOperations.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.eviction.service; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.eviction.model.event.EvictionEvent; import com.netflix.titus.api.eviction.service.EvictionException; import com.netflix.titus.api.eviction.service.EvictionOperations; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.master.eviction.service.quota.QuotaEventEmitter; import com.netflix.titus.master.eviction.service.quota.TitusQuotasManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @Singleton public class DefaultEvictionOperations implements EvictionOperations { private static final Logger logger = LoggerFactory.getLogger(DefaultEvictionOperations.class); private final V3JobOperations jobOperations; private final TitusQuotasManager quotaManager; private final TitusRuntime titusRuntime; private final Scheduler scheduler; private final EvictionServiceConfiguration configuration; private QuotaEventEmitter quotEventEmitter; private TaskTerminationExecutor taskTerminationExecutor; @Inject public DefaultEvictionOperations(EvictionServiceConfiguration configuration, V3JobOperations jobOperations, TitusQuotasManager quotaManager, TitusRuntime titusRuntime) { this.configuration = configuration; this.jobOperations = jobOperations; this.quotaManager = quotaManager; this.titusRuntime = titusRuntime; Executor executor = Executors.newSingleThreadScheduledExecutor(r -> { Thread thread = new Thread(r, DefaultEvictionOperations.class.getSimpleName()); thread.setDaemon(true); return thread; }); this.scheduler = Schedulers.fromExecutor(executor); } @Activator public void enterActiveMode() { this.quotEventEmitter = new QuotaEventEmitter(configuration, jobOperations, quotaManager, titusRuntime); this.taskTerminationExecutor = new TaskTerminationExecutor(configuration, jobOperations, quotaManager, titusRuntime, scheduler); } @PreDestroy public void shutdown() { if (quotaManager != null) { quotaManager.shutdown(); } if (quotEventEmitter != null) { quotEventEmitter.shutdown(); } if (taskTerminationExecutor != null) { taskTerminationExecutor.shutdown(); } scheduler.dispose(); } @Override public EvictionQuota getEvictionQuota(Reference reference) { return quotaManager.findEvictionQuota(reference).orElseThrow(() -> EvictionException.noQuotaFound(reference)); } @Override public Optional<EvictionQuota> findEvictionQuota(Reference reference) { return quotaManager.findEvictionQuota(reference); } @Override public Mono<Void> terminateTask(String taskId, String reason, String callerId) { return taskTerminationExecutor.terminateTask(taskId, reason, callerId); } @Override public Flux<EvictionEvent> events(boolean includeSnapshot) { return ReactorExt.protectFromMissingExceptionHandlers( Flux.merge(quotEventEmitter.events(includeSnapshot), taskTerminationExecutor.events()), logger ); } private EvictionQuota toVeryHighQuota(Reference reference) { return EvictionQuota.newBuilder() .withReference(reference) .withQuota(VERY_HIGH_QUOTA) .build(); } }
259
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/TaskTerminationExecutor.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.eviction.service; import java.time.Duration; import java.util.Optional; import com.netflix.titus.api.eviction.model.event.EvictionEvent; import com.netflix.titus.api.eviction.service.EvictionException; 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.V3JobOperations; import com.netflix.titus.api.jobmanager.service.V3JobOperations.Trigger; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.rx.invoker.ReactorSerializedInvoker; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.master.eviction.service.quota.TitusQuotasManager; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; class TaskTerminationExecutor { private static final Duration TASK_TERMINATE_TIMEOUT = Duration.ofSeconds(5); private static final Duration TASK_EXCESSIVE_RUNNING_TIMEOUT = Duration.ofSeconds(60); private final V3JobOperations jobOperations; private final TitusQuotasManager quotasManager; private final ReactorSerializedInvoker<Void> serializedInvoker; private final DirectProcessor<EvictionEvent> eventProcessor = DirectProcessor.create(); private final EvictionTransactionLog transactionLog; private final TaskTerminationExecutorMetrics metrics; TaskTerminationExecutor(EvictionServiceConfiguration configuration, V3JobOperations jobOperations, TitusQuotasManager quotasManager, TitusRuntime titusRuntime, Scheduler scheduler) { this.jobOperations = jobOperations; this.quotasManager = quotasManager; this.serializedInvoker = ReactorSerializedInvoker.<Void>newBuilder() .withName("taskTerminationExecutor") .withMaxQueueSize(configuration.getTerminationQueueSize()) .withExcessiveRunningTime(TASK_EXCESSIVE_RUNNING_TIMEOUT) .withScheduler(scheduler) .withClock(titusRuntime.getClock()) .withRegistry(titusRuntime.getRegistry()) .build(); this.metrics = new TaskTerminationExecutorMetrics(titusRuntime); this.transactionLog = new EvictionTransactionLog(); } void shutdown() { serializedInvoker.shutdown(Duration.ofSeconds(30)); } Flux<EvictionEvent> events() { return eventProcessor; } public Mono<Void> terminateTask(String taskId, String reason, String callerId) { return findAndVerifyJobAndTask(taskId, reason, callerId) .flatMap(jobTaskPair -> { Job<?> job = jobTaskPair.getLeft(); Task task = jobTaskPair.getRight(); return serializedInvoker .submit(doTerminateTask(taskId, reason, job, task, callerId)) .doOnSuccess(next -> onSuccessfulTermination(job, taskId, reason, callerId)) .doOnError(error -> onTerminationError(job, taskId, reason, callerId, error)); }); } private Mono<Pair<Job<?>, Task>> findAndVerifyJobAndTask(String taskId, String reason, String callerId) { return Mono .defer(() -> Mono.just(checkTaskIsRunningOrThrowAnException(taskId))) .doOnError(error -> onValidationError(taskId, reason, callerId, error)); } private Mono<Void> doTerminateTask(String taskId, String reason, Job<?> job, Task task, String callerId) { return Mono.defer(() -> { ConsumptionResult consumptionResult = quotasManager.tryConsumeQuota(job, task); return consumptionResult.isApproved() ? jobOperations.killTask(taskId, false, false, Trigger.Eviction, CallMetadata.newBuilder().withCallerId(callerId).withCallReason(reason).build()).timeout(TASK_TERMINATE_TIMEOUT) : Mono.error(EvictionException.noAvailableJobQuota(job, consumptionResult.getRejectionReason().get())); }); } private Pair<Job<?>, Task> checkTaskIsRunningOrThrowAnException(String taskId) { Optional<Pair<Job<?>, Task>> jobAndTask = jobOperations.findTaskById(taskId); if (!jobAndTask.isPresent()) { throw EvictionException.taskNotFound(taskId); } Task task = jobAndTask.get().getRight(); TaskState state = task.getStatus().getState(); if (state == TaskState.Accepted) { throw EvictionException.taskNotScheduledYet(task); } if (!TaskState.isBefore(state, TaskState.KillInitiated)) { throw EvictionException.taskAlreadyStopped(task); } return jobAndTask.get(); } /** * When validation error happens, we do not emit any event. */ private void onValidationError(String taskId, String reason, String callerId, Throwable error) { metrics.error(error); transactionLog.logTaskTerminationUnexpectedError(taskId, reason, callerId, error); } private void onSuccessfulTermination(Job<?> job, String taskId, String reason, String callerContext) { metrics.terminated(); transactionLog.logTaskTermination(job, taskId, reason, callerContext); eventProcessor.onNext(EvictionEvent.newSuccessfulTaskTerminationEvent(taskId, reason)); } private void onTerminationError(Job<?> job, String taskId, String reason, String callerId, Throwable error) { metrics.error(error); transactionLog.logTaskTerminationError(job, taskId, reason, callerId, error); eventProcessor.onNext(EvictionEvent.newFailedTaskTerminationEvent(taskId, reason, error)); } }
260
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/EvictionServiceConfiguration.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.eviction.service; import com.netflix.archaius.api.annotations.Configuration; import com.netflix.archaius.api.annotations.DefaultValue; @Configuration(prefix = "titusMaster.eviction") public interface EvictionServiceConfiguration { @DefaultValue("100") long getEventStreamQuotaUpdateIntervalMs(); /** * The queue size for pending task termination requests. Incoming requests above this limit are rejected. * The queue depth should be equal to at least the system disruption budget capacity. */ @DefaultValue("200") int getTerminationQueueSize(); }
261
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/EvictionTransactionLog.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.eviction.service; import com.netflix.titus.api.jobmanager.model.job.Job; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class EvictionTransactionLog { private static final Logger logger = LoggerFactory.getLogger("EvictionTransactionLog"); void logTaskTermination(Job<?> job, String taskId, String reason, String callerId) { doLog(job.getId(), taskId, reason, callerId, "success", "Task terminated"); } void logTaskTerminationError(Job<?> job, String taskId, String reason, String callerId, Throwable error) { doLog(job.getId(), taskId, reason, callerId, "error", error.getMessage()); } void logTaskTerminationUnexpectedError(String taskId, String reason, String callerId, Throwable error) { doLog("?", taskId, reason, callerId, "error", error.getMessage()); } private static void doLog(String jobId, String taskId, String reason, String callerId, String status, String summary) { String message = String.format( "jobId=%s taskId=%s caller=%-15s status=%-7s reason=%-35s summary=%s", jobId, taskId, callerId, status, reason, summary ); logger.info(message); } }
262
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/EvictionServiceModule.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.eviction.service; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.netflix.archaius.ConfigProxyFactory; import com.netflix.titus.api.eviction.service.EvictionOperations; import com.netflix.titus.master.eviction.service.quota.job.ArchaiusEffectiveJobDisruptionBudgetResolver; import com.netflix.titus.master.eviction.service.quota.job.EffectiveJobDisruptionBudgetResolver; import com.netflix.titus.master.eviction.service.quota.system.ArchaiusSystemDisruptionBudgetResolver; import com.netflix.titus.master.eviction.service.quota.system.SystemDisruptionBudgetResolver; import com.netflix.titus.runtime.connector.eviction.EvictionConfiguration; public class EvictionServiceModule extends AbstractModule { @Override protected void configure() { bind(SystemDisruptionBudgetResolver.class).to(ArchaiusSystemDisruptionBudgetResolver.class); bind(EffectiveJobDisruptionBudgetResolver.class).to(ArchaiusEffectiveJobDisruptionBudgetResolver.class); bind(EvictionOperations.class).to(DefaultEvictionOperations.class); } @Provides @Singleton public EvictionServiceConfiguration getEvictionServiceConfiguration(ConfigProxyFactory factory) { return factory.newProxy(EvictionServiceConfiguration.class); } @Provides @Singleton public EvictionConfiguration getEvictionConfiguration(ConfigProxyFactory factory) { return factory.newProxy(EvictionConfiguration.class); } }
263
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/ConsumptionResult.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.eviction.service.quota; import java.util.Objects; import java.util.Optional; public class ConsumptionResult { private static final ConsumptionResult APPROVED = new ConsumptionResult(true, Optional.empty()); private final boolean approved; private final Optional<String> rejectionReason; private ConsumptionResult(boolean approved, Optional<String> rejectionReason) { this.approved = approved; this.rejectionReason = rejectionReason; } public boolean isApproved() { return approved; } public Optional<String> getRejectionReason() { return rejectionReason; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConsumptionResult that = (ConsumptionResult) o; return approved == that.approved && Objects.equals(rejectionReason, that.rejectionReason); } @Override public int hashCode() { return Objects.hash(approved, rejectionReason); } @Override public String toString() { return "ConsumptionResult{" + "approved=" + approved + ", rejectionReason=" + rejectionReason + '}'; } public static ConsumptionResult approved() { return APPROVED; } public static ConsumptionResult rejected(String rejectionReason) { return new ConsumptionResult(false, Optional.of(rejectionReason)); } }
264
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/TitusQuotasManager.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.eviction.service.quota; import java.time.Duration; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.containerhealth.service.ContainerHealthService; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.JobState; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.RegExpExt; import com.netflix.titus.common.util.guice.annotation.Activator; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.common.util.rx.ReactorRetriers; import com.netflix.titus.master.eviction.service.quota.job.EffectiveJobDisruptionBudgetResolver; import com.netflix.titus.master.eviction.service.quota.job.JobQuotaController; import com.netflix.titus.master.eviction.service.quota.system.SystemQuotaController; import com.netflix.titus.runtime.connector.eviction.EvictionConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import static com.netflix.titus.api.eviction.service.ReadOnlyEvictionOperations.VERY_HIGH_QUOTA; import static com.netflix.titus.master.eviction.service.quota.system.SystemQuotaConsumptionResults.OUTSIDE_SYSTEM_TIME_WINDOW; @Singleton public class TitusQuotasManager { private static final Logger logger = LoggerFactory.getLogger(TitusQuotasManager.class); private static final String NAME = TitusQuotasManager.class.getSimpleName(); private static final Duration RETRY_INTERVAL = Duration.ofSeconds(5); private static final ConsumptionResult UNKNOWN_JOB = ConsumptionResult.rejected("Unknown job"); private final V3JobOperations jobOperations; private final EffectiveJobDisruptionBudgetResolver budgetResolver; private final ContainerHealthService containerHealthService; private final SystemQuotaController systemQuotaController; private final TitusRuntime titusRuntime; private final ConcurrentMap<String, JobQuotaController> jobQuotaControllersByJobId = new ConcurrentHashMap<>(); private final Object lock = new Object(); private final Function<String, Matcher> appsExemptFromSystemDisruptionWindowMatcherFactory; private Disposable jobUpdateDisposable; @Inject public TitusQuotasManager(V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver budgetResolver, ContainerHealthService containerHealthService, SystemQuotaController systemQuotaController, EvictionConfiguration evictionConfiguration, TitusRuntime titusRuntime) { this.budgetResolver = budgetResolver; this.containerHealthService = containerHealthService; this.systemQuotaController = systemQuotaController; this.jobOperations = jobOperations; this.appsExemptFromSystemDisruptionWindowMatcherFactory = RegExpExt.dynamicMatcher(evictionConfiguration::getAppsExemptFromSystemDisruptionWindow, "titus.eviction.appsExemptFromSystemDisruptionWindow", Pattern.DOTALL, logger); this.titusRuntime = titusRuntime; } @Activator public void enterActiveMode() { this.jobUpdateDisposable = jobOperations.observeJobsReactor() .filter(event -> event instanceof JobUpdateEvent) .map(event -> (Job) event.getCurrent()) .transformDeferred(ReactorExt.head(jobOperations::getJobs)) .transformDeferred(ReactorRetriers.instrumentedRetryer(NAME, RETRY_INTERVAL, logger)) .subscribe(this::updateJobController); } @PreDestroy public void shutdown() { ReactorExt.safeDispose(jobUpdateDisposable); } public ConsumptionResult tryConsumeQuota(Job<?> job, Task task) { JobQuotaController jobQuotaController = jobQuotaControllersByJobId.get(job.getId()); if (jobQuotaController == null) { return UNKNOWN_JOB; } String taskId = task.getId(); return tryConsumeSystemAndJobQuota(jobQuotaController, job, taskId); } public Optional<EvictionQuota> findEvictionQuota(Reference reference) { switch (reference.getLevel()) { case System: return Optional.of(systemQuotaController.getQuota(Reference.system())); case Tier: case CapacityGroup: return Optional.of(EvictionQuota.newBuilder().withQuota(VERY_HIGH_QUOTA).withReference(reference).withMessage("Not supported yet").build()); case Job: JobQuotaController jobQuotaController = jobQuotaControllersByJobId.get(reference.getName()); return jobQuotaController == null ? Optional.empty() : Optional.of(jobQuotaController.getQuota(reference)); case Task: return jobOperations.findTaskById(reference.getName()) .flatMap(jobTaskPair -> { JobQuotaController taskQuotaController = jobQuotaControllersByJobId.get(jobTaskPair.getLeft().getId()); return taskQuotaController == null ? Optional.empty() : Optional.of(taskQuotaController.getQuota(reference)); }); } return Optional.empty(); } private void updateJobController(Job newJob) { if (newJob.getStatus().getState() != JobState.Finished) { updateRunningJobController(newJob); } else { jobQuotaControllersByJobId.remove(newJob.getId()); } } private void updateRunningJobController(Job<?> newJob) { JobQuotaController jobQuotaController = jobQuotaControllersByJobId.get(newJob.getId()); if (jobQuotaController != null) { jobQuotaControllersByJobId.put(newJob.getId(), jobQuotaController.update(newJob)); } else { jobQuotaControllersByJobId.put(newJob.getId(), new JobQuotaController(newJob, jobOperations, budgetResolver, containerHealthService, titusRuntime)); } } @VisibleForTesting ConsumptionResult tryConsumeSystemAndJobQuota(JobQuotaController jobQuotaController, Job<?> job, String taskId) { synchronized (lock) { ConsumptionResult jobResult = jobQuotaController.consume(taskId); ConsumptionResult systemResult = systemQuotaController.consume(taskId); if (isJobExemptFromSystemDisruptionWindow(job)) { if (!systemResult.isApproved() && systemResult.getRejectionReason().isPresent() && systemResult.getRejectionReason().get().equals(OUTSIDE_SYSTEM_TIME_WINDOW.getRejectionReason().get())) { systemResult = ConsumptionResult.approved(); } } if (systemResult.isApproved() && jobResult.isApproved()) { return jobResult; } if (!systemResult.isApproved() && !jobResult.isApproved()) { return ConsumptionResult.rejected(String.format( "No job and system quota: {systemQuota=%s, jobQuota=%s}", systemResult.getRejectionReason().get(), jobResult.getRejectionReason().get() )); } if (systemResult.isApproved()) { systemQuotaController.giveBackConsumedQuota(taskId); return jobResult; } jobQuotaController.giveBackConsumedQuota(taskId); return systemResult; } } @VisibleForTesting boolean isJobExemptFromSystemDisruptionWindow(Job<?> job) { String applicationName = job.getJobDescriptor().getApplicationName(); return appsExemptFromSystemDisruptionWindowMatcherFactory.apply(applicationName).matches(); } }
265
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/QuotaTracker.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.eviction.service.quota; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.model.reference.Reference; /** * {@link QuotaTracker} provides information about the available quota. If the quota counter is managed explicitly, * the {@link QuotaController} provides an additional method to consume the quota. For other cases, the quota is computed from * other information and cannot be changed directly. For example, the quota for tasks that can be terminated is a function * of tasks being in healthy and unhealthy state. Terminating a task means the quota will be decreased by one. */ public interface QuotaTracker { /** * Returns current quota. */ EvictionQuota getQuota(Reference reference); }
266
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/QuotaEventEmitter.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.eviction.service.quota; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.eviction.model.event.EvictionEvent; import com.netflix.titus.api.eviction.model.event.EvictionQuotaEvent; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.reference.Reference; 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.retry.Retryers; import com.netflix.titus.master.eviction.service.EvictionServiceConfiguration; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; /** * {@link QuotaEventEmitter} emits quota updates at a regular interval. It is accomplished by polling periodically * all quota providers and computing the difference between the last and current state. */ @Singleton public class QuotaEventEmitter { private static final ScheduleDescriptor SCHEDULE_DESCRIPTOR = ScheduleDescriptor.newBuilder() .withName(QuotaEventEmitter.class.getSimpleName()) .withDescription("Quota update events") .withInterval(Duration.ofSeconds(1)) .withRetryerSupplier(Retryers::never) .withTimeout(Duration.ofSeconds(5)) .build(); private final V3JobOperations jobOperations; private final TitusQuotasManager quotasManager; private final ScheduleReference scheduleReference; @VisibleForTesting final Set<SinkHolder> eventSubscriberSinks = Sets.newConcurrentHashSet(); @Inject public QuotaEventEmitter(EvictionServiceConfiguration configuration, V3JobOperations jobOperations, TitusQuotasManager quotasManager, TitusRuntime titusRuntime) { this.jobOperations = jobOperations; this.quotasManager = quotasManager; this.scheduleReference = titusRuntime.getLocalScheduler().schedule( SCHEDULE_DESCRIPTOR.toBuilder() .withInterval(Duration.ofMillis(configuration.getEventStreamQuotaUpdateIntervalMs())) .build(), this::refresh, true ); } @PreDestroy public void shutdown() { scheduleReference.cancel(); } public Flux<EvictionEvent> events(boolean includeSnapshot) { return Flux.create(sink -> { Preconditions.checkState(scheduleReference != null && !scheduleReference.isClosed()); eventSubscriberSinks.add(new SinkHolder(sink, includeSnapshot)); sink.onDispose(() -> eventSubscriberSinks.remove(sink)); }); } private void refresh(ExecutionContext context) { eventSubscriberSinks.forEach(sinkHolder -> { if (sinkHolder.getSink().isCancelled()) { eventSubscriberSinks.remove(sinkHolder); } else { sinkHolder.refresh(); } }); } private class SinkHolder { private final FluxSink<EvictionEvent> sink; private Map<Reference, EvictionQuota> emittedQuotas = Collections.emptyMap(); private boolean includeSnapshot; private SinkHolder(FluxSink<EvictionEvent> sink, boolean includeSnapshot) { this.sink = sink; this.includeSnapshot = includeSnapshot; } private FluxSink<EvictionEvent> getSink() { return sink; } public void refresh() { try { if (includeSnapshot) { firstRefreshWithSnapshot(); } else if (emittedQuotas.isEmpty()) { refreshIfNoPreviousEmits(); } else { refreshWithPreviousEmits(); } } catch (Exception e) { sink.error(e); eventSubscriberSinks.remove(this); } } private void firstRefreshWithSnapshot() { HashMap<Reference, EvictionQuota> newlyEmittedQuotas = new HashMap<>(); buildSnapshot().forEach(event -> { sink.next(event); newlyEmittedQuotas.put(event.getQuota().getReference(), event.getQuota()); }); sink.next(EvictionEvent.newSnapshotEndEvent()); this.includeSnapshot = false; this.emittedQuotas = newlyEmittedQuotas; } private void refreshIfNoPreviousEmits() { HashMap<Reference, EvictionQuota> newlyEmittedQuotas = new HashMap<>(); buildSnapshot().forEach(event -> { sink.next(event); newlyEmittedQuotas.put(event.getQuota().getReference(), event.getQuota()); }); this.emittedQuotas = newlyEmittedQuotas; } private void refreshWithPreviousEmits() { HashMap<Reference, EvictionQuota> newlyEmittedQuotas = new HashMap<>(); buildSnapshot().forEach(event -> { EvictionQuota quota = event.getQuota(); EvictionQuota previous = emittedQuotas.get(quota.getReference()); if (previous == null || quota.getQuota() != previous.getQuota()) { sink.next(event); } newlyEmittedQuotas.put(quota.getReference(), quota); }); this.emittedQuotas = newlyEmittedQuotas; } private List<EvictionQuotaEvent> buildSnapshot() { List<EvictionQuotaEvent> snapshot = new ArrayList<>(); snapshot.add(EvictionEvent.newQuotaEvent(quotasManager.findEvictionQuota(Reference.system()).get())); jobOperations.getJobs() .forEach(job -> quotasManager .findEvictionQuota(Reference.job(job.getId())) .ifPresent(quota -> snapshot.add(EvictionEvent.newQuotaEvent(quota))) ); return snapshot; } } }
267
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/TimeWindowQuotaTracker.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.eviction.service.quota; import java.util.List; import java.util.function.Supplier; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindowFunctions; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; /** * Time window quota oscillates between two states. No quota, if an instant is outside of the configured time * windows, or unlimited quota if it is within the configured time windows. */ public class TimeWindowQuotaTracker implements QuotaTracker { private final Supplier<Boolean> predicate; public TimeWindowQuotaTracker(List<TimeWindow> timeWindows, TitusRuntime titusRuntime) { this.predicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, timeWindows); } @Override public EvictionQuota getQuota(Reference reference) { return predicate.get() ? EvictionQuota.unlimited(reference) : EvictionQuota.newBuilder().withReference(reference).withQuota(0).withMessage("outside time window").build(); } }
268
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/QuotaController.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.eviction.service.quota; import com.netflix.titus.api.model.reference.Reference; /** * An extension of {@link QuotaTracker} which allows the quota to be directly consumed. */ public interface QuotaController<DESCRIPTOR> extends QuotaTracker { /** * Returns quota consumption result for the given task. As {@link #getQuota(Reference)} is an aggregate, it is * possible that the quota value is greater than zero, but the task consumption fails. This may happen if there * are task level restrictions. */ ConsumptionResult consume(String taskId); /** * Return quota, which was previously consumed by the given task. */ void giveBackConsumedQuota(String taskId); /** * Produces a new {@link QuotaController} instance with the updated configuration. The state from the current * instance is carried over with possible adjustments. For example, if the {@link QuotaController} tracks * how many containers can be terminated per hour, the number of terminated containers within the last hour * would be copied into the new {@link QuotaController} instance. */ default QuotaController<DESCRIPTOR> update(DESCRIPTOR newDescriptor) { throw new IllegalStateException("Not directly updatable quota controller: type=" + getClass().getSimpleName()); } }
269
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/SystemQuotaController.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.eviction.service.quota.system; import java.time.Duration; import java.util.Collections; 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.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.eviction.model.SystemDisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindowFunctions; import com.netflix.titus.api.model.TokenBucketPolicies; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.SystemLogEvent; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.limiter.tokenbucket.TokenBucket; import com.netflix.titus.common.util.rx.ReactorExt; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.master.eviction.service.quota.QuotaController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.Disposable; import static com.netflix.titus.common.util.rx.ReactorRetriers.instrumentedRetryer; import static com.netflix.titus.master.eviction.service.quota.system.SystemQuotaConsumptionResults.OUTSIDE_SYSTEM_TIME_WINDOW; import static com.netflix.titus.master.eviction.service.quota.system.SystemQuotaConsumptionResults.QUOTA_LIMIT_EXCEEDED; @Singleton public class SystemQuotaController implements QuotaController<Void> { private static final Logger logger = LoggerFactory.getLogger(SystemQuotaController.class); private static final Duration BOOTSTRAP_TIMEOUT = Duration.ofSeconds(5); private static final Duration DEFAULT_RETRY_INTERVAL = Duration.ofSeconds(5); private static final String NAME = "system"; private final TitusRuntime titusRuntime; private final SystemQuotaMetrics metrics; private final Disposable resolverDisposable; private volatile SystemDisruptionBudget disruptionBudget; private volatile String quotaMessage; private volatile Supplier<Boolean> inTimeWindowPredicate; private volatile TokenBucket systemTokenBucket; @Inject public SystemQuotaController(SystemDisruptionBudgetResolver systemDisruptionBudgetResolver, TitusRuntime titusRuntime) { this(systemDisruptionBudgetResolver, DEFAULT_RETRY_INTERVAL, titusRuntime); } @VisibleForTesting SystemQuotaController(SystemDisruptionBudgetResolver systemDisruptionBudgetResolver, Duration retryInterval, TitusRuntime titusRuntime) { this.titusRuntime = titusRuntime; this.disruptionBudget = systemDisruptionBudgetResolver.resolve().timeout(BOOTSTRAP_TIMEOUT).blockFirst(); resetDisruptionBudget(disruptionBudget); this.metrics = new SystemQuotaMetrics(this, titusRuntime); this.resolverDisposable = systemDisruptionBudgetResolver.resolve() .transformDeferred(instrumentedRetryer("systemDisruptionBudgetResolver", retryInterval, logger)) .subscribe(next -> { try { resetDisruptionBudget(next); } catch (Exception e) { logger.warn("Invalid system disruption budget configuration: ", e); } }); } private void resetDisruptionBudget(SystemDisruptionBudget newDisruptionBudget) { this.disruptionBudget = newDisruptionBudget; this.systemTokenBucket = newTokenBucket(newDisruptionBudget); this.inTimeWindowPredicate = TimeWindowFunctions.isInTimeWindowPredicate(titusRuntime, disruptionBudget.getTimeWindows()); this.quotaMessage = String.format("System quota token bucket: capacity=%s, refillStrategy=%s", systemTokenBucket.getCapacity(), systemTokenBucket.getRefillStrategy() ); } @PreDestroy public void shutdown() { metrics.shutdown(); ReactorExt.safeDispose(resolverDisposable); } @Override public ConsumptionResult consume(String taskId) { try { if (!inTimeWindowPredicate.get()) { return OUTSIDE_SYSTEM_TIME_WINDOW; } return systemTokenBucket.tryTake(1) ? ConsumptionResult.approved() : QUOTA_LIMIT_EXCEEDED; } catch (IllegalArgumentException e) { return QUOTA_LIMIT_EXCEEDED; } } @Override public void giveBackConsumedQuota(String taskId) { systemTokenBucket.refill(1); } @Override public EvictionQuota getQuota(Reference reference) { EvictionQuota.Builder quotaBuilder = EvictionQuota.newBuilder().withReference(reference); if (!inTimeWindowPredicate.get()) { return quotaBuilder.withQuota(0).withMessage(OUTSIDE_SYSTEM_TIME_WINDOW.getRejectionReason().get()).build(); } if (systemTokenBucket.getNumberOfTokens() <= 0) { return quotaBuilder.withQuota(0).withMessage(QUOTA_LIMIT_EXCEEDED.getRejectionReason().get()).build(); } return quotaBuilder.withQuota(systemTokenBucket.getNumberOfTokens()).withMessage(quotaMessage).build(); } /** * Exposed for metrics collection (see {@link SystemQuotaMetrics}). */ SystemDisruptionBudget getDisruptionBudget() { return disruptionBudget; } private TokenBucket newTokenBucket(SystemDisruptionBudget disruptionBudget) { logger.info("Configuring new system disruption budget: {}", disruptionBudget); titusRuntime.getSystemLogService().submit(SystemLogEvent.newBuilder() .withComponent("eviction") .withPriority(SystemLogEvent.Priority.Info) .withMessage("System disruption budget update: " + disruptionBudget) .withCategory(SystemLogEvent.Category.Other) .withTags(Collections.singleton("eviction")) .build() ); return TokenBucketPolicies.newTokenBucket(NAME, disruptionBudget.getTokenBucketPolicy()); } }
270
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/SystemQuotaMetrics.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.eviction.service.quota.system; 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.FixedIntervalTokenBucketRefillPolicy; import com.netflix.titus.api.model.TokenBucketRefillPolicy; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.MetricConstants; class SystemQuotaMetrics { private static final String ROOT_NAME = MetricConstants.METRIC_SCHEDULING_EVICTION + "systemQuota."; private final Registry registry; private final Id tokenBucketCapacityId; private final Id tokenBucketRefillRateId; private final Id quotaLevelId; SystemQuotaMetrics(SystemQuotaController systemQuotaController, TitusRuntime titusRuntime) { this.registry = titusRuntime.getRegistry(); this.tokenBucketCapacityId = registry.createId(ROOT_NAME + "tokenBucket.capacity"); PolledMeter.using(registry) .withId(tokenBucketCapacityId) .monitorValue(systemQuotaController, sqc -> systemQuotaController.getDisruptionBudget().getTokenBucketPolicy().getCapacity()); this.tokenBucketRefillRateId = registry.createId(ROOT_NAME + "tokenBucket.refillRatePerSec"); PolledMeter.using(registry) .withId(tokenBucketRefillRateId) .monitorValue(systemQuotaController, sqc -> { TokenBucketRefillPolicy refillPolicy = systemQuotaController.getDisruptionBudget().getTokenBucketPolicy().getRefillPolicy(); if (refillPolicy instanceof FixedIntervalTokenBucketRefillPolicy) { FixedIntervalTokenBucketRefillPolicy fixed = (FixedIntervalTokenBucketRefillPolicy) refillPolicy; return fixed.getNumberOfTokensPerInterval() / (fixed.getIntervalMs() / 1000D); } return 0; }); this.quotaLevelId = registry.createId(ROOT_NAME + "available"); PolledMeter.using(registry) .withId(quotaLevelId) .monitorValue(systemQuotaController, sqc -> systemQuotaController.getQuota(Reference.system()).getQuota()); } void shutdown() { PolledMeter.remove(registry, tokenBucketCapacityId); PolledMeter.remove(registry, tokenBucketRefillRateId); PolledMeter.remove(registry, quotaLevelId); } }
271
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/SystemDisruptionBudgetResolver.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.eviction.service.quota.system; import com.netflix.titus.api.eviction.model.SystemDisruptionBudget; import reactor.core.publisher.Flux; /** * Resolver of the system disruption budget. */ public interface SystemDisruptionBudgetResolver { /** * For each system disruption budget change, emits one item. */ Flux<SystemDisruptionBudget> resolve(); }
272
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/SystemQuotaConsumptionResults.java
package com.netflix.titus.master.eviction.service.quota.system; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.runtime.connector.eviction.EvictionRejectionReasons; public class SystemQuotaConsumptionResults { public static final ConsumptionResult QUOTA_LIMIT_EXCEEDED = ConsumptionResult.rejected(EvictionRejectionReasons.LIMIT_EXCEEDED.getReasonMessage()); public static final ConsumptionResult OUTSIDE_SYSTEM_TIME_WINDOW = ConsumptionResult.rejected(EvictionRejectionReasons.SYSTEM_WINDOW_CLOSED.getReasonMessage()); }
273
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/SystemDisruptionBudgetDescriptor.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.eviction.service.quota.system; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow; public class SystemDisruptionBudgetDescriptor { private final long refillRatePerSecond; private final long capacity; private final List<TimeWindow> timeWindows; @JsonCreator public SystemDisruptionBudgetDescriptor(@JsonProperty("refillRatePerSecond") long refillRatePerSecond, @JsonProperty("capacity") long capacity, @JsonProperty("timeWindows") List<TimeWindow> timeWindows) { this.refillRatePerSecond = refillRatePerSecond; this.capacity = capacity; this.timeWindows = timeWindows; } public long getRefillRatePerSecond() { return refillRatePerSecond; } public long getCapacity() { return capacity; } public List<TimeWindow> getTimeWindows() { return timeWindows; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SystemDisruptionBudgetDescriptor that = (SystemDisruptionBudgetDescriptor) o; return refillRatePerSecond == that.refillRatePerSecond && capacity == that.capacity && Objects.equals(timeWindows, that.timeWindows); } @Override public int hashCode() { return Objects.hash(refillRatePerSecond, capacity, timeWindows); } @Override public String toString() { return "SystemDisruptionBudgetDescriptor{" + "refillRatePerSecond=" + refillRatePerSecond + ", capacity=" + capacity + ", timeWindows=" + timeWindows + '}'; } }
274
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/system/ArchaiusSystemDisruptionBudgetResolver.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.eviction.service.quota.system; import java.util.Collections; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import com.google.common.annotations.VisibleForTesting; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyRepository; import com.netflix.titus.api.eviction.model.SystemDisruptionBudget; import com.netflix.titus.api.eviction.service.EvictionException; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.Day; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.TimeWindow; import com.netflix.titus.api.json.ObjectMappers; import com.netflix.titus.api.model.FixedIntervalTokenBucketRefillPolicy; import com.netflix.titus.api.model.TokenBucketPolicy; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.util.StringExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.ReplayProcessor; import static com.netflix.titus.api.eviction.model.SystemDisruptionBudget.newBasicSystemDisruptionBudget; @Singleton public class ArchaiusSystemDisruptionBudgetResolver implements SystemDisruptionBudgetResolver { private static final Logger logger = LoggerFactory.getLogger(ArchaiusSystemDisruptionBudgetResolver.class); public static final String PROPERTY_KEY = "titusMaster.eviction.systemDisruptionBudget"; private static final SystemDisruptionBudget DEFAULT_SYSTEM_DISRUPTION_BUDGET = newBasicSystemDisruptionBudget( 50, 500, TimeWindow.newBuilder() .withDays(Day.weekdays()) .withwithHourlyTimeWindows(8, 16) .withTimeZone("PST") .build() ); private final Property.Subscription subscription; private final ReplayProcessor<SystemDisruptionBudget> budgetEmitter; @Inject public ArchaiusSystemDisruptionBudgetResolver(PropertyRepository repository) { this.budgetEmitter = ReplayProcessor.cacheLastOrDefault(initialBudget(repository)); this.subscription = repository.get(PROPERTY_KEY, String.class).subscribe(this::processUpdate); } @PreDestroy public void shutdown() { subscription.unsubscribe(); } @Override public Flux<SystemDisruptionBudget> resolve() { return budgetEmitter; } private SystemDisruptionBudget initialBudget(PropertyRepository repository) { Property<String> property = repository.get(PROPERTY_KEY, String.class); if (property == null || StringExt.isEmpty(property.get())) { return DEFAULT_SYSTEM_DISRUPTION_BUDGET; } try { return parse(property.get()); } catch (Exception e) { throw EvictionException.badConfiguration("invalid system disruption budget configuration (%s)", e.getMessage()); } } private void processUpdate(String newValue) { try { budgetEmitter.onNext(parse(newValue)); } catch (Exception e) { logger.warn("Invalid system disruption budget configured: newValue='{}', error={}", newValue, e.getMessage()); } } private SystemDisruptionBudget parse(String newValue) throws Exception { SystemDisruptionBudgetDescriptor descriptor = ObjectMappers.storeMapper().readValue(newValue, SystemDisruptionBudgetDescriptor.class); if (descriptor.getRefillRatePerSecond() < 0) { throw EvictionException.badConfiguration("system disruption budget refills < 0"); } if (descriptor.getCapacity() < 0) { throw EvictionException.badConfiguration("system disruption budget capacity < 0"); } return toDisruptionBudget(descriptor); } @VisibleForTesting static SystemDisruptionBudget toDisruptionBudget(SystemDisruptionBudgetDescriptor descriptor) { return SystemDisruptionBudget.newBuilder() .withReference(Reference.system()) .withTokenBucketDescriptor(TokenBucketPolicy.newBuilder() .withCapacity(descriptor.getCapacity()) .withInitialNumberOfTokens(0) .withRefillPolicy(FixedIntervalTokenBucketRefillPolicy.newBuilder() .withIntervalMs(1_000) .withNumberOfTokensPerInterval(descriptor.getRefillRatePerSecond()) .build() ) .build() ) .withTimeWindows(descriptor.getTimeWindows() != null ? descriptor.getTimeWindows() : Collections.emptyList()) .build(); } }
275
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/AbstractRatePerIntervalRateController.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.eviction.service.quota.job; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.DateTimeExt; import com.netflix.titus.common.util.histogram.RollingCount; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.master.eviction.service.quota.QuotaController; public abstract class AbstractRatePerIntervalRateController implements QuotaController<Job<?>> { private static final int RESOLUTION = 20; private final long intervalMs; private final long evictionsPerInterval; private final RollingCount rollingCount; private final ConsumptionResult rejectionResult; private final TitusRuntime titusRuntime; protected AbstractRatePerIntervalRateController(Job<?> job, long intervalMs, long evictionsPerInterval, TitusRuntime titusRuntime) { this.intervalMs = intervalMs; this.evictionsPerInterval = evictionsPerInterval; this.titusRuntime = titusRuntime; this.rollingCount = RollingCount.rollingWindow(intervalMs, RESOLUTION, titusRuntime.getClock().wallTime()); this.rejectionResult = buildRejectionResult(job, intervalMs, evictionsPerInterval); } protected AbstractRatePerIntervalRateController(Job<?> newJob, long intervalMs, long evictionsPerInterval, AbstractRatePerIntervalRateController previous) { this.intervalMs = intervalMs; this.evictionsPerInterval = evictionsPerInterval; this.titusRuntime = previous.titusRuntime; if (intervalMs == previous.intervalMs) { this.rollingCount = previous.rollingCount; } else { long now = titusRuntime.getClock().wallTime(); this.rollingCount = RollingCount.rollingWindow(intervalMs, RESOLUTION, titusRuntime.getClock().wallTime()); rollingCount.add(Math.min(evictionsPerInterval, previous.rollingCount.getCounts(now)), now); } this.rejectionResult = buildRejectionResult(newJob, intervalMs, evictionsPerInterval); } @Override public EvictionQuota getQuota(Reference reference) { long quota = getQuota(titusRuntime.getClock().wallTime()); return quota > 0 ? EvictionQuota.newBuilder().withReference(reference).withQuota(quota).withMessage("Per interval limit %s", evictionsPerInterval).build() : EvictionQuota.newBuilder().withReference(reference).withQuota(0).withMessage(rejectionResult.getRejectionReason().get()).build(); } @Override public ConsumptionResult consume(String taskId) { long now = titusRuntime.getClock().wallTime(); if (getQuota(now) >= 1) { rollingCount.addOne(now); return ConsumptionResult.approved(); } return rejectionResult; } @Override public void giveBackConsumedQuota(String taskId) { rollingCount.add(-1, titusRuntime.getClock().wallTime()); } private ConsumptionResult buildRejectionResult(Job<?> job, long intervalMs, long rate) { return ConsumptionResult.rejected(String.format( "Exceeded the number of tasks that can be evicted in %s (limit=%s, rate limiter type=%s)", DateTimeExt.toTimeUnitString(intervalMs), rate, job.getJobDescriptor().getDisruptionBudget().getDisruptionBudgetRate().getClass().getSimpleName() )); } private int getQuota(long now) { long terminatedInLastInterval = rollingCount.getCounts(now); return (int) (evictionsPerInterval - terminatedInLastInterval); } }
276
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/JobQuotaController.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.eviction.service.quota.job; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.containerhealth.service.ContainerHealthService; import com.netflix.titus.api.eviction.model.EvictionQuota; 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.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.PercentagePerHourDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RatePerIntervalDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RatePercentagePerIntervalDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RelocationLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnhealthyTasksLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.master.eviction.service.quota.QuotaController; import com.netflix.titus.master.eviction.service.quota.QuotaTracker; import com.netflix.titus.master.eviction.service.quota.TimeWindowQuotaTracker; public class JobQuotaController implements QuotaController<Job<?>> { private static final ConsumptionResult LEGACY = ConsumptionResult.rejected("Legacy job"); private final Job<?> job; private final V3JobOperations jobOperations; private final EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver; private final ContainerHealthService containerHealthService; private final TitusRuntime titusRuntime; private final List<QuotaTracker> quotaTrackers; private final List<QuotaController<Job<?>>> quotaControllers; public JobQuotaController(Job<?> job, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver, ContainerHealthService containerHealthService, TitusRuntime titusRuntime) { this.job = job; this.jobOperations = jobOperations; this.effectiveDisruptionBudgetResolver = effectiveDisruptionBudgetResolver; this.containerHealthService = containerHealthService; this.titusRuntime = titusRuntime; this.quotaTrackers = buildQuotaTrackers(job, jobOperations, effectiveDisruptionBudgetResolver, containerHealthService, titusRuntime); this.quotaControllers = buildQuotaControllers(job, jobOperations, effectiveDisruptionBudgetResolver, titusRuntime); } private JobQuotaController(Job<?> newJob, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver, ContainerHealthService containerHealthService, JobQuotaController previousJobQuotaController, TitusRuntime titusRuntime) { this.job = newJob; this.jobOperations = jobOperations; this.effectiveDisruptionBudgetResolver = effectiveDisruptionBudgetResolver; this.containerHealthService = containerHealthService; this.titusRuntime = titusRuntime; this.quotaTrackers = buildQuotaTrackers(job, jobOperations, effectiveDisruptionBudgetResolver, containerHealthService, titusRuntime); this.quotaControllers = mergeQuotaControllers(previousJobQuotaController.quotaControllers, newJob, jobOperations, effectiveDisruptionBudgetResolver, titusRuntime); } public Job<?> getJob() { return job; } @Override public EvictionQuota getQuota(Reference reference) { if (isLegacy()) { return EvictionQuota.newBuilder().withReference(reference).withQuota(0).withMessage("Legacy job").build(); } return getMinSubQuota(reference); } @Override public ConsumptionResult consume(String taskId) { if (isLegacy()) { return LEGACY; } Reference taskReference = Reference.task(taskId); StringBuilder rejectionResponseBuilder = new StringBuilder("MissingQuotas["); // Check quota trackers first boolean noQuota = false; for (QuotaTracker tracker : quotaTrackers) { EvictionQuota quotaStatus = tracker.getQuota(taskReference); if (quotaStatus.getQuota() <= 0) { noQuota = true; rejectionResponseBuilder.append(tracker.getClass().getSimpleName()).append('=').append(quotaStatus.getMessage()).append(", "); } } if (noQuota) { rejectionResponseBuilder.setLength(rejectionResponseBuilder.length() - 2); return ConsumptionResult.rejected(rejectionResponseBuilder.append(']').toString()); } // Now controllers for (int i = 0; i < quotaControllers.size(); i++) { QuotaController<Job<?>> controller = quotaControllers.get(i); ConsumptionResult result = controller.consume(taskId); if (!result.isApproved()) { for (int j = 0; j < i; j++) { quotaControllers.get(j).giveBackConsumedQuota(taskId); } rejectionResponseBuilder .append(controller.getClass().getSimpleName()) .append('=') .append(result.getRejectionReason().orElse("no quota")); return ConsumptionResult.rejected(rejectionResponseBuilder.append(']').toString()); } } return ConsumptionResult.approved(); } @Override public void giveBackConsumedQuota(String taskId) { quotaControllers.forEach(c -> c.giveBackConsumedQuota(taskId)); } @Override public JobQuotaController update(Job<?> updatedJob) { int currentDesired = JobFunctions.getJobDesiredSize(job); int newDesired = JobFunctions.getJobDesiredSize(updatedJob); if (currentDesired == newDesired) { if (job.getJobDescriptor().getDisruptionBudget().equals(updatedJob.getJobDescriptor().getDisruptionBudget())) { return this; } } return new JobQuotaController( updatedJob, jobOperations, effectiveDisruptionBudgetResolver, containerHealthService, this, titusRuntime ); } private boolean isLegacy() { return quotaTrackers.isEmpty() && quotaControllers.isEmpty(); } private EvictionQuota getMinSubQuota(Reference reference) { EvictionQuota minTrackers = getMinSubQuota(quotaTrackers, reference); EvictionQuota minControllers = getMinSubQuota(quotaControllers, reference); return minTrackers.getQuota() <= minControllers.getQuota() ? minTrackers : minControllers; } private EvictionQuota getMinSubQuota(List<? extends QuotaTracker> quotaTrackers, Reference reference) { EvictionQuota minQuota = null; for (QuotaTracker quotaTracker : quotaTrackers) { EvictionQuota next = quotaTracker.getQuota(reference); if (minQuota == null || next.getQuota() < minQuota.getQuota()) { minQuota = next; } } return minQuota == null ? EvictionQuota.unlimited(reference) : minQuota; } @VisibleForTesting static List<QuotaTracker> buildQuotaTrackers(Job<?> job, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver, ContainerHealthService containerHealthService, TitusRuntime titusRuntime) { List<QuotaTracker> quotaTrackers = new ArrayList<>(); DisruptionBudget effectiveBudget = effectiveDisruptionBudgetResolver.resolve(job); if (!effectiveBudget.getTimeWindows().isEmpty()) { quotaTrackers.add(new TimeWindowQuotaTracker(effectiveBudget.getTimeWindows(), titusRuntime)); } DisruptionBudgetPolicy policy = effectiveBudget.getDisruptionBudgetPolicy(); if (policy instanceof AvailabilityPercentageLimitDisruptionBudgetPolicy) { quotaTrackers.add(UnhealthyTasksLimitTracker.percentageLimit(job, (AvailabilityPercentageLimitDisruptionBudgetPolicy) policy, jobOperations, containerHealthService)); } else if (policy instanceof UnhealthyTasksLimitDisruptionBudgetPolicy) { quotaTrackers.add(UnhealthyTasksLimitTracker.absoluteLimit(job, (UnhealthyTasksLimitDisruptionBudgetPolicy) policy, jobOperations, containerHealthService)); } return quotaTrackers; } @VisibleForTesting static List<QuotaController<Job<?>>> buildQuotaControllers(Job<?> job, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver, TitusRuntime titusRuntime) { List<QuotaController<Job<?>>> quotaControllers = new ArrayList<>(); DisruptionBudget effectiveBudget = effectiveDisruptionBudgetResolver.resolve(job); if (effectiveBudget.getDisruptionBudgetRate() instanceof PercentagePerHourDisruptionBudgetRate) { quotaControllers.add(JobPercentagePerHourRelocationRateController.newJobPercentagePerHourRelocationRateController(job, effectiveDisruptionBudgetResolver, titusRuntime)); } else if (effectiveBudget.getDisruptionBudgetRate() instanceof RatePercentagePerIntervalDisruptionBudgetRate) { quotaControllers.add(JobPercentagePerIntervalRateController.newJobPercentagePerIntervalRateController(job, effectiveDisruptionBudgetResolver, titusRuntime)); } else if (effectiveBudget.getDisruptionBudgetRate() instanceof RatePerIntervalDisruptionBudgetRate) { quotaControllers.add(RatePerIntervalRateController.newRatePerIntervalRateController(job, effectiveDisruptionBudgetResolver, titusRuntime)); } DisruptionBudgetPolicy policy = effectiveBudget.getDisruptionBudgetPolicy(); if (policy instanceof RelocationLimitDisruptionBudgetPolicy) { quotaControllers.add(new TaskRelocationLimitController(job, jobOperations, effectiveDisruptionBudgetResolver)); } return quotaControllers; } @VisibleForTesting static List<QuotaController<Job<?>>> mergeQuotaControllers(List<QuotaController<Job<?>>> previousControllers, Job<?> job, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver effectiveDisruptionBudgetResolver, TitusRuntime titusRuntime) { List<QuotaController<Job<?>>> quotaControllers = new ArrayList<>(); DisruptionBudget effectiveBudget = effectiveDisruptionBudgetResolver.resolve(job); if (effectiveBudget.getDisruptionBudgetRate() instanceof PercentagePerHourDisruptionBudgetRate) { QuotaController<Job<?>> newController = mergeQuotaController(job, previousControllers, JobPercentagePerHourRelocationRateController.class, () -> JobPercentagePerHourRelocationRateController.newJobPercentagePerHourRelocationRateController(job, effectiveDisruptionBudgetResolver, titusRuntime) ); quotaControllers.add(newController); } else if (effectiveBudget.getDisruptionBudgetRate() instanceof RatePercentagePerIntervalDisruptionBudgetRate) { QuotaController<Job<?>> newController = mergeQuotaController(job, previousControllers, JobPercentagePerIntervalRateController.class, () -> JobPercentagePerIntervalRateController.newJobPercentagePerIntervalRateController(job, effectiveDisruptionBudgetResolver, titusRuntime) ); quotaControllers.add(newController); } else if (effectiveBudget.getDisruptionBudgetRate() instanceof RatePerIntervalDisruptionBudgetRate) { QuotaController<Job<?>> newController = mergeQuotaController(job, previousControllers, RatePerIntervalRateController.class, () -> RatePerIntervalRateController.newRatePerIntervalRateController(job, effectiveDisruptionBudgetResolver, titusRuntime) ); quotaControllers.add(newController); } DisruptionBudgetPolicy policy = effectiveBudget.getDisruptionBudgetPolicy(); if (policy instanceof RelocationLimitDisruptionBudgetPolicy) { QuotaController<Job<?>> newController = mergeQuotaController(job, previousControllers, TaskRelocationLimitController.class, () -> new TaskRelocationLimitController(job, jobOperations, effectiveDisruptionBudgetResolver) ); quotaControllers.add(newController); } return quotaControllers; } private static QuotaController<Job<?>> mergeQuotaController(Job<?> job, List<QuotaController<Job<?>>> previousQuotaControllers, Class<? extends QuotaController<Job<?>>> type, Supplier<QuotaController<Job<?>>> quotaControllerFactory) { for (QuotaController<Job<?>> next : previousQuotaControllers) { if (type.isAssignableFrom(next.getClass())) { return next.update(job); } } return quotaControllerFactory.get(); } }
277
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/TaskRelocationLimitController.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.eviction.service.quota.job; import java.util.List; import java.util.Optional; import com.netflix.titus.api.eviction.model.EvictionQuota; 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.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RelocationLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.Level; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.eviction.service.quota.ConsumptionResult; import com.netflix.titus.master.eviction.service.quota.QuotaController; public class TaskRelocationLimitController implements QuotaController<Job<?>> { private final Job<?> job; private final V3JobOperations jobOperations; private final EffectiveJobDisruptionBudgetResolver budgetResolver; private final int perTaskLimit; private static final ConsumptionResult TASK_NOT_FOUND = ConsumptionResult.rejected("Task not found"); private final ConsumptionResult taskLimitExceeded; public TaskRelocationLimitController(Job<?> job, V3JobOperations jobOperations, EffectiveJobDisruptionBudgetResolver budgetResolver) { this.job = job; this.jobOperations = jobOperations; this.budgetResolver = budgetResolver; this.perTaskLimit = computePerTaskLimit(budgetResolver.resolve(job)); this.taskLimitExceeded = buildTaskRelocationLimitExceeded(); } private TaskRelocationLimitController(Job<?> updatedJob, int perTaskLimit, TaskRelocationLimitController previous) { this.job = updatedJob; this.jobOperations = previous.jobOperations; this.perTaskLimit = perTaskLimit; this.budgetResolver = previous.budgetResolver; this.taskLimitExceeded = buildTaskRelocationLimitExceeded(); } @Override public EvictionQuota getQuota(Reference reference) { if (reference.getLevel() == Level.Task) { return getTaskQuota(reference); } return getJobQuota(reference); } private EvictionQuota getJobQuota(Reference jobReference) { EvictionQuota.Builder quotaBuilder = EvictionQuota.newBuilder().withReference(jobReference); List<Task> tasks; try { tasks = jobOperations.getTasks(job.getId()); } catch (JobManagerException e) { return quotaBuilder .withQuota(0) .withMessage("Internal error: %s", e.getMessage()) .build(); } int quota = 0; for (Task task : tasks) { if (task.getEvictionResubmitNumber() < perTaskLimit) { quota++; } } return quota > 0 ? quotaBuilder.withQuota(quota).withMessage("Per task limit is %s", perTaskLimit).build() : quotaBuilder.withQuota(0).withMessage("Each task of the job reached its maximum eviction limit %s", perTaskLimit).build(); } private EvictionQuota getTaskQuota(Reference taskReference) { String taskId = taskReference.getName(); EvictionQuota.Builder quotaBuilder = EvictionQuota.newBuilder().withReference(taskReference); Optional<Pair<Job<?>, Task>> jobTaskOpt = jobOperations.findTaskById(taskId); if (!jobTaskOpt.isPresent()) { return quotaBuilder.withQuota(0).withMessage("Task not found").build(); } Task task = jobTaskOpt.get().getRight(); int counter = task.getEvictionResubmitNumber(); if (counter < perTaskLimit) { return quotaBuilder .withQuota(1) .withMessage("Per task limit is %s, and restart count is %s", perTaskLimit, counter) .build(); } return quotaBuilder.withQuota(0).withMessage(taskLimitExceeded.getRejectionReason().get()).build(); } @Override public ConsumptionResult consume(String taskId) { Optional<Pair<Job<?>, Task>> jobTaskPair = jobOperations.findTaskById(taskId); if (!jobTaskPair.isPresent()) { return TASK_NOT_FOUND; } Task task = jobTaskPair.get().getRight(); int counter = task.getEvictionResubmitNumber(); if (counter >= perTaskLimit) { return taskLimitExceeded; } return ConsumptionResult.approved(); } @Override public void giveBackConsumedQuota(String taskId) { } @Override public TaskRelocationLimitController update(Job<?> updatedJob) { int perTaskLimit = computePerTaskLimit(budgetResolver.resolve(updatedJob)); if (perTaskLimit == this.perTaskLimit) { return this; } return new TaskRelocationLimitController(updatedJob, perTaskLimit, this); } private static int computePerTaskLimit(DisruptionBudget budget) { RelocationLimitDisruptionBudgetPolicy policy = (RelocationLimitDisruptionBudgetPolicy) budget.getDisruptionBudgetPolicy(); return policy.getLimit(); } private ConsumptionResult buildTaskRelocationLimitExceeded() { return ConsumptionResult.rejected("Task relocation limit exceeded (limit=" + perTaskLimit + ')'); } }
278
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/RatePerIntervalRateController.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.eviction.service.quota.job; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.RatePerIntervalDisruptionBudgetRate; import com.netflix.titus.common.runtime.TitusRuntime; public class RatePerIntervalRateController extends AbstractRatePerIntervalRateController { private final EffectiveJobDisruptionBudgetResolver budgetResolver; private RatePerIntervalRateController(Job<?> job, long intervalMs, long evictionsPerInterval, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { super(job, intervalMs, evictionsPerInterval, titusRuntime); this.budgetResolver = budgetResolver; } private RatePerIntervalRateController(Job<?> newJob, long intervalMs, long evictionsPerInterval, RatePerIntervalRateController previous) { super(newJob, intervalMs, evictionsPerInterval, previous); this.budgetResolver = previous.budgetResolver; } @Override public RatePerIntervalRateController update(Job<?> newJob) { RatePerIntervalDisruptionBudgetRate rate = (RatePerIntervalDisruptionBudgetRate) budgetResolver.resolve(newJob).getDisruptionBudgetRate(); return new RatePerIntervalRateController( newJob, rate.getIntervalMs(), rate.getLimitPerInterval(), this ); } public static RatePerIntervalRateController newRatePerIntervalRateController(Job<?> job, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { RatePerIntervalDisruptionBudgetRate rate = (RatePerIntervalDisruptionBudgetRate) budgetResolver.resolve(job).getDisruptionBudgetRate(); return new RatePerIntervalRateController(job, rate.getIntervalMs(), rate.getLimitPerInterval(), budgetResolver, titusRuntime); } }
279
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/SelfManagedPolicyTracker.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.eviction.service.quota.job; import com.netflix.titus.api.eviction.model.EvictionQuota; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.master.eviction.service.quota.QuotaTracker; /** * The eviction service does not impose any constraints for the self managed policy. */ public class SelfManagedPolicyTracker implements QuotaTracker { private static final SelfManagedPolicyTracker INSTANCE = new SelfManagedPolicyTracker(); @Override public EvictionQuota getQuota(Reference reference) { return EvictionQuota.unlimited(reference); } public static SelfManagedPolicyTracker getInstance() { return INSTANCE; } }
280
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/JobPercentagePerIntervalRateController.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.eviction.service.quota.job; 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.RatePercentagePerIntervalDisruptionBudgetRate; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.tuple.Pair; public class JobPercentagePerIntervalRateController extends AbstractRatePerIntervalRateController { private final EffectiveJobDisruptionBudgetResolver budgetResolver; protected JobPercentagePerIntervalRateController(Job<?> job, long intervalMs, long evictionsPerInterval, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { super(job, intervalMs, evictionsPerInterval, titusRuntime); this.budgetResolver = budgetResolver; } private JobPercentagePerIntervalRateController(Job<?> newJob, long intervalMs, long evictionsPerInterval, JobPercentagePerIntervalRateController previous) { super(newJob, intervalMs, evictionsPerInterval, previous); this.budgetResolver = previous.budgetResolver; } @Override public JobPercentagePerIntervalRateController update(Job<?> newJob) { Pair<Long, Integer> pair = getIntervalLimitPair(newJob, budgetResolver); return new JobPercentagePerIntervalRateController(newJob, pair.getLeft(), pair.getRight(), this); } public static JobPercentagePerIntervalRateController newJobPercentagePerIntervalRateController(Job<?> job, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { Pair<Long, Integer> pair = getIntervalLimitPair(job, budgetResolver); return new JobPercentagePerIntervalRateController(job, pair.getLeft(), pair.getRight(), budgetResolver, titusRuntime); } private static Pair<Long, Integer> getIntervalLimitPair(Job<?> job, EffectiveJobDisruptionBudgetResolver budgetResolver) { RatePercentagePerIntervalDisruptionBudgetRate rate = (RatePercentagePerIntervalDisruptionBudgetRate) budgetResolver.resolve(job).getDisruptionBudgetRate(); long intervalMs = rate.getIntervalMs(); double percentage = rate.getPercentageLimitPerInterval(); int desired = JobFunctions.getJobDesiredSize(job); int evictionsPerInterval = (int) ((desired * percentage) / 100); return Pair.of(intervalMs, Math.max(1, evictionsPerInterval)); } }
281
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/EffectiveJobDisruptionBudgetResolver.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.eviction.service.quota.job; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; /** * Resolves an alternative (system defined) disruption budget for a job. */ public interface EffectiveJobDisruptionBudgetResolver { DisruptionBudget resolve(Job<?> job); }
282
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/JobPercentagePerHourRelocationRateController.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.eviction.service.quota.job; import java.util.concurrent.TimeUnit; 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.PercentagePerHourDisruptionBudgetRate; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.util.tuple.Pair; public class JobPercentagePerHourRelocationRateController extends AbstractRatePerIntervalRateController { private final EffectiveJobDisruptionBudgetResolver budgetResolver; private JobPercentagePerHourRelocationRateController(Job<?> job, long intervalMs, long evictionsPerInterval, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { super(job, intervalMs, evictionsPerInterval, titusRuntime); this.budgetResolver = budgetResolver; } private JobPercentagePerHourRelocationRateController(Job<?> newJob, long intervalMs, long evictionsPerInterval, JobPercentagePerHourRelocationRateController previous) { super(newJob, intervalMs, evictionsPerInterval, previous); this.budgetResolver = previous.budgetResolver; } @Override public JobPercentagePerHourRelocationRateController update(Job<?> newJob) { Pair<Long, Integer> pair = getIntervalLimitPair(newJob, budgetResolver); return new JobPercentagePerHourRelocationRateController(newJob, pair.getLeft(), pair.getRight(), this); } public static JobPercentagePerHourRelocationRateController newJobPercentagePerHourRelocationRateController(Job<?> job, EffectiveJobDisruptionBudgetResolver budgetResolver, TitusRuntime titusRuntime) { Pair<Long, Integer> pair = getIntervalLimitPair(job, budgetResolver); return new JobPercentagePerHourRelocationRateController(job, pair.getLeft(), pair.getRight(), budgetResolver, titusRuntime); } private static Pair<Long, Integer> getIntervalLimitPair(Job<?> job, EffectiveJobDisruptionBudgetResolver budgetResolver) { PercentagePerHourDisruptionBudgetRate rate = (PercentagePerHourDisruptionBudgetRate) budgetResolver.resolve(job).getDisruptionBudgetRate(); long intervalMs = TimeUnit.HOURS.toMillis(1); double percentage = rate.getMaxPercentageOfContainersRelocatedInHour(); int desired = JobFunctions.getJobDesiredSize(job); int evictionsPerInterval = (int) ((desired * percentage) / 100); return Pair.of(intervalMs, Math.max(1, evictionsPerInterval)); } }
283
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/SelfJobDisruptionBudgetResolver.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.eviction.service.quota.job; import com.google.common.base.Preconditions; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy; /** * Resolver that points back to the job's disruption budget. */ public class SelfJobDisruptionBudgetResolver implements EffectiveJobDisruptionBudgetResolver { private static final EffectiveJobDisruptionBudgetResolver INSTANCE = new SelfJobDisruptionBudgetResolver(); @Override public DisruptionBudget resolve(Job<?> job) { Preconditions.checkArgument( !(job.getJobDescriptor().getDisruptionBudget().getDisruptionBudgetPolicy() instanceof SelfManagedDisruptionBudgetPolicy), "Self managed policy fallback policy not allowed" ); return job.getJobDescriptor().getDisruptionBudget(); } public static EffectiveJobDisruptionBudgetResolver getInstance() { return INSTANCE; } }
284
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/ArchaiusEffectiveJobDisruptionBudgetResolver.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.eviction.service.quota.job; import java.util.Collections; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.common.base.Preconditions; import com.netflix.archaius.api.Property; import com.netflix.archaius.api.PropertyRepository; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.AvailabilityPercentageLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudget; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.DisruptionBudgetFunctions; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.PercentagePerHourDisruptionBudgetRate; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.SelfManagedDisruptionBudgetPolicy; import com.netflix.titus.api.json.ObjectMappers; import com.netflix.titus.common.model.sanitizer.EntitySanitizer; import com.netflix.titus.common.model.sanitizer.ValidationError; import com.netflix.titus.common.util.StringExt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.netflix.titus.api.jobmanager.model.job.sanitizer.JobSanitizerBuilder.JOB_STRICT_SANITIZER; @Singleton public class ArchaiusEffectiveJobDisruptionBudgetResolver implements EffectiveJobDisruptionBudgetResolver { private static final Logger logger = LoggerFactory.getLogger(ArchaiusEffectiveJobDisruptionBudgetResolver.class); public static final String PROPERTY_KEY = "titusMaster.eviction.selfManagedFallbackJobDisruptionBudget"; private static final DisruptionBudget DEFAULT_SELF_MANAGED_FALLBACK_JOB_DISRUPTION_BUDGET = DisruptionBudget.newBuilder() .withDisruptionBudgetPolicy(AvailabilityPercentageLimitDisruptionBudgetPolicy.newBuilder().withPercentageOfHealthyContainers(90).build()) .withDisruptionBudgetRate(PercentagePerHourDisruptionBudgetRate.newBuilder().withMaxPercentageOfContainersRelocatedInHour(20).build()) .withTimeWindows(Collections.emptyList()) .build(); private final PropertyRepository repository; private final EntitySanitizer sanitizer; private final AtomicReference<DisruptionBudget> disruptionBudgetRef; private final Property.Subscription subscription; @Inject public ArchaiusEffectiveJobDisruptionBudgetResolver(PropertyRepository repository, @Named(JOB_STRICT_SANITIZER) EntitySanitizer sanitizer) { this.repository = repository; this.sanitizer = sanitizer; this.disruptionBudgetRef = new AtomicReference<>(refresh()); this.subscription = repository.get(PROPERTY_KEY, String.class).subscribe(update -> disruptionBudgetRef.set(refresh())); } @PreDestroy public void shutdown() { subscription.unsubscribe(); } @Override public DisruptionBudget resolve(Job<?> job) { return DisruptionBudgetFunctions.isSelfManaged(job) ? disruptionBudgetRef.get() : job.getJobDescriptor().getDisruptionBudget(); } private DisruptionBudget refresh() { Property<String> property = repository.get(PROPERTY_KEY, String.class); if (property == null || StringExt.isEmpty(property.get())) { return DEFAULT_SELF_MANAGED_FALLBACK_JOB_DISRUPTION_BUDGET; } try { return parse(property.get()); } catch (Exception e) { logger.warn("invalid SelfManaged fallback disruption budget configuration ({})", e.getMessage()); return DEFAULT_SELF_MANAGED_FALLBACK_JOB_DISRUPTION_BUDGET; } } private DisruptionBudget parse(String newValue) throws Exception { DisruptionBudget budget = ObjectMappers.storeMapper().readValue(newValue, DisruptionBudget.class); Preconditions.checkArgument( !(budget.getDisruptionBudgetPolicy() instanceof SelfManagedDisruptionBudgetPolicy), "Self managed migration policy not allowed as a fallback" ); DisruptionBudget sanitized = sanitizer.sanitize(budget).orElse(budget); Set<ValidationError> violations = sanitizer.validate(sanitized); Preconditions.checkState(violations.isEmpty(), "Invalid self managed fallback disruption budget: value=%s, violations=%s", sanitized, violations); return sanitized; } }
285
0
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota
Create_ds/titus-control-plane/titus-server-master/src/main/java/com/netflix/titus/master/eviction/service/quota/job/UnhealthyTasksLimitTracker.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.eviction.service.quota.job; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.google.common.annotations.VisibleForTesting; import com.netflix.titus.api.containerhealth.model.ContainerHealthState; import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus; import com.netflix.titus.api.containerhealth.service.ContainerHealthService; import com.netflix.titus.api.eviction.model.EvictionQuota; 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.disruptionbudget.AvailabilityPercentageLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.model.job.disruptionbudget.UnhealthyTasksLimitDisruptionBudgetPolicy; import com.netflix.titus.api.jobmanager.service.JobManagerException; import com.netflix.titus.api.jobmanager.service.V3JobOperations; import com.netflix.titus.api.model.reference.Reference; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.master.eviction.service.quota.QuotaTracker; import static com.netflix.titus.common.util.StringExt.startWithLowercase; public class UnhealthyTasksLimitTracker implements QuotaTracker { /** * Do not track health status of small jobs with size below the threshold. */ private static final int JOB_SIZE_TRACKING_THRESHOLD = 2; private static final int TASK_ID_REPORT_LIMIT = 20; private final Job<?> job; private final int minimumHealthyCount; private final boolean aboveThreshold; private final EvictionQuota belowJobSizeThresholdQuota; private final V3JobOperations jobOperations; private final ContainerHealthService containerHealthService; private UnhealthyTasksLimitTracker(Job<?> job, int minimumHealthyCount, V3JobOperations jobOperations, ContainerHealthService containerHealthService) { int jobSize = JobFunctions.getJobDesiredSize(job); this.job = job; this.minimumHealthyCount = minimumHealthyCount; this.aboveThreshold = jobSize >= JOB_SIZE_TRACKING_THRESHOLD; this.belowJobSizeThresholdQuota = EvictionQuota.newBuilder() .withReference(Reference.job(job.getId())) .withQuota(jobSize) .withMessage(String.format("Job too small to apply container health constraints: jobSize=%s, threshold=%s", jobSize, JOB_SIZE_TRACKING_THRESHOLD )) .build(); this.jobOperations = jobOperations; this.containerHealthService = containerHealthService; } @Override public EvictionQuota getQuota(Reference reference) { if (!aboveThreshold) { return belowJobSizeThresholdQuota.toBuilder().withReference(reference).build(); } int healthyCount = countHealthy().getLeft(); long quota = Math.max(0, healthyCount - minimumHealthyCount); if (quota > 0) { return EvictionQuota.newBuilder() .withReference(reference) .withQuota(quota) .withMessage("Found %s healthy containers, and the required minimum is %s", healthyCount, minimumHealthyCount) .build(); } return EvictionQuota.newBuilder() .withReference(reference) .withQuota(0) .withMessage("Not enough healthy containers. Found %s and the required minimum is %s", healthyCount, minimumHealthyCount) .build(); } private Pair<Integer, String> countHealthy() { List<Task> tasks; try { tasks = jobOperations.getTasks(job.getId()); } catch (JobManagerException e) { return Pair.of(0, "job not found"); } int healthy = 0; Map<String, String> notStartedOrUnhealthyTasks = new HashMap<>(); for (Task task : tasks) { if (task.getStatus().getState() == TaskState.Started) { Optional<ContainerHealthStatus> statusOpt = containerHealthService.findHealthStatus(task.getId()); if (statusOpt.isPresent() && statusOpt.get().getState() == ContainerHealthState.Healthy) { healthy++; } else { String report = statusOpt .map(status -> startWithLowercase(status.getState().name()) + '(' + status.getReason() + ')') .orElse("health not found"); notStartedOrUnhealthyTasks.put(task.getId(), report); } } else { notStartedOrUnhealthyTasks.put(task.getId(), String.format("Not started (current task state=%s)", task.getStatus().getState())); } } if (!notStartedOrUnhealthyTasks.isEmpty()) { StringBuilder builder = new StringBuilder("not started and healthy: "); builder.append("total=").append(notStartedOrUnhealthyTasks.size()); builder.append(", tasks=["); int counter = 0; for (Map.Entry<String, String> entry : notStartedOrUnhealthyTasks.entrySet()) { builder.append(entry.getKey()).append('=').append(entry.getValue()); counter++; if (counter < notStartedOrUnhealthyTasks.size()) { builder.append(", "); } else { builder.append("]"); } if (counter >= TASK_ID_REPORT_LIMIT && counter < notStartedOrUnhealthyTasks.size()) { builder.append(",... dropped ").append(notStartedOrUnhealthyTasks.size() - counter).append(" tasks]"); } } return Pair.of(healthy, builder.toString()); } return Pair.of( healthy, healthy > minimumHealthyCount ? "" : String.format("not enough healthy containers: healthy=%s, minimum=%s", healthy, minimumHealthyCount) ); } public static UnhealthyTasksLimitTracker percentageLimit(Job<?> job, AvailabilityPercentageLimitDisruptionBudgetPolicy policy, V3JobOperations jobOperations, ContainerHealthService containerHealthService) { return new UnhealthyTasksLimitTracker(job, computeHealthyPoolSizeFromPercentage(job, policy), jobOperations, containerHealthService); } public static UnhealthyTasksLimitTracker absoluteLimit(Job<?> job, UnhealthyTasksLimitDisruptionBudgetPolicy policy, V3JobOperations jobOperations, ContainerHealthService containerHealthService) { return new UnhealthyTasksLimitTracker(job, computeHealthyPoolSizeFromAbsoluteLimit(job, policy), jobOperations, containerHealthService); } @VisibleForTesting static int computeHealthyPoolSizeFromAbsoluteLimit(Job<?> job, UnhealthyTasksLimitDisruptionBudgetPolicy policy) { return Math.max(0, JobFunctions.getJobDesiredSize(job) - Math.max(1, policy.getLimitOfUnhealthyContainers())); } @VisibleForTesting static int computeHealthyPoolSizeFromPercentage(Job<?> job, AvailabilityPercentageLimitDisruptionBudgetPolicy policy) { int jobDesiredSize = JobFunctions.getJobDesiredSize(job); if (jobDesiredSize == 0) { return 0; } double percentageOfHealthy = policy.getPercentageOfHealthyContainers(); int minimumHealthyCount = (int) Math.ceil((percentageOfHealthy * jobDesiredSize) / 100); return Math.min(minimumHealthyCount, jobDesiredSize - 1); } }
286
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/jobmanager/JobComparatorsTest.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.runtime.jobmanager; import java.util.Arrays; import java.util.List; import com.netflix.titus.api.jobmanager.model.job.Job; 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.Task; import com.netflix.titus.api.jobmanager.model.job.TaskState; import com.netflix.titus.api.jobmanager.model.job.TaskStatus; import com.netflix.titus.api.model.IdAndTimestampKey; import com.netflix.titus.testkit.model.job.JobGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class JobComparatorsTest { @Test public void testGetJobTimestampComparator() { List<Job<?>> jobs = Arrays.asList( newJob("job3", 10), newJob("job2", 5), newJob("job1", 10) ); jobs.sort(JobComparators.getJobTimestampComparator()); assertThat(jobs.get(0).getId()).isEqualTo("job2"); assertThat(jobs.get(1).getId()).isEqualTo("job1"); assertThat(jobs.get(2).getId()).isEqualTo("job3"); } @Test public void testGetTaskTimestampComparator() { List<Task> tasks = Arrays.asList( newTask("task3", 10), newTask("task2", 5), newTask("task1", 10) ); tasks.sort(JobComparators.getTaskTimestampComparator()); assertThat(tasks.get(0).getId()).isEqualTo("task2"); assertThat(tasks.get(1).getId()).isEqualTo("task1"); assertThat(tasks.get(2).getId()).isEqualTo("task3"); } @Test public void testCreateJobKeyOf() { IdAndTimestampKey<Job<?>> key = JobComparators.createJobKeyOf(newJob("job1", 100)); assertThat(key.getId()).isEqualTo("job1"); assertThat(key.getTimestamp()).isEqualTo(100); } @Test public void testCreateTaskKeyOf() { IdAndTimestampKey<Task> key = JobComparators.createTaskKeyOf(newTask("task1", 100)); assertThat(key.getId()).isEqualTo("task1"); assertThat(key.getTimestamp()).isEqualTo(100); } private Job<?> newJob(String jobId, long timestamp) { return JobGenerator.oneBatchJob().toBuilder() .withId(jobId) .withStatus(JobStatus.newBuilder() .withState(JobState.Accepted) .withTimestamp(timestamp) .build() ) .build(); } private Task newTask(String taskId, long timestamp) { return JobGenerator.oneBatchTask().toBuilder() .withId(taskId) .withStatus(TaskStatus.newBuilder() .withState(TaskState.Accepted) .withTimestamp(timestamp) .build() ) .build(); } }
287
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/containerhealth
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/containerhealth/service/AggregatingContainerHealthServiceTest.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.runtime.containerhealth.service; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Optional; import com.netflix.titus.api.containerhealth.model.ContainerHealthState; import com.netflix.titus.api.containerhealth.model.ContainerHealthStatus; import com.netflix.titus.api.containerhealth.model.event.ContainerHealthEvent; import com.netflix.titus.api.containerhealth.service.ContainerHealthService; 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.ReadOnlyJobOperations; import com.netflix.titus.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.testkit.model.job.JobComponentStub; import com.netflix.titus.testkit.rx.TitusRxSubscriber; import org.junit.Before; import org.junit.Test; import reactor.core.Disposable; import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.havingProvider; import static com.netflix.titus.api.jobmanager.model.job.JobFunctions.ofBatchSize; import static com.netflix.titus.common.util.CollectionsExt.asSet; import static com.netflix.titus.testkit.junit.asserts.ContainerHealthAsserts.assertContainerHealthEvent; import static com.netflix.titus.testkit.junit.asserts.ContainerHealthAsserts.assertContainerHealthSnapshot; import static com.netflix.titus.testkit.model.job.JobDescriptorGenerator.batchJobDescriptors; import static org.assertj.core.api.Assertions.assertThat; public class AggregatingContainerHealthServiceTest { private final TitusRuntime titusRuntime = TitusRuntimes.test(); private final JobComponentStub jobManagerStub = new JobComponentStub(titusRuntime); private final ReadOnlyJobOperations jobOperations = jobManagerStub.getJobOperations(); private final DownstreamHealthService downstream1 = new DownstreamHealthService("downstream1"); private final DownstreamHealthService downstream2 = new DownstreamHealthService("downstream2"); private final AggregatingContainerHealthService healthService = new AggregatingContainerHealthService( asSet(downstream1, downstream2), jobOperations, titusRuntime ); private Job job1; private Task task1; private String taskId1; @Before public void setUp() { this.job1 = jobManagerStub.addBatchTemplate( "testJob", batchJobDescriptors(ofBatchSize(1), havingProvider("downstream1"), havingProvider("downstream2")) ).createJobAndTasks("testJob").getLeft(); this.task1 = jobOperations.getTasks(job1.getId()).get(0); this.taskId1 = task1.getId(); } @Test public void testSubscriptionWithSnapshot() { downstream1.makeHealthy(taskId1); downstream2.makeHealthy(taskId1); StepVerifier.create(healthService.events(true)) // Check snapshot .assertNext(event -> assertContainerHealthSnapshot( event, status -> status.getTaskId().equals(taskId1) && status.getState() == ContainerHealthState.Healthy) ) // Now trigger change .then(() -> downstream1.makeUnhealthy(taskId1)) .assertNext(event -> assertContainerHealthEvent(event, taskId1, ContainerHealthState.Unhealthy)) .thenCancel() .verify(Duration.ofSeconds(5)); } @Test public void testHealthStatusMergeFromDifferentSources() { downstream1.makeHealthy(taskId1); downstream2.makeHealthy(taskId1); StepVerifier.withVirtualTime(() -> healthService.events(false)) .expectSubscription() // Check no, snapshot .expectNoEvent(Duration.ofSeconds(1)) // Now trigger change .then(() -> { assertThat(healthService.findHealthStatus(taskId1).get().getState()).isEqualTo(ContainerHealthState.Healthy); downstream1.makeUnhealthy(taskId1); }) .assertNext(event -> { assertThat(healthService.findHealthStatus(taskId1).get().getState()).isEqualTo(ContainerHealthState.Unhealthy); assertContainerHealthEvent(event, taskId1, ContainerHealthState.Unhealthy); }) // Now trigger it back .then(() -> downstream1.makeHealthy(taskId1)) .assertNext(event -> { assertThat(healthService.findHealthStatus(taskId1).get().getState()).isEqualTo(ContainerHealthState.Healthy); assertContainerHealthEvent(event, taskId1, ContainerHealthState.Healthy); }) .thenCancel() .verify(Duration.ofSeconds(5)); } @Test public void testBadHealthDownstreamSourceTerminatesClientSubscription() { StepVerifier.create(healthService.events(false)) // Break downstream health provider .then(() -> { downstream2.breakSubscriptionsWithError(new RuntimeException("Simulated error")); }) .verifyError(RuntimeException.class); } @Test public void testBadSubscriberIsIsolated() { // First event / one subscriber TitusRxSubscriber<ContainerHealthEvent> goodSubscriber = new TitusRxSubscriber<>(); healthService.events(false).subscribe(goodSubscriber); // Add bad subscriber Disposable badSubscriber = healthService.events(false).subscribe( next -> { throw new RuntimeException("simulated error"); }, e -> { throw new RuntimeException("simulated error"); }, () -> { throw new RuntimeException("simulated error"); } ); downstream1.makeHealthy(taskId1); assertThat(goodSubscriber.isOpen()).isTrue(); assertThat(badSubscriber.isDisposed()).isTrue(); } private class DownstreamHealthService implements ContainerHealthService { private final String name; private final Map<String, ContainerHealthStatus> healthStatuses = new HashMap<>(); private volatile DirectProcessor<ContainerHealthEvent> eventSubject = DirectProcessor.create(); private DownstreamHealthService(String name) { this.name = name; } @Override public String getName() { return name; } @Override public Optional<ContainerHealthStatus> findHealthStatus(String taskId) { return Optional.ofNullable(healthStatuses.get(taskId)); } @Override public Flux<ContainerHealthEvent> events(boolean snapshot) { return Flux.defer(() -> eventSubject); } private void makeHealthy(String taskId) { updateHealth(ContainerHealthStatus.healthy(taskId, 0)); } private void makeUnhealthy(String taskId) { updateHealth(ContainerHealthStatus.unhealthy(taskId, "simulated failure",0)); } private void updateHealth(ContainerHealthStatus newStatus) { healthStatuses.put(newStatus.getTaskId(), newStatus); eventSubject.onNext(ContainerHealthEvent.healthChanged(newStatus)); } private void breakSubscriptionsWithError(RuntimeException error) { DirectProcessor<ContainerHealthEvent> current = eventSubject; this.eventSubject = DirectProcessor.create(); current.onError(error); } } }
288
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/loadbalancer/LoadBalancerCursorsTest.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.runtime.loadbalancer; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; public class LoadBalancerCursorsTest { private List<JobLoadBalancer> loadBalancerList; @Before public void setUp() { loadBalancerList = Stream.of( new JobLoadBalancer("job1", "lb1"), new JobLoadBalancer("job3", "lb3"), new JobLoadBalancer("job2", "lb2"), new JobLoadBalancer("job4", "lb4") ).sorted(LoadBalancerCursors.loadBalancerComparator()).collect(Collectors.toList()); } @Test public void checkValidCursor() { final String cursor = LoadBalancerCursors.newCursorFrom(new JobLoadBalancer("job3", "lb3")); final Optional<Integer> loadBalancerIndex = LoadBalancerCursors.loadBalancerIndexOf(loadBalancerList, cursor); assertThat(loadBalancerIndex.isPresent()).isTrue(); assertThat(loadBalancerIndex.get()).isEqualTo(2); } @Test public void checkMissingCursor() { final String cursor = LoadBalancerCursors.newCursorFrom(new JobLoadBalancer("job30", "lb3")); final Optional<Integer> loadBalancerIndex = LoadBalancerCursors.loadBalancerIndexOf(loadBalancerList, cursor); assertThat(loadBalancerIndex.isPresent()).isTrue(); assertThat(loadBalancerIndex.get()).isEqualTo(1); } @Test public void checkFirstMissingCursorElement() { final String cursor = LoadBalancerCursors.newCursorFrom(new JobLoadBalancer("job1", "lb0")); final Optional<Integer> loadBalancerIndex = LoadBalancerCursors.loadBalancerIndexOf(loadBalancerList, cursor); assertThat(loadBalancerIndex.isPresent()).isTrue(); assertThat(loadBalancerIndex.get()).isEqualTo(-1); } }
289
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/TestingAppNameSanitizer.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.runtime.endpoint.admission; import java.util.function.UnaryOperator; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.common.model.admission.AdmissionSanitizer; import reactor.core.publisher.Mono; /** * This {@link AdmissionSanitizer} implementation ensures a job's appname matches a specific string. * It is only used for testing purposes. */ class TestingAppNameSanitizer implements AdmissionSanitizer<JobDescriptor> { private final String desiredAppName; TestingAppNameSanitizer() { this("desiredAppName"); } TestingAppNameSanitizer(String desiredAppName) { this.desiredAppName = desiredAppName; } @Override public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) { return Mono.just(jd -> entity.toBuilder().withApplicationName(desiredAppName).build()); } public String getDesiredAppName() { return desiredAppName; } }
290
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSelectorsTest.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.runtime.endpoint.admission; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import com.google.common.collect.ImmutableMap; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.config.MapConfig; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.common.util.closeable.CloseableReference; import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction; import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictions; import com.netflix.titus.testkit.model.job.JobDescriptorGenerator; import org.junit.Test; import static com.jayway.awaitility.Awaitility.await; import static com.netflix.titus.runtime.endpoint.admission.JobRuntimePredictionSelectors.aboveThreshold; import static com.netflix.titus.runtime.endpoint.admission.JobRuntimePredictionSelectors.aboveThresholds; import static com.netflix.titus.runtime.endpoint.admission.JobRuntimePredictionSelectors.reloadedOnConfigurationUpdate; import static com.netflix.titus.runtime.endpoint.admission.JobRuntimePredictionUtil.HIGH_QUANTILE; import static org.assertj.core.api.Assertions.assertThat; public class JobRuntimePredictionSelectorsTest { private static final JobDescriptor JOB_DESCRIPTOR = JobDescriptorGenerator.oneTaskBatchJobDescriptor(); private static final JobRuntimePredictions JOB_PREDICTIONS = new JobRuntimePredictions("v1", "m1", new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.05, 5), new JobRuntimePrediction(0.25, 10), new JobRuntimePrediction(0.95, 20) ))); private static final JobRuntimePredictions BAD_CONFIDENCE_LEVELS = new JobRuntimePredictions("v1", "m1", new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.1, 5), new JobRuntimePrediction(0.5, 10), new JobRuntimePrediction(0.9, 20) ))); private static final Map<String, String> METADATA = Collections.singletonMap("key", "value"); @Test public void testAboveThreshold() { JobRuntimePredictionSelector selector = aboveThreshold(60, 10, HIGH_QUANTILE, METADATA); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), HIGH_QUANTILE); } @Test public void testCustomQuantile() { JobRuntimePredictionSelector selector = aboveThreshold(60, 10, 0.25, METADATA); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), 0.25); } @Test public void testQuantileFromConfig() { ImmutableMap<String, String> config = ImmutableMap.<String, String>builder() .put("runtimeThresholdInSeconds", "60") .put("sigmaThreshold", "10") .build(); JobRuntimePredictionSelector selector = aboveThreshold(new MapConfig(config), METADATA); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), HIGH_QUANTILE); } @Test public void testCustomQuantileFromConfig() { ImmutableMap<String, String> config = ImmutableMap.<String, String>builder() .put("runtimeThresholdInSeconds", "60") .put("sigmaThreshold", "10") .put("quantile", "0.25") .build(); JobRuntimePredictionSelector selector = aboveThreshold(new MapConfig(config), METADATA); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), 0.25); } @Test public void testBadQuantileFromConfig() { ImmutableMap<String, String> config = ImmutableMap.<String, String>builder() .put("runtimeThresholdInSeconds", "60") .put("sigmaThreshold", "10") .put("quantile", "0.123") .build(); JobRuntimePredictionSelector selector = aboveThreshold(new MapConfig(config), METADATA); assertThat(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS)).isEmpty(); } @Test public void testAboveThresholdWithWrongConfidenceLevels() { JobRuntimePredictionSelector selector = aboveThreshold(60, 10, HIGH_QUANTILE, METADATA); Optional<JobRuntimePredictionSelection> selectionOpt = selector.apply(JOB_DESCRIPTOR, BAD_CONFIDENCE_LEVELS); assertThat(selectionOpt).isEmpty(); } @Test public void testAboveThresholdWithLowRuntimeThreshold() { JobRuntimePredictionSelector selector = aboveThreshold(10, 1, HIGH_QUANTILE, METADATA); Optional<JobRuntimePredictionSelection> selectionOpt = selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS); assertThat(selectionOpt).isEmpty(); } @Test public void testAboveThresholdFromConfig() { ImmutableMap<String, String> config = ImmutableMap.<String, String>builder() .put("runtimeThresholdInSeconds", "60") .put("sigmaThreshold", "10") .build(); JobRuntimePredictionSelector selector = aboveThreshold(new MapConfig(config), METADATA); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), HIGH_QUANTILE); } @Test public void testAboveThresholds() { ImmutableMap<String, String> config = ImmutableMap.<String, String>builder() .put("root.cellA.runtimeThresholdInSeconds", "60") .put("root.cellA.sigmaThreshold", "10") .put("root.cellB.runtimeThresholdInSeconds", "6") .put("root.cellB.sigmaThreshold", "1") .build(); Map<String, JobRuntimePredictionSelector> selectors = aboveThresholds(new MapConfig(config).getPrefixedView("root"), METADATA); checkSelection(selectors.get("cellA").apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), HIGH_QUANTILE); assertThat(selectors.get("cellB").apply(JOB_DESCRIPTOR, JOB_PREDICTIONS)).isEmpty(); } @Test public void testAbTestRandom() { JobRuntimePredictionSelector selector = JobRuntimePredictionSelectors.abTestRandom( ImmutableMap.<String, JobRuntimePredictionSelector>builder() .put("cellA", JobRuntimePredictionSelectors.best()) .put("cellB", JobRuntimePredictionSelectors.best()) .build() ); Set<String> observed = new HashSet<>(); await().until(() -> { selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS).ifPresent(s -> observed.add(s.getMetadata().get(JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_AB_TEST)) ); return observed.size() == 2; }); } @Test public void testReloadedOnConfigurationUpdate() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("root.runtimeThresholdInSeconds", "60"); config.setProperty("root.sigmaThreshold", "10"); CloseableReference<JobRuntimePredictionSelector> selectorRef = reloadedOnConfigurationUpdate( config.getPrefixedView("root"), configUpdate -> aboveThreshold(configUpdate, METADATA) ); JobRuntimePredictionSelector selector = selectorRef.get(); checkSelection(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS), HIGH_QUANTILE); // Now change it to fail config.setProperty("root.runtimeThresholdInSeconds", "6"); assertThat(selector.apply(JOB_DESCRIPTOR, JOB_PREDICTIONS)).isEmpty(); selectorRef.close(); } private void checkSelection(Optional<JobRuntimePredictionSelection> selectionOpt, double expectedQuantile) { assertThat(selectionOpt).isNotEmpty(); assertThat(selectionOpt.get().getPrediction().getConfidence()).isEqualTo(expectedQuantile); assertThat(selectionOpt.get().getMetadata()).containsAllEntriesOf(METADATA); } }
291
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/AggregatingValidatorTest.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.runtime.endpoint.admission; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.common.model.admission.AdmissionValidator; import com.netflix.titus.common.model.admission.TitusValidatorConfiguration; import com.netflix.titus.common.model.sanitizer.ValidationError; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * This class tests the {@link AggregatingValidator} class. */ public class AggregatingValidatorTest { private static final JobDescriptor MOCK_JOB = mock(JobDescriptor.class); private final TitusValidatorConfiguration configuration = mock(TitusValidatorConfiguration.class); private final Registry registry = new DefaultRegistry(); @Before public void setUp() { when(configuration.getTimeoutMs()).thenReturn(500); when(configuration.getErrorType()).thenReturn("HARD"); } // Hard validation tests @Test public void validateHardPassPass() { AdmissionValidator pass0 = new PassJobValidator(); AdmissionValidator pass1 = new PassJobValidator(); AggregatingValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(pass0, pass1) ); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNext(Collections.emptySet()) .verifyComplete(); } @Test public void validateHardFailFail() { AdmissionValidator fail0 = new FailJobValidator(ValidationError.Type.HARD); AdmissionValidator fail1 = new FailJobValidator(ValidationError.Type.HARD); AggregatingValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(fail0, fail1)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 2) .verifyComplete(); Set<ValidationError> errors = mono.block(); validateFailErrors(errors); validateErrorType(errors, ValidationError.Type.HARD); } @Test public void validateHardPassFail() { AdmissionValidator pass = new PassJobValidator(); AdmissionValidator fail = new FailJobValidator(ValidationError.Type.HARD); AggregatingValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(pass, fail)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 1) .verifyComplete(); Set<ValidationError> errors = mono.block(); validateFailErrors(errors); validateErrorType(errors, ValidationError.Type.HARD); } @Test public void validateHardPassTimeout() { AdmissionValidator pass = new PassJobValidator(); AdmissionValidator never = new NeverJobValidator(ValidationError.Type.HARD); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(pass, never)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 1) .verifyComplete(); Set<ValidationError> errors = mono.block(); validateTimeoutErrors(errors); validateErrorType(errors, ValidationError.Type.HARD); } @Test public void validateHardPassFailTimeout() { AdmissionValidator pass = new PassJobValidator(); AdmissionValidator fail = new FailJobValidator(); AdmissionValidator never = new NeverJobValidator(); AdmissionValidator parallelValidator = new AggregatingValidator( configuration, registry, Arrays.asList(pass, fail, never)); Mono<Set<ValidationError>> mono = parallelValidator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 2) .verifyComplete(); Set<ValidationError> errors = mono.block(); validateErrorType(errors, ValidationError.Type.HARD); Collection<ValidationError> failErrors = errors.stream() .filter(error -> error.getField().equals(FailJobValidator.ERR_FIELD)) .collect(Collectors.toList()); assertThat(failErrors).hasSize(1); validateFailErrors(failErrors); Collection<ValidationError> timeoutErrors = errors.stream() .filter(error -> error.getField().equals(NeverJobValidator.class.getSimpleName())) .collect(Collectors.toList()); assertThat(timeoutErrors).hasSize(1); validateTimeoutErrors(timeoutErrors); } // Soft validation tests @Test public void validateSoftTimeout() { AdmissionValidator never = new NeverJobValidator(ValidationError.Type.SOFT); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(never)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 1) .verifyComplete(); Collection<ValidationError> errors = mono.block(); validateTimeoutErrors(errors); validateErrorType(errors, ValidationError.Type.SOFT); } @Test public void validateSoftFailure() { AdmissionValidator fail = new FailJobValidator(ValidationError.Type.HARD); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(fail)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 1) .verifyComplete(); Collection<ValidationError> errors = mono.block(); validateFailErrors(errors); validateErrorType(errors, ValidationError.Type.HARD); } @Test public void validateSoftPass() { AdmissionValidator pass = new PassJobValidator(); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(pass)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 0) .verifyComplete(); } // Hard/Soft validation tests @Test public void validateHardSoftTimeout() { AdmissionValidator<JobDescriptor> never0 = new NeverJobValidator(ValidationError.Type.HARD); AdmissionValidator never1 = new NeverJobValidator(ValidationError.Type.SOFT); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(never0, never1)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 2) .verifyComplete(); Collection<ValidationError> errors = mono.block(); validateTimeoutErrors(errors); Collection<ValidationError> hardErrors = errors.stream() .filter(error -> error.getType().equals(ValidationError.Type.HARD)) .collect(Collectors.toList()); assertThat(hardErrors).hasSize(1); Collection<ValidationError> softErrors = errors.stream() .filter(error -> error.getType().equals(ValidationError.Type.SOFT)) .collect(Collectors.toList()); assertThat(softErrors).hasSize(1); } @Test public void validateHardSoftPass() { AdmissionValidator pass0 = new PassJobValidator(); AdmissionValidator pass1 = new PassJobValidator(); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(pass0, pass1)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 0) .verifyComplete(); } @Test public void validateHardSoftFail() { AdmissionValidator fail0 = new FailJobValidator(ValidationError.Type.HARD); AdmissionValidator fail1 = new FailJobValidator(ValidationError.Type.HARD); AdmissionValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(fail0, fail1)); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNextMatches(errors -> errors.size() == 2) .verifyComplete(); Collection<ValidationError> errors = mono.block(); validateFailErrors(errors); assertThat(errors).allMatch(error -> error.getType().equals(ValidationError.Type.HARD)); } @Test public void validateIsProtectedAgainstEmpty() { AdmissionValidator<JobDescriptor> pass = new PassJobValidator(); AdmissionValidator<JobDescriptor> empty = new EmptyValidator(); AggregatingValidator validator = new AggregatingValidator( configuration, registry, Arrays.asList(empty, pass, empty) ); Mono<Set<ValidationError>> mono = validator.validate(MOCK_JOB); StepVerifier.create(mono) .expectNext(Collections.emptySet()) .verifyComplete(); } private void validateFailErrors(Collection<ValidationError> failErrors) { assertThat(failErrors.size() > 0).isTrue(); assertThat(failErrors) .allMatch(error -> error.getField().equals(FailJobValidator.ERR_FIELD)) .allMatch(error -> error.getDescription().contains(FailJobValidator.ERR_DESCRIPTION)); } private void validateTimeoutErrors(Collection<ValidationError> timeoutErrors) { assertThat(timeoutErrors.size() > 0).isTrue(); assertThat(timeoutErrors) .allMatch(error -> error.getField().equals(NeverJobValidator.class.getSimpleName())) .allMatch(error -> error.getDescription().equals(AggregatingValidator.getTimeoutMsg(Duration.ofMillis(configuration.getTimeoutMs())))); } private void validateErrorType(Collection<ValidationError> hardErrors, ValidationError.Type errorType) { assertThat(hardErrors).allMatch(error -> error.getType().equals(errorType)); } }
292
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/JobRuntimePredictionSanitizerTest.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.runtime.endpoint.admission; import java.util.Arrays; import java.util.TreeSet; import java.util.UUID; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.api.service.TitusServiceException; import com.netflix.titus.common.model.admission.AdmissionSanitizer; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.runtime.connector.prediction.JobRuntimePrediction; import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictionClient; import com.netflix.titus.runtime.connector.prediction.JobRuntimePredictions; import com.netflix.titus.testkit.model.job.JobDescriptorGenerator; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION; import static com.netflix.titus.api.jobmanager.JobAttributes.JOB_PARAMETER_SKIP_RUNTIME_PREDICTION; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JobRuntimePredictionSanitizerTest { private JobDescriptor<BatchJobExt> jobDescriptor; private String modelId; private JobRuntimePredictionConfiguration config; private JobRuntimePredictionClient client; @Before public void setup() { jobDescriptor = JobDescriptorGenerator.oneTaskBatchJobDescriptor(); modelId = UUID.randomUUID().toString(); config = mock(JobRuntimePredictionConfiguration.class); when(config.getMaxOpportunisticRuntimeLimitMs()).thenReturn(300_000L); client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.05, 5.5), new JobRuntimePrediction(0.25, 6.0), new JobRuntimePrediction(0.90, 20.1) ))); when(client.getRuntimePredictions(jobDescriptor)).thenReturn(Mono.just(predictions)); } @Test public void predictionsAreAddedToJobs() { AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "20.1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "0.9") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE, "0.05=5.5;0.25=6.0;0.9=20.1") ) .verifyComplete(); } @Test public void predictionsAreCappedToRuntimeLimit() { JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.05, 10.1), new JobRuntimePrediction(0.25, 30.2), new JobRuntimePrediction(0.90, 90.5) ))); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "60.0") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "1.0") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE, "0.05=10.1;0.25=30.2;0.9=90.5") ) .verifyComplete(); } @Test public void errorsCauseSanitizationToBeSkipped() { JobDescriptor<BatchJobExt> noRuntimeLimit = jobDescriptor.but(jd -> jd.getExtensions().toBuilder() .withRuntimeLimitMs(0) ); JobRuntimePredictionClient errorClient = mock(JobRuntimePredictionClient.class); when(errorClient.getRuntimePredictions(any())).thenReturn(Mono.error(TitusServiceException.internal("bad request"))); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(errorClient, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(noRuntimeLimit)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .doesNotContainKeys( JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION ) ) .verifyComplete(); } @Test public void errorsCauseFallbackToRuntimeLimit() { JobRuntimePredictionClient errorClient = mock(JobRuntimePredictionClient.class); when(errorClient.getRuntimePredictions(any())).thenReturn(Mono.error(TitusServiceException.internal("bad request"))); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(errorClient, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "1.0") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "60.0") ) .verifyComplete(); } @Test public void emptyPredictionsCauseSanitizationToBeSkipped() { JobDescriptor<BatchJobExt> noRuntimeLimit = jobDescriptor.but(jd -> jd.getExtensions().toBuilder() .withRuntimeLimitMs(0) ); JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>()); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(noRuntimeLimit)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .doesNotContainKeys( JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE ) ) .verifyComplete(); } @Test public void emptyPredictionsCauseFallbackToRuntimeLimit() { JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>()); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "1.0") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "60.0") .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .doesNotContainKeys(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE) ) .verifyComplete(); } @Test public void runtimeLimitIsOnlyUsedWhenWithinAllowedConfig() { JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>()); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); JobRuntimePredictionConfiguration lowConfig = mock(JobRuntimePredictionConfiguration.class); // lower than the 60s runtime limit on the job when(lowConfig.getMaxOpportunisticRuntimeLimitMs()).thenReturn(30_000L); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), lowConfig, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .doesNotContainKeys(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") ) .verifyComplete(); } @Test public void zeroedPredictionsCauseSanitizationToBeSkipped() { JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.05, 0.0), new JobRuntimePrediction(0.25, 6.0), new JobRuntimePrediction(0.90, 21.2) ))); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE, "0.05=0.0;0.25=6.0;0.9=21.2") ) .verifyComplete(); } @Test public void higherQualityPredictionsMustBeLonger() { JobRuntimePredictionClient client = mock(JobRuntimePredictionClient.class); JobRuntimePredictions predictions = new JobRuntimePredictions("v1", modelId, new TreeSet<>(Arrays.asList( new JobRuntimePrediction(0.05, 5.1), new JobRuntimePrediction(0.25, 4.0), new JobRuntimePrediction(0.35, 4.1), new JobRuntimePrediction(0.90, 4.0) ))); when(client.getRuntimePredictions(any())).thenReturn(Mono.just(predictions)); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, modelId) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION, "v1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_AVAILABLE, "0.05=5.1;0.25=4.0;0.35=4.1;0.9=4.0") ) .verifyComplete(); } @Test public void metadataFromSelectorIsAddedToJobs() { AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(CollectionsExt.asMap( "selection.extra", "foobar", // can't override prediction attributes JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "0.82", JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "1.0" )), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, "20.1") .containsEntry(JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, "0.9") .containsEntry("selection.extra", "foobar") ) .verifyComplete(); } @Test public void jobsCanOptOut() { JobDescriptor<BatchJobExt> optedOut = jobDescriptor.toBuilder() .withAttributes(CollectionsExt.copyAndAdd(jobDescriptor.getAttributes(), JOB_PARAMETER_SKIP_RUNTIME_PREDICTION, "true" )) .build(); AdmissionSanitizer<JobDescriptor> sanitizer = new JobRuntimePredictionSanitizer(client, JobRuntimePredictionSelectors.best(), config, TitusRuntimes.test()); StepVerifier.create(sanitizer.sanitizeAndApply(optedOut)) .assertNext(result -> assertThat(((JobDescriptor<?>) result).getAttributes()) .containsEntry(JOB_ATTRIBUTES_SANITIZATION_SKIPPED_RUNTIME_PREDICTION, "true") .doesNotContainKeys( JOB_ATTRIBUTES_RUNTIME_PREDICTION_CONFIDENCE, JOB_ATTRIBUTES_RUNTIME_PREDICTION_SEC, JOB_ATTRIBUTES_RUNTIME_PREDICTION_MODEL_ID, JOB_ATTRIBUTES_RUNTIME_PREDICTION_VERSION ) ) .verifyComplete(); } }
293
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/AggregatingSanitizerTest.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.runtime.endpoint.admission; import java.util.Arrays; import java.util.Collections; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.api.service.TitusServiceException; import com.netflix.titus.common.model.admission.TitusValidatorConfiguration; import com.netflix.titus.testkit.model.job.JobDescriptorGenerator; import org.junit.Before; import org.junit.Test; import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AggregatingSanitizerTest { private final TitusValidatorConfiguration configuration = mock(TitusValidatorConfiguration.class); @Before public void setUp() { when(configuration.getTimeoutMs()).thenReturn(500); } @Test public void mergeAllSanitizers() { String initialAppName = "initialAppName"; String initialCapacityGroup = "initialCapacityGroup"; TestingAppNameSanitizer appNameSanitizer = new TestingAppNameSanitizer(); TestingCapacityGroupSanitizer capacityGroupSanitizer = new TestingCapacityGroupSanitizer(); JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors() .map(jd -> jd.toBuilder() .withApplicationName(initialAppName) .withCapacityGroup(initialCapacityGroup) .build()) .getValue(); AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Arrays.asList( appNameSanitizer, capacityGroupSanitizer )); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(sanitizedJobDescriptor -> { assertThat(sanitizedJobDescriptor.getApplicationName()).isEqualTo(appNameSanitizer.getDesiredAppName()); assertThat(sanitizedJobDescriptor.getCapacityGroup()).isEqualTo(capacityGroupSanitizer.getDesiredCapacityGroup()); }) .verifyComplete(); } @Test public void sanitizeFail() { String initialAppName = "initialAppName"; JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors() .map(jd -> jd.toBuilder() .withApplicationName(initialAppName) .build()) .getValue(); AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Arrays.asList( new TestingAppNameSanitizer(), new FailJobValidator() )); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .expectError(TitusServiceException.class) .verify(); } @Test public void noSanitizersIsANoop() { AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Collections.emptyList()); JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors().getValue(); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(sanitizedJobDescriptor -> assertThat(sanitizedJobDescriptor).isSameAs(jobDescriptor)) .verifyComplete(); } @Test public void timeoutForAllSanitizers() { String initialAppName = "initialAppName"; TestingAppNameSanitizer appNameSanitizer = new TestingAppNameSanitizer(); NeverJobValidator neverSanitizer = new NeverJobValidator(); JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors() .map(jd -> jd.toBuilder() .withApplicationName(initialAppName) .build()) .getValue(); AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Arrays.asList(appNameSanitizer, neverSanitizer)); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .expectErrorMatches(error -> { if (!(error instanceof TitusServiceException)) { return false; } TitusServiceException titusException = (TitusServiceException) error; return titusException.getErrorCode().equals(TitusServiceException.ErrorCode.INTERNAL) && error.getMessage().contains("NeverJobValidator timed out"); }) .verify(); } @Test public void noopSanitizers() { String initialAppName = "initialAppName"; JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors() .map(jd -> jd.toBuilder() .withApplicationName(initialAppName) .build()) .getValue(); TestingAppNameSanitizer appNameSanitizer = new TestingAppNameSanitizer(); AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Arrays.asList( new EmptyValidator(), appNameSanitizer, new EmptyValidator() )); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(sanitizedJobDescriptor -> assertThat(sanitizedJobDescriptor.getApplicationName()) .isEqualTo(appNameSanitizer.getDesiredAppName())) .verifyComplete(); } @Test public void allNoopSanitizers() { AggregatingSanitizer sanitizer = new AggregatingSanitizer(configuration, Arrays.asList( new EmptyValidator(), new EmptyValidator(), new EmptyValidator() )); JobDescriptor<?> jobDescriptor = JobDescriptorGenerator.batchJobDescriptors().getValue(); StepVerifier.create(sanitizer.sanitizeAndApply(jobDescriptor)) .assertNext(sanitizedJobDescriptor -> assertThat(sanitizedJobDescriptor).isSameAs(jobDescriptor)) .verifyComplete(); } }
294
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/TestingCapacityGroupSanitizer.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.runtime.endpoint.admission; import java.util.function.UnaryOperator; import com.netflix.titus.api.jobmanager.model.job.JobDescriptor; import com.netflix.titus.common.model.admission.AdmissionSanitizer; import reactor.core.publisher.Mono; /** * This {@link AdmissionSanitizer} implementation ensures a job's capacity group matches a specific string. * It is only used for testing purposes. */ class TestingCapacityGroupSanitizer implements AdmissionSanitizer<JobDescriptor> { private final String desiredCapacityGroup; TestingCapacityGroupSanitizer() { this("desiredCapacityGroup"); } TestingCapacityGroupSanitizer(String desiredCapacityGroup) { this.desiredCapacityGroup = desiredCapacityGroup; } @Override public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) { return Mono.just(jd -> jd.toBuilder().withCapacityGroup(desiredCapacityGroup).build()); } public String getDesiredCapacityGroup() { return desiredCapacityGroup; } }
295
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/NeverJobValidator.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.runtime.endpoint.admission; import java.util.Set; import java.util.function.UnaryOperator; 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.common.model.sanitizer.ValidationError; import reactor.core.publisher.Mono; /** * This validator never completes. It is used to test validation in the face of unresponsive service calls. */ class NeverJobValidator implements AdmissionValidator<JobDescriptor>, AdmissionSanitizer<JobDescriptor> { private final ValidationError.Type errorType; public NeverJobValidator() { this(ValidationError.Type.HARD); } NeverJobValidator(ValidationError.Type errorType) { this.errorType = errorType; } @Override public Mono<Set<ValidationError>> validate(JobDescriptor entity) { return Mono.never(); } @Override public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) { return Mono.never(); } @Override public ValidationError.Type getErrorType() { return errorType; } }
296
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/admission/EmptyValidator.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.runtime.endpoint.admission; import java.util.Set; import java.util.function.UnaryOperator; 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.common.model.sanitizer.ValidationError; import reactor.core.publisher.Mono; class EmptyValidator implements AdmissionValidator<JobDescriptor>, AdmissionSanitizer<JobDescriptor> { @Override public Mono<Set<ValidationError>> validate(JobDescriptor entity) { return Mono.empty(); } @Override public ValidationError.Type getErrorType() { return ValidationError.Type.HARD; } @Override public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) { return Mono.empty(); } }
297
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/common
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/common/rest/JsonMessageReaderWriterTest.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.runtime.endpoint.common.rest; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import com.netflix.titus.api.endpoint.v2.rest.representation.ApplicationSlaRepresentation; import com.netflix.titus.api.endpoint.v2.rest.representation.TierRepresentation; import com.netflix.titus.runtime.endpoint.rest.ErrorResponse; import org.junit.Before; import org.junit.Test; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JsonMessageReaderWriterTest { private static final ErrorResponse ERROR_RESPONSE = ErrorResponse.newError(404, "simulated error") .debug(true) .withContext("testContext", singletonMap("key", "value")) .build(); private final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); private final JsonMessageReaderWriter provider = new JsonMessageReaderWriter(); @Before public void setUp() { provider.httpServletRequest = httpServletRequest; } @Test public void testErrorMessageWrittenInCompactForm() throws Exception { String jsonText = serialize(ERROR_RESPONSE, ErrorResponse.class); assertThat(jsonText).doesNotContain("errorContext"); } @Test public void testErrorMessageWrittenInFullForm() throws Exception { when(httpServletRequest.getParameter(JsonMessageReaderWriter.DEBUG_PARAM)).thenReturn("true"); String jsonText = serialize(ERROR_RESPONSE, ErrorResponse.class); assertThat(jsonText).contains("errorContext"); } @Test public void testFieldsSelection() throws Exception { ApplicationSlaRepresentation myAppSla = new ApplicationSlaRepresentation( "myApp", null, TierRepresentation.Critical, 1D, 2L, 3L, 4L, 5L, null, null, "", "" ); when(httpServletRequest.getParameter(JsonMessageReaderWriter.FIELDS_PARAM)).thenReturn("appName,instanceCPU"); String jsonText = serialize(myAppSla, ApplicationSlaRepresentation.class); assertThat(jsonText).contains("appName", "instanceCPU"); } private <T> String serialize(T entity, Class<T> type) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); provider.writeTo(entity, type, null, null, null, null, output); return new String(output.toByteArray()); } }
298
0
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/grpc
Create_ds/titus-control-plane/titus-server-runtime/src/test/java/com/netflix/titus/runtime/endpoint/v3/grpc/query/V3TaskQueryCriteriaEvaluatorTest.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.runtime.endpoint.v3.grpc.query; 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.common.runtime.TitusRuntime; import com.netflix.titus.common.runtime.TitusRuntimes; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.grpc.protogen.JobDescriptor; import com.netflix.titus.grpc.protogen.TaskStatus; import com.netflix.titus.runtime.endpoint.JobQueryCriteria; import com.netflix.titus.testkit.model.job.JobGenerator; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class V3TaskQueryCriteriaEvaluatorTest { private final TitusRuntime titusRuntime = TitusRuntimes.internal(); @Test public void testTaskWithSystemErrorFilter() { JobQueryCriteria<TaskStatus.TaskState, JobDescriptor.JobSpecCase> criteria = JobQueryCriteria.<TaskStatus.TaskState, JobDescriptor.JobSpecCase>newBuilder() .withSkipSystemFailures(true) .build(); V3TaskQueryCriteriaEvaluator evaluator = new V3TaskQueryCriteriaEvaluator(criteria, titusRuntime); Job<?> job = JobGenerator.oneBatchJob(); // Check non finished task Task task = JobGenerator.oneBatchTask(); assertThat(evaluator.test(Pair.of(job, task))).isTrue(); // Check finished task with non system error reason code Task finishedTask = task.toBuilder().withStatus(com.netflix.titus.api.jobmanager.model.job.TaskStatus.newBuilder() .withState(TaskState.Finished) .withReasonCode(com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_NORMAL) .build() ).build(); assertThat(evaluator.test(Pair.of(job, finishedTask))).isTrue(); // Check finish that with system error Task taskWithSystemError = task.toBuilder().withStatus(com.netflix.titus.api.jobmanager.model.job.TaskStatus.newBuilder() .withState(TaskState.Finished) .withReasonCode(com.netflix.titus.api.jobmanager.model.job.TaskStatus.REASON_LOCAL_SYSTEM_ERROR) .build() ).build(); assertThat(evaluator.test(Pair.of(job, taskWithSystemError))).isFalse(); } }
299