-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Proc.java
517 lines (467 loc) · 19.7 KB
/
Proc.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
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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* 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;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Launcher.ProcStarter;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
import hudson.util.ClassLoaderSanityThreadFactory;
import hudson.util.DaemonThreadFactory;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.NamingThreadFactory;
import hudson.util.ProcessTree;
import hudson.util.StreamCopyThread;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* External process wrapper.
*
* <p>
* Used for launching, monitoring, waiting for a process.
*
* @author Kohsuke Kawaguchi
*/
public abstract class Proc {
protected Proc() {}
/**
* Checks if the process is still alive.
*/
public abstract boolean isAlive() throws IOException, InterruptedException;
/**
* Terminates the process.
*
* @throws IOException
* if there's an error killing a process
* and a stack trace could help the trouble-shooting.
*/
public abstract void kill() throws IOException, InterruptedException;
/**
* Waits for the completion of the process.
*
* Unless the caller opts to pump the streams via {@link #getStdout()} etc.,
* this method also blocks until we finish reading everything that the process has produced
* to stdout/stderr.
*
* <p>
* If the thread is interrupted while waiting for the completion
* of the process, this method terminates the process and
* exits with a non-zero exit code.
*
* @throws IOException
* if there's an error launching/joining a process
* and a stack trace could help the trouble-shooting.
*/
public abstract int join() throws IOException, InterruptedException;
/**
* Returns an {@link InputStream} to read from {@code stdout} of the child process.
* <p>
* When this method returns null, {@link Proc} will internally pump the output from
* the child process to your {@link OutputStream} of choosing.
*
* @return
* {@code null} unless {@link ProcStarter#readStdout()} is used to indicate
* that the caller intends to pump the stream by itself.
* @since 1.399
*/
@CheckForNull
public abstract InputStream getStdout();
/**
* Returns an {@link InputStream} to read from {@code stderr} of the child process.
* <p>
* When this method returns null, {@link Proc} will internally pump the output from
* the child process to your {@link OutputStream} of choosing.
*
* @return
* {@code null} unless {@link ProcStarter#readStderr()} is used to indicate
* that the caller intends to pump the stream by itself.
* @since 1.399
*/
@CheckForNull
public abstract InputStream getStderr();
/**
* Returns an {@link OutputStream} to write to {@code stdin} of the child process.
* <p>
* When this method returns null, {@link Proc} will internally pump the {@link InputStream}
* of your choosing to the child process.
*
* @return
* {@code null} unless {@link ProcStarter#writeStdin()} is used to indicate
* that the caller intends to pump the stream by itself.
* @since 1.399
*/
@CheckForNull
public abstract OutputStream getStdin();
private static final ExecutorService executor = Executors.newCachedThreadPool(new ExceptionCatchingThreadFactory(new NamingThreadFactory(new ClassLoaderSanityThreadFactory(new DaemonThreadFactory()), "Proc.executor")));
/**
* Like {@link #join} but can be given a maximum time to wait.
* @param timeout number of time units
* @param unit unit of time
* @param listener place to send messages if there are problems, incl. timeout
* @return exit code from the process
* @throws IOException for the same reasons as {@link #join}
* @throws InterruptedException for the same reasons as {@link #join}
* @since 1.363
*/
public final int joinWithTimeout(final long timeout, final TimeUnit unit,
final TaskListener listener) throws IOException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
try {
executor.submit(new Runnable() {
@Override
public void run() {
try {
if (!latch.await(timeout, unit)) {
listener.error("Timeout after " + timeout + " " +
unit.toString().toLowerCase(Locale.ENGLISH));
kill();
}
} catch (InterruptedException | IOException | RuntimeException x) {
Functions.printStackTrace(x, listener.error("Failed to join a process"));
}
}
});
return join();
} finally {
latch.countDown();
}
}
/**
* Locally launched process.
*/
public static final class LocalProc extends Proc {
private final Process proc;
private final Thread copier, copier2;
private final OutputStream out;
private final EnvVars cookie;
private final String name;
private final InputStream stdout, stderr;
private final OutputStream stdin;
public LocalProc(String cmd, Map<String, String> env, OutputStream out, File workDir) throws IOException {
this(cmd, Util.mapToEnv(env), out, workDir);
}
public LocalProc(String[] cmd, Map<String, String> env, InputStream in, OutputStream out) throws IOException {
this(cmd, Util.mapToEnv(env), in, out);
}
public LocalProc(String cmd, String[] env, OutputStream out, File workDir) throws IOException {
this(Util.tokenize(cmd), env, out, workDir);
}
public LocalProc(String[] cmd, String[] env, OutputStream out, File workDir) throws IOException {
this(cmd, env, null, out, workDir);
}
public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out) throws IOException {
this(cmd, env, in, out, null);
}
public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out, File workDir) throws IOException {
this(cmd, env, in, out, null, workDir);
}
/**
* @param err
* null to redirect stderr to stdout.
*/
@SuppressFBWarnings(value = "COMMAND_INJECTION", justification = "Command injection is the point of this old, barely used class.")
public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out, OutputStream err, File workDir) throws IOException {
this(calcName(cmd),
stderr(environment(new ProcessBuilder(cmd), env).directory(workDir), err == null || err == SELFPUMP_OUTPUT),
in, out, err);
}
private static ProcessBuilder stderr(ProcessBuilder pb, boolean redirectError) {
if (redirectError) pb.redirectErrorStream(true);
return pb;
}
private static ProcessBuilder environment(ProcessBuilder pb, String[] env) {
if (env != null) {
Map<String, String> m = pb.environment();
m.clear();
for (String e : env) {
int idx = e.indexOf('=');
m.put(e.substring(0, idx), e.substring(idx + 1));
}
}
return pb;
}
private LocalProc(String name, ProcessBuilder procBuilder, InputStream in, OutputStream out, OutputStream err) throws IOException {
Logger.getLogger(Proc.class.getName()).log(Level.FINE, "Running: {0}", name);
this.name = name;
this.out = out;
this.cookie = EnvVars.createCookie();
procBuilder.environment().putAll(cookie);
if (procBuilder.directory() != null && !procBuilder.directory().exists()) {
throw new IOException(String.format("Process working directory '%s' doesn't exist!", procBuilder.directory().getAbsolutePath()));
}
this.proc = procBuilder.start();
InputStream procInputStream = proc.getInputStream();
if (out == SELFPUMP_OUTPUT) {
stdout = procInputStream;
copier = null;
} else {
copier = new StreamCopyThread(name + ": stdout copier", procInputStream, out);
copier.start();
stdout = null;
}
if (in == null) {
// nothing to feed to stdin
stdin = null;
proc.getOutputStream().close();
} else
if (in == SELFPUMP_INPUT) {
stdin = proc.getOutputStream();
} else {
new StdinCopyThread(name + ": stdin copier", in, proc.getOutputStream()).start();
stdin = null;
}
InputStream procErrorStream = proc.getErrorStream();
if (err != null) {
if (err == SELFPUMP_OUTPUT) {
stderr = procErrorStream;
copier2 = null;
} else {
stderr = null;
copier2 = new StreamCopyThread(name + ": stderr copier", procErrorStream, err);
copier2.start();
}
} else {
// the javadoc is unclear about what getErrorStream() returns when ProcessBuilder.redirectErrorStream(true),
//
// according to the source code, Sun JREs still still returns a distinct reader end of a pipe that needs to be closed.
// but apparently at least on some IBM JDK5, returned input and error streams are the same.
// so try to close them smartly
if (procErrorStream != procInputStream) {
procErrorStream.close();
}
copier2 = null;
stderr = null;
}
}
@Override
public InputStream getStdout() {
return stdout;
}
@Override
public InputStream getStderr() {
return stderr;
}
@Override
public OutputStream getStdin() {
return stdin;
}
/**
* Waits for the completion of the process.
*/
@Override
public int join() throws InterruptedException, IOException {
// show what we are waiting for in the thread title
Thread t = Thread.currentThread();
String oldName = t.getName();
if (SHOW_PID) {
t.setName(oldName + " waiting for pid=" + proc.pid());
}
try {
int r = proc.waitFor();
// see https://www.jenkins.io/redirect/troubleshooting/process-leaked-file-descriptors
// problems like that shows up as infinite wait in join(), which confuses great many users.
// So let's do a timed wait here and try to diagnose the problem
if (copier != null) copier.join(TimeUnit.SECONDS.toMillis(10));
if (copier2 != null) copier2.join(TimeUnit.SECONDS.toMillis(10));
if ((copier != null && copier.isAlive()) || (copier2 != null && copier2.isAlive())) {
// looks like handles are leaking.
// closing these handles should terminate the threads.
String msg = "Process leaked file descriptors. See https://www.jenkins.io/redirect/troubleshooting/process-leaked-file-descriptors for more information";
Throwable e = new Exception().fillInStackTrace();
LOGGER.log(Level.WARNING, msg, e);
// doing proc.getInputStream().close() hangs in FileInputStream.close0()
// it could be either because another thread is blocking on read, or
// it could be a bug in Windows JVM. Who knows.
// so I'm abandoning the idea of closing the stream
// try {
// proc.getInputStream().close();
// } catch (IOException x) {
// LOGGER.log(Level.FINE,"stdin termination failed",x);
// }
// try {
// proc.getErrorStream().close();
// } catch (IOException x) {
// LOGGER.log(Level.FINE,"stderr termination failed",x);
// }
out.write(msg.getBytes(Charset.defaultCharset()));
out.write('\n');
}
return r;
} catch (InterruptedException e) {
// aborting. kill the process
destroy();
throw e;
} finally {
t.setName(oldName);
}
}
@Override
public boolean isAlive() throws IOException, InterruptedException {
try {
proc.exitValue();
return false;
} catch (IllegalThreadStateException e) {
return true;
}
}
@Override
public void kill() throws InterruptedException, IOException {
destroy();
join();
}
/**
* Destroys the child process without join.
*/
private void destroy() throws InterruptedException {
ProcessTree.get().killAll(proc, cookie);
}
/**
* {@link Process#getOutputStream()} is buffered, so we need to eagerly flash
* the stream to push bytes to the process.
*/
private static class StdinCopyThread extends Thread {
private final InputStream in;
private final OutputStream out;
StdinCopyThread(String threadName, InputStream in, OutputStream out) {
super(threadName);
this.in = in;
this.out = out;
}
@Override
public void run() {
try {
try {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
out.flush();
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
// TODO: what to do?
}
}
}
private static String calcName(String[] cmd) {
return String.join(" ", cmd);
}
public static final InputStream SELFPUMP_INPUT = InputStream.nullInputStream();
public static final OutputStream SELFPUMP_OUTPUT = OutputStream.nullOutputStream();
}
/**
* Remotely launched process via {@link Channel}.
*
* @deprecated as of 1.399. Replaced by {@link Launcher.RemoteLauncher.ProcImpl}
*/
@Deprecated
public static final class RemoteProc extends Proc implements ProcWithJenkins23271Patch {
private final Future<Integer> process;
public RemoteProc(Future<Integer> process) {
this.process = process;
}
@Override
public void kill() throws IOException, InterruptedException {
try {
process.cancel(true);
} finally {
if (this.isAlive()) { // Should never happen but this forces Proc to not be removed and early GC by escape analysis
// TODO: Report exceptions if they happen?
LOGGER.log(Level.WARNING, "Process {0} has not really finished after the kill() method execution", this);
}
}
}
@Override
public int join() throws IOException, InterruptedException {
try {
return process.get();
} catch (InterruptedException e) {
LOGGER.log(Level.FINE, String.format("Join operation has been interrupted for the process %s. Killing the process", this), e);
kill();
throw e;
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException)
throw (IOException) e.getCause();
throw new IOException("Failed to join the process", e);
} catch (CancellationException x) {
return -1;
} finally {
if (this.isAlive()) { // Should never happen but this forces Proc to not be removed and early GC by escape analysis
LOGGER.log(Level.WARNING, "Process {0} has not really finished after the join() method completion", this);
}
}
}
@Override
public boolean isAlive() throws IOException, InterruptedException {
return !process.isDone();
}
@Override
public InputStream getStdout() {
return null;
}
@Override
public InputStream getStderr() {
return null;
}
@Override
public OutputStream getStdin() {
return null;
}
}
private static final Logger LOGGER = Logger.getLogger(Proc.class.getName());
/**
* Debug switch to have the thread display the process it's waiting for.
*/
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for debugging")
public static boolean SHOW_PID = true;
/**
* An instance of {@link Proc}, which has an internal workaround for JENKINS-23271.
* It presumes that the instance of the object is guaranteed to be used after the {@link Proc#join()} call.
* See <a href="https://issues.jenkins.io/browse/JENKINS-23271">JENKINS-23271</a>
* @author Oleg Nenashev
*/
@Restricted(NoExternalUse.class)
public interface ProcWithJenkins23271Patch {
// Empty marker interface
}
}