| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.util; |
| 7 |
|
| 8 |
import java.io.ByteArrayOutputStream; |
| 9 |
import java.io.IOException; |
| 10 |
import java.io.InputStream; |
| 11 |
import java.io.LineNumberReader; |
| 12 |
import java.io.OutputStream; |
| 13 |
import java.io.Reader; |
| 14 |
import java.io.StringReader; |
| 15 |
import java.lang.instrument.Instrumentation; |
| 16 |
import java.nio.charset.StandardCharsets; |
| 17 |
import java.nio.file.Files; |
| 18 |
import java.nio.file.Path; |
| 19 |
import java.nio.file.Paths; |
| 20 |
import java.util.ArrayList; |
| 21 |
import java.util.HashMap; |
| 22 |
import java.util.Iterator; |
| 23 |
import java.util.List; |
| 24 |
import java.util.Map; |
| 25 |
import java.util.concurrent.TimeUnit; |
| 26 |
|
| 27 |
/** |
| 28 |
* A simple CPU profiling tool similar to java -Xrunhprof. It can be used |
| 29 |
* in-process (to profile the current application) or as a standalone program |
| 30 |
* (to profile a different process, or files containing full thread dumps). |
| 31 |
*/ |
| 32 |
public class Profiler implements Runnable { |
| 33 |
|
| 34 |
private static Instrumentation instrumentation; |
| 35 |
private static final String LINE_SEPARATOR = |
| 36 |
System.getProperty("line.separator", "\n"); |
| 37 |
private static final int MAX_ELEMENTS = 1000; |
| 38 |
|
| 39 |
public int interval = 2; |
| 40 |
public int depth = 48; |
| 41 |
public boolean paused; |
| 42 |
public boolean sumClasses; |
| 43 |
public boolean sumMethods; |
| 44 |
|
| 45 |
private int pid; |
| 46 |
|
| 47 |
private final String[] ignoreLines = ( |
| 48 |
"java," + |
| 49 |
"sun," + |
| 50 |
"com.sun.," + |
| 51 |
"com.google.common.," + |
| 52 |
"com.mongodb.," + |
| 53 |
"org.bson.," |
| 54 |
).split(","); |
| 55 |
private final String[] ignorePackages = ( |
| 56 |
"java," + |
| 57 |
"sun," + |
| 58 |
"com.sun.," + |
| 59 |
"com.google.common.," + |
| 60 |
"com.mongodb.," + |
| 61 |
"org.bson" |
| 62 |
).split(","); |
| 63 |
private final String[] ignoreThreads = ( |
| 64 |
"java.lang.Object.wait," + |
| 65 |
"java.lang.Thread.dumpThreads," + |
| 66 |
"java.lang.Thread.getThreads," + |
| 67 |
"java.lang.Thread.sleep," + |
| 68 |
"java.lang.UNIXProcess.waitForProcessExit," + |
| 69 |
"java.net.PlainDatagramSocketImpl.receive0," + |
| 70 |
"java.net.PlainSocketImpl.accept," + |
| 71 |
"java.net.PlainSocketImpl.socketAccept," + |
| 72 |
"java.net.SocketInputStream.socketRead," + |
| 73 |
"java.net.SocketOutputStream.socketWrite," + |
| 74 |
"org.eclipse.jetty.io.nio.SelectorManager$SelectSet.doSelect," + |
| 75 |
"sun.awt.windows.WToolkit.eventLoop," + |
| 76 |
"sun.misc.Unsafe.park," + |
| 77 |
"sun.nio.ch.EPollArrayWrapper.epollWait," + |
| 78 |
"sun.nio.ch.KQueueArrayWrapper.kevent0," + |
| 79 |
"sun.nio.ch.ServerSocketChannelImpl.accept," + |
| 80 |
"dalvik.system.VMStack.getThreadStackTrace," + |
| 81 |
"dalvik.system.NativeStart.run" |
| 82 |
).split(","); |
| 83 |
|
| 84 |
private volatile boolean stop; |
| 85 |
private final HashMap<String, Integer> counts = |
| 86 |
new HashMap<>(); |
| 87 |
|
| 88 |
/** |
| 89 |
* The summary (usually one entry per package, unless sumClasses is enabled, |
| 90 |
* in which case it's one entry per class). |
| 91 |
*/ |
| 92 |
private final HashMap<String, Integer> summary = |
| 93 |
new HashMap<>(); |
| 94 |
private int minCount = 1; |
| 95 |
private int total; |
| 96 |
private Thread thread; |
| 97 |
private long start; |
| 98 |
private long time; |
| 99 |
private int threadDumps; |
| 100 |
|
| 101 |
/** |
| 102 |
* This method is called when the agent is installed. |
| 103 |
* |
| 104 |
* @param agentArgs the agent arguments |
| 105 |
* @param inst the instrumentation object |
| 106 |
*/ |
| 107 |
public static void premain(@SuppressWarnings("unused") String agentArgs, Instrumentation inst) { |
| 108 |
instrumentation = inst; |
| 109 |
} |
| 110 |
|
| 111 |
/** |
| 112 |
* Get the instrumentation object if started as an agent. |
| 113 |
* |
| 114 |
* @return the instrumentation, or null |
| 115 |
*/ |
| 116 |
public static Instrumentation getInstrumentation() { |
| 117 |
return instrumentation; |
| 118 |
} |
| 119 |
|
| 120 |
/** |
| 121 |
* Run the command line version of the profiler. The JDK (jps and jstack) |
| 122 |
* need to be in the path. |
| 123 |
* |
| 124 |
* @param args the process id of the process - if not set the java processes |
| 125 |
* are listed |
| 126 |
*/ |
| 127 |
public static void main(String... args) { |
| 128 |
new Profiler().run(args); |
| 129 |
} |
| 130 |
|
| 131 |
private void run(String... args) { |
| 132 |
if (args.length == 0) { |
| 133 |
System.out.println("Show profiling data"); |
| 134 |
System.out.println("Usage: java " + getClass().getName() + |
| 135 |
" <pid> | <stackTraceFileNames>"); |
| 136 |
System.out.println("Processes:"); |
| 137 |
String processes = exec("jps", "-l"); |
| 138 |
System.out.println(processes); |
| 139 |
return; |
| 140 |
} |
| 141 |
start = System.nanoTime(); |
| 142 |
if (args[0].matches("\\d+")) { |
| 143 |
pid = Integer.parseInt(args[0]); |
| 144 |
long last = 0; |
| 145 |
while (true) { |
| 146 |
tick(); |
| 147 |
long t = System.nanoTime(); |
| 148 |
if (t - last > TimeUnit.SECONDS.toNanos(5)) { |
| 149 |
time = System.nanoTime() - start; |
| 150 |
System.out.println(getTopTraces(3)); |
| 151 |
last = t; |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
try { |
| 156 |
for (String arg : args) { |
| 157 |
if (arg.startsWith("-")) { |
| 158 |
if ("-classes".equals(arg)) { |
| 159 |
sumClasses = true; |
| 160 |
} else if ("-methods".equals(arg)) { |
| 161 |
sumMethods = true; |
| 162 |
} else if ("-packages".equals(arg)) { |
| 163 |
sumClasses = false; |
| 164 |
sumMethods = false; |
| 165 |
} else { |
| 166 |
throw new IllegalArgumentException(arg); |
| 167 |
} |
| 168 |
continue; |
| 169 |
} |
| 170 |
Path file = Paths.get(arg); |
| 171 |
try (Reader reader = Files.newBufferedReader(file)) { |
| 172 |
LineNumberReader r = new LineNumberReader(reader); |
| 173 |
for (String line; (line = r.readLine()) != null;) { |
| 174 |
if (line.startsWith("Full thread dump")) { |
| 175 |
threadDumps++; |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
try (Reader reader = Files.newBufferedReader(file)) { |
| 180 |
processList(readStackTrace(new LineNumberReader(reader))); |
| 181 |
} |
| 182 |
} |
| 183 |
System.out.println(getTopTraces(5)); |
| 184 |
} catch (IOException e) { |
| 185 |
throw new RuntimeException(e); |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
private static List<Object[]> getRunnableStackTraces() { |
| 190 |
ArrayList<Object[]> list = new ArrayList<>(); |
| 191 |
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces(); |
| 192 |
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) { |
| 193 |
Thread t = entry.getKey(); |
| 194 |
if (t.getState() != Thread.State.RUNNABLE) { |
| 195 |
continue; |
| 196 |
} |
| 197 |
StackTraceElement[] dump = entry.getValue(); |
| 198 |
if (dump == null || dump.length == 0) { |
| 199 |
continue; |
| 200 |
} |
| 201 |
list.add(dump); |
| 202 |
} |
| 203 |
return list; |
| 204 |
} |
| 205 |
|
| 206 |
private static List<Object[]> readRunnableStackTraces(int pid) { |
| 207 |
try { |
| 208 |
String jstack = exec("jstack", Integer.toString(pid)); |
| 209 |
LineNumberReader r = new LineNumberReader( |
| 210 |
new StringReader(jstack)); |
| 211 |
return readStackTrace(r); |
| 212 |
} catch (IOException e) { |
| 213 |
throw new RuntimeException(e); |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
private static List<Object[]> readStackTrace(LineNumberReader r) |
| 218 |
throws IOException { |
| 219 |
ArrayList<Object[]> list = new ArrayList<>(); |
| 220 |
while (true) { |
| 221 |
String line = r.readLine(); |
| 222 |
if (line == null) { |
| 223 |
break; |
| 224 |
} |
| 225 |
if (!line.startsWith("\"")) { |
| 226 |
// not a thread |
| 227 |
continue; |
| 228 |
} |
| 229 |
line = r.readLine(); |
| 230 |
if (line == null) { |
| 231 |
break; |
| 232 |
} |
| 233 |
line = line.trim(); |
| 234 |
if (!line.startsWith("java.lang.Thread.State: RUNNABLE")) { |
| 235 |
continue; |
| 236 |
} |
| 237 |
ArrayList<String> stack = new ArrayList<>(); |
| 238 |
while (true) { |
| 239 |
line = r.readLine(); |
| 240 |
if (line == null) { |
| 241 |
break; |
| 242 |
} |
| 243 |
line = line.trim(); |
| 244 |
if (line.startsWith("- ")) { |
| 245 |
continue; |
| 246 |
} |
| 247 |
if (!line.startsWith("at ")) { |
| 248 |
break; |
| 249 |
} |
| 250 |
line = StringUtils.trimSubstring(line, 3); |
| 251 |
stack.add(line); |
| 252 |
} |
| 253 |
if (!stack.isEmpty()) { |
| 254 |
String[] s = stack.toArray(new String[0]); |
| 255 |
list.add(s); |
| 256 |
} |
| 257 |
} |
| 258 |
return list; |
| 259 |
} |
| 260 |
|
| 261 |
private static String exec(String... args) { |
| 262 |
ByteArrayOutputStream err = new ByteArrayOutputStream(); |
| 263 |
ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 264 |
try { |
| 265 |
Process p = Runtime.getRuntime().exec(args); |
| 266 |
copyInThread(p.getInputStream(), out); |
| 267 |
copyInThread(p.getErrorStream(), err); |
| 268 |
p.waitFor(); |
| 269 |
String e = Utils10.byteArrayOutputStreamToString(err, StandardCharsets.UTF_8); |
| 270 |
if (e.length() > 0) { |
| 271 |
throw new RuntimeException(e); |
| 272 |
} |
| 273 |
return Utils10.byteArrayOutputStreamToString(out, StandardCharsets.UTF_8); |
| 274 |
} catch (Exception e) { |
| 275 |
throw new RuntimeException(e); |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
private static void copyInThread(final InputStream in, |
| 280 |
final OutputStream out) { |
| 281 |
new Thread("Profiler stream copy") { |
| 282 |
@Override |
| 283 |
public void run() { |
| 284 |
byte[] buffer = new byte[4096]; |
| 285 |
try { |
| 286 |
while (true) { |
| 287 |
int len = in.read(buffer, 0, buffer.length); |
| 288 |
if (len < 0) { |
| 289 |
break; |
| 290 |
} |
| 291 |
out.write(buffer, 0, len); |
| 292 |
} |
| 293 |
} catch (Exception e) { |
| 294 |
throw new RuntimeException(e); |
| 295 |
} |
| 296 |
} |
| 297 |
}.start(); |
| 298 |
} |
| 299 |
|
| 300 |
/** |
| 301 |
* Start collecting profiling data. |
| 302 |
* |
| 303 |
* @return this |
| 304 |
*/ |
| 305 |
public Profiler startCollecting() { |
| 306 |
thread = new Thread(this, "Profiler"); |
| 307 |
thread.setDaemon(true); |
| 308 |
thread.start(); |
| 309 |
return this; |
| 310 |
} |
| 311 |
|
| 312 |
/** |
| 313 |
* Stop collecting. |
| 314 |
* |
| 315 |
* @return this |
| 316 |
*/ |
| 317 |
public Profiler stopCollecting() { |
| 318 |
stop = true; |
| 319 |
if (thread != null) { |
| 320 |
try { |
| 321 |
thread.join(); |
| 322 |
} catch (InterruptedException e) { |
| 323 |
// ignore |
| 324 |
} |
| 325 |
thread = null; |
| 326 |
} |
| 327 |
return this; |
| 328 |
} |
| 329 |
|
| 330 |
@Override |
| 331 |
public void run() { |
| 332 |
start = System.nanoTime(); |
| 333 |
while (!stop) { |
| 334 |
try { |
| 335 |
tick(); |
| 336 |
} catch (Throwable t) { |
| 337 |
break; |
| 338 |
} |
| 339 |
} |
| 340 |
time = System.nanoTime() - start; |
| 341 |
} |
| 342 |
|
| 343 |
private void tick() { |
| 344 |
if (interval > 0) { |
| 345 |
if (paused) { |
| 346 |
return; |
| 347 |
} |
| 348 |
try { |
| 349 |
Thread.sleep(interval, 0); |
| 350 |
} catch (Exception e) { |
| 351 |
// ignore |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
List<Object[]> list; |
| 356 |
if (pid != 0) { |
| 357 |
list = readRunnableStackTraces(pid); |
| 358 |
} else { |
| 359 |
list = getRunnableStackTraces(); |
| 360 |
} |
| 361 |
threadDumps++; |
| 362 |
processList(list); |
| 363 |
} |
| 364 |
|
| 365 |
private void processList(List<Object[]> list) { |
| 366 |
for (Object[] dump : list) { |
| 367 |
if (startsWithAny(dump[0].toString(), ignoreThreads)) { |
| 368 |
continue; |
| 369 |
} |
| 370 |
StringBuilder buff = new StringBuilder(); |
| 371 |
// simple recursive calls are ignored |
| 372 |
String last = null; |
| 373 |
boolean packageCounts = false; |
| 374 |
for (int j = 0, i = 0; i < dump.length && j < depth; i++) { |
| 375 |
String el = dump[i].toString(); |
| 376 |
if (!el.equals(last) && !startsWithAny(el, ignoreLines)) { |
| 377 |
last = el; |
| 378 |
buff.append("at ").append(el).append(LINE_SEPARATOR); |
| 379 |
if (!packageCounts && !startsWithAny(el, ignorePackages)) { |
| 380 |
packageCounts = true; |
| 381 |
int index = 0; |
| 382 |
for (; index < el.length(); index++) { |
| 383 |
char c = el.charAt(index); |
| 384 |
if (c == '(' || Character.isUpperCase(c)) { |
| 385 |
break; |
| 386 |
} |
| 387 |
} |
| 388 |
if (index > 0 && el.charAt(index - 1) == '.') { |
| 389 |
index--; |
| 390 |
} |
| 391 |
if (sumClasses) { |
| 392 |
int m = el.indexOf('.', index + 1); |
| 393 |
index = m >= 0 ? m : index; |
| 394 |
} |
| 395 |
if (sumMethods) { |
| 396 |
int m = el.indexOf('(', index + 1); |
| 397 |
index = m >= 0 ? m : index; |
| 398 |
} |
| 399 |
String groupName = el.substring(0, index); |
| 400 |
increment(summary, groupName, 0); |
| 401 |
} |
| 402 |
j++; |
| 403 |
} |
| 404 |
} |
| 405 |
if (buff.length() > 0) { |
| 406 |
minCount = increment(counts, buff.toString().trim(), minCount); |
| 407 |
total++; |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
private static boolean startsWithAny(String s, String[] prefixes) { |
| 413 |
for (String p : prefixes) { |
| 414 |
if (p.length() > 0 && s.startsWith(p)) { |
| 415 |
return true; |
| 416 |
} |
| 417 |
} |
| 418 |
return false; |
| 419 |
} |
| 420 |
|
| 421 |
private static int increment(HashMap<String, Integer> map, String trace, |
| 422 |
int minCount) { |
| 423 |
Integer oldCount = map.get(trace); |
| 424 |
if (oldCount == null) { |
| 425 |
map.put(trace, 1); |
| 426 |
} else { |
| 427 |
map.put(trace, oldCount + 1); |
| 428 |
} |
| 429 |
while (map.size() > MAX_ELEMENTS) { |
| 430 |
for (Iterator<Map.Entry<String, Integer>> ei = |
| 431 |
map.entrySet().iterator(); ei.hasNext();) { |
| 432 |
Map.Entry<String, Integer> e = ei.next(); |
| 433 |
if (e.getValue() <= minCount) { |
| 434 |
ei.remove(); |
| 435 |
} |
| 436 |
} |
| 437 |
if (map.size() > MAX_ELEMENTS) { |
| 438 |
minCount++; |
| 439 |
} |
| 440 |
} |
| 441 |
return minCount; |
| 442 |
} |
| 443 |
|
| 444 |
/** |
| 445 |
* Get the top stack traces. |
| 446 |
* |
| 447 |
* @param count the maximum number of stack traces |
| 448 |
* @return the stack traces. |
| 449 |
*/ |
| 450 |
public String getTop(int count) { |
| 451 |
stopCollecting(); |
| 452 |
return getTopTraces(count); |
| 453 |
} |
| 454 |
|
| 455 |
private String getTopTraces(int count) { |
| 456 |
StringBuilder buff = new StringBuilder(); |
| 457 |
buff.append("Profiler: top ").append(count).append(" stack trace(s) of "); |
| 458 |
if (time > 0) { |
| 459 |
buff.append(" of ").append(TimeUnit.NANOSECONDS.toMillis(time)).append(" ms"); |
| 460 |
} |
| 461 |
if (threadDumps > 0) { |
| 462 |
buff.append(" of ").append(threadDumps).append(" thread dumps"); |
| 463 |
} |
| 464 |
buff.append(":").append(LINE_SEPARATOR); |
| 465 |
if (counts.size() == 0) { |
| 466 |
buff.append("(none)").append(LINE_SEPARATOR); |
| 467 |
} |
| 468 |
HashMap<String, Integer> copy = new HashMap<>(counts); |
| 469 |
appendTop(buff, copy, count, total, false); |
| 470 |
buff.append("summary:").append(LINE_SEPARATOR); |
| 471 |
copy = new HashMap<>(summary); |
| 472 |
appendTop(buff, copy, count, total, true); |
| 473 |
buff.append('.'); |
| 474 |
return buff.toString(); |
| 475 |
} |
| 476 |
|
| 477 |
private static void appendTop(StringBuilder buff, |
| 478 |
HashMap<String, Integer> map, int count, int total, boolean table) { |
| 479 |
for (int x = 0, min = 0;;) { |
| 480 |
int highest = 0; |
| 481 |
Map.Entry<String, Integer> best = null; |
| 482 |
for (Map.Entry<String, Integer> el : map.entrySet()) { |
| 483 |
if (el.getValue() > highest) { |
| 484 |
best = el; |
| 485 |
highest = el.getValue(); |
| 486 |
} |
| 487 |
} |
| 488 |
if (best == null) { |
| 489 |
break; |
| 490 |
} |
| 491 |
map.remove(best.getKey()); |
| 492 |
if (++x >= count) { |
| 493 |
if (best.getValue() < min) { |
| 494 |
break; |
| 495 |
} |
| 496 |
min = best.getValue(); |
| 497 |
} |
| 498 |
int c = best.getValue(); |
| 499 |
int percent = 100 * c / Math.max(total, 1); |
| 500 |
if (table) { |
| 501 |
if (percent > 1) { |
| 502 |
buff.append(percent). |
| 503 |
append("%: ").append(best.getKey()). |
| 504 |
append(LINE_SEPARATOR); |
| 505 |
} |
| 506 |
} else { |
| 507 |
buff.append(c).append('/').append(total).append(" ("). |
| 508 |
append(percent). |
| 509 |
append("%):").append(LINE_SEPARATOR). |
| 510 |
append(best.getKey()). |
| 511 |
append(LINE_SEPARATOR); |
| 512 |
} |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
} |