forked from btraceio/btrace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
740 lines (688 loc) · 28.5 KB
/
Copy pathMain.java
File metadata and controls
740 lines (688 loc) · 28.5 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/*
* Copyright (c) 2008, 2016, 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 com.sun.btrace.agent;
import com.sun.btrace.ArgsMap;
import com.sun.btrace.runtime.BTraceTransformer;
import com.sun.btrace.DebugSupport;
import com.sun.btrace.SharedSettings;
import java.io.File;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
import com.sun.btrace.BTraceRuntime;
import com.sun.btrace.runtime.Constants;
import com.sun.btrace.comm.ErrorCommand;
import com.sun.btrace.util.Messages;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;
/**
* This is the main class for BTrace java.lang.instrument agent.
*
* @author A. Sundararajan
* @author Joachim Skeie (rolling output)
*/
public final class Main {
private static long ts = System.nanoTime();
private static volatile ArgsMap argMap;
private static volatile Instrumentation inst;
private static volatile Long fileRollMilliseconds;
private static final Pattern KV_PATTERN = Pattern.compile(",");
private static final SharedSettings settings = SharedSettings.GLOBAL;
private static final DebugSupport debug = new DebugSupport(settings);
private static final BTraceTransformer transformer = new BTraceTransformer(debug);
// #BTRACE-42: Non-daemon thread prevents traced application from exiting
private static final ThreadFactory qProcessorThreadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread result = new Thread(r, "BTrace Command Queue Processor");
result.setDaemon(true);
return result;
}
};
private static final ExecutorService serializedExecutor = Executors.newSingleThreadExecutor(qProcessorThreadFactory);
public static void premain(String args, Instrumentation inst) {
main(args, inst);
}
public static void agentmain(String args, Instrumentation inst) {
main(args, inst);
}
private static synchronized void main(final String args, final Instrumentation inst) {
if (Main.inst != null) {
return;
} else {
Main.inst = inst;
}
List<Client> scriptClients = new ArrayList<>();
try {
loadArgs(args);
// set the debug level based on cmdline config
settings.setDebug(Boolean.parseBoolean(argMap.get("debug")));
if (isDebug()) {
debugPrint("parsed command line arguments");
}
parseArgs();
int startedScripts = collectScriptClients(scriptClients);
String tmp = argMap.get("noServer");
// noServer is defaulting to true if startup scripts are defined
boolean noServer = tmp != null ? Boolean.parseBoolean(tmp) : hasScripts();
if (noServer) {
if (isDebug()) {
debugPrint("noServer is true, server not started");
}
return;
}
Thread agentThread = new Thread(new Runnable() {
@Override
public void run() {
BTraceRuntime.enter();
try {
startServer();
} finally {
BTraceRuntime.leave();
}
}
});
BTraceRuntime.initUnsafe();
BTraceRuntime.enter();
try {
agentThread.setDaemon(true);
if (isDebug()) {
debugPrint("starting agent thread");
}
agentThread.start();
} finally {
BTraceRuntime.leave();
}
} finally {
inst.addTransformer(transformer, true);
startClients(scriptClients);
Main.debugPrint("Agent init took: " + (System.nanoTime() - ts) + "ns");
}
}
private static void startClients(List<Client> scriptClients) {
for (Client client : scriptClients) {
try {
handleNewClient(client).get();
} catch (ExecutionException e) {
if (isDebug()) {
debugPrint(e);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private static boolean hasScripts() {
return argMap.containsKey("script") || argMap.containsKey("scriptDir");
}
private static void loadDefaultArguments(String config) {
try {
String propTarget = Constants.EMBEDDED_BTRACE_SECTION_HEADER + "agent.properties";
InputStream is = ClassLoader.getSystemResourceAsStream(propTarget);
if (is != null) {
Properties ps = new Properties();
ps.load(is);
StringBuilder log = new StringBuilder();
for (Map.Entry<Object, Object> entry : ps.entrySet()) {
String keyConfig = "";
String argKey = (String) entry.getKey();
int configPos = argKey.lastIndexOf('#');
if (configPos > -1) {
keyConfig = argKey.substring(0, configPos);
argKey = argKey.substring(configPos + 1);
}
if (config == null || keyConfig.isEmpty() || config.equals(keyConfig)) {
String argVal = (String) entry.getValue();
switch (argKey) {
case "script": {
// special treatment for the 'script' parameter
boolean replace = false;
String scriptVal = argVal;
if (scriptVal.startsWith("!")) {
scriptVal = scriptVal.substring(1);
replace = true;
} else {
String oldVal = argMap.get(argKey);
if (oldVal != null && !oldVal.isEmpty()) {
scriptVal = oldVal + ":" + scriptVal;
} else {
replace = true;
}
}
if (replace) {
log.append("setting default agent argument '").append(argKey)
.append("' to '").append(scriptVal).append("'\n");
} else {
log.append("augmenting default agent argument '").append(argKey)
.append("':'").append(argMap.get(argKey)).append("' with '").append(argVal)
.append("'\n");
}
argMap.put(argKey, scriptVal);
break;
}
case "systemClassPath": // fall through
case "bootClassPath": // fall through
case "config": {
log.append("argument '").append(argKey).append("' is not overridable\n");
break;
}
default: {
if (!argMap.containsKey(argKey)) {
log.append("applying default agent argument '").append(argKey)
.append("'='").append(argVal).append("'\n");
argMap.put(argKey, argVal);
}
}
}
}
}
if (argMap.containsKey("debug") && argMap.get("debug").equalsIgnoreCase("true")) {
DebugSupport.info(log.toString());
}
}
} catch (IOException e) {
debug.debug(e);
}
}
private static int collectScriptClients(List<Client> scriptClients) {
int scriptCount = 0;
String p = argMap.get("stdout");
boolean traceToStdOut = p != null && !"false".equals(p);
if (isDebug()) {
debugPrint("stdout is " + traceToStdOut);
}
String script = argMap.get("script");
String scriptDir = argMap.get("scriptdir");
if (script != null) {
StringTokenizer tokenizer = new StringTokenizer(script, ":");
if (isDebug()) {
debugPrint(((tokenizer.countTokens() == 1) ? "initial script is " : "initial scripts are ") + script);
}
while (tokenizer.hasMoreTokens()) {
if (loadBTraceScript(tokenizer.nextToken(), traceToStdOut, scriptClients)) {
scriptCount++;
}
}
}
if (scriptDir != null) {
File dir = new File(scriptDir);
if (dir.isDirectory()) {
if (isDebug()) {
debugPrint("found scriptdir: " + dir.getAbsolutePath());
}
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (loadBTraceScript(file.getAbsolutePath(), traceToStdOut, scriptClients)) {
scriptCount++;
}
}
}
}
}
return scriptCount;
}
private static void usage() {
System.out.println(Messages.get("btrace.agent.usage"));
System.exit(0);
}
private static void loadArgs(String args) {
if (args == null) {
args = "";
}
String[] pairs = KV_PATTERN.split(args);
argMap = new ArgsMap();
for (String s : pairs) {
int i = s.indexOf('=');
String key, value = "";
if (i != -1) {
key = s.substring(0, i).trim();
if (i + 1 < s.length()) {
value = s.substring(i + 1).trim();
}
} else {
key = s;
}
argMap.put(key, value);
}
}
private static void parseArgs() {
String p = argMap.get("help");
if (p != null) {
usage();
}
String libs = argMap.get("libs");
String config = argMap.get("config");
processClasspaths(libs);
loadDefaultArguments(config);
p = argMap.get("debug");
settings.setDebug(p != null && !"false".equals(p));
if (isDebug()) {
debugPrint("debugMode is " + settings.isDebug());
}
for (Map.Entry<String, String> e : argMap) {
String key = e.getKey();
p = e.getValue();
switch (key) {
case "startupRetransform": {
if (!p.isEmpty()) {
settings.setRetransformStartup(p.isEmpty() ? false : Boolean.parseBoolean(p));
if (isDebug()) {
debugPrint("startupRetransform is " + settings.isRetransformStartup());
}
}
break;
}
case "dumpDir": {
String dumpClassesVal = argMap.get("dumpClasses");
if (dumpClassesVal != null) {
boolean dumpClasses = Boolean.parseBoolean(dumpClassesVal);
if (isDebug()) {
debugPrint("dumpClasses is " + dumpClasses);
}
if (dumpClasses) {
String dumpDir = argMap.get("dumpDir");
settings.setDumpDir(dumpDir != null ? dumpDir : ".");
if (isDebug()) {
debugPrint("dumpDir is " + dumpDir);
}
}
}
break;
}
case "cmdQueueLimit": {
if (!p.isEmpty()) {
System.setProperty(BTraceRuntime.CMD_QUEUE_LIMIT_KEY, p);
if (isDebug()) {
debugPrint("cmdQueueLimit provided: " + p);
}
}
break;
}
case "trackRetransforms": {
if (!p.isEmpty()) {
settings.setTrackRetransforms(Boolean.parseBoolean(p));
if (settings.isTrackRetransforms()) {
debugPrint("trackRetransforms is " + settings.isTrackRetransforms());
}
}
break;
}
case "scriptOutputFile": {
if (!p.isEmpty()) {
settings.setOutputFile(p);
if (isDebug()) {
debugPrint("scriptOutputFile is " + p);
}
}
break;
}
case "scriptOutputDir": {
if (!p.isEmpty()) {
settings.setOutputDir(p);
if (isDebug()) {
debugPrint("scriptOutputDir is " + p);
}
}
break;
}
case "fileRollMilliseconds": {
if (!p.isEmpty()) {
Long msParsed = null;
try {
msParsed = Long.parseLong(p);
fileRollMilliseconds = msParsed;
} catch (NumberFormatException nfe) {
fileRollMilliseconds = null;
}
if (fileRollMilliseconds != null) {
settings.setFileRollMilliseconds(fileRollMilliseconds.intValue());
if (isDebug()) {
debugPrint("fileRollMilliseconds is " + fileRollMilliseconds);
}
}
}
break;
}
case "fileRollMaxRolls": {
if (!p.isEmpty()) {
Integer rolls = null;
try {
rolls = Integer.parseInt(p);
} catch (NumberFormatException nfe) {
rolls = null;
}
if (rolls != null) {
settings.setFileRollMaxRolls(rolls);
}
}
break;
}
case "unsafe": // fallthrough
case "trusted": {
if (!p.isEmpty()) {
settings.setTrusted(Boolean.parseBoolean(p));
if (isDebug()) {
debugPrint("trustedMode is " + settings.isTrusted());
}
}
break;
}
case "statsd": {
if (!p.isEmpty()) {
String[] parts = p.split(":");
if (parts.length == 2) {
settings.setStatsdHost(parts[0].trim());
try {
settings.setStatsdPort(Integer.parseInt(parts[1].trim()));
} catch (NumberFormatException ex) {
DebugSupport.warning("Invalid statsd port number: " + parts[1]);
// leave the port unconfigured
}
} else if (parts.length == 1) {
settings.setStatsdHost(parts[0].trim());
}
}
break;
}
case "probeDescPath": {
if (!p.isEmpty()) {
settings.setProbeDescPath(!p.isEmpty() ? p : ".");
if (isDebug()) {
debugPrint("probe descriptor path is " + settings.getProbeDescPath());
}
}
break;
}
default: {
if (key.startsWith("$")) {
String pKey = key.substring(1);
System.setProperty(pKey, p);
if (isDebug()) {
debugPrint("Setting system property: " + pKey + "=" + p);
}
}
}
}
}
}
private static void processClasspaths(String libs) {
String bootClassPath = argMap.get("bootClassPath");
if (bootClassPath != null) {
if (isDebug()) {
debugPrint("Bootstrap ClassPath: " + bootClassPath);
}
StringTokenizer tokenizer = new StringTokenizer(bootClassPath, File.pathSeparator);
try {
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
File f = new File(path);
if (!f.exists()) {
debug.warning("BTrace bootstrap classpath resource [ " + path + "] does not exist");
} else {
if (f.isFile() && f.getName().toLowerCase().endsWith(".jar")) {
JarFile jf = new JarFile(f);
inst.appendToBootstrapClassLoaderSearch(jf);
} else {
debugPrint("ignoring boot classpath element '" + path
+ "' - only jar files allowed");
}
}
}
} catch (IOException ex) {
debugPrint("adding to boot classpath failed!");
debugPrint(ex);
return;
}
}
String systemClassPath = argMap.get("systemClassPath");
if (systemClassPath != null) {
if (isDebug()) {
debugPrint("System ClassPath: " + systemClassPath);
}
StringTokenizer tokenizer = new StringTokenizer(systemClassPath, File.pathSeparator);
try {
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
File f = new File(path);
if (!f.exists()) {
debug.warning("BTrace system classpath resource [" + path + "] does not exist.");
} else {
if (f.isFile() && f.getName().toLowerCase().endsWith(".jar")) {
JarFile jf = new JarFile(f);
inst.appendToSystemClassLoaderSearch(jf);
} else {
debugPrint("ignoring system classpath element '" + path
+ "' - only jar files allowed");
}
}
}
} catch (IOException ex) {
debugPrint("adding to boot classpath failed!");
debugPrint(ex);
return;
}
}
addPreconfLibs(libs);
}
private static void addPreconfLibs(String libs) {
URL u = Main.class.getClassLoader().getResource(Main.class.getName().replace('.', '/') + ".class");
if (u != null) {
String path = u.toString();
int delimiterPos = path.lastIndexOf('!');
if (delimiterPos > -1) {
String jar = path.substring(9, delimiterPos);
File jarFile = new File(jar);
Path libRoot = new File(jarFile.getParent() + File.separator + "btrace-libs").toPath();
Path libFolder = libs != null ? libRoot.resolve(libs) : libRoot;
if (Files.exists(libFolder)) {
appendToBootClassPath(libFolder);
appendToSysClassPath(libFolder);
} else if (libs != null) {
// for user provided libs config report error if the location does not exist
DebugSupport.warning("Invalid 'libs' configuration [" + libs + "]. " +
"Path '" + libFolder.toAbsolutePath().toString() + "' does not exist.");
}
}
}
}
private static void appendToBootClassPath(Path libFolder) {
Path bootLibs = libFolder.resolve("boot");
if (Files.exists(bootLibs)) {
for (File f : bootLibs.toFile().listFiles()) {
if (f.getName().toLowerCase().endsWith(".jar")) {
try {
if (isDebug()) {
debugPrint("Adding " + f.getAbsolutePath() + " to bootstrap classpath");
}
inst.appendToBootstrapClassLoaderSearch(new JarFile(f));
} catch (IOException e) {
}
}
}
}
}
private static void appendToSysClassPath(Path libFolder) {
Path sysLibs = libFolder.resolve("system");
if (Files.exists(sysLibs)) {
for (File f : sysLibs.toFile().listFiles()) {
if (f.getName().toLowerCase().endsWith(".jar")) {
try {
if (isDebug()) {
debugPrint("Adding " + f.getAbsolutePath() + " to system classpath");
}
inst.appendToSystemClassLoaderSearch(new JarFile(f));
} catch (IOException e) {
}
}
}
}
}
private static boolean loadBTraceScript(String filePath, boolean traceToStdOut, List<Client> scriptClients) {
try {
String scriptName = "";
String scriptParent = "";
File traceScript = new File(filePath);
scriptName = traceScript.getName();
scriptParent = traceScript.getParent();
if (!traceScript.exists()) {
traceScript = new File(Constants.EMBEDDED_BTRACE_SECTION_HEADER + filePath);
}
if (scriptName.endsWith(".java")) {
if (isDebug()) {
debugPrint("refusing " + filePath + " - script should be a pre-compiled class file");
}
return false;
}
SharedSettings clientSettings = new SharedSettings();
clientSettings.from(settings);
clientSettings.setClientName(scriptName);
if (traceToStdOut) {
clientSettings.setOutputFile("::stdout");
} else {
String traceOutput = clientSettings.getOutputFile();
String outDir = clientSettings.getOutputDir();
if (traceOutput == null || traceOutput.length() == 0) {
clientSettings.setOutputFile("${client}-${agent}.${ts}.btrace[default]");
if (outDir == null || outDir.length() == 0) {
clientSettings.setOutputDir(scriptParent);
}
}
}
ClientContext ctx = new ClientContext(inst, transformer, argMap, clientSettings);
Client client = new FileClient(ctx, traceScript);
if (client.isInitialized()) {
scriptClients.add(client);
return true;
}
} catch (NullPointerException e) {
if (isDebug()) {
debugPrint("script " + filePath + " does not exist!");
}
} catch (RuntimeException | IOException re) {
if (isDebug()) {
debugPrint(re);
}
}
return false;
}
public static final int BTRACE_DEFAULT_PORT = 2020;
//-- Internals only below this point
private static void startServer() {
int port = BTRACE_DEFAULT_PORT;
String p = argMap.get("port");
if (p != null) {
try {
port = Integer.parseInt(p);
} catch (NumberFormatException exp) {
error("invalid port assuming default..");
}
}
ServerSocket ss;
try {
if (isDebug()) {
debugPrint("starting server at " + port);
}
System.setProperty("btrace.port", String.valueOf(port));
String scriptOutputFile = settings.getOutputFile();
if (scriptOutputFile != null && scriptOutputFile.length() > 0) {
System.setProperty("btrace.output", scriptOutputFile);
}
ss = new ServerSocket(port);
} catch (IOException ioexp) {
ioexp.printStackTrace();
return;
}
while (true) {
try {
if (isDebug()) {
debugPrint("waiting for clients");
}
Socket sock = ss.accept();
if (isDebug()) {
debugPrint("client accepted " + sock);
}
ClientContext ctx = new ClientContext(inst, transformer, argMap, settings);
Client client = new RemoteClient(ctx, sock);
handleNewClient(client).get();
} catch (RuntimeException | IOException | ExecutionException re) {
if (isDebug()) {
debugPrint(re);
}
} catch (InterruptedException e) {
return;
}
}
}
private static Future<?> handleNewClient(final Client client) {
return serializedExecutor.submit(new Runnable() {
@Override
public void run() {
boolean entered = BTraceRuntime.enter();
try {
client.debugPrint("new Client created " + client);
client.retransformLoaded();
} catch (UnmodifiableClassException uce) {
if (isDebug()) {
debugPrint(uce);
}
client.getRuntime().send(new ErrorCommand(uce));
} finally {
if (entered) {
BTraceRuntime.leave();
}
}
}
});
}
private static void error(String msg) {
System.err.println("btrace ERROR: " + msg);
}
private static boolean isDebug() {
return settings.isDebug();
}
private static void debugPrint(String msg) {
debug.debug(msg);
}
private static void debugPrint(Throwable th) {
debug.debug(th);
}
}