source: main/trunk/gli/src/org/greenstone/gatherer/util/SafeProcess.java@ 31720

Last change on this file since 31720 was 31720, checked in by ak19, 7 years ago
  1. GLI's DownloadJobs don't allow pausing and resuming (the button used to work, but didn't ever pause/resume in the background, at least it's been stopping the wget download activity after wget related changes from some years back). Changing the Pause/Resume button in the DownloadProgressBar to the Stop/Stopped button. 2. Added another useful link on InterruptedException to SafeProgress and its documentation.
File size: 65.5 KB
Line 
1package org.greenstone.gatherer.util;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.Closeable;
6import java.io.File;
7import java.io.InputStream;
8import java.io.InputStreamReader;
9import java.io.IOException;
10import java.io.OutputStream;
11import java.io.OutputStreamWriter;
12import java.net.Socket;
13import java.util.Arrays;
14import java.util.Scanner;
15import java.util.Stack;
16import javax.swing.SwingUtilities;
17
18
19import com.sun.jna.*;
20import com.sun.jna.platform.win32.Kernel32;
21import com.sun.jna.platform.win32.WinNT;
22
23import java.lang.reflect.Field;
24
25import org.apache.log4j.*;
26
27import org.greenstone.gatherer.DebugStream;
28
29// Use this class to run a Java Process. It follows the good and safe practices at
30// http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
31// to avoid blocking problems that can arise from a Process' input and output streams.
32
33// On Windows, Perl could launch processes as proper ProcessTrees: http://search.cpan.org/~gsar/libwin32-0.191/
34// Then killing the root process will kill child processes naturally.
35
36public class SafeProcess {
37 public static int DEBUG = 0;
38
39 public static final int STDERR = 0;
40 public static final int STDOUT = 1;
41 public static final int STDIN = 2;
42 // can't make this variable final and init in a static block, because it needs to use other SafeProcess static methods which rely on this in turn:
43 public static String WIN_KILL_CMD;
44
45 /**
46 * Boolean interruptible is used to mark any sections of blocking code that should not be interrupted
47 * with an InterruptedExceptions. At present only the cancelRunningProcess() attempts to do such a thing
48 * and avoids doing so when interruptible is false.
49 * Note that interruptible is also used as a lock, so remember to synchronize on it when using it!
50 */
51 public Boolean interruptible = Boolean.TRUE;
52
53 // charset for reading process stderr and stdout streams
54 //public static final String UTF8 = "UTF-8";
55
56 ///static Logger logger = Logger.getLogger(org.greenstone.util.SafeProcess.class.getName());
57
58 // input to SafeProcess and initialising it
59 private String command = null;
60 private String[] command_args = null;
61 private String[] envp = null;
62 private File dir = null;
63 private String inputStr = null;
64 private Process process = null;
65 private boolean forciblyTerminateProcess = false;
66
67 /** a ref to the thread in which the Process is being executed (the thread wherein Runtime.exec() is called) */
68 private Thread theProcessThread = null;
69
70 // output from running SafeProcess.runProcess()
71 private String outputStr = "";
72 private String errorStr = "";
73 private int exitValue = -1;
74 //private String charset = null;
75
76 // allow callers to process exceptions of the main process thread if they want
77 private ExceptionHandler exceptionHandler = null;
78 /** allow callers to implement hooks that get called during the main phases of the internal
79 * process' life cycle, such as before and after process.destroy() gets called
80 */
81 private MainProcessHandler mainHandler = null;
82
83 // whether std/err output should be split at new lines
84 private boolean splitStdOutputNewLines = false;
85 private boolean splitStdErrorNewLines = false;
86
87 // call one of these constructors
88
89 // cmd args version
90 public SafeProcess(String[] cmd_args)
91 {
92 command_args = cmd_args;
93 }
94
95 // cmd string version
96 public SafeProcess(String cmdStr)
97 {
98 command = cmdStr;
99 }
100
101 // cmd args with env version, launchDir can be null.
102 public SafeProcess(String[] cmd_args, String[] envparams, File launchDir)
103 {
104 command_args = cmd_args;
105 envp = envparams;
106 dir = launchDir;
107 }
108
109 // The important methods:
110 // to get the output from std err and std out streams after the process has been run
111 public String getStdOutput() { return outputStr; }
112 public String getStdError() { return errorStr; }
113 public int getExitValue() { return exitValue; }
114
115 //public void setStreamCharSet(String charset) { this.charset = charset; }
116
117 // set any string to send as input to the process spawned by SafeProcess
118 public void setInputString(String sendStr) {
119 inputStr = sendStr;
120 }
121
122 // register a SafeProcess ExceptionHandler whose gotException() method will
123 // get called for each exception encountered
124 public void setExceptionHandler(ExceptionHandler exception_handler) {
125 exceptionHandler = exception_handler;
126 }
127
128 /** to set a handler that will handle the main (SafeProcess) thread,
129 * implementing the hooks that will get called during the internal process' life cycle,
130 * such as before and after process.destroy() is called */
131 public void setMainHandler(MainProcessHandler handler) {
132 this.mainHandler = handler;
133 }
134
135 // set if you want the std output or err output to have \n at each newline read from the stream
136 public void setSplitStdOutputNewLines(boolean split) {
137 splitStdOutputNewLines = split;
138 }
139 public void setSplitStdErrorNewLines(boolean split) {
140 splitStdErrorNewLines = split;
141 }
142
143
144 /*
145 public boolean canInterrupt() {
146 boolean canInterrupt;
147 synchronized(interruptible) {
148 canInterrupt = interruptible.booleanValue();
149 }
150 return canInterrupt;
151 }
152 */
153
154 /**
155 * If calling this method from a GUI thread when the SafeProcess is in the uninterruptible
156 * phase of natural termination, then this method will return immediately before that phase
157 * has ended. To force the caller to wait until the natural termination phase has ended,
158 * call the other variant of this method with param forceWaitUntilInterruptible set to true:
159 * cancelRunningProcess(true).
160 * @return false if process has already terminated or if it was already terminating when
161 * cancel was called. In such cases no interrupt is sent.
162 * This method returns a boolean that you can call sentInterrupt.
163 */
164 public boolean cancelRunningProcess() {
165
166 boolean forceWaitUntilInterruptible = true;
167 // by default, event dispatch threads may not want to wait for any joins() taking
168 // place at the time of cancel to be completed.
169 // So don't wait until the SafeProcess becomes interruptible
170 return this.cancelRunningProcess(!forceWaitUntilInterruptible);
171 }
172
173 /**
174 * Call this method when you want to prematurely and safely terminate any process
175 * that SafeProcess may be running.
176 * You may want to implement the SafeProcess.MainHandler interface to write code
177 * for any hooks that will get called during the process' life cycle.
178 * @param forceWaitUntilInterruptible if set to true by a calling GUI thread, then this method
179 * won't return until the running process is interruptible, even if SafeProcess is in the phase
180 * of naturally terminating, upon which no interrupts will be sent to the SafeProcess
181 * thread anyway. The join() calls within SafeProcess.runProcess() are blocking calls and are
182 * therefore sensitive to InterruptedExceptions. But the join() calls are part of the cleanup
183 * phase and shouldn't be interrupted, and nothing thereafter can be interrupted anyway.
184 * This method tends to be called with the param set to false. In that case, if the SafeProcess
185 * is in an uninterruptible phase (as can then only happen during clean up of natural
186 * termination) then a calling GUI thread will just return immediately. Meaning, the GUI thread
187 * won't wait for the SafeProcess thread to finish cleaning up.
188 * @return false if process has already terminated or if it was already terminating when
189 * cancel was called. In such cases no interrupt is sent.
190 * This method returns a boolean that you can call sentInterrupt.
191 */
192 public synchronized boolean cancelRunningProcess(boolean forceWaitUntilInterruptible) {
193 // on interrupt:
194 // - forciblyTerminate will be changed to true if the interrupt came in when the process was
195 // still running (and so before the process' streams were being joined)
196 // - and forciblyTerminate will still remain false if the interrupt happens when the process'
197 // streams are being/about to be joined (hence after the process naturally terminated).
198 // So we don't touch the value of this.forciblyTerminate here.
199 // The value of forciblyTerminate determines whether Process.destroy() and its associated before
200 // and after handlers are called or not: we don't bother destroying the process if it came to
201 // a natural end.
202
203 // no process to interrupt, so we're done
204 if(this.process == null) {
205 log("@@@ No Java process to interrupt.");
206 return false;
207 }
208
209 boolean sentInterrupt = false;
210
211 // can't interrupt when SafeProcess is joining (cleanly terminating) worker threads
212 // have to wait until afterward
213 if (interruptible) {
214 // either way, we can now interrupt the thread that SafeProcess.runProcess() is running in
215 if(this.theProcessThread != null) { // we stored a ref to the main thread that's to be interrupted
216 this.theProcessThread.interrupt();
217 log("@@@ Successfully sent interrupt to process.");
218 sentInterrupt = true;
219 }
220 }
221 else { // wait for join()s to finish, if we've been asked to wait
222
223 // During and after joining(), there's no need to interrupt any more anyway: no calls
224 // subsequent to joins() block, so everything thereafter is insensitive to InterruptedExceptions
225 // and everything from the joins() onward are cleanup on natural process termination, so no
226 // interrupt is needed after the joins().
227 // Still, even if the caller is a GUI thread, they can decide if they want to wait until this
228 // method's end: until the SafeProcess becomes interruptible again
229
230 if(!forceWaitUntilInterruptible && SwingUtilities.isEventDispatchThread()) {
231 log("#### Event Dispatch thread, returning");
232 return false;
233 }
234
235 while(!interruptible) {
236
237 log("######### Waiting for process to become interruptible...");
238
239 // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
240 // wait will release lock on this object, and regain it when loop condition interruptible is true
241 try {
242 this.wait(); // can't interrupt when SafeProcess is joining (cleanly terminating) worker threads, so wait
243 } catch(Exception e) {
244 log("@@@ Interrupted exception while waiting for SafeProcess' worker threads to finish joining on cancelling process");
245 }
246 }
247
248 // now the process is sure to have ended as the worker threads would have been joined
249 }
250
251 return sentInterrupt;
252 }
253
254
255 // In future, think of changing the method doRuntimeExec() over to using ProcessBuilder
256 // instead of Runtime.exec(). ProcessBuilder seems to have been introduced from Java 5.
257 // https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
258 // See also https://zeroturnaround.com/rebellabs/how-to-deal-with-subprocesses-in-java/
259 // which suggests using Apache Common Exec to launch processes and says what will be forthcoming in Java 9
260
261 private Process doRuntimeExec() throws IOException {
262 Process prcs = null;
263 Runtime rt = Runtime.getRuntime();
264
265 if(this.command != null) {
266 log("SafeProcess running: " + command);
267 prcs = rt.exec(this.command);
268 }
269 else { // at least command_args must be set now
270
271 // http://stackoverflow.com/questions/5283444/convert-array-of-strings-into-a-string-in-java
272 //log("SafeProcess running:" + Arrays.toString(command_args));
273 StringBuffer cmdDisplay = new StringBuffer();
274 for(int i = 0; i < command_args.length; i++) {
275 cmdDisplay.append(" ").append(command_args[i]);
276 }
277 log("SafeProcess running: [" + cmdDisplay + "]");
278 cmdDisplay = null; // let the GC have it
279
280
281 if(this.envp == null) {
282 prcs = rt.exec(this.command_args);
283 } else { // launch process using cmd str with env params
284
285 if(this.dir == null) {
286 //log("\twith: " + Arrays.toString(this.envp));
287 prcs = rt.exec(this.command_args, this.envp);
288 } else {
289 //log("\tfrom directory: " + this.dir);
290 //log("\twith: " + Arrays.toString(this.envp));
291 prcs = rt.exec(this.command_args, this.envp, this.dir);
292 }
293 }
294 }
295
296 this.theProcessThread = Thread.currentThread(); // store a ref to the thread wherein the Process is being run
297 return prcs;
298 }
299
300 // Copied from gli's gui/FormatConversionDialog.java
301 private int waitForWithStreams(SafeProcess.OutputStreamGobbler inputGobbler,
302 SafeProcess.InputStreamGobbler outputGobbler,
303 SafeProcess.InputStreamGobbler errorGobbler)
304 throws IOException, InterruptedException
305 {
306 // kick off the stream gobblers
307 inputGobbler.start();
308 errorGobbler.start();
309 outputGobbler.start();
310
311 try {
312 this.exitValue = process.waitFor(); // can throw an InterruptedException if process was cancelled/prematurely terminated
313 } catch(InterruptedException ie) {
314 log("*** Process interrupted (InterruptedException). Expected to be a Cancel operation.");
315 // don't print stacktrace: an interrupt here is not an error, it's expected to be a cancel action
316 if(exceptionHandler != null) {
317 exceptionHandler.gotException(ie);
318 }
319
320 // propagate interrupts to worker threads here
321 // unless the interrupt emanated from any of them in any join(),
322 // which will be caught by the calling method's own catch on InterruptedException.
323 // Only if the thread that SafeProcess runs in was interrupted
324 // should we propagate the interrupt to the worker threads.
325 // http://stackoverflow.com/questions/2126997/who-is-calling-the-java-thread-interrupt-method-if-im-not
326 // "I know that in JCiP it is mentioned that you should never interrupt threads you do not own"
327 // But SafeProcess owns the worker threads, so it has every right to interrupt them
328 // Also read http://stackoverflow.com/questions/13623445/future-cancel-method-is-not-working?noredirect=1&lq=1
329
330 // http://stackoverflow.com/questions/3976344/handling-interruptedexception-in-java
331 // http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception
332 // "Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests."
333 // Does that mean that since this code implements this thread's interruption policy, it's ok
334 // to swallow the interrupt this time and not let it propagate by commenting out the next line?
335 //Thread.currentThread().interrupt(); // re-interrupt the thread
336
337 inputGobbler.interrupt();
338 errorGobbler.interrupt();
339 outputGobbler.interrupt();
340
341 // Since we have been cancelled (InterruptedException), or on any Exception, we need
342 // to forcibly terminate process eventually after the finally code first waits for each worker thread
343 // to die off. Don't set process=null until after we've forcibly terminated it if needs be.
344 this.forciblyTerminateProcess = true;
345
346 // even after the interrupts, we want to proceed to calling join() on all the worker threads
347 // in order to wait for each of them to die before attempting to destroy the process if it
348 // still hasn't terminated after all that.
349 } finally {
350
351 //log("Process exitValue: " + exitValue);
352 ///log("@@@@ Before join phase. Forcibly terminating: " + this.forciblyTerminateProcess);
353
354 // From the comments of
355 // http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
356 // To avoid running into nondeterministic failures to get the process output
357 // if there's no waiting for the threads, call join() on each Thread (StreamGobbler) object.
358 // From Thread API: join() "Waits for this thread (the thread join() is invoked on) to die."
359
360 // Wait for each of the threads to die, before attempting to destroy the process
361 // Any of these can throw InterruptedExceptions too
362 // and will be processed by the calling function's catch on InterruptedException.
363
364
365 // Thread.joins() below are blocking calls, same as Process.waitFor(), and a cancel action could
366 // send an interrupt during any Join: the InterruptedException ensuing will then break out of the
367 // joins() section. We don't want that to happen: by the time the joins() start happening, the
368 // actual process has finished in some way (naturally terminated or interrupted), and nothing
369 // should interrupt the joins() (nor ideally any potential p.destroy after that).
370 // So we mark the join() section as an un-interruptible section, and make anyone who's seeking
371 // to interrupt just then first wait for this Thread (in which SafeProcess runs) to become
372 // interruptible again. Thos actually assumes anything interruptible can still happen thereafter
373 // when in reality, none of the subsequent actions after the joins() block. So they nothing
374 // thereafter, which is the cleanup phase, will actually respond to an InterruptedException.
375
376
377 if(this.mainHandler != null) {
378 // this method can unset forcible termination flag
379 // if the process had already naturally terminated by this stage:
380 this.forciblyTerminateProcess = mainHandler.beforeWaitingForStreamsToEnd(this.forciblyTerminateProcess);
381 }
382
383 ///log("@@@@ After beforeJoin Handler. Forcibly terminating: " + this.forciblyTerminateProcess);
384
385 // Anyone could interrupt/cancel during waitFor() above,
386 // but no one should interrupt while the worker threads come to a clean close,
387 // so make anyone wanting to cancel the process at this stage wait()
388 // until we're done with the join()s:
389 synchronized(interruptible) {
390 interruptible = Boolean.FALSE;
391 }
392 //Thread.sleep(5000); // Uncomment to test this uninterruptible section, also comment out block checking for
393 // EventDispatchThread in cancelRunningProcess() and 2 calls to progress.enableCancelJob() in DownloadJob.java
394 outputGobbler.join();
395 errorGobbler.join();
396 inputGobbler.join();
397
398 synchronized(interruptible) {
399 interruptible = Boolean.TRUE;
400 }
401
402 ///log("@@@@ Join phase done...");
403
404 // notify any of those waiting to interrupt this thread, that they may feel free to do so again
405 // https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
406 synchronized(this) {
407 this.notify();
408 }
409
410 // set the variables that the code which created a SafeProcess object may want to inspect
411 this.outputStr = outputGobbler.getOutput();
412 this.errorStr = errorGobbler.getOutput();
413
414 // call the after join()s hook
415 if(this.mainHandler != null) {
416 this.forciblyTerminateProcess = mainHandler.afterStreamsEnded(this.forciblyTerminateProcess);
417 }
418 }
419
420 // Don't return from finally, it's considered an abrupt completion and exceptions are lost, see
421 // http://stackoverflow.com/questions/18205493/can-we-use-return-in-finally-block
422 return this.exitValue;
423 }
424
425
426 public synchronized boolean processRunning() {
427 if(process == null) return false;
428 return SafeProcess.processRunning(this.process);
429 }
430
431 // Run a very basic process: with no reading from or writing to the Process' iostreams,
432 // this just execs the process and waits for it to return.
433 // Don't call this method but the zero-argument runProcess() instead if your process will
434 // output stuff to its stderr and stdout streams but you don't need to monitory these.
435 // Because, as per a comment in GLI's GS3ServerThread.java,
436 // in Java 6, it wil block if you don't handle a process' streams when the process is
437 // outputting something. (Java 7+ won't block if you don't bother to handle the output streams)
438 public int runBasicProcess() {
439 try {
440 this.forciblyTerminateProcess = true;
441
442 // 1. create the process
443 process = doRuntimeExec();
444 // 2. basic waitFor the process to finish
445 this.exitValue = process.waitFor();
446
447 // 3. if we managed to get here, the process naturally terminated (wasn't interrupted):
448 this.forciblyTerminateProcess = false;
449 } catch(IOException ioe) {
450
451 if(exceptionHandler != null) {
452 exceptionHandler.gotException(ioe);
453 } else {
454 log("IOException: " + ioe.getMessage(), ioe);
455 }
456 } catch(InterruptedException ie) {
457
458 if(exceptionHandler != null) {
459 exceptionHandler.gotException(ie);
460 } else { // Unexpected InterruptedException, so printstacktrace
461 log("Process InterruptedException: " + ie.getMessage(), ie);
462 }
463
464 Thread.currentThread().interrupt();
465 } finally {
466
467 cleanUp("SafeProcess.runBasicProcess");
468 }
469 return this.exitValue;
470 }
471
472 // Runs a process with default stream processing. Returns the exitValue
473 public int runProcess() {
474 return runProcess(null, null, null); // use default processing of all 3 of the process' iostreams
475 }
476
477 // Run a process with custom stream processing (any custom handlers passed in that are null
478 // will use the default stream processing).
479 // Returns the exitValue from running the Process
480 public int runProcess(CustomProcessHandler procInHandler,
481 CustomProcessHandler procOutHandler,
482 CustomProcessHandler procErrHandler)
483 {
484 SafeProcess.OutputStreamGobbler inputGobbler = null;
485 SafeProcess.InputStreamGobbler errorGobbler = null;
486 SafeProcess.InputStreamGobbler outputGobbler = null;
487
488 try {
489 this.forciblyTerminateProcess = false;
490
491 // 1. get the Process object
492 process = doRuntimeExec();
493
494
495 // 2. create the streamgobblers and set any specified handlers on them
496
497 // PROC INPUT STREAM
498 if(procInHandler == null) {
499 // send inputStr to process. The following constructor can handle inputStr being null
500 inputGobbler = // WriterToProcessInputStream
501 new SafeProcess.OutputStreamGobbler(process.getOutputStream(), this.inputStr);
502 } else { // user will do custom handling of process' InputStream
503 inputGobbler = new SafeProcess.OutputStreamGobbler(process.getOutputStream(), procInHandler);
504 }
505
506 // PROC ERR STREAM to monitor for any error messages or expected output in the process' stderr
507 if(procErrHandler == null) {
508 errorGobbler // ReaderFromProcessOutputStream
509 = new SafeProcess.InputStreamGobbler(process.getErrorStream(), this.splitStdErrorNewLines);
510 } else {
511 errorGobbler
512 = new SafeProcess.InputStreamGobbler(process.getErrorStream(), procErrHandler);
513 }
514
515 // PROC OUT STREAM to monitor for the expected std output line(s)
516 if(procOutHandler == null) {
517 outputGobbler
518 = new SafeProcess.InputStreamGobbler(process.getInputStream(), this.splitStdOutputNewLines);
519 } else {
520 outputGobbler
521 = new SafeProcess.InputStreamGobbler(process.getInputStream(), procOutHandler);
522 }
523
524
525 // 3. kick off the stream gobblers
526 this.exitValue = waitForWithStreams(inputGobbler, outputGobbler, errorGobbler);
527
528 } catch(IOException ioe) {
529 this.forciblyTerminateProcess = true;
530
531 if(exceptionHandler != null) {
532 exceptionHandler.gotException(ioe);
533 } else {
534 log("IOexception: " + ioe.getMessage(), ioe);
535 }
536 } catch(InterruptedException ie) { // caused during any of the gobblers.join() calls, this is unexpected so print stack trace
537 this.forciblyTerminateProcess = true;
538
539 if(exceptionHandler != null) {
540 exceptionHandler.gotException(ie);
541 log("@@@@ Unexpected InterruptedException when waiting for process stream gobblers to die");
542 } else {
543 log("*** Unexpected InterruptException when waiting for process stream gobblers to die: " + ie.getMessage(), ie);
544 }
545
546 // see comments in other runProcess()
547 Thread.currentThread().interrupt();
548
549 } finally {
550
551 cleanUp("SafeProcess.runProcess(3 params)");
552 }
553
554 return this.exitValue;
555 }
556
557 public int runProcess(LineByLineHandler outLineByLineHandler, LineByLineHandler errLineByLineHandler)
558 {
559 SafeProcess.OutputStreamGobbler inputGobbler = null;
560 SafeProcess.InputStreamGobbler errorGobbler = null;
561 SafeProcess.InputStreamGobbler outputGobbler = null;
562
563 try {
564 this.forciblyTerminateProcess = false;
565
566 // 1. get the Process object
567 process = doRuntimeExec();
568
569
570 // 2. create the streamgobblers and set any specified handlers on them
571
572 // PROC INPUT STREAM
573 // send inputStr to process. The following constructor can handle inputStr being null
574 inputGobbler = // WriterToProcessInputStream
575 new SafeProcess.OutputStreamGobbler(process.getOutputStream(), this.inputStr);
576
577 // PROC ERR STREAM to monitor for any error messages or expected output in the process' stderr
578 errorGobbler // ReaderFromProcessOutputStream
579 = new SafeProcess.InputStreamGobbler(process.getErrorStream(), splitStdErrorNewLines);
580 // PROC OUT STREAM to monitor for the expected std output line(s)
581 outputGobbler
582 = new SafeProcess.InputStreamGobbler(process.getInputStream(), splitStdOutputNewLines);
583
584
585 // 3. register line by line handlers, if any were set, for the process stderr and stdout streams
586 if(outLineByLineHandler != null) {
587 outputGobbler.setLineByLineHandler(outLineByLineHandler);
588 }
589 if(errLineByLineHandler != null) {
590 errorGobbler.setLineByLineHandler(errLineByLineHandler);
591 }
592
593
594 // 3. kick off the stream gobblers
595 this.exitValue = waitForWithStreams(inputGobbler, outputGobbler, errorGobbler);
596
597 } catch(IOException ioe) {
598 this.forciblyTerminateProcess = true;
599
600 if(exceptionHandler != null) {
601 exceptionHandler.gotException(ioe);
602 } else {
603 log("IOexception: " + ioe.getMessage(), ioe);
604 }
605 } catch(InterruptedException ie) { // caused during any of the gobblers.join() calls, this is unexpected so log it
606 this.forciblyTerminateProcess = true;
607
608 if(exceptionHandler != null) {
609 exceptionHandler.gotException(ie);
610 log("@@@@ Unexpected InterruptedException when waiting for process stream gobblers to die");
611 } else {
612 log("*** Unexpected InterruptException when waiting for process stream gobblers to die: " + ie.getMessage(), ie);
613 }
614 // We're not causing any interruptions that may occur when trying to stop the worker threads
615 // So resort to default behaviour in this catch?
616 // "On catching InterruptedException, re-interrupt the thread."
617 // This is just how InterruptedExceptions tend to be handled
618 // See also http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception
619 // and https://praveer09.github.io/technology/2015/12/06/understanding-thread-interruption-in-java/
620 // http://michaelscharf.blogspot.co.nz/2006/09/dont-swallow-interruptedexception-call.html
621 Thread.currentThread().interrupt(); // re-interrupt the thread - which thread? Infinite loop?
622
623 } finally {
624
625 cleanUp("SafeProcess.runProcess(2 params)");
626 }
627
628 return this.exitValue;
629 }
630
631 private void cleanUp(String callingMethod) {
632
633 // Moved into here from GS2PerlConstructor and GShell.runLocal() which said
634 // "I need to somehow kill the child process. Unfortunately Thread.stop() and Process.destroy() both fail to do this. But now, thankx to the magic of Michaels 'close the stream suggestion', it works fine (no it doesn't!)"
635 // http://steveliles.github.io/invoking_processes_from_java.html
636 // http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
637 // http://mark.koli.ch/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec
638
639 //String cmd = (this.command == null) ? Arrays.toString(this.command_args) : this.command;
640 //log("*** In finally of " + callingMethod + ": " + cmd);
641
642 // if we're forcibly terminating the process, call the before- and afterDestroy hooks
643 // besides actually destroying the process
644 if( this.forciblyTerminateProcess ) {
645 log("*** Going to call process.destroy from " + callingMethod);
646
647 if(mainHandler != null) mainHandler.beforeProcessDestroy();
648 boolean noNeedToDestroyIfOnLinux = true; // Interrupt handling suffices to cleanup process and subprocesses on Linux
649 SafeProcess.destroyProcess(process, noNeedToDestroyIfOnLinux); // see runProcess(2 args/3 args)
650 if(mainHandler != null) mainHandler.afterProcessDestroy();
651
652 log("*** Have called process.destroy from " + callingMethod);
653 }
654
655 process = null;
656 this.theProcessThread = null; // let the process thread ref go too
657 boolean wasForciblyTerminated = this.forciblyTerminateProcess;
658 this.forciblyTerminateProcess = false; // reset
659
660 if(mainHandler != null) mainHandler.doneCleanup(wasForciblyTerminated);
661 }
662
663/*
664
665 On Windows, p.destroy() terminates process p that Java launched,
666 but does not terminate any processes that p may have launched. Presumably since they didn't form a proper process tree.
667 https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/e3cb7532-87f6-4ae3-9d80-a3afc8b9d437/how-to-kill-a-process-tree-in-cc-on-windows-platform?forum=vclanguage
668 https://msdn.microsoft.com/en-us/library/windows/desktop/ms684161(v=vs.85).aspx
669
670 Searching for: "forcibly terminate external process launched by Java on Windows"
671 Not possible: stackoverflow.com/questions/1835885/send-ctrl-c-to-process-open-by-java
672 But can use taskkill or tskill or wmic commands to terminate a process by processID
673 stackoverflow.com/questions/912889/how-to-send-interrupt-key-sequence-to-a-java-process
674 Taskkill command can kill by Image Name, such as all running perl, e.g. taskkill /f /im perl.exe
675 But what if we kill perl instances not launched by GS?
676 /f Specifies to forcefully terminate the process(es). We need this flag switched on to kill childprocesses.
677 /t Terminates the specified process and any child processes which were started by it.
678 /t didn't work to terminate subprocesses. Maybe since the process wasn't launched as
679 a properly constructed processtree.
680 /im is the image name (the name of the program), see Image Name column in Win Task Manager.
681
682 We don't want to kill all perl running processes.
683 Another option is to use wmic, available since Windows XP, to kill a process based on its command
684 which we sort of know (SafeProcess.command) and which can be seen in TaskManager under the
685 "Command Line" column of the Processes tab.
686 https://superuser.com/questions/52159/kill-a-process-with-a-specific-command-line-from-command-line
687 The following works kill any Command Line that matches -site localsite lucene-jdbm-demo
688 C:>wmic PATH win32_process Where "CommandLine like '%-site%localsite%%lucene-jdbm-demo%'" Call Terminate
689 "WMIC Wildcard Search using 'like' and %"
690 https://codeslammer.wordpress.com/2009/02/21/wmic-wildcard-search-using-like-and/
691 However, we're not even guaranteed that every perl command GS launches will contain the collection name
692 Nor do we want to kill all perl processes that GS launches with bin\windows\perl\bin\perl, though this works:
693 wmic PATH win32_process Where "CommandLine like '%bin%windows%perl%bin%perl%'" Call Terminate
694 The above could kill GS perl processes we don't intend to terminate, as they're not spawned by the particular
695 Process we're trying to terminate from the root down.
696
697 Solution: We can use taskkill or the longstanding tskill or wmic to kill a process by ID. Since we can
698 kill an external process that SafeProcess launched OK, and only have trouble killing any child processes
699 it launched, we need to know the pids of the child processes.
700
701 We can use Windows' wmic to discover the childpids of a process whose id we know.
702 And we can use JNA to get the process ID of the external process that SafeProcess launched.
703
704 To find the processID of the process launched by SafeProcess,
705 need to use Java Native Access (JNA) jars, available jna.jar and jna-platform.jar.
706 http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
707 http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
708 http://www.golesny.de/p/code/javagetpid
709 https://github.com/java-native-access/jna/blob/master/www/GettingStarted.md
710 We're using JNA v 4.1.0, https://mvnrepository.com/artifact/net.java.dev.jna/jna
711
712 WMIC can show us a list of parent process id and process id of running processes, and then we can
713 kill those child processes with a specific process id.
714 https://superuser.com/questions/851692/track-which-program-launches-a-certain-process
715 http://stackoverflow.com/questions/7486717/finding-parent-process-id-on-windows
716 WMIC can get us the pids of all childprocesses launched by parent process denoted by parent pid.
717 And vice versa:
718 if you know the parent pid and want to know all the pids of the child processes spawned:
719 wmic process where (parentprocessid=596) get processid
720 if you know a child process id and want to know the parent's id:
721 wmic process where (processid=180) get parentprocessid
722
723 The above is the current solution.
724
725 Eventually, instead of running a windows command to kill the process ourselves, consider changing over to use
726 https://github.com/flapdoodle-oss/de.flapdoodle.embed.process/blob/master/src/main/java/de/flapdoodle/embed/process/runtime/Processes.java
727 (works with Apache license, http://www.apache.org/licenses/LICENSE-2.0)
728 This is a Java class that uses JNA to terminate processes. It also has the getProcessID() method.
729
730 Linux ps equivalent on Windows is "tasklist", see
731 http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
732
733*/
734
735// http://stackoverflow.com/questions/4750470/how-to-get-pid-of-process-ive-just-started-within-java-program
736// Uses Java Native Access, JNA
737public static long getProcessID(Process p)
738{
739 long pid = -1;
740 try {
741 //for windows
742 if (p.getClass().getName().equals("java.lang.Win32Process") ||
743 p.getClass().getName().equals("java.lang.ProcessImpl"))
744 {
745 Field f = p.getClass().getDeclaredField("handle");
746 f.setAccessible(true);
747 long handl = f.getLong(p);
748 Kernel32 kernel = Kernel32.INSTANCE;
749 WinNT.HANDLE hand = new WinNT.HANDLE();
750 hand.setPointer(Pointer.createConstant(handl));
751 pid = kernel.GetProcessId(hand);
752 f.setAccessible(false);
753 }
754 //for unix based operating systems
755 else if (p.getClass().getName().equals("java.lang.UNIXProcess"))
756 {
757 Field f = p.getClass().getDeclaredField("pid");
758 f.setAccessible(true);
759 pid = f.getLong(p);
760 f.setAccessible(false);
761 }
762
763 } catch(Exception ex) {
764 log("SafeProcess.getProcessID(): Exception when attempting to get process ID for process " + ex.getMessage(), ex);
765 pid = -1;
766 }
767 return pid;
768}
769
770
771// Can't artificially send Ctrl-C: stackoverflow.com/questions/1835885/send-ctrl-c-to-process-open-by-java
772// (Taskkill command can kill all running perl. But what if we kill perl instances not launched by GS?)
773// stackoverflow.com/questions/912889/how-to-send-interrupt-key-sequence-to-a-java-process
774// Searching for: "forcibly terminate external process launched by Java on Windows"
775static void killWinProcessWithID(long processID) {
776
777 String cmd = SafeProcess.getWinProcessKillCmd(processID);
778 if (cmd == null) return;
779
780 try {
781 log("\tAttempting to terminate Win subprocess with pid: " + processID);
782 SafeProcess proc = new SafeProcess(cmd);
783 int exitValue = proc.runProcess(); // no IOstreams for Taskkill, but for "wmic process pid delete"
784 // there is output that needs flushing, so don't use runBasicProcess()
785
786 } catch(Exception e) {
787 log("@@@ Exception attempting to stop perl " + e.getMessage(), e);
788 }
789}
790
791// Kill signals, their names and numerical equivalents: http://www.faqs.org/qa/qa-831.html
792// https://stackoverflow.com/questions/8533377/why-child-process-still-alive-after-parent-process-was-killed-in-linux
793// Works on Linux but not Mac when build scripts run from GLI: kill -TERM -pid
794// Works on Macs but not Linux: pkill -TERM -P pid
795// More reading:
796// https://superuser.com/questions/343031/sigterm-with-a-keyboard-shortcut
797// Ctrl-C sends a SIGNINT, not SIGTERM or SIGKILL. And on Ctrl-C, "the signal is sent to the foreground *process group*."
798// https://linux.die.net/man/1/kill (manual)
799// https://unix.stackexchange.com/questions/117227/why-pidof-and-pgrep-are-behaving-differently
800// https://unix.stackexchange.com/questions/67635/elegantly-get-list-of-children-processes
801// https://stackoverflow.com/questions/994033/mac-os-x-quickest-way-to-kill-quit-an-entire-process-tree-from-within-a-cocoa-a
802// https://unix.stackexchange.com/questions/132224/is-it-possible-to-get-process-group-id-from-proc
803// https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated
804
805/**
806 * On Unix, will kill the process denoted by processID and any subprocesses this launched. Tested on a Mac, where this is used.
807 * @param force if true will send the -KILL (-9) signal, which may result in abrupt termination without cleanup
808 * if false, will send the -TERM (-15) signal, which will allow cleanup before termination. Sending a SIGTERM is preferred.
809 * @param killEntireTree if false, will terminate only the process denoted by processID, otherwise all descendants/subprocesses too.
810 * @return true if running the kill process returned an exit value of 0 or if it had already been terminated
811*/
812static boolean killUnixProcessWithID(long processID, boolean force, boolean killEntireTree) {
813
814 String signal = force ? "KILL" : "TERM"; // kill -KILL (kill -9) vs preferred kill -TERM (kill -15)
815 String cmd;
816 if(killEntireTree) { // kill the process denoted by processID and any subprocesses this launched
817
818 if(Utility.isMac()) {
819 // this cmd works on Mac (tested Snow Leopard), but on Linux this cmd only terminates toplevel process
820 // when doing full-import, and doesn't always terminate subprocesses when doing full-buildcol.pl
821 cmd = "pkill -"+signal + " -P " + processID; // e.g. "pkill -TERM -P pid"
822 }
823 else { // other unix
824 // this cmd works on linux, not recognised on Mac (tested Snow Leopard):
825 cmd = "kill -"+signal + " -"+processID; // e.g. "kill -TERM -pid"
826 // note the hyphen before pid to terminate subprocesses too
827 }
828
829 } else { // kill only the process represented by the processID.
830 cmd = "kill -"+signal + " " + processID; // e.g. "kill -TERM pid"
831 }
832
833 SafeProcess proc = new SafeProcess(cmd);
834 int exitValue = proc.runProcess();
835
836
837 if(exitValue == 0) {
838 if(force) {
839 log("@@@ Successfully sent SIGKILL to unix process tree rooted at " + processID);
840 } else {
841 log("@@@ Successfully sent SIGTERM to unix process tree rooted at " + processID);
842 }
843 return true;
844 } else if(exitValue == 1 && proc.getStdOutput().trim().equals("") && proc.getStdError().trim().equals("")) {
845 // https://stackoverflow.com/questions/28332888/return-value-of-kill
846 // "kill returns an exit code of 0 (true) if the process still existed it and was killed.
847 // kill returns an exit code of 1 (false) if the kill failed, probably because the process was no longer running."
848 // On Linux, interrupting the process and its worker threads and closing resources already successfully terminates
849 // the process and its subprocesses (don't need to call this method at all to terminate the processes: the processes
850 // aren't running when we get to this method)
851 log("@@@ Sending termination signal returned exit value 1. On unix this can happen when the process has already been terminated.");
852 return true;
853 } else {
854 log("@@@ Not able to successfully terminate process. Got exitvalue: " + exitValue);
855 log("@@@ Got output: |" + proc.getStdOutput() + "|");
856 log("@@@ Got err output: |" + proc.getStdError() + "|");
857 // caller can try again with kill -KILL, by setting force parameter to true
858 return false;
859 }
860}
861
862public static void destroyProcess(Process p) {
863 // A cancel action results in an interruption to the process thread, which in turn interrupts
864 // the SafeProcess' worker threads, all which clean up after themselves.
865 // On linux, this suffices to cleanly terminate a Process and any subprocesses that may have launched
866 // so we don't need to do extra work in such a case. But the interrupts happen only when SafeProcess calls
867 // destroyProcess() on the Process it was running internally, and not if anyone else tries to end a
868 // Process by calling SafeProcess.destroyProcess(p). In such cases, the Process needs to be actively terminated:
869 boolean canSkipExtraWorkIfLinux = true;
870 SafeProcess.destroyProcess(p, !canSkipExtraWorkIfLinux);
871}
872
873// On linux, the SafeProcess code handling an Interruption suffices to successfully and cleanly terminate
874// the process and any subprocesses launched by p as well (and not even an extra p.destroy() is needed).
875// On Windows, and Mac too, we need to do more work, since otherwise processes launched by p remain
876// around executing until they naturally terminate.
877// e.g. full-import.pl may be terminated with p.destroy(), but it launches import.pl which is left running until it naturally terminates.
878private static void destroyProcess(Process p, boolean canSkipExtraWorkIfLinux) {
879 log("### in SafeProcess.destroyProcess(Process p)");
880
881 // If it isn't windows, process.destroy() terminates any child processes too
882 if(Utility.isWindows()) {
883
884 if(!SafeProcess.isAvailable("wmic")) {
885 log("wmic, used to kill subprocesses, is not available. Unable to terminate subprocesses...");
886 log("Kill them manually from the TaskManager or they will proceed to run to termination");
887
888 // At least we can get rid of the top level process we launched
889 p.destroy();
890 return;
891 }
892
893 // get the process id of the process we launched,
894 // so we can use it to find the pids of any subprocesses it launched in order to terminate those too.
895
896 long processID = SafeProcess.getProcessID(p);
897 if(processID == -1) { // the process doesn't exist or no longer exists (terminated naturally?)
898 p.destroy(); // minimum step, do this anyway, at worst there's no process and this won't have any effect
899 } else {
900 log("Attempting to terminate sub processes of Windows process with pid " + processID);
901 terminateSubProcessesRecursively(processID, p);
902 }
903 return;
904
905 }
906 else { // linux or mac
907
908 // if we're on linux and would have already terminated by now (in which case canSkipExtraWorkForLinux would be true),
909 // then there's nothing much left to do. This would only be the case if SafeProcess is calling this method on its
910 // internal process, since it would have successfully cleaned up on Interruption and there would be no process left running
911 if(!Utility.isMac() && canSkipExtraWorkIfLinux) {
912 log("@@@ Linux: Cancelling a SafeProcess instance does not require any complicated system destroy operation");
913 p.destroy(); // vestigial: this will have no effect if the process had already terminated, which is the case in this block
914 return;
915 }
916 // else we're on a Mac or an external caller (not SafeProcess) has requested explicit termination on Linux
917
918 long pid = SafeProcess.getProcessID(p);
919 /*
920 // On Macs (all Unix?) can't get the child processes of a process once it's been destroyed
921 macTerminateSubProcessesRecursively(pid, p);
922 */
923
924 if(pid == -1) { // if the process has already terminated, or we can't get the pid for any reason:
925 p.destroy(); // at minimum. Will have no effect if the process had already terminated
926 } else {
927 boolean forceKill = true;
928 boolean killEntireProcessTree = true;
929
930 if(!killUnixProcessWithID(pid, !forceKill, killEntireProcessTree)) { // send sig TERM (kill -15 or kill -TERM)
931 killUnixProcessWithID(pid, forceKill, killEntireProcessTree); // send sig KILL (kill -9 or kill -KILL)
932 }
933 // if both kill commands failed for whatever reason, can still at least end the top level process:
934 p.destroy(); // no effect if the process has already terminated.
935 }
936
937 return;
938 }
939}
940
941
942// UNUSED and INCOMPLETE METHOD
943// But if this method is needed, then need to parse childpids printed by "pgrep -P pid" and write recursive step
944// The childpids are probably listed one per line, see https://unix.stackexchange.com/questions/117227/why-pidof-and-pgrep-are-behaving-differently
945private static void macTerminateSubProcessesRecursively(long parent_pid, Process p) { //boolean isTopLevelProcess) {
946 log("@@@ Attempting to terminate mac process recursively");
947
948 // https://unix.stackexchange.com/questions/67635/elegantly-get-list-of-children-processes
949 SafeProcess proc = new SafeProcess("pgrep -P "+parent_pid);
950 int exitValue = proc.runProcess();
951 String stdOutput = proc.getStdOutput();
952 String stdErrOutput = proc.getStdError();
953
954 // now we have the child processes, can terminate the parent process
955 if(p != null) { // top level process, can just be terminated the java way with p.destroy()
956 p.destroy();
957 } else {
958 boolean forceKill = true;
959 boolean killSubprocesses = true;
960 // get rid of process denoted by the current pid (but not killing subprocesses it may have launched,
961 // since we'll deal with them recursively)
962 if(!SafeProcess.killUnixProcessWithID(parent_pid, !forceKill, !killSubprocesses)) { // send kill -TERM, kill -15
963 SafeProcess.killUnixProcessWithID(parent_pid, forceKill, !killSubprocesses); // send kill -9, kill -KILL
964 }
965 }
966
967 /*
968 // get rid of any process with current pid
969 if(!isTopLevelProcess && !SafeProcess.killUnixProcessWithID(parent_pid, false)) { // send kill -TERM, kill -15
970 SafeProcess.killUnixProcessWithID(parent_pid, true); // send kill -9, kill -KILL
971 }
972 */
973
974 if(stdOutput.trim().equals("") && stdErrOutput.trim().equals("") && exitValue == 1) {
975 log("No child processes");
976 // we're done
977 return;
978 } else {
979 log("Got childpids on STDOUT: " + stdOutput);
980 log("Got childpids on STDERR: " + stdErrOutput);
981 }
982}
983
984// Helper function. Only for Windows.
985// Counterintuitively, we're be killing all parent processess and then all child procs and all their descendants
986// as soon as we discover any further process each (sub)process has launched. The parent processes are killed
987// first in each case for 2 reasons:
988// 1. on Windows, killing the parent process leaves the child running as an orphan anyway, so killing the
989// parent is an independent action, the child process is not dependent on the parent;
990// 2. Killing a parent process prevents it from launching further processes while we're killing off each child process
991private static void terminateSubProcessesRecursively(long parent_pid, Process p) {
992
993 // Use Windows wmic to find the pids of any sub processes launched by the process denoted by parent_pid
994 SafeProcess proc = new SafeProcess("wmic process where (parentprocessid="+parent_pid+") get processid");
995 proc.setSplitStdOutputNewLines(true); // since this is windows, splits lines by \r\n
996 int exitValue = proc.runProcess(); // exitValue (%ERRORLEVEL%) is 0 either way.
997 //log("@@@@ Return value from proc: " + exitValue);
998
999 // need output from both stdout and stderr: stderr will say there are no pids, stdout will contain pids
1000 String stdOutput = proc.getStdOutput();
1001 String stdErrOutput = proc.getStdError();
1002
1003
1004 // Now we know the pids of the immediate subprocesses, we can get rid of the parent process
1005 // We know the children remain running: since the whole problem on Windows is that these
1006 // child processes remain running as orphans after the parent is forcibly terminated.
1007 if(p != null) { // we're the top level process, terminate the java way
1008 p.destroy();
1009 } else { // terminate windows way
1010 SafeProcess.killWinProcessWithID(parent_pid); // get rid of process with current pid
1011 }
1012
1013 // parse the output to get the sub processes' pids
1014 // Output looks like:
1015 // ProcessId
1016 // 6040
1017 // 180
1018 // 4948
1019 // 1084
1020 // 6384
1021 // If no children, then STDERR output starts with the following, possibly succeeded by empty lines:
1022 // No Instance(s) Available.
1023
1024 // base step of the recursion
1025 if(stdErrOutput.indexOf("No Instance(s) Available.") != -1) {
1026 //log("@@@@ Got output on stderr: " + stdErrOutput);
1027 // No further child processes. And we already terminated the parent process, so we're done
1028 return;
1029 } else {
1030 //log("@@@@ Got output on stdout:\n" + stdOutput);
1031
1032 // http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split
1033
1034 // find all childprocesses for that pid and terminate them too:
1035 Stack<Long> subprocs = new Stack<Long>();
1036 Scanner sc = new Scanner(stdOutput);
1037 while (sc.hasNext()) {
1038 if(!sc.hasNextLong()) {
1039 sc.next(); // discard the current token since it's not a Long
1040 } else {
1041 long child_pid = sc.nextLong();
1042 subprocs.push(new Long(child_pid));
1043 }
1044 }
1045 sc.close();
1046
1047 // recursion step if subprocs is not empty (but if it is empty, then it's another base step)
1048 if(!subprocs.empty()) {
1049 long child_pid = subprocs.pop().longValue();
1050 terminateSubProcessesRecursively(child_pid, null);
1051 }
1052 }
1053}
1054
1055// This method should only be called on a Windows OS
1056private static String getWinProcessKillCmd(Long processID) {
1057 // check if we first need to init WIN_KILL_CMD. We do this only once, but can't do it in a static codeblock
1058 // because of a cyclical dependency regarding this during static initialization
1059
1060 if(WIN_KILL_CMD == null) {
1061 if(SafeProcess.isAvailable("wmic")) {
1062 // https://isc.sans.edu/diary/Windows+Command-Line+Kung+Fu+with+WMIC/1229
1063 WIN_KILL_CMD = "wmic process _PROCID_ delete"; // like "kill -9" on Windows
1064 }
1065 else if(SafeProcess.isAvailable("taskkill")) { // check if we have taskkill or else use the longstanding tskill
1066
1067 WIN_KILL_CMD = "taskkill /f /t /PID _PROCID_"; // need to forcefully /f terminate the process
1068 // /t "Terminates the specified process and any child processes which were started by it."
1069 // But despite the /T flag, the above doesn't kill subprocesses.
1070 }
1071 else { //if(SafeProcess.isAvailable("tskill")) { can't check availability since "which tskill" doesn't ever succeed
1072 WIN_KILL_CMD = "tskill _PROCID_"; // https://ss64.com/nt/tskill.html
1073 }
1074 }
1075
1076 if(WIN_KILL_CMD == null) { // can happen if none of the above cmds were available
1077 return null;
1078 }
1079 return WIN_KILL_CMD.replace( "_PROCID_", Long.toString(processID) );
1080}
1081
1082
1083// Run `which` on a program to find out if it is available. which.exe is included in winbin.
1084// On Windows, can use where or which. GLI's file/FileAssociationManager.java used which, so we stick to the same.
1085// where is not part of winbin. where is a system command on windows, but only since 2003, https://ss64.com/nt/where.html
1086// There is no `where` on Linux/Mac, must use which for them.
1087// On windows, "which tskill" fails (and "where tskill" works), but "which" succeeds on taskkill|wmic|browser names.
1088public static boolean isAvailable(String program) {
1089 try {
1090 // On linux `which bla` does nothing, prompt is returned; on Windows, it prints "which: no bla in"
1091 // `which grep` returns a line of output with the path to grep. On windows too, the location of the program is printed
1092 SafeProcess prcs = new SafeProcess("which " + program);
1093 prcs.runProcess();
1094 String output = prcs.getStdOutput().trim();
1095 ///System.err.println("*** 'which " + program + "' returned: |" + output + "|");
1096 if(output.equals("")) {
1097 return false;
1098 } else if(output.indexOf("no "+program) !=-1) { // from GS3's org.greenstone.util.BrowserLauncher.java's isAvailable(program)
1099 log("@@@ SafeProcess.isAvailable(): " + program + "is not available");
1100 return false;
1101 }
1102 //System.err.println("*** 'which " + program + "' returned: " + output);
1103 return true;
1104 } catch (Exception exc) {
1105 return false;
1106 }
1107}
1108
1109// Google Java external process destroy kill subprocesses
1110// https://zeroturnaround.com/rebellabs/how-to-deal-with-subprocesses-in-java/
1111
1112//******************** Inner class and interface definitions ********************//
1113// Static inner classes can be instantiated without having to instantiate an object of the outer class first
1114
1115// Can have public static interfaces too,
1116// see http://stackoverflow.com/questions/71625/why-would-a-static-nested-interface-be-used-in-java
1117// Implementors need to take care that the implementations are thread safe
1118// http://stackoverflow.com/questions/14520814/why-synchronized-method-is-not-included-in-interface
1119public static interface ExceptionHandler {
1120
1121 /**
1122 * Called whenever an exception occurs during the execution of the main thread of SafeProcess
1123 * (the thread in which the Process is run).
1124 * Since this method can't be declared as synchronized in this interface method declaration,
1125 * when implementing ExceptionHandler.gotException(), if it manipulates anything that's
1126 * not threadsafe, declare gotException() as a synchronized method to ensure thread safety
1127 */
1128 public void gotException(Exception e);
1129}
1130
1131/** On interrupting (cancelling) a process,
1132 * if the class that uses SafeProcess wants to do special handling
1133 * either before and after join() is called on all the worker threads,
1134 * or, only on forcible termination, before and after process.destroy() is to be called,
1135 * then that class can implement this MainProcessHandler interface
1136 */
1137public static interface MainProcessHandler {
1138 /**
1139 * Called before the streamgobbler join()s.
1140 * If not overriding, the default implementation should be:
1141 * public boolean beforeWaitingForStreamsToEnd(boolean forciblyTerminating) { return forciblyTerminating; }
1142 * When overriding:
1143 * @param forciblyTerminating is true if currently it's been decided that the process needs to be
1144 * forcibly terminated. Return false if you don't want it to be. For a basic implementation,
1145 * return the parameter.
1146 * @return true if the process is still running and therefore still needs to be destroyed, or if
1147 * you can't determine whether it's still running or not. Process.destroy() will then be called.
1148 * @return false if the process has already naturally terminated by this stage. Process.destroy()
1149 * won't be called, and neither will the before- and after- processDestroy methods of this class.
1150 */
1151 public boolean beforeWaitingForStreamsToEnd(boolean forciblyTerminating);
1152 /**
1153 * Called after the streamgobbler join()s have finished.
1154 * If not overriding, the default implementation should be:
1155 * public boolean afterStreamsEnded(boolean forciblyTerminating) { return forciblyTerminating; }
1156 * When overriding:
1157 * @param forciblyTerminating is true if currently it's been decided that the process needs to be
1158 * forcibly terminated. Return false if you don't want it to be. For a basic implementation,
1159 * return the parameter (usual case).
1160 * @return true if the process is still running and therefore still needs to be destroyed, or if
1161 * can't determine whether it's still running or not. Process.destroy() will then be called.
1162 * @return false if the process has already naturally terminated by this stage. Process.destroy()
1163 * won't be called, and neither will the before- and after- processDestroy methods of this class.
1164 */
1165 public boolean afterStreamsEnded(boolean forciblyTerminating);
1166 /**
1167 * called after join()s and before process.destroy()/destroyProcess(Process), iff forciblyTerminating
1168 */
1169 public void beforeProcessDestroy();
1170 /**
1171 * Called after process.destroy()/destroyProcess(Process), iff forciblyTerminating
1172 */
1173 public void afterProcessDestroy();
1174
1175 /**
1176 * Always called after process ended: whether it got destroyed or not
1177 */
1178 public void doneCleanup(boolean wasForciblyTerminated);
1179}
1180
1181// Write your own run() body for any StreamGobbler. You need to create an instance of a class
1182// extending CustomProcessHandler for EACH IOSTREAM of the process that you want to handle.
1183// Do not create a single CustomProcessHandler instance and reuse it for all three streams,
1184// i.e. don't call SafeProcess' runProcess(x, x, x); It should be runProcess(x, y, z).
1185// Make sure your implementation is threadsafe if you're sharing immutable objects between the threaded streams
1186// example implementation is in the GS2PerlConstructor.SynchronizedProcessHandler class.
1187// CustomProcessHandler is made an abstract class instead of an interface to force classes that want
1188// to use a CustomProcessHandler to create a separate class that extends CustomProcessHandler, rather than
1189// that the classes that wish to use it "implementing" the CustomProcessHandler interface itself: the
1190// CustomProcessHandler.run() method may then be called in the major thread from which the Process is being
1191// executed, rather than from the individual threads that deal with each iostream of the Process.
1192public static abstract class CustomProcessHandler {
1193
1194 protected final int source;
1195
1196 protected CustomProcessHandler(int src) {
1197 this.source = src; // STDERR or STDOUT or STDIN
1198 }
1199
1200 public String getThreadNamePrefix() {
1201 return SafeProcess.streamToString(this.source);
1202 }
1203
1204 public abstract void run(Closeable stream); //InputStream or OutputStream
1205}
1206
1207// When using the default stream processing to read from a process' stdout or stderr stream, you can
1208// create a class extending LineByLineHandler for the process' err stream and one for its output stream
1209// to do something on a line by line basis, such as sending the line to a log
1210public static abstract class LineByLineHandler {
1211 protected final int source;
1212
1213 protected LineByLineHandler(int src) {
1214 this.source = src; // STDERR or STDOUT
1215 }
1216
1217 public String getThreadNamePrefix() {
1218 return SafeProcess.streamToString(this.source);
1219 }
1220
1221 public abstract void gotLine(String line); // first non-null line
1222 public abstract void gotException(Exception e); // for when an exception occurs instead of getting a line
1223}
1224
1225
1226//**************** StreamGobbler Inner class definitions (stream gobblers copied from GLI) **********//
1227
1228// http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
1229// This class is used in FormatConversionDialog to properly read from the stdout and stderr
1230// streams of a Process, Process.getInputStream() and Process.getErrorSream()
1231public static class InputStreamGobbler extends Thread
1232{
1233 private InputStream is = null;
1234 private StringBuffer outputstr = new StringBuffer();
1235 private boolean split_newlines = false;
1236 private CustomProcessHandler customHandler = null;
1237 private LineByLineHandler lineByLineHandler = null;
1238
1239 protected InputStreamGobbler() {
1240 super("InputStreamGobbler");
1241 }
1242
1243 public InputStreamGobbler(InputStream is)
1244 {
1245 this(); // sets thread name
1246 this.is = is;
1247 this.split_newlines = false;
1248 }
1249
1250 public InputStreamGobbler(InputStream is, boolean split_newlines)
1251 {
1252 this(); // sets thread name
1253 this.is = is;
1254 this.split_newlines = split_newlines;
1255
1256 }
1257
1258 public InputStreamGobbler(InputStream is, CustomProcessHandler customHandler)
1259 {
1260 this(); // thread name
1261 this.is = is;
1262 this.customHandler = customHandler;
1263 this.adjustThreadName(customHandler.getThreadNamePrefix());
1264 }
1265
1266
1267 private void adjustThreadName(String prefix) {
1268 this.setName(prefix + this.getName());
1269 }
1270
1271 public void setLineByLineHandler(LineByLineHandler lblHandler) {
1272 this.lineByLineHandler = lblHandler;
1273 this.adjustThreadName(lblHandler.getThreadNamePrefix());
1274 }
1275
1276 // default run() behaviour
1277 public void runDefault()
1278 {
1279 BufferedReader br = null;
1280 try {
1281 br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
1282 String line=null;
1283 while ( !this.isInterrupted() && (line = br.readLine()) != null ) {
1284
1285 //log("@@@ GOT LINE: " + line);
1286 outputstr.append(line);
1287 if(split_newlines) {
1288 outputstr.append(Utility.NEWLINE); // "\n" is system dependent (Win must be "\r\n")
1289 }
1290
1291 if(lineByLineHandler != null) { // let handler deal with newlines
1292 lineByLineHandler.gotLine(line);
1293 }
1294 }
1295
1296 } catch (IOException ioe) {
1297 if(lineByLineHandler != null) {
1298 lineByLineHandler.gotException(ioe);
1299 } else {
1300 log("Exception when reading process stream with " + this.getName() + ": ", ioe);
1301 }
1302 } finally {
1303 if(this.isInterrupted()) {
1304 log("@@@ Successfully interrupted " + this.getName() + ".");
1305 }
1306 SafeProcess.closeResource(br);
1307 }
1308 }
1309
1310 public void runCustom() {
1311 this.customHandler.run(is);
1312 }
1313
1314 public void run() {
1315 if(this.customHandler == null) {
1316 runDefault();
1317 } else {
1318 runCustom();
1319 }
1320 }
1321
1322 public String getOutput() {
1323 return outputstr.toString(); // implicit toString() call anyway. //return outputstr;
1324 }
1325} // end static inner class InnerStreamGobbler
1326
1327
1328// http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
1329// This class is used in FormatConversionDialog to properly write to the inputstream of a Process
1330// Process.getOutputStream()
1331public static class OutputStreamGobbler extends Thread
1332{
1333 private OutputStream os = null;
1334 private String inputstr = "";
1335 private CustomProcessHandler customHandler = null;
1336
1337 protected OutputStreamGobbler() {
1338 super("stdinOutputStreamGobbler"); // thread name
1339 }
1340
1341 public OutputStreamGobbler(OutputStream os) {
1342 this(); // set thread name
1343 this.os = os;
1344 }
1345
1346 public OutputStreamGobbler(OutputStream os, String inputstr)
1347 {
1348 this(); // set thread name
1349 this.os = os;
1350 this.inputstr = inputstr;
1351 }
1352
1353 public OutputStreamGobbler(OutputStream os, CustomProcessHandler customHandler) {
1354 this(); // set thread name
1355 this.os = os;
1356 this.customHandler = customHandler;
1357 }
1358
1359 // default run() behaviour
1360 public void runDefault() {
1361
1362 if (inputstr == null) {
1363 return;
1364 }
1365
1366 // also quit if the process was interrupted before we could send anything to its stdin
1367 if(this.isInterrupted()) {
1368 log(this.getName() + " thread was interrupted.");
1369 return;
1370 }
1371
1372 BufferedWriter osw = null;
1373 try {
1374 osw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
1375 //System.out.println("@@@ SENDING LINE: " + inputstr);
1376 osw.write(inputstr, 0, inputstr.length());
1377 osw.newLine();//osw.write("\n");
1378 osw.flush();
1379
1380 // Don't explicitly send EOF when using StreamGobblers as below,
1381 // as the EOF char is echoed to output.
1382 // Flushing the write handle and/or closing the resource seems
1383 // to already send EOF silently.
1384
1385 /*if(Utility.isWindows()) {
1386 osw.write("\032"); // octal for Ctrl-Z, EOF on Windows
1387 } else { // EOF on Linux/Mac is Ctrl-D
1388 osw.write("\004"); // octal for Ctrl-D, see http://www.unix-manuals.com/refs/misc/ascii-table.html
1389 }
1390 osw.flush();
1391 */
1392 } catch (IOException ioe) {
1393 log("Exception writing to SafeProcess' inputstream: ", ioe);
1394 } finally {
1395 SafeProcess.closeResource(osw);
1396 }
1397 }
1398
1399 // call the user's custom handler for the run() method
1400 public void runCustom() {
1401 this.customHandler.run(os);
1402 }
1403
1404 public void run()
1405 {
1406 if(this.customHandler == null) {
1407 runDefault();
1408 } else {
1409 runCustom();
1410 }
1411 }
1412} // end static inner class OutputStreamGobbler
1413
1414//**************** Static methods **************//
1415
1416
1417 // logger and DebugStream print commands are synchronized, therefore thread safe.
1418 public static void log(String msg) {
1419 if(DEBUG == 0) return;
1420 //logger.info(msg);
1421
1422 System.err.println(msg);
1423
1424 //DebugStream.println(msg);
1425 }
1426
1427 public static void log(String msg, Exception e) { // Print stack trace on the exception
1428 //logger.error(msg, e);
1429
1430 System.err.println(msg);
1431 e.printStackTrace();
1432
1433 //DebugStream.println(msg);
1434 //DebugStream.printStackTrace(e);
1435 }
1436
1437 public static void log(Exception e) {
1438 //logger.error(e);
1439
1440 e.printStackTrace();
1441
1442 //DebugStream.printStackTrace(e);
1443 }
1444
1445 public static void log(String msg, Exception e, boolean printStackTrace) {
1446 if(printStackTrace) {
1447 log(msg, e);
1448 } else {
1449 log(msg);
1450 }
1451 }
1452
1453 public static String streamToString(int src) {
1454 String stream;
1455 switch(src) {
1456 case STDERR:
1457 stream = "stderr";
1458 break;
1459 case STDOUT:
1460 stream = "stdout";
1461 break;
1462 default:
1463 stream = "stdin";
1464 }
1465 return stream;
1466 }
1467
1468//**************** Useful static methods. Copied from GLI's Utility.java ******************
1469 // For safely closing streams/handles/resources.
1470 // For examples of use look in the Input- and OutputStreamGobbler classes.
1471 // http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
1472 // http://stackoverflow.com/questions/481446/throws-exception-in-finally-blocks
1473 public static boolean closeResource(Closeable resourceHandle) {
1474 boolean success = false;
1475 try {
1476 if(resourceHandle != null) {
1477 resourceHandle.close();
1478 resourceHandle = null;
1479 success = true;
1480 }
1481 } catch(Exception e) {
1482 log("Exception closing resource: " + e.getMessage(), e);
1483 resourceHandle = null;
1484 success = false;
1485 } finally {
1486 return success;
1487 }
1488 }
1489
1490 // in Java 6, Sockets don't yet implement Closeable
1491 public static boolean closeSocket(Socket resourceHandle) {
1492 boolean success = false;
1493 try {
1494 if(resourceHandle != null) {
1495 resourceHandle.close();
1496 resourceHandle = null;
1497 success = true;
1498 }
1499 } catch(Exception e) {
1500 log("Exception closing resource: " + e.getMessage(), e);
1501 resourceHandle = null;
1502 success = false;
1503 } finally {
1504 return success;
1505 }
1506 }
1507
1508 public static boolean closeProcess(Process prcs) {
1509 boolean success = true;
1510 if( prcs != null ) {
1511 success = success && closeResource(prcs.getErrorStream());
1512 success = success && closeResource(prcs.getOutputStream());
1513 success = success && closeResource(prcs.getInputStream());
1514 prcs.destroy();
1515 }
1516 return success;
1517 }
1518
1519// Moved from GShell.java
1520 /** Determine if the given process is still executing. It does this by attempting to throw an exception - not the most efficient way, but the only one as far as I know
1521 * @param process the Process to test
1522 * @return true if it is still executing, false otherwise
1523 */
1524 static public boolean processRunning(Process process) {
1525 boolean process_running = false;
1526
1527 try {
1528 process.exitValue(); // This will throw an exception if the process hasn't ended yet.
1529 }
1530 catch(IllegalThreadStateException itse) {
1531 process_running = true;
1532 }
1533 catch(Exception exception) {
1534 log(exception); // DebugStream.printStackTrace(exception);
1535 }
1536 return process_running;
1537 }
1538
1539} // end class SafeProcess
Note: See TracBrowser for help on using the repository browser.