-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathThreadDumper.java
370 lines (341 loc) · 13.2 KB
/
ThreadDumper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.vm;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Thread dump support.
*
* This class defines methods to dump threads to an output stream or file in plain
* text or JSON format.
*/
public class ThreadDumper {
private ThreadDumper() { }
// the maximum byte array to return when generating the thread dump to a byte array
private static final int MAX_BYTE_ARRAY_SIZE = 16_000;
/**
* Generate a thread dump in plain text format to a byte array or file, UTF-8 encoded.
*
* This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
*
* @param file the file path to the file, null or "-" to return a byte array
* @param okayToOverwrite true to overwrite an existing file
* @return the UTF-8 encoded thread dump or message to return to the user
*/
public static byte[] dumpThreads(String file, boolean okayToOverwrite) {
if (file == null || file.equals("-")) {
return dumpThreadsToByteArray(false, MAX_BYTE_ARRAY_SIZE);
} else {
return dumpThreadsToFile(file, okayToOverwrite, false);
}
}
/**
* Generate a thread dump in JSON format to a byte array or file, UTF-8 encoded.
*
* This method is invoked by the VM for the Thread.dump_to_file diagnostic command.
*
* @param file the file path to the file, null or "-" to return a byte array
* @param okayToOverwrite true to overwrite an existing file
* @return the UTF-8 encoded thread dump or message to return to the user
*/
public static byte[] dumpThreadsToJson(String file, boolean okayToOverwrite) {
if (file == null || file.equals("-")) {
return dumpThreadsToByteArray(true, MAX_BYTE_ARRAY_SIZE);
} else {
return dumpThreadsToFile(file, okayToOverwrite, true);
}
}
/**
* Generate a thread dump in plain text or JSON format to a byte array, UTF-8 encoded.
*/
private static byte[] dumpThreadsToByteArray(boolean json, int maxSize) {
try (var out = new BoundedByteArrayOutputStream(maxSize);
PrintStream ps = new PrintStream(out, true, StandardCharsets.UTF_8)) {
if (json) {
dumpThreadsToJson(ps);
} else {
dumpThreads(ps);
}
return out.toByteArray();
}
}
/**
* Generate a thread dump in plain text or JSON format to the given file, UTF-8 encoded.
*/
private static byte[] dumpThreadsToFile(String file, boolean okayToOverwrite, boolean json) {
Path path = Path.of(file).toAbsolutePath();
OpenOption[] options = (okayToOverwrite)
? new OpenOption[0]
: new OpenOption[] { StandardOpenOption.CREATE_NEW };
String reply;
try (OutputStream out = Files.newOutputStream(path, options);
BufferedOutputStream bos = new BufferedOutputStream(out);
PrintStream ps = new PrintStream(bos, false, StandardCharsets.UTF_8)) {
if (json) {
dumpThreadsToJson(ps);
} else {
dumpThreads(ps);
}
reply = String.format("Created %s%n", path);
} catch (FileAlreadyExistsException e) {
reply = String.format("%s exists, use -overwrite to overwrite%n", path);
} catch (IOException ioe) {
reply = String.format("Failed: %s%n", ioe);
}
return reply.getBytes(StandardCharsets.UTF_8);
}
/**
* Generate a thread dump in plain text format to the given output stream,
* UTF-8 encoded.
*
* This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
*/
public static void dumpThreads(OutputStream out) {
BufferedOutputStream bos = new BufferedOutputStream(out);
PrintStream ps = new PrintStream(bos, false, StandardCharsets.UTF_8);
try {
dumpThreads(ps);
} finally {
ps.flush(); // flushes underlying stream
}
}
/**
* Generate a thread dump in plain text format to the given print stream.
*/
private static void dumpThreads(PrintStream ps) {
ps.println(processId());
ps.println(Instant.now());
ps.println(Runtime.version());
ps.println();
dumpThreads(ThreadContainers.root(), ps);
}
private static void dumpThreads(ThreadContainer container, PrintStream ps) {
container.threads().forEach(t -> dumpThread(t, ps));
container.children().forEach(c -> dumpThreads(c, ps));
}
private static void dumpThread(Thread thread, PrintStream ps) {
String suffix = thread.isVirtual() ? " virtual" : "";
ps.println("#" + thread.threadId() + " \"" + thread.getName() + "\"" + suffix);
for (StackTraceElement ste : thread.getStackTrace()) {
ps.print(" ");
ps.println(ste);
}
ps.println();
}
/**
* Generate a thread dump in JSON format to the given output stream, UTF-8 encoded.
*
* This method is invoked by HotSpotDiagnosticMXBean.dumpThreads.
*/
public static void dumpThreadsToJson(OutputStream out) {
BufferedOutputStream bos = new BufferedOutputStream(out);
PrintStream ps = new PrintStream(bos, false, StandardCharsets.UTF_8);
try {
dumpThreadsToJson(ps);
} finally {
ps.flush(); // flushes underlying stream
}
}
/**
* Generate a thread dump to the given print stream in JSON format.
*/
private static void dumpThreadsToJson(PrintStream out) {
out.println("{");
out.println(" \"threadDump\": {");
String now = Instant.now().toString();
String runtimeVersion = Runtime.version().toString();
out.format(" \"processId\": \"%d\",%n", processId());
out.format(" \"time\": \"%s\",%n", escape(now));
out.format(" \"runtimeVersion\": \"%s\",%n", escape(runtimeVersion));
out.println(" \"threadContainers\": [");
List<ThreadContainer> containers = allContainers();
Iterator<ThreadContainer> iterator = containers.iterator();
while (iterator.hasNext()) {
ThreadContainer container = iterator.next();
boolean more = iterator.hasNext();
dumpThreadsToJson(container, out, more);
}
out.println(" ]"); // end of threadContainers
out.println(" }"); // end threadDump
out.println("}"); // end object
}
/**
* Dump the given thread container to the print stream in JSON format.
*/
private static void dumpThreadsToJson(ThreadContainer container,
PrintStream out,
boolean more) {
out.println(" {");
out.format(" \"container\": \"%s\",%n", escape(container.toString()));
ThreadContainer parent = container.parent();
if (parent == null) {
out.format(" \"parent\": null,%n");
} else {
out.format(" \"parent\": \"%s\",%n", escape(parent.toString()));
}
Thread owner = container.owner();
if (owner == null) {
out.format(" \"owner\": null,%n");
} else {
out.format(" \"owner\": \"%d\",%n", owner.threadId());
}
long threadCount = 0;
out.println(" \"threads\": [");
Iterator<Thread> threads = container.threads().iterator();
while (threads.hasNext()) {
Thread thread = threads.next();
dumpThreadToJson(thread, out, threads.hasNext());
threadCount++;
}
out.println(" ],"); // end of threads
// thread count
if (!ThreadContainers.trackAllThreads()) {
threadCount = Long.max(threadCount, container.threadCount());
}
out.format(" \"threadCount\": \"%d\"%n", threadCount);
if (more) {
out.println(" },");
} else {
out.println(" }"); // last container, no trailing comma
}
}
/**
* Dump the given thread and its stack trace to the print stream in JSON format.
*/
private static void dumpThreadToJson(Thread thread, PrintStream out, boolean more) {
out.println(" {");
out.println(" \"tid\": \"" + thread.threadId() + "\",");
out.println(" \"name\": \"" + escape(thread.getName()) + "\",");
out.println(" \"stack\": [");
int i = 0;
StackTraceElement[] stackTrace = thread.getStackTrace();
while (i < stackTrace.length) {
out.print(" \"");
out.print(escape(stackTrace[i].toString()));
out.print("\"");
i++;
if (i < stackTrace.length) {
out.println(",");
} else {
out.println(); // last element, no trailing comma
}
}
out.println(" ]");
if (more) {
out.println(" },");
} else {
out.println(" }"); // last thread, no trailing comma
}
}
/**
* Returns a list of all thread containers that are "reachable" from
* the root container.
*/
private static List<ThreadContainer> allContainers() {
List<ThreadContainer> containers = new ArrayList<>();
collect(ThreadContainers.root(), containers);
return containers;
}
private static void collect(ThreadContainer container, List<ThreadContainer> containers) {
containers.add(container);
container.children().forEach(c -> collect(c, containers));
}
/**
* Escape any characters that need to be escape in the JSON output.
*/
private static String escape(String value) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"' -> sb.append("\\\"");
case '\\' -> sb.append("\\\\");
case '/' -> sb.append("\\/");
case '\b' -> sb.append("\\b");
case '\f' -> sb.append("\\f");
case '\n' -> sb.append("\\n");
case '\r' -> sb.append("\\r");
case '\t' -> sb.append("\\t");
default -> {
if (c <= 0x1f) {
sb.append(String.format("\\u%04x", c));
} else {
sb.append(c);
}
}
}
}
return sb.toString();
}
/**
* A ByteArrayOutputStream of bounded size. Once the maximum number of bytes is
* written the subsequent bytes are discarded.
*/
private static class BoundedByteArrayOutputStream extends ByteArrayOutputStream {
final int max;
BoundedByteArrayOutputStream(int max) {
this.max = max;
}
@Override
public void write(int b) {
if (max < count) {
super.write(b);
}
}
@Override
public void write(byte[] b, int off, int len) {
int remaining = max - count;
if (remaining > 0) {
super.write(b, off, Integer.min(len, remaining));
}
}
@Override
public void close() {
}
}
/**
* Returns the process ID or -1 if not supported.
*/
private static long processId() {
try {
return ProcessHandle.current().pid();
} catch (UnsupportedOperationException e) {
return -1L;
}
}
}