use of java.lang.management.ThreadMXBean in project hazelcast by hazelcast.
the class AbstractHazelcastClassRunner method generateThreadDump.
private String generateThreadDump() {
StringBuilder dump = new StringBuilder();
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
long currentThreadId = Thread.currentThread().getId();
for (ThreadInfo threadInfo : threadInfos) {
long threadId = threadInfo.getThreadId();
if (threadId == currentThreadId) {
continue;
}
dump.append('"');
dump.append(threadInfo.getThreadName());
dump.append("\" ");
Thread.State state = threadInfo.getThreadState();
dump.append("\n\tjava.lang.Thread.State: ");
dump.append(state);
if (threadInfo.getLockName() != null) {
dump.append(", on lock=").append(threadInfo.getLockName());
}
if (threadInfo.getLockOwnerName() != null) {
dump.append(", owned by ").append(threadInfo.getLockOwnerName());
dump.append(", id=").append(threadInfo.getLockOwnerId());
}
if (THREAD_CPU_TIME_INFO_AVAILABLE) {
dump.append(", cpu=").append(threadMXBean.getThreadCpuTime(threadId)).append(" nsecs");
dump.append(", usr=").append(threadMXBean.getThreadUserTime(threadId)).append(" nsecs");
}
if (THREAD_CONTENTION_INFO_AVAILABLE) {
dump.append(", blocked=").append(threadInfo.getBlockedTime()).append(" msecs");
dump.append(", waited=").append(threadInfo.getWaitedTime()).append(" msecs");
}
StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
for (StackTraceElement stackTraceElement : stackTraceElements) {
dump.append("\n\t\tat ");
dump.append(stackTraceElement);
}
dump.append("\n\n");
}
return dump.toString();
}
use of java.lang.management.ThreadMXBean in project wycheproof by google.
the class EcdsaTest method testTiming.
/**
* Tests for a potential timing attack. This test checks if there is a correlation between the
* timing of signature generation and the size of the one-time key k. This is for example the case
* if a double and add method is used for the point multiplication. The test fails if such a
* correlation can be shown with high confidence. Further analysis will be necessary to determine
* how easy it is to exploit the bias in a timing attack.
*/
// TODO(bleichen): Determine if there are exploitable providers.
//
// SunEC currently fails this test. Since ECDSA typically is used with EC groups whose order
// is 224 bits or larger, it is unclear whether the same attacks that apply to DSA are practical.
//
// The ECDSA implementation in BouncyCastle leaks information about k through timing too.
// The test has not been optimized to detect this bias. It would require about 5'000'000 samples,
// which is too much for a simple unit test.
//
// BouncyCastle uses FixedPointCombMultiplier for ECDSA. This is a method using
// precomputation. The implementation is not constant time, since the precomputation table
// contains the point at infinity and adding this point is faster than ordinary point additions.
// The timing leak only has a small correlation to the size of k and at the moment it is is very
// unclear if the can be exploited. (Randomizing the precomputation table by adding the same
// random point to each element in the table and precomputing the necessary offset to undo the
// precomputation seems much easier than analyzing this.)
public void testTiming(String algorithm, String curve, ECParameterSpec ecParams) throws Exception {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
if (!bean.isCurrentThreadCpuTimeSupported()) {
System.out.println("getCurrentThreadCpuTime is not supported. Skipping");
return;
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
try {
keyGen.initialize(ecParams);
} catch (InvalidAlgorithmParameterException ex) {
System.out.println("This provider does not support curve:" + curve);
return;
}
KeyPair keyPair = keyGen.generateKeyPair();
ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();
String message = "Hello";
String hashAlgorithm = getHashAlgorithm(algorithm);
byte[] messageBytes = message.getBytes("UTF-8");
byte[] digest = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
BigInteger h = new BigInteger(1, digest);
Signature signer = Signature.getInstance(algorithm);
signer.initSign(priv);
// The number of samples used for the test. This number is a bit low.
// I.e. it just barely detects that SunEC leaks information about the size of k.
int samples = 50000;
long[] timing = new long[samples];
BigInteger[] k = new BigInteger[samples];
for (int i = 0; i < samples; i++) {
long start = bean.getCurrentThreadCpuTime();
signer.update(messageBytes);
byte[] signature = signer.sign();
timing[i] = bean.getCurrentThreadCpuTime() - start;
k[i] = extractK(signature, h, priv);
}
long[] sorted = Arrays.copyOf(timing, timing.length);
Arrays.sort(sorted);
double n = priv.getParams().getOrder().doubleValue();
double expectedAverage = n / 2;
double maxSigma = 0;
System.out.println("testTiming algorithm:" + algorithm);
for (int idx = samples - 1; idx > 10; idx /= 2) {
long cutoff = sorted[idx];
int count = 0;
BigInteger total = BigInteger.ZERO;
for (int i = 0; i < samples; i++) {
if (timing[i] <= cutoff) {
total = total.add(k[i]);
count += 1;
}
}
double expectedStdDev = n / Math.sqrt(12 * count);
double average = total.doubleValue() / count;
// Number of standard deviations that the average is away from
// the expected value:
double sigmas = (expectedAverage - average) / expectedStdDev;
if (sigmas > maxSigma) {
maxSigma = sigmas;
}
System.out.println("count:" + count + " cutoff:" + cutoff + " relative average:" + (average / expectedAverage) + " sigmas:" + sigmas);
}
// than 10^{-10}.
if (maxSigma >= 7) {
fail("Signatures with short timing have a biased k");
}
}
use of java.lang.management.ThreadMXBean in project commons by twitter.
the class JvmStats method export.
/**
* Exports stats related to the JVM and runtime environment.
*/
public static void export() {
final OperatingSystemMXBean osMbean = ManagementFactory.getOperatingSystemMXBean();
if (osMbean instanceof com.sun.management.OperatingSystemMXBean) {
final com.sun.management.OperatingSystemMXBean sunOsMbean = (com.sun.management.OperatingSystemMXBean) osMbean;
Stats.exportAll(ImmutableList.<Stat<? extends Number>>builder().add(new StatImpl<Long>("system_free_physical_memory_mb") {
@Override
public Long read() {
return sunOsMbean.getFreePhysicalMemorySize() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("system_free_swap_mb") {
@Override
public Long read() {
return sunOsMbean.getFreeSwapSpaceSize() / BYTES_PER_MB;
}
}).add(Rate.of(new StatImpl<Long>("process_cpu_time_nanos") {
@Override
public Long read() {
return sunOsMbean.getProcessCpuTime();
}
}).withName("process_cpu_cores_utilized").withScaleFactor(SECS_PER_NANO).build()).build());
}
if (osMbean instanceof com.sun.management.UnixOperatingSystemMXBean) {
final com.sun.management.UnixOperatingSystemMXBean unixOsMbean = (com.sun.management.UnixOperatingSystemMXBean) osMbean;
Stats.exportAll(ImmutableList.<Stat<? extends Number>>builder().add(new StatImpl<Long>("process_max_fd_count") {
@Override
public Long read() {
return unixOsMbean.getMaxFileDescriptorCount();
}
}).add(new StatImpl<Long>("process_open_fd_count") {
@Override
public Long read() {
return unixOsMbean.getOpenFileDescriptorCount();
}
}).build());
}
final Runtime runtime = Runtime.getRuntime();
final ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();
final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
final ThreadMXBean threads = ManagementFactory.getThreadMXBean();
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
Stats.exportAll(ImmutableList.<Stat<? extends Number>>builder().add(new StatImpl<Long>("jvm_time_ms") {
@Override
public Long read() {
return System.currentTimeMillis();
}
}).add(new StatImpl<Integer>("jvm_available_processors") {
@Override
public Integer read() {
return runtime.availableProcessors();
}
}).add(new StatImpl<Long>("jvm_memory_free_mb") {
@Override
public Long read() {
return runtime.freeMemory() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_max_mb") {
@Override
public Long read() {
return runtime.maxMemory() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_mb_total") {
@Override
public Long read() {
return runtime.totalMemory() / BYTES_PER_MB;
}
}).add(new StatImpl<Integer>("jvm_class_loaded_count") {
@Override
public Integer read() {
return classLoadingBean.getLoadedClassCount();
}
}).add(new StatImpl<Long>("jvm_class_total_loaded_count") {
@Override
public Long read() {
return classLoadingBean.getTotalLoadedClassCount();
}
}).add(new StatImpl<Long>("jvm_class_unloaded_count") {
@Override
public Long read() {
return classLoadingBean.getUnloadedClassCount();
}
}).add(new StatImpl<Long>("jvm_gc_collection_time_ms") {
@Override
public Long read() {
long collectionTimeMs = 0;
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
collectionTimeMs += bean.getCollectionTime();
}
return collectionTimeMs;
}
}).add(new StatImpl<Long>("jvm_gc_collection_count") {
@Override
public Long read() {
long collections = 0;
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
collections += bean.getCollectionCount();
}
return collections;
}
}).add(new StatImpl<Long>("jvm_memory_heap_mb_used") {
@Override
public Long read() {
return memoryBean.getHeapMemoryUsage().getUsed() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_heap_mb_committed") {
@Override
public Long read() {
return memoryBean.getHeapMemoryUsage().getCommitted() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_heap_mb_max") {
@Override
public Long read() {
return memoryBean.getHeapMemoryUsage().getMax() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_non_heap_mb_used") {
@Override
public Long read() {
return memoryBean.getNonHeapMemoryUsage().getUsed() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_non_heap_mb_committed") {
@Override
public Long read() {
return memoryBean.getNonHeapMemoryUsage().getCommitted() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_memory_non_heap_mb_max") {
@Override
public Long read() {
return memoryBean.getNonHeapMemoryUsage().getMax() / BYTES_PER_MB;
}
}).add(new StatImpl<Long>("jvm_uptime_secs") {
@Override
public Long read() {
return runtimeMXBean.getUptime() / 1000;
}
}).add(new StatImpl<Double>("system_load_avg") {
@Override
public Double read() {
return osMbean.getSystemLoadAverage();
}
}).add(new StatImpl<Integer>("jvm_threads_peak") {
@Override
public Integer read() {
return threads.getPeakThreadCount();
}
}).add(new StatImpl<Long>("jvm_threads_started") {
@Override
public Long read() {
return threads.getTotalStartedThreadCount();
}
}).add(new StatImpl<Integer>("jvm_threads_daemon") {
@Override
public Integer read() {
return threads.getDaemonThreadCount();
}
}).add(new StatImpl<Integer>("jvm_threads_active") {
@Override
public Integer read() {
return threads.getThreadCount();
}
}).build());
// Export per memory pool gc time and cycle count like Ostrich
// This is based on code in Bridcage: https://cgit.twitter.biz/birdcage/tree/ \
// ostrich/src/main/scala/com/twitter/ostrich/stats/StatsCollection.scala
Stats.exportAll(Iterables.transform(ManagementFactory.getGarbageCollectorMXBeans(), new Function<GarbageCollectorMXBean, Stat<? extends Number>>() {
@Override
public Stat<? extends Number> apply(final GarbageCollectorMXBean gcMXBean) {
return new StatImpl<Long>("jvm_gc_" + Stats.normalizeName(gcMXBean.getName()) + "_collection_count") {
@Override
public Long read() {
return gcMXBean.getCollectionCount();
}
};
}
}));
Stats.exportAll(Iterables.transform(ManagementFactory.getGarbageCollectorMXBeans(), new Function<GarbageCollectorMXBean, Stat<? extends Number>>() {
@Override
public Stat<? extends Number> apply(final GarbageCollectorMXBean gcMXBean) {
return new StatImpl<Long>("jvm_gc_" + Stats.normalizeName(gcMXBean.getName()) + "_collection_time_ms") {
@Override
public Long read() {
return gcMXBean.getCollectionTime();
}
};
}
}));
Stats.exportString(new StatImpl<String>("jvm_input_arguments") {
@Override
public String read() {
return runtimeMXBean.getInputArguments().toString();
}
});
for (final String property : System.getProperties().stringPropertyNames()) {
Stats.exportString(new StatImpl<String>("jvm_prop_" + Stats.normalizeName(property)) {
@Override
public String read() {
return System.getProperty(property);
}
});
}
for (final Map.Entry<String, String> environmentVariable : System.getenv().entrySet()) {
Stats.exportString(new StatImpl<String>("system_env_" + Stats.normalizeName(environmentVariable.getKey())) {
@Override
public String read() {
return environmentVariable.getValue();
}
});
}
}
use of java.lang.management.ThreadMXBean in project commons by twitter.
the class ContentionPrinter method getLines.
@Override
public Iterable<String> getLines(HttpServletRequest request) {
List<String> lines = Lists.newLinkedList();
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
Map<Long, StackTraceElement[]> threadStacks = Maps.newHashMap();
for (Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) {
threadStacks.put(entry.getKey().getId(), entry.getValue());
}
Set<Long> lockOwners = Sets.newHashSet();
lines.add("Locked threads:");
for (ThreadInfo t : bean.getThreadInfo(bean.getAllThreadIds())) {
switch(t.getThreadState()) {
case BLOCKED:
case WAITING:
case TIMED_WAITING:
lines.addAll(getThreadInfo(t, threadStacks.get(t.getThreadId())));
if (t.getLockOwnerId() != -1)
lockOwners.add(t.getLockOwnerId());
break;
}
}
if (lockOwners.size() > 0) {
lines.add("\nLock Owners");
for (ThreadInfo t : bean.getThreadInfo(Longs.toArray(lockOwners))) {
lines.addAll(getThreadInfo(t, threadStacks.get(t.getThreadId())));
}
}
return lines;
}
use of java.lang.management.ThreadMXBean in project orientdb by orientechnologies.
the class OAbstractProfiler method threadDump.
@Override
public String threadDump() {
final StringBuilder dump = new StringBuilder();
dump.append("THREAD DUMP\n");
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
for (ThreadInfo threadInfo : threadInfos) {
dump.append('"');
dump.append(threadInfo.getThreadName());
dump.append("\" ");
final Thread.State state = threadInfo.getThreadState();
dump.append("\n java.lang.Thread.State: ");
dump.append(state);
final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
for (final StackTraceElement stackTraceElement : stackTraceElements) {
dump.append("\n at ");
dump.append(stackTraceElement);
}
dump.append("\n\n");
}
return dump.toString();
}
Aggregations