/
ProcessManager.java
273 lines (235 loc) · 8.48 KB
/
ProcessManager.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
/*
* Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation
* Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.universal.process;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Use this class for painless process spawning.
* <p>
* This class was originally written to be compatible with JDK 1.4, using Runtime.exec(),
* but has been refactored to use ProcessBuilder for better control and configurability.
*
* @since JDK 1.4
* @author bnevins 2005
*/
public class ProcessManager {
private static final Logger LOG = System.getLogger(ProcessManager.class.getName());
protected final ProcessBuilder builder;
private String stdout;
private String stderr;
private int timeout;
private boolean echo = true;
private String[] stdinLines;
public ProcessManager(String... cmds) {
builder = new ProcessBuilder(cmds);
}
public ProcessManager(List<String> cmdline) {
builder = new ProcessBuilder(cmdline);
}
public void setTimeoutMsec(int num) {
if (num > 0) {
timeout = num;
}
}
public void setEnvironment(String name, String value) {
Map<String, String> env = builder.environment();
env.put(name, value);
}
public void setWorkingDir(File directory) {
builder.directory(directory);
}
public void setStdinLines(List<String> list) {
if (list != null && !list.isEmpty()) {
stdinLines = new String[list.size()];
stdinLines = list.toArray(stdinLines);
}
}
/**
* Should the output of the process be echoed to stdout?
*
* @param newEcho
*/
public void setEcho(boolean newEcho) {
echo = newEcho;
}
public int execute() throws ProcessManagerException {
LOG.log(Level.DEBUG, "Executing command:\n command={0} \nenv={1}", builder.command(), builder.environment());
final Process process;
try {
process = builder.start();
} catch (IOException e) {
throw new IllegalStateException("Could not execute command: " + builder.command(), e);
}
ReaderThread threadErr = new ReaderThread(process.getErrorStream(), echo, "stderr");
threadErr.start();
ReaderThread threadOut = new ReaderThread(process.getInputStream(), echo, "stdout");
threadOut.start();
try {
writeStdin(process);
await(process);
try {
return process.exitValue();
} catch (IllegalThreadStateException tse) {
// this means that the process is still running...
throw new ProcessManagerTimeoutException("Process is still running.", tse);
}
} catch (ProcessManagerException pme) {
throw pme;
} catch (Exception e) {
throw new ProcessManagerException(e);
} finally {
destroy(process);
// Always wait for reader threads -- unless the boolean flag is false.
// note that this won't block when there was a timeout because the process
// has been forcibly destroyed above.
stderr = threadErr.finish();
stdout = threadOut.finish();
}
}
private void destroy(Process process) {
if (process == null) {
return;
}
process.destroy();
// Wait for a while to let the process stop
try {
boolean exited = process.waitFor(10, TimeUnit.SECONDS);
if (!exited) {
// If the process hasn't exited, force it to stop
process.destroyForcibly();
}
} catch (InterruptedException e) {
LOG.log(Level.INFO, "Interrupted while waiting for process to terminate", e);
Thread.currentThread().interrupt();
}
}
public String getStdout() {
return stdout;
}
public String getStderr() {
return stderr;
}
@Override
public String toString() {
return builder.command().toString();
}
private void writeStdin(Process process) throws ProcessManagerException {
if (stdinLines == null || stdinLines.length <= 0) {
return;
}
if (process == null) {
throw new ProcessManagerException("Parameter process was null.");
}
try (PrintWriter pipe = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())))) {
for (String stdinLine : stdinLines) {
LOG.log(Level.DEBUG, "InputLine -->" + stdinLine + "<--");
pipe.println(stdinLine);
pipe.flush();
}
} catch (Exception e) {
throw new ProcessManagerException(e);
}
}
private void await(Process process) throws InterruptedException, ProcessManagerException {
if (timeout <= 0) {
waitForever(process);
} else {
waitAwhile(process);
}
}
private void waitForever(Process process) throws InterruptedException, ProcessManagerException {
if (process == null) {
throw new ProcessManagerException("Parameter process was null.");
}
process.waitFor();
}
private void waitAwhile(Process process) throws InterruptedException, ProcessManagerException {
if (process == null) {
throw new ProcessManagerException("Parameter process was null.");
}
process.waitFor(timeout, TimeUnit.MILLISECONDS);
}
static class ReaderThread extends Thread {
private final BufferedReader reader;
private final StringBuilder sb;
private final boolean echo;
private final AtomicBoolean stop = new AtomicBoolean();
ReaderThread(InputStream stream, boolean echo, String threadName) {
setName(threadName);
this.reader = new BufferedReader(new InputStreamReader(stream));
this.sb = new StringBuilder();
this.echo = echo;
}
@Override
public void run() {
try {
while (true) {
String line;
if (reader.ready()) {
line = reader.readLine();
} else if (stop.getAcquire()) {
break;
} else {
Thread.yield();
continue;
}
sb.append(line).append('\n');
if (echo) {
System.out.println(line);
}
}
} catch (Exception e) {
LOG.log(Level.ERROR, "ReaderThread broke ...", e);
} finally {
try {
reader.close();
} catch (IOException e) {
LOG.log(Level.ERROR, "Failed to close BufferedReader", e);
}
}
LOG.log(Level.TRACE, "ReaderThread exiting...");
}
/**
* Asks the thread to finish it's job and waits until the thread dies.
* <p>
* The maximal time for the waiting is 10 seconds.
*
* @return the final output of the process.
*/
public String finish() {
stop.setRelease(true);
try {
join(10000L);
} catch (InterruptedException ex) {
// nothing to do
}
return sb.toString();
}
}
}