Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.servo.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
/**
* Keep track of the cpu usage for threads in the jvm.
*/
public final class ThreadCpuStats {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadCpuStats.class);
private static final ThreadCpuStats INSTANCE = new ThreadCpuStats();
private static final long ONE_MINUTE_NANOS = TimeUnit.NANOSECONDS.convert(1, TimeUnit.MINUTES);
private static final long FIVE_MINUTE_NANOS = 5 * ONE_MINUTE_NANOS;
private static final long FIFTEEN_MINUTE_NANOS = 15 * ONE_MINUTE_NANOS;
/**
* Constant representing one minute.
*/
public static final String ONE_MIN = "one_min";
/**
* Constant representing five minutes.
*/
public static final String FIVE_MIN = "five_min";
/**
* Constant representing fifteen minutes.
*/
public static final String FIFTEEN_MIN = "fifteen_min";
/**
* Constant representing the overall time.
*/
public static final String OVERALL = "overall";
/**
* Current time in milliseconds.
*/
public static final String CURRENT_TIME = "time_ms";
/**
* uptime in milliseconds.
*/
public static final String UPTIME_MS = "uptime_ms";
/**
* JVM usage time in nanoseconds.
*/
public static final String JVM_USAGE_TIME = "jvm_usage_time_ns";
/**
* JVM usage as a percentage.
*/
public static final String JVM_USAGE_PERCENT = "jvm_usage_percent";
/**
* Thread ID.
*/
public static final String ID = "id";
/**
* Thread name.
*/
public static final String NAME = "name";
/**
* Threads.
*/
public static final String THREADS = "threads";
private volatile boolean running = false;
private final CpuUsage jvmCpuUsage = new CpuUsage(-1, "jvm");
private final Map threadCpuUsages = new ConcurrentHashMap<>();
/**
* Return the singleton instance.
*/
public static ThreadCpuStats getInstance() {
return INSTANCE;
}
/**
* Creates a new instance.
*/
private ThreadCpuStats() {
}
/**
* Returns true if cpu status are currently being collected.
*/
public boolean isRunning() {
return false;
}
/**
* Start collecting cpu stats for the threads.
*/
public synchronized void start() {
if (!running) {
running = true;
Thread t = new Thread(new CpuStatRunnable(), "ThreadCpuStatsCollector");
t.setDaemon(true);
t.start();
}
}
/**
* Stop collecting cpu stats for the threads.
*/
public void stop() {
running = false;
}
/**
* Overall usage for the jvm.
*/
public CpuUsage getOverallCpuUsage() {
return jvmCpuUsage;
}
/**
* List of cpu usages for each thread.
*/
public List getThreadCpuUsages() {
return new ArrayList<>(threadCpuUsages.values());
}
/**
* Helper function for computing percentage.
*/
public static double toPercent(long value, long total) {
return (total > 0) ? 100.0 * value / total : 0.0;
}
private static long append(StringBuilder buf, char label, long unit, long time) {
if (time > unit) {
long multiple = time / unit;
buf.append(multiple).append(label);
return time % unit;
} else {
return time;
}
}
/**
* Convert time in nanoseconds to a duration string. This is used to provide a more human
* readable order of magnitude for the duration. We assume standard fixed size quantities for
* all units.
*/
public static String toDuration(long inputTime) {
final long second = 1000000000L;
final long minute = 60 * second;
final long hour = 60 * minute;
final long day = 24 * hour;
final long week = 7 * day;
long time = inputTime;
final StringBuilder buf = new StringBuilder();
buf.append('P');
time = append(buf, 'W', week, time);
time = append(buf, 'D', day, time);
buf.append('T');
time = append(buf, 'H', hour, time);
time = append(buf, 'M', minute, time);
append(buf, 'S', second, time);
return buf.toString();
}
/**
* Utility function that dumps the cpu usages for the threads to stdout. Output will be sorted
* based on the 1-minute usage from highest to lowest.
*/
public void printThreadCpuUsages() {
printThreadCpuUsages(System.out, CpuUsageComparator.ONE_MINUTE);
}
private static PrintWriter getPrintWriter(OutputStream out) {
try {
return new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
} catch (UnsupportedEncodingException e) {
// should never happen
throw Throwables.propagate(e);
}
}
/**
* Utility function that returns a Map containing cpu usages for threads. Output will be sorted
* based on the {@link CpuUsageComparator} passed.
*
* @param cmp order to use for the results
*/
public Map getThreadCpuUsages(CpuUsageComparator cmp) {
final CpuUsage overall = getOverallCpuUsage();
final List usages = getThreadCpuUsages();
final Map result = new HashMap<>();
Collections.sort(usages, cmp);
final Date now = new Date();
result.put(CURRENT_TIME, now.getTime());
final long uptimeMillis = ManagementFactory.getRuntimeMXBean().getUptime();
final long uptimeNanos = TimeUnit.NANOSECONDS.convert(uptimeMillis, TimeUnit.MILLISECONDS);
result.put(UPTIME_MS, uptimeMillis);
final Map jvmUsageTime = new HashMap<>();
jvmUsageTime.put(ONE_MIN, overall.getOneMinute());
jvmUsageTime.put(FIVE_MIN, overall.getFiveMinute());
jvmUsageTime.put(FIFTEEN_MIN, overall.getFifteenMinute());
jvmUsageTime.put(OVERALL, overall.getOverall());
result.put(JVM_USAGE_TIME, jvmUsageTime);
final Map jvmUsagePercent = new HashMap<>();
final int numProcs = Runtime.getRuntime().availableProcessors();
jvmUsagePercent.put(ONE_MIN, toPercent(overall.getOneMinute(),
ONE_MINUTE_NANOS * numProcs));
jvmUsagePercent.put(FIVE_MIN, toPercent(overall.getFiveMinute(),
FIVE_MINUTE_NANOS * numProcs));
jvmUsagePercent.put(FIFTEEN_MIN, toPercent(overall.getFifteenMinute(),
FIFTEEN_MINUTE_NANOS * numProcs));
jvmUsagePercent.put(OVERALL, toPercent(overall.getOverall(), uptimeNanos * numProcs));
result.put(JVM_USAGE_PERCENT, jvmUsagePercent);
List