forked from jenkinsci/jenkins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessTree.java
More file actions
2142 lines (1874 loc) · 85.2 KB
/
ProcessTree.java
File metadata and controls
2142 lines (1874 loc) · 85.2 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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import static com.sun.jna.Pointer.NULL;
import static hudson.util.jna.GNUCLibrary.LIBC;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.FINEST;
import com.sun.jna.LastErrorException;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Util;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.ProcessKillingVeto.VetoCause;
import hudson.util.ProcessTree.OSProcess;
import hudson.util.ProcessTreeRemoting.IOSProcess;
import hudson.util.ProcessTreeRemoting.IProcessTree;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.agents.AgentComputerUtil;
import jenkins.security.SlaveToMasterCallable;
import jenkins.util.SystemProperties;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.jvnet.winp.WinProcess;
import org.jvnet.winp.WinpException;
/**
* Represents a snapshot of the process tree of the current system.
*
* <p>
* A {@link ProcessTree} is really conceptually a map from process ID to a {@link OSProcess} object.
* When Hudson runs on platforms that support process introspection, this allows you to introspect
* and do some useful things on processes. On other platforms, the implementation falls back to
* "do nothing" behavior.
*
* <p>
* {@link ProcessTree} is remotable.
*
* @author Kohsuke Kawaguchi
* @since 1.315
*/
public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, SerializableOnlyOverRemoting {
/**
* To be filled in the constructor of the derived type.
*/
protected final Map<Integer/*pid*/, OSProcess> processes = new HashMap<>();
/**
* Lazily obtained {@link ProcessKiller}s to be applied on this process tree.
*/
private transient volatile List<ProcessKiller> killers;
/**
* Flag to skip the veto check since there aren't any.
*/
private boolean skipVetoes;
// instantiation only allowed for subtypes in this class
private ProcessTree() {
skipVetoes = false;
}
private ProcessTree(boolean vetoesExist) {
skipVetoes = !vetoesExist;
}
/**
* Gets the process given a specific ID, or null if no such process exists.
*/
@CheckForNull
public final OSProcess get(int pid) {
return processes.get(pid);
}
/**
* Lists all the processes in the system.
*/
@Override
@NonNull
public final Iterator<OSProcess> iterator() {
return processes.values().iterator();
}
/**
* Try to convert {@link Process} into this process object
* or null if it fails (for example, maybe the snapshot is taken after
* this process has already finished.)
*/
@CheckForNull
public abstract OSProcess get(@NonNull Process proc);
/**
* Kills all the processes that have matching environment variables.
*
* <p>
* In this method, the method is given a
* "model environment variables", which is a list of environment variables
* and their values that are characteristic to the launched process.
* The implementation is expected to find processes
* in the system that inherit these environment variables, and kill
* them all. This is suitable for locating daemon processes
* that cannot be tracked by the regular ancestor/descendant relationship.
*/
@Override
public abstract void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException;
/**
* The time to wait between sending Ctrl+C and killing the process. (JENKINS-17116)
*
* The default is 5 seconds. Careful! There are other timers in the system that may
* interfere with this value here, e.g. in org.jenkinsci.plugins.workflow.cps.CpsThread.stop
*/
private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 5);
/**
* Convenience method that does {@link #killAll(Map)} and {@link OSProcess#killRecursively()}.
* This is necessary to reliably kill the process and its descendants, as some OS
* may not implement {@link #killAll(Map)}.
*
* Either of the parameter can be null.
*/
public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException {
LOGGER.fine("killAll: process=" + proc + " and envs=" + modelEnvVars);
if (proc != null) {
OSProcess p = get(proc);
if (p != null) p.killRecursively();
}
if (modelEnvVars != null)
killAll(modelEnvVars);
}
/**
* Obtains the list of killers.
*/
@NonNull
/*package*/ final List<ProcessKiller> getKillers() throws InterruptedException {
if (killers == null)
try {
VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
if (channelToController != null) {
killers = channelToController.call(new ListAll());
} else {
// used in an environment that doesn't support talk-back to the master.
// let's do with what we have.
killers = Collections.emptyList();
}
} catch (IOException | Error e) {
LOGGER.log(Level.WARNING, "Failed to obtain killers", e);
killers = Collections.emptyList();
}
return killers;
}
private static class ListAll extends SlaveToMasterCallable<List<ProcessKiller>, IOException> {
@Override
public List<ProcessKiller> call() throws IOException {
return new ArrayList<>(ProcessKiller.all());
}
}
/**
* Represents a process.
*/
public abstract class OSProcess implements IOSProcess, Serializable {
final int pid;
// instantiation only allowed for subtypes in this class
private OSProcess(int pid) {
this.pid = pid;
}
@Override
public final int getPid() {
return pid;
}
/**
* Gets the parent process. This method may return null, because
* there's no guarantee that we are getting a consistent snapshot
* of the whole system state.
*/
@Override
@CheckForNull
public abstract OSProcess getParent();
/*package*/ final ProcessTree getTree() {
return ProcessTree.this;
}
/**
* Immediate child processes.
*/
@NonNull
public final List<OSProcess> getChildren() {
List<OSProcess> r = new ArrayList<>();
for (OSProcess p : ProcessTree.this)
if (p.getParent() == this)
r.add(p);
return r;
}
/**
* Kills this process.
*/
@Override
public abstract void kill() throws InterruptedException;
void killByKiller() throws InterruptedException {
for (ProcessKiller killer : getKillers())
try {
if (killer.kill(this)) {
break;
}
} catch (IOException | Error e) {
LOGGER.log(Level.WARNING, "Failed to kill pid=" + getPid(), e);
}
}
/**
* Kills this process and all the descendants.
* <p>
* Note that the notion of "descendants" is somewhat vague,
* in the presence of such things like daemons. On platforms
* where the recursive operation is not supported, this just kills
* the current process.
*/
@Override
public abstract void killRecursively() throws InterruptedException;
/**
* @return The first non-null {@link VetoCause} provided by a process killing veto extension for this OSProcess.
* null if no one objects killing the process.
*/
protected @CheckForNull VetoCause getVeto() {
String causeMessage = null;
// Quick check, does anything exist to check against
if (!skipVetoes) {
try {
VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
if (channelToController != null) {
CheckVetoes vetoCheck = new CheckVetoes(this);
causeMessage = channelToController.call(vetoCheck);
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "I/O Exception while checking for vetoes", e);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Interrupted Exception while checking for vetoes", e);
}
}
if (causeMessage != null) {
return new VetoCause(causeMessage);
}
return null;
}
/**
* Gets the command-line arguments of this process.
*
* <p>
* On Windows, where the OS models command-line arguments as a single string, this method
* computes the approximated tokenization.
*/
@Override
@NonNull
public abstract List<String> getArguments();
/**
* Obtains the environment variables of this process.
*
* @return
* empty map if failed (for example because the process is already dead,
* or the permission was denied.)
*/
@Override
@NonNull
public abstract EnvVars getEnvironmentVariables();
/**
* Given the environment variable of a process and the "model environment variable" that Hudson
* used for launching the build, returns true if there's a match (which means the process should
* be considered a descendant of a build.)
*/
public final boolean hasMatchingEnvVars(Map<String, String> modelEnvVar) {
if (modelEnvVar.isEmpty())
// sanity check so that we don't start rampage.
return false;
SortedMap<String, String> envs = getEnvironmentVariables();
for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
String v = envs.get(e.getKey());
if (v == null || !v.equals(e.getValue()))
return false; // no match
}
return true;
}
/**
* Executes a chunk of code at the same machine where this process resides.
*/
@Override
public <T> T act(ProcessCallable<T> callable) throws IOException, InterruptedException {
return callable.invoke(this, FilePath.localChannel);
}
Object writeReplace() {
return new SerializedProcess(pid);
}
private class CheckVetoes extends SlaveToMasterCallable<String, IOException> {
private IOSProcess process;
CheckVetoes(IOSProcess processToCheck) {
process = processToCheck;
}
@Override
public String call() throws IOException {
for (ProcessKillingVeto vetoExtension : ProcessKillingVeto.all()) {
VetoCause cause = vetoExtension.vetoProcessKilling(process);
if (cause != null) {
if (LOGGER.isLoggable(FINEST))
LOGGER.info("Killing of pid " + getPid() + " vetoed by " + vetoExtension.getClass().getName() + ": " + cause.getMessage());
return cause.getMessage();
}
}
return null;
}
}
}
/**
* Serialized form of {@link OSProcess} is the PID and {@link ProcessTree}
*/
@SuppressFBWarnings(value = "SE_INNER_CLASS", justification = "Serializing the outer instance is intended")
private final class SerializedProcess implements Serializable {
private final int pid;
private static final long serialVersionUID = 1L;
private SerializedProcess(int pid) {
this.pid = pid;
}
Object readResolve() {
return get(pid);
}
}
/**
* Code that gets executed on the machine where the {@link OSProcess} is local.
* Used to act on {@link OSProcess}.
*
* @see ProcessTree.OSProcess#act(ProcessTree.ProcessCallable)
*/
public interface ProcessCallable<T> extends Serializable {
/**
* Performs the computational task on the node where the data is located.
*
* @param process
* {@link OSProcess} that represents the local process.
* @param channel
* The "back pointer" of the {@link Channel} that represents the communication
* with the node from where the code was sent.
*/
T invoke(OSProcess process, VirtualChannel channel) throws IOException;
}
/* package */ static volatile Boolean vetoersExist;
/**
* Gets the {@link ProcessTree} of the current system
* that JVM runs in, or in the worst case return the default one
* that's not capable of killing descendants at all.
*/
public static ProcessTree get() {
if (!enabled)
return DEFAULT;
// Check for the existence of vetoers if I don't know already
if (vetoersExist == null) {
try {
VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
if (channelToController != null) {
vetoersExist = channelToController.call(new DoVetoersExist());
}
}
catch (InterruptedException ie) {
// If we receive an InterruptedException here, we probably can't do much anyway.
// Perhaps we should just return at this point since we probably can't do anything else.
// It might make sense to introduce retries, but it's probably not going to get better.
LOGGER.log(Level.FINE, "Caught InterruptedException while checking if vetoers exist: ", ie);
Thread.interrupted(); // Clear the interrupt flag and just accept that no known vetoers exist.
}
catch (Exception e) {
LOGGER.log(Level.FINE, "Error while determining if vetoers exist", e);
}
}
// Null-check in case the previous call worked
boolean vetoes = vetoersExist == null || vetoersExist;
try {
if (File.pathSeparatorChar == ';')
return new Windows(vetoes);
String os = Util.fixNull(System.getProperty("os.name"));
if (os.equals("Linux"))
return new Linux(vetoes);
if (os.equals("AIX"))
return new AIX(vetoes);
if (os.equals("SunOS"))
return new Solaris(vetoes);
if (os.equals("Mac OS X"))
return new Darwin(vetoes);
if (os.equals("FreeBSD"))
return new FreeBSD(vetoes);
} catch (LinkageError e) {
LOGGER.log(Level.FINE, "Failed to load OS-specific implementation; reverting to the default", e);
enabled = false;
}
return DEFAULT;
}
private static class DoVetoersExist extends SlaveToMasterCallable<Boolean, IOException> {
@Override
public Boolean call() throws IOException {
return !ProcessKillingVeto.all().isEmpty();
}
}
//
//
// implementation follows
//-------------------------------------------
//
/**
* Empty process list as a default value if the platform doesn't support it.
*/
/*package*/ static final ProcessTree DEFAULT = new Local() {
@Override
public OSProcess get(@NonNull final Process proc) {
return new OSProcess(-1) {
@Override
@CheckForNull
public OSProcess getParent() {
return null;
}
@Override
public void killRecursively() {
// fall back to a single process killer
proc.destroy();
}
@Override
public void kill() throws InterruptedException {
if (getVeto() != null)
return;
proc.destroy();
killByKiller();
}
@Override
@NonNull
public List<String> getArguments() {
return Collections.emptyList();
}
@Override
@NonNull
public EnvVars getEnvironmentVariables() {
return new EnvVars();
}
};
}
@Override
public void killAll(@NonNull Map<String, String> modelEnvVars) {
// no-op
}
};
private class WindowsOSProcess extends OSProcess {
private final WinProcess p;
private EnvVars env;
private List<String> args;
WindowsOSProcess(WinProcess p) {
super(p.getPid());
this.p = p;
}
@CheckForNull
@Override
public OSProcess getParent() {
// Windows process doesn't have parent/child relationship
return null;
}
@Override
public void killRecursively() throws InterruptedException {
if (getVeto() != null)
return;
LOGGER.log(FINER, "Killing recursively {0}", getPid());
// Firstly try to kill the root process gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
killSoftly();
p.killRecursively();
killByKiller();
}
@Override
public void kill() throws InterruptedException {
if (getVeto() != null) {
return;
}
LOGGER.log(FINER, "Killing {0}", getPid());
// Firstly try to kill it gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
killSoftly();
p.kill();
killByKiller();
}
private void killSoftly() throws InterruptedException {
// send Ctrl+C to the process
try {
if (!p.sendCtrlC()) {
return;
}
}
catch (WinpException e) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Failed to send CTRL+C to pid=" + getPid(), e);
}
return;
}
// after that wait for it to cease to exist
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
do {
if (!p.isRunning()) {
break;
}
Thread.sleep(sleepTime);
sleepTime = Math.min(sleepTime * 2, 1000);
} while (System.nanoTime() < deadline);
}
@NonNull
@Override
public synchronized List<String> getArguments() {
if (args == null) {
args = Arrays.asList(QuotedStringTokenizer.tokenize(p.getCommandLine()));
}
return args;
}
@NonNull
@Override
public synchronized EnvVars getEnvironmentVariables() {
try {
return getEnvironmentVariables2();
} catch (WindowsOSProcessException e) {
if (LOGGER.isLoggable(FINEST)) {
LOGGER.log(FINEST, "Failed to get the environment variables of process with pid=" + p.getPid(), e);
}
}
return env;
}
private synchronized EnvVars getEnvironmentVariables2() throws WindowsOSProcessException {
if (env != null) {
return env;
}
env = new EnvVars();
try {
env.putAll(p.getEnvironmentVariables());
} catch (WinpException e) {
throw new WindowsOSProcessException("Failed to get the environment variables", e);
}
return env;
}
private boolean hasMatchingEnvVars2(Map<String, String> modelEnvVar) throws WindowsOSProcessException {
if (modelEnvVar.isEmpty())
// sanity check so that we don't start rampage.
return false;
SortedMap<String, String> envs = getEnvironmentVariables2();
for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
String v = envs.get(e.getKey());
if (v == null || !v.equals(e.getValue()))
return false; // no match
}
return true;
}
}
//TODO: Cleanup once Winp provides proper API
/**
* Wrapper for runtime {@link WinpException}.
*/
private static class WindowsOSProcessException extends Exception {
WindowsOSProcessException(WinpException ex) {
super(ex);
}
WindowsOSProcessException(String message, WinpException ex) {
super(message, ex);
}
}
private static final class Windows extends Local {
Windows(boolean vetoesExist) {
super(vetoesExist);
for (final WinProcess p : WinProcess.all()) {
int pid = p.getPid();
if (pid == 0 || pid == 4) continue; // skip the System Idle and System processes
super.processes.put(pid, new WindowsOSProcess(p));
}
}
@CheckForNull
@Override
public OSProcess get(@NonNull Process proc) {
return get(new WinProcess(proc).getPid());
}
@Override
public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
for (OSProcess p : this) {
if (p.getPid() < 10)
continue; // ignore system processes like "idle process"
LOGGER.log(FINEST, "Considering to kill {0}", p.getPid());
boolean matched;
try {
matched = hasMatchingEnvVars(p, modelEnvVars);
} catch (WindowsOSProcessException e) {
// likely a missing privilege
// TODO: not a minor issue - causes process termination error in JENKINS-30782
if (LOGGER.isLoggable(FINEST)) {
LOGGER.log(FINEST, "Failed to check environment variable match for process with pid=" + p.getPid(), e);
}
continue;
}
if (matched) {
p.killRecursively();
} else {
LOGGER.log(Level.FINEST, "Environment variable didn't match for process with pid={0}", p.getPid());
}
}
}
static {
WinProcess.enableDebugPrivilege();
}
private static boolean hasMatchingEnvVars(@NonNull OSProcess p, @NonNull Map<String, String> modelEnvVars)
throws WindowsOSProcessException {
if (p instanceof WindowsOSProcess) {
return ((WindowsOSProcess) p).hasMatchingEnvVars2(modelEnvVars);
} else {
// Should never happen, but there is a risk of getting such class during deserialization
try {
return p.hasMatchingEnvVars(modelEnvVars);
} catch (WinpException e) {
// likely a missing privilege
throw new WindowsOSProcessException(e);
}
}
}
}
abstract static class Unix extends Local {
Unix(boolean vetoersExist) {
super(vetoersExist);
}
@CheckForNull
@Override
public OSProcess get(@NonNull Process proc) {
return get(Math.toIntExact(proc.pid()));
}
@Override
public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
for (OSProcess p : this)
if (p.hasMatchingEnvVars(modelEnvVars))
p.killRecursively();
}
}
/**
* {@link ProcessTree} based on /proc.
*/
abstract static class ProcfsUnix extends Unix {
ProcfsUnix(boolean vetoersExist) {
super(vetoersExist);
File[] processes = new File("/proc").listFiles(File::isDirectory);
if (processes == null) {
LOGGER.info("No /proc");
return;
}
for (File p : processes) {
int pid;
try {
pid = Integer.parseInt(p.getName());
} catch (NumberFormatException e) {
// other sub-directories
continue;
}
try {
this.processes.put(pid, createProcess(pid));
} catch (IOException e) {
// perhaps the process status has changed since we obtained a directory listing
}
}
}
protected abstract OSProcess createProcess(int pid) throws IOException;
}
/**
* A process.
*/
public abstract class UnixProcess extends OSProcess {
protected UnixProcess(int pid) {
super(pid);
}
protected final File getFile(String relativePath) {
return new File(new File("/proc/" + getPid()), relativePath);
}
/**
* Tries to kill this process.
*/
@Override
public void kill() throws InterruptedException {
// after sending SIGTERM, wait for the process to cease to exist
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
kill(deadline);
}
private void kill(long deadline) throws InterruptedException {
if (getVeto() != null)
return;
int pid = getPid();
LOGGER.fine("Killing pid=" + pid);
ProcessHandle.of(pid).ifPresent(ProcessHandle::destroy);
// after sending SIGTERM, wait for the process to cease to exist
int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
File status = getFile("status");
do {
if (!status.exists()) {
break; // status is gone, process therefore as well
}
Thread.sleep(sleepTime);
sleepTime = Math.min(sleepTime * 2, 1000);
} while (System.nanoTime() < deadline);
killByKiller();
}
@Override
public void killRecursively() throws InterruptedException {
// after sending SIGTERM, wait for the processes to cease to exist until the deadline
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
killRecursively(deadline);
}
private void killRecursively(long deadline) throws InterruptedException {
// We kill individual processes of a tree, so handling vetoes inside #kill() is enough for UnixProcess es
LOGGER.fine("Recursively killing pid=" + getPid());
for (OSProcess p : getChildren()) {
if (p instanceof UnixProcess) {
((UnixProcess) p).killRecursively(deadline);
} else {
p.killRecursively(); // should not happen, fallback to non-deadline version
}
}
kill(deadline);
}
/**
* Obtains the argument list of this process.
*
* @return
* empty list if failed (for example because the process is already dead,
* or the permission was denied.)
*/
@Override
@NonNull
public abstract List<String> getArguments();
}
static class Linux extends ProcfsUnix {
Linux(boolean vetoersExist) {
super(vetoersExist);
}
@Override
protected LinuxProcess createProcess(int pid) throws IOException {
return new LinuxProcess(pid);
}
class LinuxProcess extends UnixProcess {
private int ppid = -1;
private EnvVars envVars;
private List<String> arguments;
LinuxProcess(int pid) throws IOException {
super(pid);
try (BufferedReader r = Files.newBufferedReader(Util.fileToPath(getFile("status")), StandardCharsets.UTF_8)) {
String line;
while ((line = r.readLine()) != null) {
line = line.toLowerCase(Locale.ENGLISH);
if (line.startsWith("ppid:")) {
ppid = Integer.parseInt(line.substring(5).trim());
break;
}
}
}
if (ppid == -1)
throw new IOException("Failed to parse PPID from /proc/" + pid + "/status");
}
@Override
@CheckForNull
public OSProcess getParent() {
return get(ppid);
}
@Override
@NonNull
public synchronized List<String> getArguments() {
if (arguments != null)
return arguments;
arguments = new ArrayList<>();
try {
byte[] cmdline = Files.readAllBytes(Util.fileToPath(getFile("cmdline")));
int pos = 0;
for (int i = 0; i < cmdline.length; i++) {
byte b = cmdline[i];
if (b == 0) {
arguments.add(new String(cmdline, pos, i - pos, StandardCharsets.UTF_8));
pos = i + 1;
}
}
} catch (IOException e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
arguments = Collections.unmodifiableList(arguments);
return arguments;
}
@Override
@NonNull
public synchronized EnvVars getEnvironmentVariables() {
if (envVars != null)
return envVars;
envVars = new EnvVars();
try {
byte[] environ = Files.readAllBytes(Util.fileToPath(getFile("environ")));
int pos = 0;
for (int i = 0; i < environ.length; i++) {
byte b = environ[i];
if (b == 0) {
envVars.addLine(new String(environ, pos, i - pos, StandardCharsets.UTF_8));
pos = i + 1;
}
}
} catch (IOException e) {
// failed to read. this can happen under normal circumstances (most notably permission denied)
// so don't report this as an error.
}
return envVars;
}
}
}
/**
* Implementation for AIX that uses {@code /proc}.
*
* /proc/PID/status contains a pstatus struct. We use it to determine if the process is 32 or 64 bit
*
* /proc/PID/psinfo contains a psinfo struct. We use it to determine where the
* process arguments and environment are located in PID's address space.
*
* /proc/PID/as contains the address space of the process we are inspecting. We can
* follow the pr_envp and pr_argv pointers from psinfo to find the vectors to the
* environment variables and process arguments, respectvely. When following pointers
* in this address space we need to make sure to use 32-bit or 64-bit pointers
* depending on what sized pointers PID uses, regardless of what size pointers
* the Java process uses.
*
* Note that the size of a 64-bit address space is larger than Long.MAX_VALUE (because
* longs are signed). So normal Java utilities like RandomAccessFile and FileChannel
* (which use signed longs as offsets) are not able to read from the end of the address
* space, where envp and argv will be. Therefore we need to use LIBC.pread() directly.
* when accessing this file.
*/
static class AIX extends ProcfsUnix {
AIX(boolean vetoersExist) {
super(vetoersExist);
}
@Override
protected OSProcess createProcess(final int pid) throws IOException {
return new AIXProcess(pid);
}
private class AIXProcess extends UnixProcess {
private static final byte PR_MODEL_ILP32 = 0;
private static final byte PR_MODEL_LP64 = 1;
/*
* An arbitrary upper-limit on how many characters readLine() will
* try reading before giving up. This avoids having readLine() loop
* over the entire process address space if this class has bugs.
*/
private final int LINE_LENGTH_LIMIT =
SystemProperties.getInteger(AIX.class.getName() + ".lineLimit", 10000);
/*
* True if target process is 64-bit (Java process may be different).