code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
public Set<Integer> getContainersOfTerminatedFlows() {
Set<Integer> activeFlows = new HashSet<>();
Set<Integer> currentNameSpacedPods = new HashSet<>();
Set<Integer> result = new HashSet<>();
// The unfinished statuses DISPATCHING, PREPARING, RUNNING, PAUSED, KILLING, FAILED_FINISHING.
// This map will be used to find out all executions of above statuses where
// submit_time < current system time - 0 from the DB
ImmutableMap<Status, Pair<Duration, String>> unFinishedStatusesMap =
this.validityMap.keySet().stream().collect(ImmutableMap.toImmutableMap(e -> e,
e -> new Pair<>(Duration.ZERO, SUBMIT_TIME)));
// Obtain all pods in current namespace which are dispatched from current Azkaban cluster
try {
currentNameSpacedPods = this.containerizedImpl.getContainersByDuration(Duration.ZERO);
} catch (final ExecutorManagerException e) {
logger.error("Unable to obtain the pods in the current namespace and Azkaban cluster", e);
}
// Obtain all containerized executions that are in unfinished statuses
for (Status status : unFinishedStatusesMap.keySet()) {
try {
List<ExecutableFlow> flows = this.executorLoader.fetchStaleFlowsForStatus(status,
unFinishedStatusesMap);
activeFlows.addAll(
flows.stream().map(ExecutableFlow::getExecutionId).collect(Collectors.toSet()));
} catch (final ExecutorManagerException e) {
logger.error("Unable to obtain current flows executions of status {}, cannot cross-check "
+ "to-be-killed pods, returning", status, e);
return result;
}
}
// cross-check: the pod needs to be cleaned up if its execution status is finished
for (int executionId : currentNameSpacedPods) {
if (!activeFlows.contains(executionId)) {
result.add(executionId);
}
}
return result;
}
|
From all pods in the current namespace and Azkaban cluster, select the pods whose executions
are not in unfinished statuses, e.g. DISPATCHING, PREPARING, RUNNING, PAUSED, KILLING,
FAILED_FINISHING in DB (select pods whose executions are finished/terminated)
|
getContainersOfTerminatedFlows
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
@NotNull
Set<Integer> getRecentlyTerminatedFlows() {
Set<Integer> recentlyTerminatedFlows = new HashSet<>();
this.recentTerminatedStatusMap.forEach((status, value) -> {
try {
List<ExecutableFlow> flows = this.executorLoader.fetchFreshFlowsForStatus(
status, this.recentTerminatedStatusMap);
recentlyTerminatedFlows.addAll(
flows.stream().map(ExecutableFlow::getExecutionId).collect(Collectors.toSet()));
logger.info("Got recently terminated flows executions of Status " + status + ": " +
flows.stream().map(ExecutableFlow::getExecutionId).map(Objects::toString)
.collect(Collectors.joining(",")));
} catch (final ExecutorManagerException e) {
logger.error("Unable to obtain current flows executions of Status " + status, e);
}
});
return recentlyTerminatedFlows;
}
|
Get the flows recently (last 15 minutes) terminated: status in (execution_stopped, killed,
killing, failed, failed_finishing, failed_succeeded, canceled)
|
getRecentlyTerminatedFlows
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
public void cleanUpStaleFlows(final Status status) {
logger.info("Cleaning up stale flows for status: " + status.name());
List<ExecutableFlow> staleFlows;
try {
staleFlows = this.executorLoader.fetchStaleFlowsForStatus(status, this.validityMap);
// emit metrics around stale flows of this status
this.containerizationMetrics.addCleanupStaleStatusFlowNumber(status.name(), staleFlows.size());
} catch (final Exception e) {
logger.error("Exception occurred while fetching stale flows during clean up." + e);
return;
}
for (final ExecutableFlow flow : staleFlows) {
if (shouldIgnore(flow, status)) {
continue;
}
Status originalStatus = flow.getStatus();
cancelFlowQuietly(flow, originalStatus);
retryFlowQuietly(flow, originalStatus);
deleteContainerQuietly(flow.getExecutionId());
// If pod is cleaned up when flow is in DISPATCHING or PREPARING state, the
// container-dispatch-fail meter should be incremented
if (originalStatus == Status.DISPATCHING || originalStatus == Status.PREPARING) {
this.containerizationMetrics.markContainerDispatchFail();
}
}
}
|
Try cleaning the stale flows for a given status. This will try to cancel the flow, if
unreachable, flow will be finalized. Pod Container will be deleted.
@param status
|
cleanUpStaleFlows
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
private boolean shouldIgnore(final ExecutableFlow flow, final Status status) {
if (status != Status.PREPARING) {
return false;
}
final ExecutionOptions executionOptions = flow.getExecutionOptions();
if (null == executionOptions) {
return false;
}
boolean isDevPod = Boolean.parseBoolean(
executionOptions.getFlowParameters().get(FlowParameters.FLOW_PARAM_ENABLE_DEV_POD));
if (!isDevPod) {
return false;
}
return flow.getSubmitTime() > System.currentTimeMillis() - Duration.ofDays(2).toMillis();
}
|
Handles special cases. If the flow is in PREPARING STATE and enable.dev.pod=true then ignore
executions from the last 2 days.
@param flow
@param status
@return
|
shouldIgnore
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
private void cancelFlowQuietly(ExecutableFlow flow, Status originalStatus) {
try {
logger.info(
"Cleaning up stale flow " + flow.getExecutionId() + " in state " + originalStatus
.name());
this.containerizedDispatchManager.cancelFlow(flow, flow.getSubmitUser());
} catch (final Exception e) {
logger.error("Unexpected Exception while canceling and finalizing flow during clean up." + e);
}
}
|
Try to quietly cancel the flow. Cancel flow tries to gracefully kill the executions if they are
reachable, otherwise, flow will be finalized.
@param flow
|
cancelFlowQuietly
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
logger.info("Start container cleanup service");
// Default execution clean up interval is 10 min, container clean up interval is 60 min
this.cleanupService.scheduleAtFixedRate(this::cleanUpStaleFlows, 0L,
this.executionCleanupIntervalMin, TimeUnit.MINUTES);
this.cleanupService.scheduleAtFixedRate(this::cleanUpContainersInTerminalStatuses, 0L,
this.containerCleanupIntervalMin, TimeUnit.MINUTES);
if (this.yarnAppCleanupIntervalMin <= 0) {
logger.warn("Yarn application cleanup schedule not started: "
+ "invalid time interval " + this.yarnAppCleanupIntervalMin + ", please correct value "
+ ContainerizedDispatchManagerProperties.CONTAINERIZED_YARN_APPLICATION_CLEANUP_INTERVAL_MIN);
} else {
this.cleanupService.scheduleAtFixedRate(this::cleanUpDanglingYarnApplications, 0L,
this.yarnAppCleanupIntervalMin, TimeUnit.MINUTES);
}
}
|
Start periodic deletions of per-container resources for stale executions.
|
start
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerCleanupManager.java
|
Apache-2.0
|
public static TreeSet<String> getJobTypesForFlow(final ExecutableFlow flow) {
final TreeSet<String> jobTypes = new TreeSet<>();
populateJobTypeForFlow(flow, jobTypes);
return jobTypes;
}
|
This method is used to get jobTypes for a flow. This method is going to call
populateJobTypeForFlow which has recursive method call to traverse the DAG for a flow.
@param flow Executable flow object
@return
@throws ExecutorManagerException
|
getJobTypesForFlow
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerImplUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerImplUtils.java
|
Apache-2.0
|
private static void populateJobTypeForFlow(final ExecutableNode node, Set<String> jobTypes) {
if (node instanceof ExecutableFlowBase) {
final ExecutableFlowBase base = (ExecutableFlowBase) node;
for (ExecutableNode subNode : base.getExecutableNodes()) {
populateJobTypeForFlow(subNode, jobTypes);
}
} else {
// If a node is disabled, we don't need to initialize its jobType container image when
// creating a pod.
if (node.getStatus() != Status.DISABLED) {
jobTypes.add(node.getType());
}
}
}
|
This method is used to populate jobTypes for ExecutableNode.
@param node
@param jobTypes
|
populateJobTypeForFlow
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerImplUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerImplUtils.java
|
Apache-2.0
|
public List<Integer> getQueuedFlowIds() {
final List<Integer> allIds = new ArrayList<>();
try {
allIds.addAll(this.executorLoader.selectQueuedFlows(Status.DISPATCHING));
allIds.addAll(this.executorLoader.selectQueuedFlows(Status.PREPARING));
} catch (final ExecutorManagerException e) {
logger.error("Failed to get queued flow ids.", e);
}
return allIds;
}
|
Get queued flow ids from database. The status for queued flows is PREPARING or DISPATCHING for
containerization.
@return
|
getQueuedFlowIds
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public long getQueuedFlowSize() {
return getQueuedFlowIds().size();
}
|
Get size of queued flows. The status for queued flows is PREPARING or DISPATCHING for containerization.
@return
|
getQueuedFlowSize
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public DispatchMethod getDispatchMethod() {
return this.containerRampUpCriteria.getDispatchMethod();
}
|
Get dispatch method enum for this class.
@return
|
getDispatchMethod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public Status getStartStatus() {
return Status.READY;
}
|
Get the status for executions maintained in queue. For other dispatch implementations, the
status for executions in queue is PREPARING. But for containerized dispatch method, the status
will be READY.
@return
|
getStartStatus
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public Status getStartStatus(ExecutableFlow execFlow) {
if (execFlow.getDispatchMethod() == DispatchMethod.CONTAINERIZED) {
return Status.READY;
} else {
return Status.PREPARING;
}
}
|
@param execFlow {@link ExecutableFlow} containing all the information for a flow execution
including dispatch method which will be utilized here.
@return READY if the dispatchMethod is CONTAINERIZED otherwise PREPARING.
|
getStartStatus
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public void shutdown() {
logger.info("Shutting down queue processor thread for containerized dispatch implementation.");
if (null != this.queueProcessor) {
this.queueProcessor.shutdown();
}
if (this.azkProps.getBoolean(ContainerizedDispatchManagerProperties.KUBERNETES_WATCH_ENABLED,
false) && containerizedWatch.isPresent()) {
logger.info("Shutting down containerized watch");
containerizedWatch.get().requestShutdown();
}
this.executorHealthChecker.ifPresent(ehc -> ehc.shutdown());
}
|
This method will shutdown the queue processor thread. It won't pick up executions from queue
for dispatch after this. This method will be called when webserver will shutdown.
|
shutdown
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public void enableQueueProcessorThread() {
this.queueProcessor.setActive(true);
}
|
This method is used to enable queue processor thread. It will resume dispatching executions.
Due to any maintenance of containerized infrastructure, if queue processor was disabled then it
can enabled again using this method.
|
enableQueueProcessorThread
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public void run() {
// Loops till QueueProcessorThread is shutdown
while (!this.shutdown) {
try {
// Start processing queue if active, otherwise wait for sometime
if (this.isActive) {
processQueuedFlows();
}
} catch (final Exception e) {
ContainerizedDispatchManager.logger.error(
"QueueProcessorThread Interrupted. Probably to shut down.", e);
}
}
}
|
This QueueProcessorThread will fetch executions from database in batch/single execution at a
time and dispatch it in container.
|
run
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
@Override
public void run() {
try {
logger.info("Creating a container for {}", executionId);
long startTime = System.currentTimeMillis();
// Create a container for execution id. The container creation will throw exception if it
//is not able read template files, unable to parse files, unable to replace dynamic
//variables etc.
ContainerizedDispatchManager.this.containerizedImpl.createContainer(executionId);
logger.info("Time taken to dispatch a container for {} is {} seconds", executionId,
(System.currentTimeMillis() - startTime) / 1000);
} catch (ExecutorManagerException e) {
logger.info("Unable to dispatch container in Kubernetes for : {}", executionId);
logger.info("Reason for dispatch failure: {}", e.getMessage());
// Finalize the flow if the dispatch failed.
try {
ContainerizedDispatchManager.this.containerizationMetrics.markContainerDispatchFail();
ExecutableFlow execFlow =
ContainerizedDispatchManager.this.executorLoader.fetchExecutableFlow(executionId);
Status originalStatus = execFlow.getStatus();
finalizeFlow(execFlow, "Failed to dispatch", e, Status.EXECUTION_STOPPED);
logger.info("Finalizing the flow execution ", executionId);
ExecutionControllerUtils.restartFlow(execFlow, originalStatus);
} catch (ExecutorManagerException executorManagerException) {
logger.error("Unable to update execution status to EXECUTION_STOPPED for : {}", executionId);
} catch (RuntimeException re) {
logger.error("Unexpected RuntimeException in ExecutionDispatcher", re);
}
}
}
|
This class is a worker class to dispatch execution in container.
|
run
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedDispatchManager.java
|
Apache-2.0
|
public Class getImplClass() {
return this.implClass;
}
|
This enum represents implementation for Containerization. For now, we are adding
implementation for Kubernetes but in future, execution can be dispatched on any other
containerized infrastructure.
|
getImplClass
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerizedImplType.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerizedImplType.java
|
Apache-2.0
|
public DispatchMethod getDispatchMethod(final ExecutableFlow flow) {
if (this.allowList.contains(ALL)) {
return DispatchMethod.CONTAINERIZED;
}
Set<String> jobTypesForFlow = ContainerImplUtils.getJobTypesForFlow(flow);
for (String jobType : jobTypesForFlow) {
if (!this.allowList.contains(jobType)) {
return DispatchMethod.POLL;
}
}
return DispatchMethod.CONTAINERIZED;
}
|
If the set of JobTypes extracted from the flow is not allowed, the return DispatchMethod.POLL
other DispatchMethod.CONTAINERIZED. If the allowList contains "ALL", then
DispatchMethod.CONTAINERIZED is returned.
|
getDispatchMethod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerJobTypeCriteria.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerJobTypeCriteria.java
|
Apache-2.0
|
public DispatchMethod getDispatchMethod(final ExecutableFlow flow) {
if (CollectionUtils.containsAny(flow.getProxyUsers(), this.denyList)) {
return DispatchMethod.POLL;
} else {
return DispatchMethod.CONTAINERIZED;
}
}
|
If the set of flow proxy users contains a proxy user on the deny list,
then return DispatchMethod.POLL, else return DispatchMethod.CONTAINERIZED
@param flow
@return DispatchMethod
|
getDispatchMethod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerProxyUserCriteria.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerProxyUserCriteria.java
|
Apache-2.0
|
public DispatchMethod getDispatchMethod() {
if (this.rampUp == 0) {
return DispatchMethod.POLL;
} else if (this.rampUp == 100) {
return DispatchMethod.CONTAINERIZED;
}
ThreadLocalRandom rand = ThreadLocalRandom.current();
int randomInt = rand.nextInt(100);
if (randomInt < this.rampUp) {
return DispatchMethod.CONTAINERIZED;
} else {
return DispatchMethod.POLL;
}
}
|
Return DispatchMethod based on the rampUp percentage and random selection
|
getDispatchMethod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/ContainerRampUpCriteria.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/ContainerRampUpCriteria.java
|
Apache-2.0
|
private void addIncludedJobTypes() {
INCLUDED_JOB_TYPES.add("command");
INCLUDED_JOB_TYPES.add("gobblin");
INCLUDED_JOB_TYPES.add("hadoopJava");
INCLUDED_JOB_TYPES.add("hadoopShell");
INCLUDED_JOB_TYPES.add("hive");
INCLUDED_JOB_TYPES.add("java");
INCLUDED_JOB_TYPES.add("java2");
INCLUDED_JOB_TYPES.add("pig");
INCLUDED_JOB_TYPES.add("pigLi");
INCLUDED_JOB_TYPES.add("javaprocess");
INCLUDED_JOB_TYPES.add("noop");
}
|
Populate the included job types set with all the types that are readily available as part of
azkaban base image.
|
addIncludedJobTypes
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private boolean isPresentInIncludedJobTypes(final String jobType) {
if (INCLUDED_JOB_TYPES.contains(jobType)) {
return true;
} else {
return isStartWithIncludedJobTypes(jobType);
}
}
|
Check if job type contains in the included job types. If not check if the job type starts with
the any of the job types present in the included job type set. For example, in case of pig job
type it can contain version such as pigLi-0.11.1. This is nothing but pointing to the different
installation pig job. Hence, it just matches the prefix i.e. pigLi which is the actual job type
name.
@param jobType
@return boolean
|
isPresentInIncludedJobTypes
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private boolean isStartWithIncludedJobTypes(final String jobType) {
for (final String includedJobType : INCLUDED_JOB_TYPES) {
if (jobType.toLowerCase().startsWith(includedJobType.toLowerCase())) {
return true;
}
}
return false;
}
|
Check if the job type starts with the aay of the job types present in the included job type
set. For example, in case of pig job type it can contain version such as pigLi-0.11.1. This is
nothing but pointing to the different installation pig job. Hence, it just matches the prefix
i.e. pigLi which is the actual job type name.
@param jobType
@return boolean
|
isStartWithIncludedJobTypes
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private Set<String> filterIncludedJobTypes(final Set<String> jobTypes) {
return jobTypes.stream()
.filter(jobType -> !isPresentInIncludedJobTypes(jobType))
.collect(Collectors.toSet());
}
|
Filter out the included job types from the given job types.
@param jobTypes
@return Set<String>
|
filterIncludedJobTypes
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@Override
public synchronized void createContainer(final int executionId) throws ExecutorManagerException {
createPod(executionId);
if (isServiceRequired()) {
createService(executionId);
}
}
|
This method is used to create container during dispatch of execution. It will create pod for a
flow execution. It will also create a service for a pod if azkaban.kubernetes.service .required
property is set.
@param executionId
@throws ExecutorManagerException
|
createContainer
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@Override
public synchronized void deleteContainer(final int executionId) throws ExecutorManagerException {
try { // if pod deletion is not successful, the service deletion can still be handled
deletePod(executionId);
} finally {
if (isServiceRequired()) {
deleteService(executionId);
}
}
}
|
This method is used to delete container. It will delete pod for a flow execution. If the
service was created then it will also delete the service. This method can be called as a part
of cleanup process for containers in case containers didn't shutdown gracefully.
@param executionId
@throws ExecutorManagerException
|
deleteContainer
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@Override
public Set<Integer> getContainersByDuration(final Duration containerDuration) throws ExecutorManagerException {
// Get the list of pods from current Azkaban cluster and namespace
final V1PodList podList= this.getListNamespacedPod();
// Get all execution ids of the pods whose age is older than a certain time duration
final OffsetDateTime validStartTimeStamp = OffsetDateTime.now().minus(
containerDuration.toMillis(), ChronoUnit.MILLIS);
return getExecutionIdsFromPodList(podList, validStartTimeStamp);
}
|
This method is used to fetch all pods in the current az cluster and namespace that are
created a time duration ago
@param containerDuration duration between container start timestamp and current timestamp
@return Set of container's execution ids
|
getContainersByDuration
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private V1PodList getListNamespacedPod() throws ExecutorManagerException {
try {
// Select pods from current Azkaban cluster and namespace
final String label =
CLUSTER_LABEL_NAME + "=" + this.clusterName + "," + APP_LABEL_NAME + "=" + POD_APPLICATION_TAG;
return this.coreV1Api.listNamespacedPod(
this.namespace,
null,
null,
null,
null,
label,
null,
null,
null,
null,
null
);
} catch (final ApiException e) {
logger.error(String.format("Unable to fetch pods in %s.", this.clusterName),
e.getResponseBody());
throw new ExecutorManagerException(e);
}
}
|
This method is used to fetch a list of all pods in the current az cluster and namespace
@return
@throws ExecutorManagerException
|
getListNamespacedPod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@VisibleForTesting
Set<Integer> getExecutionIdsFromPodList(final V1PodList podList, final OffsetDateTime validStartTimeStamp) {
final Set<Integer> staleContainerExecIdSet = new HashSet<>();
for (final V1Pod pod: podList.getItems()) {
final V1ObjectMeta podMetadata = pod.getMetadata();
if (podMetadata.getCreationTimestamp().isBefore(validStartTimeStamp)) {
final String execIdLabel =
podMetadata.getLabels().getOrDefault(EXECUTION_ID_LABEL_NAME,
EXECUTION_ID_LABEL_PREFIX + DEFAULT_EXECUTION_ID);
try {
final String execId = execIdLabel.substring(execIdLabel.indexOf(
EXECUTION_ID_LABEL_PREFIX) + EXECUTION_ID_LABEL_PREFIX.length());
final int id = Integer.valueOf(execId);
if (id > 0) {
staleContainerExecIdSet.add(id);
}
} catch (final Exception e) {
logger.error(String.format("Unable to retrieve execution id from pod %s",
podMetadata.getName()), e.getMessage());
}
}
}
return staleContainerExecIdSet;
}
|
Obtain a set of execution ids from stale pod list
@param podList a stable pod list fetched from current az cluster and namespace
@param validStartTimeStamp earliest creation timestamp for a valid pod
@return
|
getExecutionIdsFromPodList
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private String imageTypeOverrideParam(final String imageType) {
return String.join(".", IMAGE, imageType, VERSION);
}
|
Construct the flow override parameter (key) for image version.
@param imageType
@return flow override param
|
imageTypeOverrideParam
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@VisibleForTesting
VersionSet fetchVersionSet(final int executionId, final Map<String, String> flowParams,
Set<String> imageTypesUsedInFlow, final ExecutableFlow executableFlow)
throws ExecutorManagerException {
VersionSet versionSet = null;
try {
if (flowParams != null &&
flowParams.containsKey(Constants.FlowParameters.FLOW_PARAM_VERSION_SET_ID)) {
final int versionSetId = Integer.parseInt(flowParams
.get(Constants.FlowParameters.FLOW_PARAM_VERSION_SET_ID));
try {
versionSet = this.versionSetLoader.getVersionSetById(versionSetId).get();
// Validate if the versionSet contains valid version. If not update the correct
// version using rampup and active image version information.
final Map<String, VersionInfo> updatedVersionInfoMap =
this.imageRampupManager.validateAndGetUpdatedVersionMap(executableFlow, versionSet);
if (!updatedVersionInfoMap.isEmpty()) {
// Rebuild version set with correct version
final VersionSetBuilder versionSetBuilder = new VersionSetBuilder(
this.versionSetLoader);
versionSetBuilder.addElements(updatedVersionInfoMap);
versionSet = versionSetBuilder.build();
}
/*
* Validate that all images part of the flow are included in the retrieved
* VersionSet. If there are images that were not part of the retrieved version
* set, then create a new VersionSet with a superset of all images.
*/
final Set<String> imageVersionsNotFound = new TreeSet<>();
final Map<String, VersionInfo> overlayMap = new HashMap<>();
for (final String imageType : imageTypesUsedInFlow) {
if (flowParams.containsKey(imageTypeOverrideParam(imageType))) {
// Fetches the user overridden version from the database and this will make sure if
// the overridden version exists/registered on Azkaban database. Hence, it follows a
// fail fast mechanism to throw exception if the version does not exist for the
// given image type.
final Set<State> allowedImageStates = getImageVersionState(flowParams);
final VersionInfo versionInfo = this.imageRampupManager.getVersionInfo(imageType,
flowParams.get(imageTypeOverrideParam(imageType)),
allowedImageStates);
overlayMap.put(imageType, versionInfo);
logger.info("User overridden image type {} of version {} is used", imageType,
versionInfo.getVersion());
} else if (!(isPresentInIncludedJobTypes(imageType) || versionSet.getVersion(imageType)
.isPresent())) {
logger.info("ExecId: {}, imageType: {} not found in versionSet {}",
executionId, imageType, versionSetId);
imageVersionsNotFound.add(imageType);
}
}
if (!(imageVersionsNotFound.isEmpty() && overlayMap.isEmpty())) {
// Populate a new Version Set
logger.info("ExecId: {}, Flow had more imageTypes than specified in versionSet {}. "
+ "Constructing a new one", executionId, versionSetId);
final VersionSetBuilder versionSetBuilder = new VersionSetBuilder(
this.versionSetLoader);
versionSetBuilder.addElements(versionSet.getImageToVersionMap());
// The following is a safety check. Just in case: getVersionByImageTypes fails below due to an
// exception, we will have an incomplete/incorrect versionSet. Setting it null ensures, it will
// be processed from scratch in the following code block
versionSet = null;
if (!imageVersionsNotFound.isEmpty()) {
versionSetBuilder.addElements(
this.imageRampupManager
.getVersionByImageTypes(executableFlow, imageVersionsNotFound,
overlayMap.keySet()));
}
if (!overlayMap.isEmpty()) {
versionSetBuilder.addElements(overlayMap);
}
versionSet = versionSetBuilder.build();
}
} catch (final Exception e) {
logger.error("ExecId: {}, Could not find version set id: {} as specified by flow params. "
+ "Will continue by creating a new one.", executionId, versionSetId);
}
}
if (versionSet == null) {
// Need to build a version set
// Filter all the job types available in azkaban base image from the input image types set
imageTypesUsedInFlow = this.filterIncludedJobTypes(imageTypesUsedInFlow);
// Now we will check the flow params for any override versions provided and apply them
final Map<String, VersionInfo> overlayMap = new HashMap<>();
for (final String imageType : imageTypesUsedInFlow) {
final String imageTypeVersionOverrideParam = imageTypeOverrideParam(imageType);
VersionInfo versionInfo;
if (flowParams != null && flowParams.containsKey(imageTypeVersionOverrideParam)) {
// Fetches the user overridden version from the database and this will make sure if
// the overridden version exists/registered on Azkaban database. Hence, it follows a
// fail fast mechanism to throw exception if the version does not exist for the
// given image type.
// Allow test version override if allow.test.version flow parameter is set to true
if (flowParams.containsKey(FlowParameters.FLOW_PARAM_ALLOW_IMAGE_TEST_VERSION) &&
Boolean.TRUE.equals(Boolean
.valueOf(flowParams.get(FlowParameters.FLOW_PARAM_ALLOW_IMAGE_TEST_VERSION)))) {
versionInfo = this.imageRampupManager.getVersionInfo(imageType,
flowParams.get(imageTypeVersionOverrideParam),
State.getNewActiveTestAndStableStateFilter());
overlayMap.put(imageType, versionInfo);
logger.info("User overridden image type {} of version {} is used", imageType,
versionInfo.getVersion());
} else {
final Set<State> allowedImageStates = getImageVersionState(flowParams);
versionInfo = this.imageRampupManager.getVersionInfo(imageType,
flowParams.get(imageTypeVersionOverrideParam),
allowedImageStates);
overlayMap.put(imageType, versionInfo);
logger.info("User overridden image type {} of version {} is used", imageType,
versionInfo.getVersion());
}
}
}
final Map<String, VersionInfo> versionMap =
this.imageRampupManager.getVersionByImageTypes(executableFlow, imageTypesUsedInFlow,
overlayMap.keySet());
final VersionSetBuilder versionSetBuilder = new VersionSetBuilder(this.versionSetLoader);
versionSetBuilder.addElements(versionMap);
versionSet = versionSetBuilder.addElements(overlayMap).build();
}
} catch (NumberFormatException | IOException | ImageMgmtException e) {
logger.error("ExecId: {}, Exception in fetching the VersionSet. Error msg: {}",
executionId, e.getMessage());
throw new ExecutorManagerException(e);
}
return versionSet;
}
|
This method fetches the complete version set information (Map of jobs and their versions)
required to run the flow.
@param flowParams Set of flow properties and flow parameters
@param imageTypesUsedInFlow
@return VersionSet
@throws ExecutorManagerException
|
fetchVersionSet
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@VisibleForTesting
VPARecommendation getFlowContainerRecommendedRequests(final ExecutableFlow executableFlow,
final FlowResourceRecommendation flowResourceRecommendation,
final ConcurrentHashMap<String, FlowResourceRecommendation> flowResourceRecommendationMap) {
// VPA is disabled globally: do not create VPA object.
if (!this.vpaEnabled) {
return EMPTY_VPA_RECOMMENDATION;
}
try {
// Top-down approach to apply maxAllowedMemory first and then find the optimal memory request
final VPARecommendation vpaRecommendation =
this.vpaRecommender.getFlowContainerRecommendedRequests(this.namespace,
FLOW_VPA_LABEL_NAME, this.getVPAName(flowResourceRecommendation.getId()),
this.flowContainerName, this.cpuRecommendationMultiplier,
this.memoryRecommendationMultiplier, this.minAllowedCPU,
this.minAllowedMemory, this.maxAllowedCPU, this.maxAllowedMemory);
// Migration/Rollout purpose: set up VPA objects even though the feature is not ramped up.
if (!IsVPAEnabledForFlow(executableFlow)) {
return EMPTY_VPA_RECOMMENDATION;
}
if (vpaRecommendation == null) {
return maxVpaRecommendation;
}
if (!vpaRecommendation.getCpuRecommendation().equals(flowResourceRecommendation.getCpuRecommendation()) ||
!vpaRecommendation.getMemoryRecommendation().equals(flowResourceRecommendation.getMemoryRecommendation())) {
flowResourceRecommendation.setCpuRecommendation(vpaRecommendation.getCpuRecommendation());
flowResourceRecommendation.setMemoryRecommendation(vpaRecommendation.getMemoryRecommendation());
// Atomic lock-free update
flowResourceRecommendationMap.put(flowResourceRecommendation.getFlowId(),
flowResourceRecommendation);
// We may choose to update DB periodically instead of every time.
this.projectManager.updateFlowResourceRecommendation(flowResourceRecommendation);
}
executableFlow.setVPAEnabled(true);
return vpaRecommendation;
} catch (ExecutorManagerException | ProjectManagerException e) {
logger.error("Cannot apply resource recommendation from VPA for execId {}", executableFlow
.getExecutionId(), e);
// It is fine if cpu recommendation or memory recommendation is null here.
return new VPARecommendation(flowResourceRecommendation.getCpuRecommendation(),
flowResourceRecommendation.getMemoryRecommendation());
}
}
|
Create FlowResourceRecommendation if not exist; Get recommended requests from VPA; Persist
recommendation to DB for caching if changed.
@param executableFlow
@param flowResourceRecommendation
@param flowResourceRecommendationMap it is used for updating flowResourceRecommendation
@return Nullable CPU request and nullable memory request for a flow container
|
getFlowContainerRecommendedRequests
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@VisibleForTesting
String getFlowContainerDiskRequest(final Map<String, String> flowParam) {
if (flowParam == null || flowParam.isEmpty() || !flowParam
.containsKey(FlowParameters.FLOW_PARAM_FLOW_CONTAINER_DISK_REQUEST)) {
return this.diskRequest;
}
String userDiskRequest =
flowParam.get(FlowParameters.FLOW_PARAM_FLOW_CONTAINER_DISK_REQUEST);
int resourceCompare = compareResources(this.maxAllowedDisk, userDiskRequest);
if (resourceCompare < 0) {
// User request disk capacity exceeds max allowed disk
userDiskRequest = this.maxAllowedDisk;
} else if (resourceCompare == 0) {
// If comparison fails for any reason, use the value from the config.
userDiskRequest = this.diskRequest;
}
return userDiskRequest;
}
|
This method is used to get disk request for flow container. Precedence is defined below.
a) Use disk request set in flow parameter constrained by max allowed disk set in config
b) Use disk request set in system properties or default is set in @diskRequest
@param flowParam
@return Disk request for a flow container
|
getFlowContainerDiskRequest
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void setupJavaRemoteDebug(final Map<String, String> envVariables,
final Map<String, String> flowParam) {
if (flowParam != null && !flowParam.isEmpty() && flowParam
.containsKey(Constants.FlowParameters.FLOW_PARAM_JAVA_ENABLE_DEBUG)) {
envVariables.put(ContainerizedDispatchManagerProperties.ENV_JAVA_ENABLE_DEBUG,
flowParam.get(Constants.FlowParameters.FLOW_PARAM_JAVA_ENABLE_DEBUG));
}
}
|
This method is used to setup environment variable to enable remote debug on kubernetes flow
container. Based on this environment variable, you can decide to enable or disable remote
debug.
@param envVariables
@param flowParam
|
setupJavaRemoteDebug
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void setupDevPod(final Map<String, String> envVariables,
final Map<String, String> flowParam) {
if (isDevPod(flowParam)) {
envVariables.put(ContainerizedDispatchManagerProperties.ENV_ENABLE_DEV_POD,
flowParam.get(FlowParameters.FLOW_PARAM_ENABLE_DEV_POD));
}
}
|
This method is used to setup environment variable to enable pod as dev pod which can be helpful
for testing. Based on this environment variable, you can decide to start the flow container or
not.
@param envVariables
@param flowParam
|
setupDevPod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
void setupPodEnvVariables(final Map<String, String> envVariables,
final Map<String, String> flowParam) {
if (flowParam != null && !flowParam.isEmpty()) {
flowParam.forEach((k, v) -> {
if (k.startsWith(FlowParameters.FLOW_PARAM_POD_ENV_VAR)) {
envVariables
.put(StringUtils.removeStart(k, FlowParameters.FLOW_PARAM_POD_ENV_VAR).toUpperCase(),
v);
}
});
}
}
|
This method is used to setup any environment variable for a pod which can be passed from flow
parameter. To provide the generic solution, it is adding all the flow parameters starting with
(@FlowParameters.FLOW_PARAM_POD_ENV_VAR)
@param envVariables
@param flowParam
|
setupPodEnvVariables
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void addEnvVariablesToSpecBuilder(final AzKubernetesV1SpecBuilder v1SpecBuilder,
final Map<String, String> envVariables) {
envVariables.forEach((key, value) -> v1SpecBuilder.addEnvVarToFlowContainer(key, value));
}
|
Adding environment variables in pod spec builder.
@param v1SpecBuilder
@param envVariables
|
addEnvVariablesToSpecBuilder
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
@VisibleForTesting
V1Pod createPodFromMetadataAndSpec(final V1ObjectMeta podMetadata, final V1PodSpec podSpec) {
return new AzKubernetesV1PodBuilder(podMetadata, podSpec).build();
}
|
Creates a pod instance.
@param podMetadata metadata to use during pod instantiation
@param podSpec spec to use during pod instantiation
@return a {@link V1Pod} instance
|
createPodFromMetadataAndSpec
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private static void logPodSpecYaml(final int executionId, final Object podObject,
final Map<String, String> flowParam, String message) {
final String podSpecYaml = Yaml.dump(podObject).trim();
if (isDevPod(flowParam)) {
logger.info(message, executionId, podSpecYaml);
} else {
logger.debug(message, executionId, podSpecYaml);
}
}
|
This method is used to log pod spec yaml for debugging purpose. If Pod is marked as dev pod
then pod spec yaml will be printed in logs for INFO level else it will be logged for DEBUG
level.
@param executionId
@param podObject Pod/PodSpec depending on the log
@param flowParam
|
logPodSpecYaml
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private ImmutableMap getLabelsForPod(final ExecutableFlow executableFlow,
final int flowResourceRecommendationId, Map<String, String> flowParam) {
final int executionId = executableFlow.getExecutionId();
final ImmutableMap.Builder mapBuilder = ImmutableMap.builder();
mapBuilder.put(CLUSTER_LABEL_NAME, this.clusterName);
mapBuilder.put(EXECUTION_ID_LABEL_NAME, EXECUTION_ID_LABEL_PREFIX + executionId);
mapBuilder.put(APP_LABEL_NAME, POD_APPLICATION_TAG);
// Each azkaban execution pod will share the same flow vpa label if it comes from the same
// azkaban flow. This label is used for VPA to map multiple azkaban execution pods with one
// azkaban flow.
// In VPA, each VPA object will have its own label selector to choose all pods having the
// same flow vpa label so that it can provide resource recommendation to one azkaban flow.
mapBuilder.put(FLOW_VPA_LABEL_NAME, this.getVPAName(flowResourceRecommendationId));
// Note that the service label must match the selector used for the corresponding service
if (isServiceRequired()) {
mapBuilder.put("service", String.join("-", SERVICE_SELECTOR_PREFIX,
clusterQualifiedExecId(this.clusterName, executionId)));
}
// Set the label for disabling pod-cleanup.
if (flowParam != null && !flowParam.isEmpty() && flowParam
.containsKey(FlowParameters.FLOW_PARAM_DISABLE_POD_CLEANUP)) {
mapBuilder.put(DISABLE_CLEANUP_LABEL_NAME,
flowParam.get(FlowParameters.FLOW_PARAM_DISABLE_POD_CLEANUP));
}
return mapBuilder.build();
}
|
Create labels that should be applied to the Pod.
@return
|
getLabelsForPod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
public static String getLabelSelector(final Props azkProps) {
requireNonNull(azkProps, "azkaban properties must not be null");
final String clusterName = azkProps.getString(ConfigurationKeys.AZKABAN_CLUSTER_NAME,
DEFAULT_CLUSTER_NAME);
final StringBuilder selectorBuilder = new StringBuilder();
selectorBuilder.append(CLUSTER_LABEL_NAME + "=" + clusterName).append(",")
.append(APP_LABEL_NAME + "=" + POD_APPLICATION_TAG);
return selectorBuilder.toString();
}
|
Get a {@code lableSelector} that can be used to list all the flow-container-pods for the
current namespace.
Example Selector: 'cluster=cluster1,app=azkaban-exec-server'
@return label selector
|
getLabelSelector
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private boolean IsVPAEnabledForFlow(ExecutableFlow executableFlow) {
int flowNameHashValMapping = ContainerImplUtils.getFlowNameHashValMapping(executableFlow);
return vpaEnabled && flowNameHashValMapping <= this.vpaRampUp && this.vpaFlowCriteria.IsVPAEnabledForFlow(executableFlow);
}
|
Return a boolean value indicates whether vertical pod autoscaler is enabled for a given flow
based on ramp up rate and global vpa enabled flag
@param executableFlow
@return vpa enable status
|
IsVPAEnabledForFlow
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private ImmutableMap getAnnotationsForPod() {
return ImmutableMap.of();
}
|
TODO: Add implementation to get annotations for Pod.
@return
|
getAnnotationsForPod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void createService(final int executionId) throws ExecutorManagerException {
try {
final AzKubernetesV1ServiceBuilder azKubernetesV1ServiceBuilder =
new AzKubernetesV1ServiceBuilder(
"v1Service.yaml");
final V1Service serviceObject = azKubernetesV1ServiceBuilder
.withExecId(clusterQualifiedExecId(this.clusterName, executionId))
.withServiceName(getServiceName(executionId))
.withNamespace(this.namespace)
.withApiVersion(SERVICE_API_VERSION_2)
.withKind(MAPPING)
.withPort(String.valueOf(this.servicePort))
.withTimeoutMs(String.valueOf(this.serviceTimeout))
.build();
this.coreV1Api.createNamespacedService(this.namespace, serviceObject, null,
null, null, null);
logger.info("ExecId: {}, Service is created.", executionId);
} catch (final IOException e) {
logger.error("ExecId: {}, Unable to create service in Kubernetes. Msg: {}", executionId,
e.getMessage());
throw new ExecutorManagerException(e);
} catch (final ApiException e) {
logger.error("ExecId: {}, Unable to create service in Kubernetes. Msg: {} ",
executionId, e.getResponseBody());
throw new ExecutorManagerException(e);
}
}
|
This method is used to create service for flow container for execution id.
@param executionId
@throws ExecutorManagerException
|
createService
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private boolean isServiceRequired() {
return this.azkProps
.getBoolean(ContainerizedDispatchManagerProperties.KUBERNETES_SERVICE_REQUIRED, false);
}
|
This method is used to check whether service should be created in Kubernetes for flow container
pod or not.
@return
|
isServiceRequired
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void deletePod(final int executionId) throws ExecutorManagerException {
final String podName = getPodName(executionId);
try {
final GenericKubernetesApi<V1Pod, V1PodList> podClient =
new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "",
"v1", "pods", this.client);
final int statusCode =
podClient.delete(this.namespace, podName).throwsApiException().getHttpStatusCode();
logger.info("ExecId: {}, Action: Pod Deletion, Pod Name: {}, Status: {}", executionId,
podName, statusCode);
if (statusCode == 200) {
logger.info("Pod deletion successful");
} else if (statusCode == 202 ) {
logger.info("Pod deletion request accepted, deletion in background");
} else {
logger.error("Pod deletion failed");
throw new ExecutorManagerException("Pod " + podName + "deletion failed");
}
} catch (final ApiException e) {
logger.warn("Exception occurred when deleting Pod {} in Kubernetes: {}", podName, e.getResponseBody());
throw new ExecutorManagerException(e);
}
}
|
This method is used to delete pod in Kubernetes. It will terminate the pod.
@param executionId
@throws ExecutorManagerException
|
deletePod
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private void deleteService(final int executionId) throws ExecutorManagerException {
final String serviceName = getServiceName(executionId);
try {
// Using GenericKubernetesApi due to a Known issue in K8s Java client and OpenAPIv2:
// See more here: https://github.com/kubernetes-client/java/issues/86
final GenericKubernetesApi<V1Service, V1ServiceList> serviceClient =
new GenericKubernetesApi<>(V1Service.class, V1ServiceList.class, "",
"v1", "services", this.client);
final int statusCode =
serviceClient.delete(this.namespace, serviceName).throwsApiException().getHttpStatusCode();
logger.info("ExecId: {}, Action: Service Deletion, Service Name: {}, Status: {}",
executionId, serviceName, statusCode);
if (statusCode == 200) {
logger.info("Service deletion successful");
} else if (statusCode == 202 ) {
logger.info("Service deletion request accepted, deletion in background");
} else {
logger.error("Service deletion failed");
throw new ExecutorManagerException("Service " + serviceName + "deletion failed");
}
} catch (final ApiException e) {
logger.error("ExecId: {}, Unable to delete service in Kubernetes: {}", executionId,
e.getResponseBody());
throw new ExecutorManagerException(e);
}
}
|
This method is used to delete service in Kubernetes which is created for Pod.
@param executionId
@throws ExecutorManagerException
|
deleteService
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private String getVPAName(final int recommendationId) {
return getK8sEntityName(this.vpaPrefix, this.clusterName, recommendationId);
}
|
This method is used to get vpa name. It will be created using vpa name prefix, azkaban
cluster name and flow resource recommendation id.
@param recommendationId
@return
|
getVPAName
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private String getServiceName(final int executionId) {
return getK8sEntityName(this.servicePrefix, this.clusterName, executionId);
}
|
This method is used to get service name. It will be created using service name prefix, azkaban
cluster name and execution id.
@param executionId
@return
|
getServiceName
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private String getPodName(final int executionId) {
return getK8sEntityName(this.podPrefix, this.clusterName, executionId);
}
|
This method is used to get name of Pod based on naming convention. It will be created using pod
name prefix, azkaban cluster name and execution id.
@param executionId
@return
|
getPodName
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesContainerizedImpl.java
|
Apache-2.0
|
private okhttp3.Call getNamespacedVPACall(
String namespace,
String vpaObjectName)
throws ApiException {
// create path and map variables
String path = String.format(KUBERNETES_GET_VPA_RECOMMENDER_API_FORMAT, namespace, vpaObjectName);
String[] authNames = new String[] { "BearerToken" };
return localVarApiClient.buildCall(
path,
"GET",
new ArrayList<>(),
new ArrayList<>(),
null,
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
authNames,
null);
}
|
Build call for getNamespacedVPACall
@return Call to execute
|
getNamespacedVPACall
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
Apache-2.0
|
public ApiResponse<V1VerticalPodAutoscaler> getNamespacedVPA(
String namespace,
String vpaObjectName)
throws ApiException {
okhttp3.Call localVarCall = getNamespacedVPACall(namespace, vpaObjectName);
Type localVarReturnType = new TypeToken<V1VerticalPodAutoscaler>() {}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
|
Get VPA recommendation for a given vpa object in namespace
@param namespace kubernetes namespace
@param vpaObjectName VPA object name
@return response in V1VerticalPodAutoscaler format
|
getNamespacedVPA
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
Apache-2.0
|
private okhttp3.Call createNamespacedVPACall(
String namespace,
V1VerticalPodAutoscaler vpaObject)
throws ApiException {
// create path and map variables
String path = String.format(KUBERNETES_POST_VPA_RECOMMENDER_API_FORMAT, namespace);
String[] authNames = new String[] { "BearerToken" };
return localVarApiClient.buildCall(
path,
"POST",
new ArrayList<>(),
new ArrayList<>(),
vpaObject,
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
authNames,
null);
}
|
Build call for createNamespacedVPACall
@return Call to execute
|
createNamespacedVPACall
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
Apache-2.0
|
public ApiResponse<V1VerticalPodAutoscaler> createNamespacedVPA(
String namespace,
V1VerticalPodAutoscaler vpaObject)
throws ApiException {
okhttp3.Call localVarCall = createNamespacedVPACall(namespace, vpaObject);
Type localVarReturnType = new TypeToken<V1VerticalPodAutoscaler>() {}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
|
Get VPA recommendation for a given vpa object in namespace
@param namespace kubernetes namespace
@param vpaObject VPA object
@return response in V1VerticalPodAutoscaler format
|
createNamespacedVPA
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/KubernetesVPARecommenderV1Api.java
|
Apache-2.0
|
public static boolean isTransitionValid(AzPodStatus oldStatus, AzPodStatus newStatus) {
Set<AzPodStatus> invalidSet = invalidSourceStatusMap
.getOrDefault(newStatus, ImmutableSet.of());
return !invalidSet.contains(oldStatus);
}
|
Checks if the transition from {@code oldStatus} to {@code newStatus} is supported.
A return value of 'false' indicates a event status sequence that is not expected to occur in
practice and can help to identify problem with the event processing behavior.
@param oldStatus
@param newStatus
@return true if transition is supported, false otherwise.
|
isTransitionValid
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatus.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatus.java
|
Apache-2.0
|
private void extractConditions() {
requireNonNull(this.podConditions, "pod status conditions must not be null");
Map<String, V1PodCondition> conditionMap = new HashMap<>();
this.podConditions.stream().forEach(
condition ->
conditionMap.put(condition.getType().toString(), condition));
this.scheduledCondition =
Optional.ofNullable(conditionMap.remove(PodCondition.PodScheduled.name()));
this.containersReadyCondition =
Optional.ofNullable(conditionMap.remove(PodCondition.ContainersReady.name()));
this.initializedCondition =
Optional.ofNullable(conditionMap.remove(PodCondition.Initialized.name()));
this.readyCondition = Optional.ofNullable(conditionMap.remove(PodCondition.Ready.name()));
conditionMap.keySet().stream().forEach(type -> logger.warn("Unexpected condition of type: " + type));
}
|
Extract the 4 kubernetes conditions from the event. Events can have either any number of
conditions [0 - 4] present in them. Optional.empty() denotes a missing condition in the event.
@see
<a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/">Pod Lifecycle</a>
|
extractConditions
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private void extractConditionStatuses() {
this.scheduledCondition.ifPresent(cond -> {
requireNonNull(cond.getStatus());
this.scheduledConditionStatus = Optional.of(PodConditionStatus.valueOf(cond.getStatus()));
});
this.containersReadyCondition.ifPresent(cond -> {
requireNonNull(cond.getStatus());
this.containersReadyConditionStatus = Optional
.of(PodConditionStatus.valueOf(cond.getStatus()));
});
this.initializedCondition.ifPresent(cond -> {
requireNonNull(cond.getStatus());
this.initializedConditionStatus =
Optional.of(PodConditionStatus.valueOf(cond.getStatus()));
});
this.readyCondition.ifPresent(cond -> {
requireNonNull(cond.getStatus());
this.readyConditionStatus = Optional.of(PodConditionStatus.valueOf(cond.getStatus()));
});
}
|
For each of the Conditions present in the the event, extract the corresponding status.
Optional.empty() denotes the corresponding condition was not present.
|
extractConditionStatuses
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private void extractPhase() {
requireNonNull(this.v1PodStatus.getPhase(), "pod status phase must not be null");
// This will throw an IllegalArgumentException in case of an unexpected phase name.
this.podPhase = PodPhase.valueOf(String.valueOf(this.v1PodStatus.getPhase()));
}
|
Extract the Pod Phase from the event.
@see
<a href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/">Pod Lifecycle</a>
|
extractPhase
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean checkForAzPodRequested() {
if (isPodCompleted()) {
logger.debug("PodRequested is false as podPhase is in completion state");
return false;
}
// Scheduled conditions should either not be present or be false
if (this.scheduledConditionStatus.isPresent() &&
this.scheduledConditionStatus.get() == PodConditionStatus.True) {
logger.debug("PodRequested is false as scheduled conditions is true");
return false;
}
logger.debug("PodRequested is true");
return true;
}
|
Evaluate if event can be classified as status {@link AzPodStatus#AZ_POD_REQUESTED}
@return true if the classification succeeds, false otherwise.
|
checkForAzPodRequested
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean checkForAzPodInitContainersRunning() {
if (isPodCompleted()) {
logger.debug("InitRunning is false as podPhase is in completion state");
return false;
}
// Pod must have scheduled
if (!this.scheduledConditionStatus.isPresent() ||
this.scheduledConditionStatus.get() != PodConditionStatus.True) {
logger.debug("InitRunning false as scheduled condition is not present or not true");
return false;
}
// Initialization must have started, i.e condition should exist
if (!this.initializedConditionStatus.isPresent()) {
logger.debug("InitRunning false as initialized conditions is not present");
return false;
}
// Initialization must not be complete
if (this.initializedConditionStatus.get() == PodConditionStatus.True) {
logger.debug("InitRunning false as initialized condition is true");
return false;
}
// There must not be any failed init container
if (isAnyInitContainerFailed()) {
logger.debug("InitRunning false as an init container has failed");
return false;
}
logger.debug("InitRunning is true");
return true;
}
|
Evaluate if event can be classified as status
{@link AzPodStatus#AZ_POD_INIT_CONTAINERS_RUNNING}
@return true if the classification succeeds, false otherwise.
|
checkForAzPodInitContainersRunning
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean anyContainerFailed(List<V1ContainerStatus> containerStatuses) {
return containerStatuses.stream().anyMatch(status ->
{
if (status.getState().getTerminated() != null) {
return status.getState().getTerminated().getExitCode() == null ||
status.getState().getTerminated().getExitCode() != 0;
}
// If the current state is waiting and the last state was terminated, then the
// container has most likely failed.
else if (status.getState().getWaiting() != null
&& status.getLastState().getTerminated() != null) {
logger.debug("Container failed as state is Waiting and last state is Terminated.");
return true;
} else {
return false;
}
});
}
|
This method can be utilized to check for any failed container among the list provided. The
containers can be init or app containers.
@param containerStatuses
@return true if any of the container failed, otherwise false.
|
anyContainerFailed
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean checkForAzPodReady() {
if (isPodCompleted()) {
logger.debug("PodReady is false as podPhase is in completion state");
return false;
}
// ContainersReady condition must be True
if (!this.containersReadyConditionStatus.isPresent() ||
this.containersReadyConditionStatus.get() != PodConditionStatus.True) {
logger.debug("PodReady false as container-ready condition is not present or not true");
return false;
}
// All application containers should have started
List<V1ContainerStatus> containerStatuses = this.v1PodStatus.getContainerStatuses();
if (containerStatuses == null || containerStatuses.isEmpty()) {
logger.debug("PodReady false as container status is null or empty");
return false;
}
boolean allContainersRunning = containerStatuses.stream().allMatch(status ->
status.getState().getRunning() != null &&
status.getState().getRunning().getStartedAt() != null);
if (!allContainersRunning) {
logger.debug("PodReady false as all containers did not start running");
return false;
}
// No applications containers should have failed
if(isAnyAppContainerFailed()) {
logger.debug("PodReady false as an application container has failed");
return false;
}
logger.debug("PodReady is true");
return true;
}
|
Evaluate if event can be classified as status {@link AzPodStatus#AZ_POD_READY}
@return true if the classification succeeds, false otherwise.
|
checkForAzPodReady
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean checkForAzPodCompleted() {
// Phase should be succeeded
if(this.podPhase != PodPhase.Succeeded) {
logger.debug("PodCompleted is false as phase is not succeeded");
return false;
}
logger.debug("PodCompleted is true");
return true;
}
|
Evaluate if event can be classified as status {@link AzPodStatus#AZ_POD_COMPLETED}
@return true if the classification succeeds, false otherwise.
|
checkForAzPodCompleted
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean checkForAzPodInitFailure() {
// Phase must be failed.
if (this.podPhase != PodPhase.Failed) {
logger.debug("InitFailed is false and phase is not failed");
return false;
}
// Initalized conditions should not be true
if (this.initializedConditionStatus.isPresent() &&
this.initializedConditionStatus.get() == PodConditionStatus.True) {
logger.debug("InitFailed is failed as initialized conditions is not present or true");
return false;
}
// There must be at least 1 failed init container
if (!isAnyInitContainerFailed()) {
logger.debug("InitFailed is false as as all init container are terminated with exit code 0");
return false;
}
logger.debug("InitFailed is true");
return true;
}
|
Evaluate if event can be classified as status {@link AzPodStatus#AZ_POD_INIT_FAILURE}
@return true if the classification succeeds, false otherwise.
|
checkForAzPodInitFailure
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
public AzPodStatus createAzPodStatus() {
// All pod statuses are checked for any status extracted from the pod event. If multiple
// statuses are detected, the first derived pod status will be returned, and the conflict
// will be logged
List<AzPodStatus> derivedStatuses = new ArrayList<>();
if (checkForAzPodRequested()) {
derivedStatuses.add(AzPodStatus.AZ_POD_REQUESTED);
}
logInitContainerStatuses();
if (checkForAzPodScheduled()) {
derivedStatuses.add(AzPodStatus.AZ_POD_SCHEDULED);
}
logAppContainerStatuses();
if (checkForAzPodInitContainersRunning()) {
derivedStatuses.add(AzPodStatus.AZ_POD_INIT_CONTAINERS_RUNNING);
}
if (checkForAzPodAppContainerStarting()) {
derivedStatuses.add(AzPodStatus.AZ_POD_APP_CONTAINERS_STARTING);
}
if (checkForAzPodReady()) {
derivedStatuses.add(AzPodStatus.AZ_POD_READY);
}
if (checkForAzPodCompleted()) {
derivedStatuses.add(AzPodStatus.AZ_POD_COMPLETED);
}
if (checkForAzPodInitFailure()) {
derivedStatuses.add(AzPodStatus.AZ_POD_INIT_FAILURE);
}
if (checkForAzPodAppFailure()) {
derivedStatuses.add(AzPodStatus.AZ_POD_APP_FAILURE);
}
if (derivedStatuses.size() > 1) {
logger.warn(format("%d pod statuses are derived from current pod watch event: %s",
derivedStatuses.size(),
derivedStatuses.stream().map(s -> s.toString()).collect(Collectors.joining(","))));
}
return derivedStatuses.isEmpty() ? AzPodStatus.AZ_POD_UNEXPECTED : derivedStatuses.get(0);
}
|
Return the {@link AzPodStatus} derived from given Pod watch event.
@return
|
createAzPodStatus
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
public static AzPodStatusMetadata getAzPodStatusFromEvent(Watch.Response<V1Pod> event) {
return new AzPodStatusMetadata(new AzPodStatusExtractor(event));
}
|
Convenience method to create AzPodStatus from event in a single call.
@param event
@return
|
getAzPodStatusFromEvent
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/AzPodStatusExtractor.java
|
Apache-2.0
|
private boolean validateTransition(AzPodStatusMetadata event, AzPodStatus currentStatus) {
logger.debug(format("Transition requested from %s -> %s, for pod %s",
currentStatus,
event.getAzPodStatus(),
event.getPodName()));
return TransitionValidator.isTransitionValid(currentStatus, event.getAzPodStatus());
}
|
Validate the the transition from the current state to the new state in the {@code event}
is supported. Note that the validation is on best-effort basis as the cache may not always
contain an event for all running flows. This could happen, for example, during webserver
restarts.
@param event pod watch event
@returns true if transition is valid else false
|
validateTransition
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void validateAndPreProcess(AzPodStatusMetadata event) {
// Confirm that event is for a FlowContainer and has the corresponding Flow metadata.
if (!event.getFlowPodMetadata().isPresent()) {
IllegalStateException ise = new IllegalStateException(
format("Flow metadata is not present for pod %s", event.getPodName()));
logger.error("Pod is likely not a Flow Container.", ise);
throw ise;
}
long eventCount = flowContainerEventCount.incrementAndGet();
logEventCacheStats(eventCount);
AzPodStatus currentStatus = getCurrentAzPodStatus(event.getPodName());
boolean isTransitionValid = validateTransition(event, currentStatus);
if (!isTransitionValid) {
IllegalStateException transitionException = new IllegalStateException(
format("Pod status transition is not supported %s -> %s, for pod %s",
currentStatus,
event.getAzPodStatus(),
event.getPodName()));
logger.error("Unsupported state transition.", transitionException);
try {
finalizeFlowAndDeleteContainer(event);
} catch (Exception deletionException) {
transitionException.addSuppressed(deletionException);
}
throw transitionException;
}
}
|
Includes any validations needed on event that are common to all {@link AzPodStatus}
@param event pod watch event
|
validateAndPreProcess
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void logEventCacheStats(long eventCount) {
if (eventCount % EVENT_CACHE_STATS_FREQUENCY != 0) {
return;
}
CacheStats stats = podStatusCache.stats();
logger.info("Pod Event Cache Stats at flow event count " + eventCount + ": " + stats.toString());
}
|
Common event processing required for all {@link AzPodStatus} callbacks.
This is also responsible for updating the event cache/map.
@param event pod watch event
|
logEventCacheStats
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void deleteFlowContainer(AzPodStatusMetadata event) {
logger.info("Deleting Flow Pod: " + event.getPodName());
if (event.getFlowPodMetadata().get().isCleanupDisabled()) {
logger.warn(format("Pod deletion is disabled for pod %s, please delete it manually.",
event.getPodName()));
return;
}
try {
containerizedImpl.deleteContainer(
Integer.parseInt(
event.getFlowPodMetadata().get().getExecutionId()));
} catch (ExecutorManagerException e) {
String message = format("Exception while deleting flow container.");
logger.error(message, e);
throw new AzkabanWatchException(message, e);
} catch (NumberFormatException ne) {
String message = format("Flow metadata execution id is not a valid integer %s",
event.getFlowPodMetadata().get().getExecutionId());
throw new AzkabanWatchException(message, ne);
}
}
|
Delete the the flow pod and any other related objects (such as services).
@param event pod watch event
|
deleteFlowContainer
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void finalizeFlowAndDeleteContainer(AzPodStatusMetadata event) {
Optional<Status> originalFlowStatus = compareAndFinalizeFlowStatus(event);
if (originalFlowStatus.isPresent() &&
!Status.isStatusFinished(originalFlowStatus.get())) {
logger.warn(format("Flow for pod %s was in the non-final state %s and was finalized",
event.getPodName(), originalFlowStatus.get()));
}
deleteFlowContainer(event);
}
|
Finalize the flow for the given event and delete its container.
@param event
|
finalizeFlowAndDeleteContainer
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void processFinalState(AzPodStatusMetadata event) {
requireNonNull(event, "event must not be null");
validateAndPreProcess(event);
boolean skipUpdates = !isUpdatedPodStatusDistinct(event);
postProcess(event);
if (!skipUpdates) {
finalizeFlowAndDeleteContainer(event);
}
}
|
Common processing for all the final states of the flow-pod. This is responsible
for deleting the flow container as well as finalizing the Flow status in the Db in case
it's not already in a final state.
@param event pod event
|
processFinalState
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/FlowStatusManagerListener.java
|
Apache-2.0
|
private void initializeAndStartPodWatch() {
while(!this.isShutdownRequested.get()) {
try {
this.podWatchInitCount++;
logger.info("Initializing pod watch, initialization count: " + this.podWatchInitCount);
initializePodWatch();
startPodWatch();
} catch (Exception e) {
logger.warn("Exception during pod watch was suppressed.", e);
} finally {
logger.info("Closing pod watch");
closePodWatchQuietly();
}
logger.info("Pod watch was terminated, will be reset with delay if shutdown was not "
+ "requested. Shutdown Requested is: " + this.isShutdownRequested.get());
try {
Thread.sleep(this.podWatchParams.getResetDelayMillis());
} catch (InterruptedException e) {
if (Thread.currentThread().isInterrupted()) {
logger.info("Pod watch reset delay was interrupted.");
}
}
}
}
|
Initialize and start the Pod watch procedure. The processing is expected to continue until a
shutdown request is received. The method will handle any exceptions received during both (1)
the execution of kubernetes API calls (2) processing of events received by the watch.
This also includes re-initialization of the watch using Kuberentes watch API, as needed.
|
initializeAndStartPodWatch
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/KubernetesWatch.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/KubernetesWatch.java
|
Apache-2.0
|
public static void logWatchEvent(AzPodStatusMetadata event, String message) {
try {
logger.info(new StringBuffer(message)
.append(System.lineSeparator())
.append(event.getPodWatchEvent().object.toString())
.toString());
} catch (Exception e) {
logger.error("Unexpected exception while logging watch event for pod " + event.getPodName()
, e);
}
}
|
Contains methods for logging of Kubernetes watch events.
This currently utilizes the {@code toString()} method of {@link V1Pod} which generates
a human-friendly string representation of the event.
However, there is value in logging the raw json representation of the events received
from the Kubernetes APIServer as they will be more useful for scripted analyses, something we
can consider in future.
Also note that having a dedicated class for logging of watch events makes it easier to define
the logging properties which can redirect these events to a dedicated log file.
|
logWatchEvent
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/WatchEventLogger.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/WatchEventLogger.java
|
Apache-2.0
|
public static ApiClient createApiClient(final Props azkProps) {
final String kubeConfigPath;
final KubeConfig kubeConfig;
final ApiClient apiClient;
requireNonNull(azkProps, "azkaban properties must not be null");
try {
kubeConfigPath = azkProps
.getString(ContainerizedDispatchManagerProperties.KUBERNETES_KUBE_CONFIG_PATH);
logger.info("Creating ApiClient with kubeconfig: " + kubeConfigPath);
kubeConfig = KubeConfig.loadKubeConfig(Files.newBufferedReader(Paths.get(kubeConfigPath),
Charset.defaultCharset()));
apiClient = ClientBuilder.kubeconfig(kubeConfig).build();
} catch (IOException ioe) {
AzkabanWatchException awe = new AzkabanWatchException("IOException while creating Api client", ioe);
logger.error("Could not create container Api client", awe);
throw awe;
}
logger.debug("Created ApiClient with kubeconfig: " + kubeConfigPath);
return apiClient;
}
|
Utility method for creating a Kubernetes (@link ApiClient} from given Azkaban properties.
@param azkProps
@return api client
|
createApiClient
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/WatchUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/WatchUtils.java
|
Apache-2.0
|
public static PodWatchParams createPodWatchParams(final Props azkProps) {
requireNonNull(azkProps, "azkaban properties must not be null");
final String namespace =
azkProps.getString(ContainerizedDispatchManagerProperties.KUBERNETES_NAMESPACE);
final String labelSelector = KubernetesContainerizedImpl.getLabelSelector(azkProps);
return new PodWatchParams(namespace, labelSelector);
}
|
Creates {@link PodWatchParams} using Akzaban properties, with the correct Pod {@code
labelSelector} provied by the Kubernetes dispatch implementation.
@param azkProps
@return
|
createPodWatchParams
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/container/watch/WatchUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/container/watch/WatchUtils.java
|
Apache-2.0
|
protected boolean tieBreak(final T object1, final T object2) {
if (null == object2) {
return true;
}
if (null == object1) {
return false;
}
return object1.hashCode() >= object2.hashCode();
}
|
tieBreak method which will kick in when the comparator list generated an equality result for
both sides. the tieBreak method will try best to make sure a stable result is returned.
|
tieBreak
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
Apache-2.0
|
protected void registerFactorComparator(final FactorComparator<T> comparator) {
if (null == comparator ||
Integer.MAX_VALUE - this.getTotalWeight() < comparator.getWeight()) {
throw new IllegalArgumentException("unable to register comparator." +
" The passed comparator is null or has an invalid weight value.");
}
// add or replace the Comparator.
this.factorComparatorList.put(comparator.getFactorName(), comparator);
logger.debug(String.format("Factor comparator added for '%s'. Weight = '%s'",
comparator.getFactorName(), comparator.getWeight()));
}
|
function to register a factorComparator to the internal Map for future reference.
@param factorComparator : the comparator object to be registered.
|
registerFactorComparator
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
Apache-2.0
|
public int getTotalWeight() {
int totalWeight = 0;
// save out a copy of the values as HashMap.values() takes o(n) to return the value.
final Collection<FactorComparator<T>> allValues = this.factorComparatorList.values();
for (final FactorComparator<T> item : allValues) {
if (item != null) {
totalWeight += item.getWeight();
}
}
return totalWeight;
}
|
function returns the total weight of the registered comparators.
@return the value of total weight.
|
getTotalWeight
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/CandidateComparator.java
|
Apache-2.0
|
protected void registerFactorFilter(final FactorFilter<T, V> filter) {
if (null == filter) {
throw new IllegalArgumentException("unable to register factor filter. " +
"The passed comaractor is null or has an invalid weight value.");
}
// add or replace the filter.
this.factorFilterList.put(filter.getFactorName(), filter);
logger.debug(String.format("Factor filter added for '%s'.",
filter.getFactorName()));
}
|
function to register a factorFilter to the internal Map for future reference.
@param factorfilter : the Filter object to be registered.
|
registerFactorFilter
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/CandidateFilter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/CandidateFilter.java
|
Apache-2.0
|
public boolean filterTarget(final T filteringTarget, final V referencingObject) {
logger.debug(String.format("start filtering '%s' with factor filter for '%s'",
filteringTarget == null ? "(null)" : filteringTarget.toString(),
this.getName()));
final Collection<FactorFilter<T, V>> filterList = this.factorFilterList.values();
boolean result = true;
for (final FactorFilter<T, V> filter : filterList) {
result &= filter.filterTarget(filteringTarget, referencingObject);
logger.debug(String.format("[Factor: %s] filter result : %s ",
filter.getFactorName(), result));
if (!result) {
break;
}
}
logger.debug(String.format("Final filtering result : %s ", result));
return result;
}
|
function to analyze the target item according to the reference object to decide whether the
item should be filtered.
@param filteringTarget: object to be checked.
@param referencingObject: object which contains statistics based on which a decision is made
whether the object being checked need to be filtered or not.
@return true if the check passed, false if check failed, which means the item need to be
filtered.
|
filterTarget
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/CandidateFilter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/CandidateFilter.java
|
Apache-2.0
|
public static Set<String> getAvailableComparatorNames() {
return comparatorCreatorRepository.keySet();
}
|
Gets the name list of all available comparators.
@return the list of the names.
|
getAvailableComparatorNames
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java
|
Apache-2.0
|
private static boolean statisticsObjectCheck(final ExecutorInfo statisticsObj1,
final ExecutorInfo statisticsObj2, final String caller) {
// both doesn't expose the info
if (null == statisticsObj1 && null == statisticsObj2) {
logger.debug(String.format("%s : neither of the executors exposed statistics info.",
caller));
return true;
}
//right side doesn't expose the info.
if (null == statisticsObj2) {
logger.debug(String.format(
"%s : choosing left side and the right side executor doesn't expose statistics info",
caller));
return true;
}
//left side doesn't expose the info.
if (null == statisticsObj1) {
logger.debug(String.format(
"%s : choosing right side and the left side executor doesn't expose statistics info",
caller));
return true;
}
// both not null
return false;
}
|
<pre>
helper function that does the object on two statistics, comparator can leverage this function
to provide
shortcuts if the statistics object is missing from one or both sides of the executors.
</pre>
@param stat1 the first statistics object to be checked .
@param stat2 the second statistics object to be checked.
@param caller the name of the calling function, for logging purpose.
@return true if the passed statistics are NOT both valid, a shortcut can be made (caller can
consume the result), false otherwise.
|
statisticsObjectCheck
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/ExecutorComparator.java
|
Apache-2.0
|
public static Set<String> getAvailableFilterNames() {
return filterRepository.keySet();
}
|
Gets the name list of all available filters.
@return the list of the names.
|
getAvailableFilterNames
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/ExecutorFilter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/ExecutorFilter.java
|
Apache-2.0
|
private static FactorFilter<Executor, ExecutableFlow> getStaticRemainingFlowSizeFilter() {
return FactorFilter
.create(STATICREMAININGFLOWSIZE_FILTER_NAME, (filteringTarget, referencingObject) -> {
if (null == filteringTarget) {
logger.debug(String.format("%s : filtering out the target as it is null.",
STATICREMAININGFLOWSIZE_FILTER_NAME));
return false;
}
final ExecutorInfo stats = filteringTarget.getExecutorInfo();
if (null == stats) {
logger.debug(String.format("%s : filtering out %s as it's stats is unavailable.",
STATICREMAININGFLOWSIZE_FILTER_NAME,
filteringTarget.toString()));
return false;
}
return stats.getRemainingFlowCapacity() > 0;
});
}
|
<pre>
function to register the static remaining flow size filter.
NOTE : this is a static filter which means the filter will be filtering based on the system
standard which is not
Coming for the passed flow.
Ideally this filter will make sure only the executor hasn't reached the Max allowed #
of
executing flows.
</pre>
|
getStaticRemainingFlowSizeFilter
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/executor/selector/ExecutorFilter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/executor/selector/ExecutorFilter.java
|
Apache-2.0
|
public static ImmutableFlowProps createFlowProps(final String parentSource, final String propSource) {
ImmutableFlowProps candidate = new ImmutableFlowProps(parentSource, propSource);
return interner.intern(candidate);
}
|
Factory for building ImmutableFlowProps, and initialize it with the names of prop's source
and parent source.
The factory returns a reference of deduped object. Instead of returning a duplicate, it
returns the reference of the pre-existing object. De-dup process checks for the name of prop's
source and parent source to be the same. It also checks for reference to prop being the same.
Two distinct references for the props, even if their contents are the sane, will be treated
as non-equivalent.
@param parentSource Name of the prop's parents' source
@param propSource Name of the prop's source
@return A de-duplicated reference to ImmutableFlowProps
|
createFlowProps
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
public static ImmutableFlowProps createFlowProps(final Props props) {
ImmutableFlowProps candidate = new ImmutableFlowProps(props);
return interner.intern(candidate);
}
|
Factory for building ImmutableFlowProps, and initialize it with the props object.
The the names of prop's source and parent source, are retrieved from the props object
itself.
The factory returns a reference of de-duped object. Instead of returning a duplicate, it
returns the reference of the pre-existing object. De-dup process checks for the name of prop's
source and parent source to be the same. It also checks for reference to prop being the same.
Two distinct references for the props, even if their contents are the sane, will be treated
as non-equivalent.
@param props The reference of props this class stores.
@return A de-duplicated reference to ImmutableFlowProps
|
createFlowProps
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
static ImmutableFlowProps fromObject(final Object obj) {
final Map<String, Object> flowMap = (Map<String, Object>) obj;
final String source = (String) flowMap.get("source");
final String parentSource = (String) flowMap.get("inherits");
final ImmutableFlowProps immutableFlowProps = createFlowProps(parentSource, source);
return immutableFlowProps;
}
|
Deserealizes an Object into ImmutableFlowProps.
source and parentSource fields are the only ones that are part of
serialization/deserialization.
@param obj The objects from which ImmutableFlowProps is deserialized.
@return ImmutableFlowProps that's created upon deserialization.
@see #toObject()
|
fromObject
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
public Props getProps() {
return this.props;
}
|
Returns the props
@return Prop Props of this object.
|
getProps
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
public String getSource() {
return this.propSource;
}
|
Returns the name of the source.
@return the name of the prop's source
|
getSource
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
public String getInheritedSource() {
return this.parentSource;
}
|
Returns the name of the prop's parents' source.
@return The name of the prop's parents' source.
|
getInheritedSource
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
@Override
public boolean equals(Object obj) {
/*
Since ImmutableFlowProps will be interned based on equivalence, this equivalence should not
be breakable. Breaking it will cause overwrittes to seemingly unrelated references.
In other words, if something can be edited later, then consider the objects to be
non-equivalent, even if there contents are the same.
*/
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final ImmutableFlowProps other = (ImmutableFlowProps) obj;
if (!equalRef(this.parentSource, other.parentSource) &&
!this.parentSource.equals(other.parentSource)) {
return false;
}
if (!equalRef(this.propSource, other.propSource) &&
!this.propSource.equals(other.propSource)) {
return false;
}
// Even though the contents of two props might be the same, the two will be considered to be
// different if their objects are different. This is because Props are mutable, and future
// equivalence may be broken.
if (!equalRef(this.props, other.props)) {
return false;
}
return true;
}
|
Tells whether the two objects can be considered equivalent.
The class and this function are designed so that the equivalence will not be breakable. Once
the two objects are equivalent, they are guaranteed to always be equivalent.
@param obj The reference object to compare with.
@see #hashCode()
|
equals
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
@Override
public int hashCode() {
// This method gets used by interning.
// Interning, first uses hashcode. If hashcode is same, it then uses equals/to deterine whether
//an object can be interned.
// The hashCodeBuilder_17_37 maintains a state, hence it has to be created afresh.
// Otherwise, the hash-code will be different for the same inputs.
// For reference:
// https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html
HashCodeBuilder hashCodeBuilder_17_37 = new HashCodeBuilder(17, 37);
return hashCodeBuilder_17_37
.append(parentSource)
.append(propSource)
.append(props)
.toHashCode();
}
|
Returns a hash code for this object.
@return Hash of this object.
|
hashCode
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
public void print() {
System.out.println("this = " + System.identityHashCode(this));
System.out.println("parentSource = " + System.identityHashCode(parentSource));
System.out.println("propSource = " + System.identityHashCode(propSource));
System.out.println("props = " + System.identityHashCode(props));
}
|
Prints identity hash codes for the fields in this object.
This method very handy to use this with unit-test and understand the interning.
|
print
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/flow/ImmutableFlowProps.java
|
Apache-2.0
|
private ImageRampup convertToRampupModel(final ImageRampupDTO imageRampupRequest) {
final ImageRampup imageRampup = new ImageRampup();
imageRampup.setId(imageRampupRequest.getId());
imageRampup.setCreatedBy(imageRampupRequest.getCreatedBy());
imageRampup.setCreatedOn(imageRampupRequest.getCreatedOn());
imageRampup.setModifiedBy(imageRampupRequest.getModifiedBy());
imageRampup.setModifiedOn(imageRampupRequest.getModifiedOn());
imageRampup.setPlanId(imageRampupRequest.getPlanId());
imageRampup.setImageVersion(imageRampupRequest.getImageVersion());
imageRampup.setRampupPercentage(imageRampupRequest.getRampupPercentage());
imageRampup.setStabilityTag(imageRampupRequest.getStabilityTag());
return imageRampup;
}
|
Converts from image rampup request to image rampup model.
@param imageRampupRequest
@return ImageRampup
|
convertToRampupModel
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageRampupPlanConverter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageRampupPlanConverter.java
|
Apache-2.0
|
private ImageRampupDTO convertToRampupResponseDTO(final ImageRampup imageRampup) {
final ImageRampupDTO imageRampupResponse = new ImageRampupDTO();
imageRampupResponse.setId(imageRampup.getId());
imageRampupResponse.setCreatedBy(imageRampup.getCreatedBy());
imageRampupResponse.setCreatedOn(imageRampup.getCreatedOn());
imageRampupResponse.setModifiedBy(imageRampup.getModifiedBy());
imageRampupResponse.setModifiedOn(imageRampup.getModifiedOn());
imageRampupResponse.setPlanId(imageRampup.getPlanId());
imageRampupResponse.setImageVersion(imageRampup.getImageVersion());
imageRampupResponse.setRampupPercentage(imageRampup.getRampupPercentage());
imageRampupResponse.setStabilityTag(imageRampup.getStabilityTag());
return imageRampupResponse;
}
|
Converts from image rampup model to image rampup response DTO.
@param imageRampup
@return ImageRampupDTO
|
convertToRampupResponseDTO
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageRampupPlanConverter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageRampupPlanConverter.java
|
Apache-2.0
|
private ImageOwnership convertToImageOwnershipModel(
final ImageOwnershipDTO imageOwnershipRequest) {
final ImageOwnership imageOwnership = new ImageOwnership();
imageOwnership.setId(imageOwnershipRequest.getId());
imageOwnership.setCreatedBy(imageOwnershipRequest.getCreatedBy());
imageOwnership.setCreatedOn(imageOwnershipRequest.getCreatedOn());
imageOwnership.setModifiedBy(imageOwnershipRequest.getModifiedBy());
imageOwnership.setModifiedOn(imageOwnershipRequest.getModifiedOn());
imageOwnership.setName(imageOwnershipRequest.getName());
imageOwnership.setRole(imageOwnershipRequest.getRole());
imageOwnership.setOwner(imageOwnershipRequest.getOwner());
return imageOwnership;
}
|
Converts from request ImageOwnershipDTO to ImageOwnership model.
@param imageOwnershipRequest
@return ImageOwnership
|
convertToImageOwnershipModel
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageTypeConverter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageTypeConverter.java
|
Apache-2.0
|
private ImageOwnershipDTO convertToImageOwnershipResponse(
final ImageOwnership imageOwnership) {
final ImageOwnershipDTO imageOwnershipResponse = new ImageOwnershipDTO();
imageOwnershipResponse.setId(imageOwnership.getId());
imageOwnershipResponse.setCreatedBy(imageOwnership.getCreatedBy());
imageOwnershipResponse.setCreatedOn(imageOwnership.getCreatedOn());
imageOwnershipResponse.setModifiedBy(imageOwnership.getModifiedBy());
imageOwnershipResponse.setModifiedOn(imageOwnership.getModifiedOn());
imageOwnershipResponse.setName(imageOwnership.getName());
imageOwnershipResponse.setRole(imageOwnership.getRole());
imageOwnershipResponse.setOwner(imageOwnership.getOwner());
return imageOwnershipResponse;
}
|
Converts from ImageOwnership model to ImageOwnershipDTO response.
@param imageOwnership
@return ImageOwnershipDTO
|
convertToImageOwnershipResponse
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageTypeConverter.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/imagemgmt/converters/ImageTypeConverter.java
|
Apache-2.0
|
private void updateImageRampupPlanInternal(final ImageRampupPlan imageRampupPlan)
throws ImageMgmtException {
try {
final List<Object> params = new ArrayList<>();
final StringBuilder queryBuilder = new StringBuilder("update image_rampup_plan set ");
// As update is allowed only for active plan, if activatePlan is false then deactivate the
// current plan.
if ((imageRampupPlan.getActivatePlan() != null && !imageRampupPlan.getActivatePlan()) ||
(imageRampupPlan.getForceActivatePlan() != null && !imageRampupPlan
.getForceActivatePlan())) {
queryBuilder.append(" active = ?, ");
params.add(Boolean.FALSE);
}
queryBuilder.append(" modified_by = ?, modified_on = ?");
params.add(imageRampupPlan.getModifiedBy());
params.add(Timestamp.valueOf(LocalDateTime.now()));
queryBuilder.append(" where id = ? ");
params.add(imageRampupPlan.getId());
final int updateCount = this.databaseOperator
.update(queryBuilder.toString(), Iterables.toArray(params, Object.class));
if (updateCount < 1) {
log.error(String.format("Exception while updating image rampup plan for image type: %s, "
+ "updateCount: %d. ",
imageRampupPlan.getImageTypeName(), updateCount));
throw new ImageMgmtDaoException(ErrorCode.BAD_REQUEST, String.format("Exception while "
+ "updating image rampup plan for image type: %s. ",
imageRampupPlan.getImageTypeName()));
}
} catch (final SQLException ex) {
log.error(String.format("Exception while updating image rampup plan for image type: %s. ",
imageRampupPlan.getImageTypeName()), ex);
throw new ImageMgmtDaoException(ErrorCode.BAD_REQUEST, String.format("Exception while "
+ "updating image rampup plan for image type: %s. ",
imageRampupPlan.getImageTypeName()));
}
}
|
This method updates image rampup plan for an image type and the plan can be either made active
or inactive.
@param imageRampupPlan
@throws ImageMgmtException
|
updateImageRampupPlanInternal
|
java
|
azkaban/azkaban
|
azkaban-common/src/main/java/azkaban/imagemgmt/daos/ImageRampupDaoImpl.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/main/java/azkaban/imagemgmt/daos/ImageRampupDaoImpl.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.