source: main/trunk/greenstone3/src/java/org/greenstone/util/SafeProcess.java@ 31707

Last change on this file since 31707 was 31707, checked in by ak19, 7 years ago

Adding an option to cancelProcess() that allows you to force the caller, even if it's a GUI thread, to wait until the cancelProcess() method's end (which ends when the SafeProcess becomes interruptible). There's now a default cancelProcess() again, that takes no arguments, and this is what we call. It behaves as before: if called from a GUI thread, it won't wait for the SafeProcess to become interruptible.

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