forked from robaho/httpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessTools.java
More file actions
947 lines (852 loc) · 35.1 KB
/
ProcessTools.java
File metadata and controls
947 lines (852 loc) · 35.1 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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/*
* Copyright (c) 2013, 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.
*
* 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.test.lib.process;
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.Platform;
import jdk.test.lib.Utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.Thread.State;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public final class ProcessTools {
private static final class LineForwarder extends StreamPumper.LinePump {
private final PrintStream ps;
private final String prefix;
LineForwarder(String prefix, PrintStream os) {
this.ps = os;
this.prefix = prefix;
}
@Override
protected void processLine(String line) {
ps.println("[" + prefix + "] " + line);
}
}
private ProcessTools() {
}
/**
* <p>Starts a process from its builder.</p>
* <span>The default redirects of STDOUT and STDERR are started</span>
* <p>
* Same as
* {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess}
* {@code (name, processBuilder, null, null, -1, TimeUnit.NANOSECONDS)}
* </p>
* @param name The process name
* @param processBuilder The process builder
* @return Returns the initialized process
* @throws IOException
*/
public static Process startProcess(String name,
ProcessBuilder processBuilder)
throws IOException {
return startProcess(name, processBuilder, (Consumer<String>) null);
}
/**
* <p>Starts a process from its builder.</p>
* <span>The default redirects of STDOUT and STDERR are started</span>
* <p>
* Same as
* {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess}
* {@code (name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS)}
* </p>
*
* @param name The process name
* @param processBuilder The process builder
* @param consumer {@linkplain Consumer} instance to process the in-streams
* @return Returns the initialized process
* @throws IOException
*/
@SuppressWarnings("overloads")
public static Process startProcess(String name,
ProcessBuilder processBuilder,
Consumer<String> consumer)
throws IOException {
try {
return startProcess(name, processBuilder, consumer, null, -1, TimeUnit.NANOSECONDS);
} catch (InterruptedException | TimeoutException | CancellationException e) {
// will never happen
throw new RuntimeException(e);
}
}
/**
* <p>Starts a process from its builder.</p>
* <span>The default redirects of STDOUT and STDERR are started</span>
* <p>
* Same as
* {@linkplain #startProcess(String, ProcessBuilder, Consumer, Predicate, long, TimeUnit) startProcess}
* {@code (name, processBuilder, null, linePredicate, timeout, unit)}
* </p>
*
* @param name The process name
* @param processBuilder The process builder
* @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR.
* Used to determine the moment the target app is
* properly warmed-up.
* It can be null - in that case the warmup is skipped.
* @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever
* @param unit The timeout {@linkplain TimeUnit}
* @return Returns the initialized {@linkplain Process}
* @throws IOException
* @throws InterruptedException
* @throws TimeoutException
*/
public static Process startProcess(String name,
ProcessBuilder processBuilder,
final Predicate<String> linePredicate,
long timeout,
TimeUnit unit)
throws IOException, InterruptedException, TimeoutException {
return startProcess(name, processBuilder, null, linePredicate, timeout, unit);
}
/*
BufferOutputStream and BufferInputStream allow to re-use p.getInputStream() amd p.getOutputStream() of
processes started with ProcessTools.startProcess(...).
Implementation cashes ALL process output and allow to read it through InputStream.
The stream uses Future<Void> task from StreamPumper.process() to check if output is complete.
*/
private static class BufferOutputStream extends ByteArrayOutputStream {
private int current = 0;
final private Process p;
private Future<Void> task;
public BufferOutputStream(Process p) {
this.p = p;
}
synchronized void setTask(Future<Void> task) {
this.task = task;
}
synchronized int readNext() {
if (current > count) {
throw new RuntimeException("Shouldn't ever happen. start: "
+ current + " count: " + count + " buffer: " + this);
}
while (current == count) {
if (!p.isAlive() && (task != null)) {
try {
task.get(10, TimeUnit.MILLISECONDS);
if (current == count) {
return -1;
}
} catch (TimeoutException e) {
// continue execution, so wait() give a chance to write
} catch (InterruptedException | ExecutionException e) {
return -1;
}
}
try {
wait(1);
} catch (InterruptedException ie) {
return -1;
}
}
return this.buf[current++];
}
}
private static class BufferInputStream extends InputStream {
private final BufferOutputStream buffer;
public BufferInputStream(Process p) {
buffer = new BufferOutputStream(p);
}
BufferOutputStream getOutputStream() {
return buffer;
}
@Override
public int read() throws IOException {
return buffer.readNext();
}
}
/**
* <p>Starts a process from its builder.</p>
* <span>The default redirects of STDOUT and STDERR are started</span>
* <p>
* It is possible to wait for the process to get to a warmed-up state
* via {@linkplain Predicate} condition on the STDOUT/STDERR and monitor the
* in-streams via the provided {@linkplain Consumer}
* </p>
*
* @param name The process name
* @param processBuilder The process builder
* @param lineConsumer The {@linkplain Consumer} the lines will be forwarded to
* @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR.
* Used to determine the moment the target app is
* properly warmed-up.
* It can be null - in that case the warmup is skipped.
* @param timeout The timeout for the warmup waiting; -1 = no wait; 0 = wait forever
* @param unit The timeout {@linkplain TimeUnit}
* @return Returns the initialized {@linkplain Process}
* @throws IOException
* @throws InterruptedException
* @throws TimeoutException
*/
public static Process startProcess(String name,
ProcessBuilder processBuilder,
final Consumer<String> lineConsumer,
final Predicate<String> linePredicate,
long timeout,
TimeUnit unit)
throws IOException, InterruptedException, TimeoutException {
System.out.println("[" + name + "]:" + String.join(" ", processBuilder.command()));
Process p = privilegedStart(processBuilder);
StreamPumper stdout = new StreamPumper(p.getInputStream());
StreamPumper stderr = new StreamPumper(p.getErrorStream());
stdout.addPump(new LineForwarder(name, System.out));
stderr.addPump(new LineForwarder(name, System.err));
BufferInputStream stdOut = new BufferInputStream(p);
BufferInputStream stdErr = new BufferInputStream(p);
stdout.addOutputStream(stdOut.getOutputStream());
stderr.addOutputStream(stdErr.getOutputStream());
if (lineConsumer != null) {
StreamPumper.LinePump pump = new StreamPumper.LinePump() {
@Override
protected void processLine(String line) {
lineConsumer.accept(line);
}
};
stdout.addPump(pump);
stderr.addPump(pump);
}
CountDownLatch latch = new CountDownLatch(1);
if (linePredicate != null) {
StreamPumper.LinePump pump = new StreamPumper.LinePump() {
// synchronization between stdout and stderr pumps
private final Object sync = new Object();
@Override
protected void processLine(String line) {
synchronized (sync) {
if (latch.getCount() > 0 && linePredicate.test(line)) {
latch.countDown();
}
}
}
};
stdout.addPump(pump);
stderr.addPump(pump);
} else {
latch.countDown();
}
final Future<Void> stdoutTask = stdout.process();
final Future<Void> stderrTask = stderr.process();
stdOut.getOutputStream().setTask(stdoutTask);
stdErr.getOutputStream().setTask(stderrTask);
try {
if (timeout > -1) {
long timeoutMs = timeout == 0 ? -1: unit.toMillis(Utils.adjustTimeout(timeout));
// Every second check if line is printed and if process is still alive
Utils.waitForCondition(() -> latch.getCount() == 0 || !p.isAlive(),
timeoutMs , 1000);
if (latch.getCount() > 0) {
if (!p.isAlive()) {
// Give some extra time for the StreamPumper to run after the process completed
Thread.sleep(1000);
if (latch.getCount() > 0) {
throw new RuntimeException("Started process " + name + " terminated before producing the expected output.");
}
} else {
throw new TimeoutException();
}
}
}
} catch (TimeoutException | RuntimeException | InterruptedException e) {
System.err.println("Failed to start a process (thread dump follows)");
for (Map.Entry<Thread, StackTraceElement[]> s : Thread.getAllStackTraces().entrySet()) {
printStack(s.getKey(), s.getValue());
}
if (p.isAlive()) {
p.destroyForcibly();
}
stdoutTask.cancel(true);
stderrTask.cancel(true);
throw e;
}
return new ProcessImpl(p, stdoutTask, stderrTask, stdOut, stdErr);
}
/**
* <p>Starts a process from its builder.</p>
* <span>The default redirects of STDOUT and STDERR are started</span>
* <p>
* It is possible to wait for the process to get to a warmed-up state
* via {@linkplain Predicate} condition on the STDOUT/STDERR.
* The warm-up will wait indefinitely.
* </p>
*
* @param name The process name
* @param processBuilder The process builder
* @param linePredicate The {@linkplain Predicate} to use on the STDOUT and STDERR.
* Used to determine the moment the target app is
* properly warmed-up.
* It can be null - in that case the warmup is skipped.
* @return Returns the initialized {@linkplain Process}
* @throws IOException
* @throws InterruptedException
* @throws TimeoutException
*/
@SuppressWarnings("overloads")
public static Process startProcess(String name,
ProcessBuilder processBuilder,
final Predicate<String> linePredicate)
throws IOException, InterruptedException, TimeoutException {
return startProcess(name, processBuilder, linePredicate, 0, TimeUnit.SECONDS);
}
/**
* Get the process id of the current running Java process
*
* @return Process id
*/
public static long getProcessId() throws Exception {
return ProcessHandle.current().pid();
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested.
*
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createJavaProcessBuilder(List<String> command) {
return createJavaProcessBuilder(command.toArray(String[]::new));
}
/*
Convert arguments for tests running with virtual threads main wrapper
When test is executed with process wrapper the line is changed from
java <jvm-args> <test-class> <test-args>
to
java <jvm-args> -Dmain.wrapper=<wrapper-name> jdk.test.lib.process.ProcessTools <wrapper-name> <test-class> <test-args>
*/
private static List<String> addMainWrapperArgs(String mainWrapper, List<String> command) {
final List<String> unsupportedArgs = List.of(
"-jar", "-cp", "-classpath", "--class-path", "--describe-module", "-d",
"--dry-run", "--list-modules","--validate-modules", "-m", "--module", "-version");
final List<String> doubleWordArgs = List.of(
"--add-opens", "--upgrade-module-path", "--add-modules", "--add-exports",
"--limit-modules", "--add-reads", "--patch-module", "--module-path", "-p");
ArrayList<String> args = new ArrayList<>();
boolean expectSecondArg = false;
boolean isWrapperClassAdded = false;
for (String cmd : command) {
if (isWrapperClassAdded) {
args.add(cmd);
continue;
}
if (expectSecondArg) {
expectSecondArg = false;
args.add(cmd);
continue;
}
if (unsupportedArgs.contains(cmd)) {
return command;
}
if (doubleWordArgs.contains(cmd)) {
expectSecondArg = true;
args.add(cmd);
continue;
}
if (expectSecondArg) {
continue;
}
// command-line or name command-line file
if (cmd.startsWith("-") || cmd.startsWith("@")) {
args.add(cmd);
continue;
}
// if command is like 'java source.java' then return
if (cmd.endsWith(".java")) {
return command;
}
// Some tests might check property to understand
// if virtual threads are tested
args.add("-Dmain.wrapper=" + mainWrapper);
args.add("jdk.test.lib.process.ProcessTools");
args.add(mainWrapper);
isWrapperClassAdded = true;
args.add(cmd);
}
return args;
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested.
*
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createJavaProcessBuilder(String... command) {
String javapath = JDKToolFinder.getJDKTool("java");
ArrayList<String> args = new ArrayList<>();
args.add(javapath);
String noCPString = System.getProperty("test.noclasspath", "false");
boolean noCP = Boolean.valueOf(noCPString);
if (!noCP) {
args.add("-cp");
args.add(System.getProperty("java.class.path"));
}
String mainWrapper = System.getProperty("main.wrapper");
if (mainWrapper != null) {
args.addAll(addMainWrapperArgs(mainWrapper, Arrays.asList(command)));
} else {
Collections.addAll(args, command);
}
// Reporting
StringBuilder cmdLine = new StringBuilder();
for (String cmd : args)
cmdLine.append(cmd).append(' ');
System.out.println("Command line: [" + cmdLine.toString() + "]");
ProcessBuilder pb = new ProcessBuilder(args);
if (noCP) {
// clear CLASSPATH from the env
pb.environment().remove("CLASSPATH");
}
return pb;
}
private static void printStack(Thread t, StackTraceElement[] stack) {
System.out.println("\t" + t + " stack: (length = " + stack.length + ")");
if (t != null) {
for (StackTraceElement stack1 : stack) {
System.out.println("\t" + stack1);
}
System.out.println();
}
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested.
* The default jvm options from jtreg, test.vm.opts and test.java.opts, are added.
* <p>
* The command line will be like:
* {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds
* Create ProcessBuilder using the java launcher from the jdk to be tested.
*
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createTestJvm(List<String> command) {
return createTestJvm(command.toArray(String[]::new));
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested.
* The default jvm options from jtreg, test.vm.opts and test.java.opts, are added.
* <p>
* The command line will be like:
* {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds
* Create ProcessBuilder using the java launcher from the jdk to be tested.
*
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createTestJvm(String... command) {
return createJavaProcessBuilder(Utils.prependTestJavaOpts(command));
}
/**
* Executes a test jvm process, waits for it to finish and returns the process output.
* The default jvm options from jtreg, test.vm.opts and test.java.opts, are added.
* The java from the test.jdk is used to execute the command.
* <p>
* The command line will be like:
* {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds
* <p>
* The jvm process will have exited before this method returns.
*
* @param cmds User specified arguments.
* @return The output from the process.
*/
public static OutputAnalyzer executeTestJvm(List<String> cmds) throws Exception {
return executeTestJvm(cmds.toArray(String[]::new));
}
/**
* Executes a test jvm process, waits for it to finish and returns the process output.
* The default jvm options from jtreg, test.vm.opts and test.java.opts, are added.
* The java from the test.jdk is used to execute the command.
* <p>
* The command line will be like:
* {test.jdk}/bin/java {test.vm.opts} {test.java.opts} cmds
* <p>
* The jvm process will have exited before this method returns.
*
* @param cmds User specified arguments.
* @return The output from the process.
*/
public static OutputAnalyzer executeTestJvm(String... cmds) throws Exception {
ProcessBuilder pb = createTestJvm(cmds);
return executeProcess(pb);
}
/**
* @param cmds User specified arguments.
* @return The output from the process.
* @see #executeTestJvm(String...)
*/
public static OutputAnalyzer executeTestJava(String... cmds) throws Exception {
return executeTestJvm(cmds);
}
/**
* Executes a process, waits for it to finish and returns the process output.
* The process will have exited before this method returns.
*
* @param pb The ProcessBuilder to execute.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Exception {
return executeProcess(pb, null);
}
/**
* Executes a process, pipe some text into its STDIN, waits for it
* to finish and returns the process output. The process will have exited
* before this method returns.
*
* @param pb The ProcessBuilder to execute.
* @param input The text to pipe into STDIN. Can be null.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeProcess(ProcessBuilder pb, String input) throws Exception {
return executeProcess(pb, input, null);
}
/**
* Executes a process, pipe some text into its STDIN, waits for it
* to finish and returns the process output. The process will have exited
* before this method returns.
*
* @param pb The ProcessBuilder to execute.
* @param input The text to pipe into STDIN. Can be null.
* @param cs The charset used to convert from bytes to chars or null for
* the default charset.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
@SuppressWarnings("removal")
public static OutputAnalyzer executeProcess(ProcessBuilder pb, String input,
Charset cs) throws Exception {
OutputAnalyzer output = null;
Process p = null;
boolean failed = false;
try {
p = privilegedStart(pb);
if (input != null) {
try (PrintStream ps = new PrintStream(p.getOutputStream())) {
ps.print(input);
}
}
output = new OutputAnalyzer(p, cs);
p.waitFor();
{ // Dumping the process output to a separate file
var fileName = String.format("pid-%d-output.log", p.pid());
var processOutput = getProcessLog(pb, output);
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
Files.writeString(Path.of(fileName), processOutput);
return null;
});
System.out.printf(
"Output and diagnostic info for process %d " +
"was saved into '%s'%n", p.pid(), fileName);
}
return output;
} catch (Throwable t) {
if (p != null) {
p.destroyForcibly().waitFor();
}
failed = true;
System.out.println("executeProcess() failed: " + t);
throw t;
} finally {
if (failed) {
System.err.println(getProcessLog(pb, output));
}
}
}
/**
* Executes a process, waits for it to finish and returns the process output.
* <p>
* The process will have exited before this method returns.
*
* @param cmds The command line to execute.
* @return The output from the process.
*/
public static OutputAnalyzer executeProcess(String... cmds) throws Throwable {
return executeProcess(new ProcessBuilder(cmds));
}
/**
* Used to log command line, stdout, stderr and exit code from an executed process.
*
* @param pb The executed process.
* @param output The output from the process.
*/
public static String getProcessLog(ProcessBuilder pb, OutputAnalyzer output) {
String stderr = output == null ? "null" : output.getStderr();
String stdout = output == null ? "null" : output.getStdout();
String exitValue = output == null ? "null" : Integer.toString(output.getExitValue());
return String.format("--- ProcessLog ---%n" +
"cmd: %s%n" +
"exitvalue: %s%n" +
"stderr: %s%n" +
"stdout: %s%n",
getCommandLine(pb), exitValue, stderr, stdout);
}
/**
* @return The full command line for the ProcessBuilder.
*/
public static String getCommandLine(ProcessBuilder pb) {
if (pb == null) {
return "null";
}
StringBuilder cmd = new StringBuilder();
for (String s : pb.command()) {
cmd.append(s).append(" ");
}
return cmd.toString().trim();
}
/**
* Executes a process, waits for it to finish, prints the process output
* to stdout, and returns the process output.
* <p>
* The process will have exited before this method returns.
*
* @param cmds The command line to execute.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeCommand(String... cmds)
throws Throwable {
String cmdLine = String.join(" ", cmds);
System.out.println("Command line: [" + cmdLine + "]");
OutputAnalyzer analyzer = ProcessTools.executeProcess(cmds);
System.out.println(analyzer.getOutput());
return analyzer;
}
/**
* Executes a process, waits for it to finish, prints the process output
* to stdout and returns the process output.
* <p>
* The process will have exited before this method returns.
*
* @param pb The ProcessBuilder to execute.
* @return The {@linkplain OutputAnalyzer} instance wrapping the process.
*/
public static OutputAnalyzer executeCommand(ProcessBuilder pb)
throws Throwable {
String cmdLine = pb.command().stream()
.map(x -> (x.contains(" ") || x.contains("$"))
? ("'" + x + "'") : x)
.collect(Collectors.joining(" "));
System.out.println("Command line: [" + cmdLine + "]");
OutputAnalyzer analyzer = ProcessTools.executeProcess(pb);
System.out.println(analyzer.getOutput());
return analyzer;
}
/**
* Helper method to create a process builder for launching native executable
* test that uses/loads JVM.
*
* @param executableName The name of an executable to be launched.
* @param args Arguments for the executable.
* @return New ProcessBuilder instance representing the command.
*/
public static ProcessBuilder createNativeTestProcessBuilder(String executableName,
String... args) throws Exception {
executableName = Platform.isWindows() ? executableName + ".exe" : executableName;
String executable = Paths.get(Utils.TEST_NATIVE_PATH, executableName)
.toAbsolutePath()
.toString();
ProcessBuilder pb = new ProcessBuilder(executable);
pb.command().addAll(Arrays.asList(args));
return addJvmLib(pb);
}
/**
* Adds JVM library path to the native library path.
*
* @param pb ProcessBuilder to be updated with JVM library path.
* @return pb Update ProcessBuilder instance.
*/
public static ProcessBuilder addJvmLib(ProcessBuilder pb) throws Exception {
String jvmLibDir = Platform.jvmLibDir().toString();
String libPathVar = Platform.sharedLibraryPathVariableName();
String currentLibPath = pb.environment().get(libPathVar);
String newLibPath = jvmLibDir;
if (Platform.isWindows()) {
String libDir = Platform.libDir().toString();
newLibPath = newLibPath + File.pathSeparator + libDir;
}
if ((currentLibPath != null) && !currentLibPath.isEmpty()) {
newLibPath = newLibPath + File.pathSeparator + currentLibPath;
}
pb.environment().put(libPathVar, newLibPath);
return pb;
}
@SuppressWarnings("removal")
private static Process privilegedStart(ProcessBuilder pb) throws IOException {
try {
return AccessController.doPrivileged(
(PrivilegedExceptionAction<Process>) pb::start);
} catch (PrivilegedActionException e) {
throw (IOException) e.getException();
}
}
private static class ProcessImpl extends Process {
private final InputStream stdOut;
private final InputStream stdErr;
private final Process p;
private final Future<Void> stdoutTask;
private final Future<Void> stderrTask;
public ProcessImpl(Process p, Future<Void> stdoutTask, Future<Void> stderrTask,
InputStream stdOut, InputStream etdErr) {
this.p = p;
this.stdoutTask = stdoutTask;
this.stderrTask = stderrTask;
this.stdOut = stdOut;
this.stdErr = etdErr;
}
@Override
public OutputStream getOutputStream() {
return p.getOutputStream();
}
@Override
public InputStream getInputStream() {
return stdOut;
}
@Override
public InputStream getErrorStream() {
return stdErr;
}
@Override
public int waitFor() throws InterruptedException {
int rslt = p.waitFor();
waitForStreams();
return rslt;
}
@Override
public int exitValue() {
return p.exitValue();
}
@Override
public void destroy() {
p.destroy();
}
@Override
public long pid() {
return p.pid();
}
@Override
public boolean isAlive() {
return p.isAlive();
}
@Override
public Process destroyForcibly() {
return p.destroyForcibly();
}
@Override
public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException {
boolean rslt = p.waitFor(timeout, unit);
if (rslt) {
waitForStreams();
}
return rslt;
}
private void waitForStreams() throws InterruptedException {
try {
stdoutTask.get();
} catch (ExecutionException e) {
}
try {
stderrTask.get();
} catch (ExecutionException e) {
}
}
}
public static final String OLD_MAIN_THREAD_NAME = "old-m-a-i-n";
// ProcessTools as a wrapper
// It executes method main in a separate virtual or platform thread
public static void main(String[] args) throws Throwable {
String wrapper = args[0];
String className = args[1];
String[] classArgs = new String[args.length - 2];
System.arraycopy(args, 2, classArgs, 0, args.length - 2);
Class c = Class.forName(className);
Method mainMethod = c.getMethod("main", new Class[] { String[].class });
mainMethod.setAccessible(true);
if (wrapper.equals("Virtual")) {
// MainThreadGroup used just as a container for exceptions
// when main is executed in virtual thread
MainThreadGroup tg = new MainThreadGroup();
Thread vthread = Thread.ofVirtual().unstarted(() -> {
try {
mainMethod.invoke(null, new Object[] { classArgs });
} catch (InvocationTargetException e) {
tg.uncaughtThrowable = e.getCause();
} catch (Throwable error) {
tg.uncaughtThrowable = error;
}
});
Thread.currentThread().setName(OLD_MAIN_THREAD_NAME);
vthread.setName("main");
vthread.start();
vthread.join();
if (tg.uncaughtThrowable != null) {
throw tg.uncaughtThrowable;
}
} else if (wrapper.equals("Kernel")) {
MainThreadGroup tg = new MainThreadGroup();
Thread t = new Thread(tg, () -> {
try {
mainMethod.invoke(null, new Object[] { classArgs });
} catch (InvocationTargetException e) {
tg.uncaughtThrowable = e.getCause();
} catch (Throwable error) {
tg.uncaughtThrowable = error;
}
});
t.start();
t.join();
if (tg.uncaughtThrowable != null) {
throw tg.uncaughtThrowable;
}
} else {
mainMethod.invoke(null, new Object[] { classArgs });
}
}
static class MainThreadGroup extends ThreadGroup {
MainThreadGroup() {
super("MainThreadGroup");
}
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace(System.err);
uncaughtThrowable = e;
}
Throwable uncaughtThrowable = null;
}
}