All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.flink.runtime.healthmanager.plugins.detectors.LowCpuDetector Maven / Gradle / Ivy

There is a newer version: 1.5.1
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.runtime.healthmanager.plugins.detectors;

import org.apache.flink.api.common.JobID;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.runtime.healthmanager.HealthMonitor;
import org.apache.flink.runtime.healthmanager.RestServerClient;
import org.apache.flink.runtime.healthmanager.metrics.JobTMMetricSubscription;
import org.apache.flink.runtime.healthmanager.metrics.MetricProvider;
import org.apache.flink.runtime.healthmanager.metrics.timeline.TimelineAggType;
import org.apache.flink.runtime.healthmanager.plugins.Detector;
import org.apache.flink.runtime.healthmanager.plugins.Symptom;
import org.apache.flink.runtime.healthmanager.plugins.symptoms.JobVertexLowCpu;
import org.apache.flink.runtime.healthmanager.plugins.utils.HealthMonitorOptions;
import org.apache.flink.runtime.healthmanager.plugins.utils.MetricNames;
import org.apache.flink.runtime.healthmanager.plugins.utils.MetricUtils;
import org.apache.flink.runtime.jobgraph.ExecutionVertexID;
import org.apache.flink.runtime.jobgraph.JobVertexID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * LowCpuDetector detects low cpu usage of a job.
 * Detects {@link JobVertexLowCpu} if the max avg cpu usage of the TM
 * is lower than threshold.
 */
public class LowCpuDetector implements Detector {

	private static final Logger LOGGER = LoggerFactory.getLogger(LowCpuDetector.class);

	public static final ConfigOption LOW_CPU_THRESHOLD =
		ConfigOptions.key("healthmonitor.low-cpu-detector.threashold").defaultValue(0.5);

	private JobID jobID;
	private RestServerClient restServerClient;
	private MetricProvider metricProvider;
	private HealthMonitor monitor;

	private long checkInterval;
	private double threshold;
	private long waitTime;

	private JobTMMetricSubscription tmCpuAllocatedSubscription;
	private JobTMMetricSubscription tmCpuUsageSubscription;

	private Map lowCpuSince;
	private Map maxCpuUsage;
	private Map maxCpuUtility;

	@Override
	public void open(HealthMonitor monitor) {
		this.monitor = monitor;
		jobID = monitor.getJobID();
		restServerClient = monitor.getRestServerClient();
		metricProvider = monitor.getMetricProvider();

		checkInterval = monitor.getConfig().getLong(HealthMonitorOptions.RESOURCE_SCALE_INTERVAL);
		threshold = monitor.getConfig().getDouble(LOW_CPU_THRESHOLD);
		waitTime = monitor.getConfig().getLong(HealthMonitorOptions.RESOURCE_SCALE_DOWN_WAIT_TIME);

		tmCpuAllocatedSubscription = metricProvider.subscribeAllTMMetric(jobID, MetricNames.TM_CPU_CAPACITY, checkInterval, TimelineAggType.AVG);
		tmCpuUsageSubscription = metricProvider.subscribeAllTMMetric(jobID, MetricNames.TM_CPU_USAGE, checkInterval, TimelineAggType.AVG);

		lowCpuSince = new HashMap<>();
		maxCpuUsage = new HashMap<>();
		maxCpuUtility = new HashMap<>();
	}

	@Override
	public void close() {
		if (metricProvider != null && tmCpuAllocatedSubscription != null) {
			metricProvider.unsubscribe(tmCpuAllocatedSubscription);
		}

		if (metricProvider != null && tmCpuUsageSubscription != null) {
			metricProvider.unsubscribe(tmCpuUsageSubscription);
		}
	}

	@Override
	public Symptom detect() throws Exception {
		LOGGER.debug("Start detecting.");

		long now = System.currentTimeMillis();

		Map> tmCapacities = tmCpuAllocatedSubscription.getValue();
		Map> tmUsages = tmCpuUsageSubscription.getValue();

		if (tmCapacities == null || tmCapacities.isEmpty() || tmUsages == null || tmUsages.isEmpty()) {
			return null;
		}

		removeOutdatedMaxUsage();

		Map vertexTaskMaxUtility = new HashMap<>();
		for (String tmId : tmCapacities.keySet()) {
			if (!MetricUtils.validateTmMetric(monitor, checkInterval * 2, tmCapacities.get(tmId), tmUsages.get(tmId))) {
				LOGGER.debug("Skip tm {}, metrics missing.", tmId);
				continue;
			}

			double capacity = tmCapacities.get(tmId).f1;
			double usage = tmUsages.get(tmId).f1;

			if (capacity == 0.0) {
				LOGGER.warn("Skip vertex {}, capacity is 0. SHOULD NOT HAPPEN!", tmId);
				continue;
			}
			double utility = usage / capacity;

			List jobExecutionVertexIds = restServerClient.getTaskManagerTasks(tmId);
			for (ExecutionVertexID jobExecutionVertexId : jobExecutionVertexIds) {
				JobVertexID jvId = jobExecutionVertexId.getJobVertexID();
				if (!vertexTaskMaxUtility.containsKey(jvId) || vertexTaskMaxUtility.get(jvId) < utility) {
					vertexTaskMaxUtility.put(jvId, utility);
				}
			}
		}

		RestServerClient.JobConfig jobConfig = monitor.getJobConfig();
		for (Map.Entry entry : vertexTaskMaxUtility.entrySet()) {
			JobVertexID vertexID = entry.getKey();
			double utility = entry.getValue();
			if (utility >= threshold) {
				lowCpuSince.put(vertexID, Long.MAX_VALUE);
				maxCpuUsage.remove(vertexID);
				maxCpuUtility.remove(vertexID);
			} else {
				double usage = jobConfig.getVertexConfigs().get(vertexID).getResourceSpec().getCpuCores() * utility;
				lowCpuSince.put(vertexID, Math.min(now, lowCpuSince.getOrDefault(vertexID, Long.MAX_VALUE)));
				maxCpuUsage.put(vertexID, Math.max(usage, maxCpuUsage.getOrDefault(vertexID, 0.0)));
				maxCpuUtility.put(vertexID, Math.max(utility, maxCpuUtility.getOrDefault(vertexID, 0.0)));
			}
			LOGGER.debug("Vertex {}, utility {}, lowCpuSince {}, maxCpuUsage {}.",
				vertexID, utility, lowCpuSince.get(vertexID), maxCpuUsage.getOrDefault(vertexID, 0.0));
		}

		Map vertexMaxUtility = new HashMap<>();
		for (JobVertexID vertexID : lowCpuSince.keySet()) {
			if (now - lowCpuSince.get(vertexID) > waitTime) {
				vertexMaxUtility.put(vertexID, maxCpuUtility.get(vertexID));
			}
		}

		if (vertexMaxUtility != null && !vertexMaxUtility.isEmpty()) {
			LOGGER.info("Cpu low detected for vertices with max utilities {}.", vertexMaxUtility);
			return new JobVertexLowCpu(jobID, vertexMaxUtility);
		}
		return null;
	}

	private void removeOutdatedMaxUsage() {
		RestServerClient.JobConfig jobConfig = monitor.getJobConfig();
		Set verticeToRemove = new HashSet<>();
		for (JobVertexID vertexID : maxCpuUsage.keySet()) {
			double maxUsage = maxCpuUsage.get(vertexID);
			double capacity = jobConfig.getVertexConfigs().get(vertexID).getResourceSpec().getCpuCores();
			if (maxUsage / capacity >= threshold) {
				verticeToRemove.add(vertexID);
				LOGGER.debug("Remove outdated max usage for vertex {}, maxUsage: {}, capacity: {}.", vertexID, maxUsage, capacity);
			}
		}
		for (JobVertexID vertexID : verticeToRemove) {
			lowCpuSince.put(vertexID, Long.MAX_VALUE);
			maxCpuUsage.remove(vertexID);
			maxCpuUtility.remove(vertexID);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy