1 package org
.argeo
.slc
.core
.execution
.tasks
;
4 import java
.io
.FileOutputStream
;
5 import java
.io
.FileWriter
;
6 import java
.io
.IOException
;
7 import java
.io
.InputStream
;
8 import java
.io
.OutputStream
;
9 import java
.io
.PipedInputStream
;
10 import java
.io
.PipedOutputStream
;
11 import java
.io
.Writer
;
12 import java
.util
.ArrayList
;
13 import java
.util
.Collections
;
14 import java
.util
.HashMap
;
15 import java
.util
.List
;
17 import java
.util
.UUID
;
19 import javax
.security
.auth
.callback
.CallbackHandler
;
21 import org
.apache
.commons
.exec
.CommandLine
;
22 import org
.apache
.commons
.exec
.DefaultExecutor
;
23 import org
.apache
.commons
.exec
.ExecuteException
;
24 import org
.apache
.commons
.exec
.ExecuteResultHandler
;
25 import org
.apache
.commons
.exec
.ExecuteStreamHandler
;
26 import org
.apache
.commons
.exec
.ExecuteWatchdog
;
27 import org
.apache
.commons
.exec
.Executor
;
28 import org
.apache
.commons
.exec
.LogOutputStream
;
29 import org
.apache
.commons
.exec
.PumpStreamHandler
;
30 import org
.apache
.commons
.exec
.ShutdownHookProcessDestroyer
;
31 import org
.apache
.commons
.io
.FileUtils
;
32 import org
.apache
.commons
.io
.IOUtils
;
33 import org
.apache
.commons
.logging
.Log
;
34 import org
.apache
.commons
.logging
.LogFactory
;
35 import org
.argeo
.slc
.SlcException
;
36 import org
.argeo
.slc
.UnsupportedException
;
37 import org
.argeo
.slc
.core
.execution
.ExecutionResources
;
38 import org
.argeo
.slc
.runtime
.test
.SimpleResultPart
;
39 import org
.argeo
.slc
.test
.TestResult
;
40 import org
.argeo
.slc
.test
.TestStatus
;
41 import org
.springframework
.core
.io
.Resource
;
43 /** Execute an OS specific system call. */
44 public class SystemCall
implements Runnable
{
45 public final static String LOG_STDOUT
= "System.out";
47 private final Log log
= LogFactory
.getLog(getClass());
49 private String execDir
;
51 private String cmd
= null;
52 private List
<Object
> command
= null;
54 private Executor executor
= new DefaultExecutor();
55 private Boolean synchronous
= true;
57 private String stdErrLogLevel
= "ERROR";
58 private String stdOutLogLevel
= "INFO";
60 private Resource stdOutFile
= null;
61 private Resource stdErrFile
= null;
63 private Resource stdInFile
= null;
65 * If no {@link #stdInFile} provided, writing to this stream will write to
66 * the stdin of the process.
68 private OutputStream stdInSink
= null;
70 private Boolean redirectStdOut
= false;
72 private List
<SystemCallOutputListener
> outputListeners
= Collections
73 .synchronizedList(new ArrayList
<SystemCallOutputListener
>());
75 private Map
<String
, List
<Object
>> osCommands
= new HashMap
<String
, List
<Object
>>();
76 private Map
<String
, String
> osCmds
= new HashMap
<String
, String
>();
77 private Map
<String
, String
> environmentVariables
= new HashMap
<String
, String
>();
79 private Boolean logCommand
= false;
80 private Boolean redirectStreams
= true;
81 private Boolean exceptionOnFailed
= true;
82 private Boolean mergeEnvironmentVariables
= true;
84 // private Authentication authentication;
86 private String osConsole
= null;
87 private String generateScript
= null;
90 private Long watchdogTimeout
= 24 * 60 * 60 * 1000l;
92 private TestResult testResult
;
94 private ExecutionResources executionResources
;
96 /** Sudo the command, as root if empty or as user if not. */
97 private String sudo
= null;
98 // TODO make it more secure and robust, test only once
99 private final String sudoPrompt
= UUID
.randomUUID().toString();
100 private String askPassProgram
= "/usr/libexec/openssh/ssh-askpass";
101 @SuppressWarnings("unused")
102 private boolean firstLine
= true;
103 @SuppressWarnings("unused")
104 private CallbackHandler callbackHandler
;
105 /** Chroot to the this path (must not be empty) */
106 private String chroot
= null;
109 /** Current watchdog, null if process is completed */
110 ExecuteWatchdog currentWatchdog
= null;
112 /** Empty constructor */
113 public SystemCall() {
118 * Constructor based on the provided command list.
123 public SystemCall(List
<Object
> command
) {
124 this.command
= command
;
128 * Constructor based on the provided command.
131 * the command. If the provided string contains no space a
132 * command list is initialized with the argument as first
133 * component (useful for chained construction)
135 public SystemCall(String cmd
) {
136 if (cmd
.indexOf(' ') < 0) {
137 command
= new ArrayList
<Object
>();
144 /** Executes the system call. */
146 // authentication = SecurityContextHolder.getContext().getAuthentication();
149 Writer stdOutWriter
= null;
150 OutputStream stdOutputStream
= null;
151 Writer stdErrWriter
= null;
152 InputStream stdInStream
= null;
153 if (stdOutFile
!= null)
155 stdOutputStream
= createOutputStream(stdOutFile
);
157 stdOutWriter
= createWriter(stdOutFile
, true);
159 if (stdErrFile
!= null) {
160 stdErrWriter
= createWriter(stdErrFile
, true);
162 if (stdOutFile
!= null && !redirectStdOut
)
163 stdErrWriter
= createWriter(stdOutFile
, true);
167 if (stdInFile
!= null)
168 stdInStream
= stdInFile
.getInputStream();
170 stdInStream
= new PipedInputStream();
171 stdInSink
= new PipedOutputStream(
172 (PipedInputStream
) stdInStream
);
174 } catch (IOException e2
) {
175 throw new SlcException("Cannot open a stream for " + stdInFile
, e2
);
178 if (log
.isTraceEnabled()) {
179 log
.debug("os.name=" + System
.getProperty("os.name"));
180 log
.debug("os.arch=" + System
.getProperty("os.arch"));
181 log
.debug("os.version=" + System
.getProperty("os.version"));
184 // Execution directory
185 File dir
= new File(getExecDirToUse());
186 // if (!dir.exists())
189 // Watchdog to check for lost processes
190 Executor executorToUse
;
191 if (executor
!= null)
192 executorToUse
= executor
;
194 executorToUse
= new DefaultExecutor();
195 executorToUse
.setWatchdog(createWatchdog());
197 if (redirectStreams
) {
198 // Redirect standard streams
199 executorToUse
.setStreamHandler(createExecuteStreamHandler(
200 stdOutWriter
, stdOutputStream
, stdErrWriter
, stdInStream
));
202 // Dummy stream handler (otherwise pump is used)
203 executorToUse
.setStreamHandler(new DummyexecuteStreamHandler());
206 executorToUse
.setProcessDestroyer(new ShutdownHookProcessDestroyer());
207 executorToUse
.setWorkingDirectory(dir
);
209 // Command line to use
210 final CommandLine commandLine
= createCommandLine();
212 log
.info("Execute command:\n" + commandLine
213 + "\n in working directory: \n" + dir
+ "\n");
216 Map
<String
, String
> environmentVariablesToUse
= null;
217 environmentVariablesToUse
= new HashMap
<String
, String
>();
218 if (mergeEnvironmentVariables
)
219 environmentVariablesToUse
.putAll(System
.getenv());
220 if (environmentVariables
.size() > 0)
221 environmentVariablesToUse
.putAll(environmentVariables
);
224 ExecuteResultHandler executeResultHandler
= createExecuteResultHandler(commandLine
);
227 // THE EXECUTION PROPER
232 int exitValue
= executorToUse
.execute(commandLine
,
233 environmentVariablesToUse
);
234 executeResultHandler
.onProcessComplete(exitValue
);
235 } catch (ExecuteException e1
) {
236 if (e1
.getExitValue() == Executor
.INVALID_EXITVALUE
) {
237 Thread
.currentThread().interrupt();
240 // Sleep 1s in order to make sure error logs are flushed
242 executeResultHandler
.onProcessFailed(e1
);
245 executorToUse
.execute(commandLine
, environmentVariablesToUse
,
246 executeResultHandler
);
247 } catch (SlcException e
) {
249 } catch (Exception e
) {
250 throw new SlcException("Could not execute command " + commandLine
,
253 IOUtils
.closeQuietly(stdOutWriter
);
254 IOUtils
.closeQuietly(stdErrWriter
);
255 IOUtils
.closeQuietly(stdInStream
);
256 IOUtils
.closeQuietly(stdInSink
);
261 public synchronized String
function() {
262 final StringBuffer buf
= new StringBuffer("");
263 SystemCallOutputListener tempOutputListener
= new SystemCallOutputListener() {
264 private Long lineCount
= 0l;
266 public void newLine(SystemCall systemCall
, String line
,
276 addOutputListener(tempOutputListener
);
278 removeOutputListener(tempOutputListener
);
279 return buf
.toString();
282 public String
asCommand() {
283 return createCommandLine().toString();
287 public String
toString() {
292 * Build a command line based on the properties. Can be overridden by
293 * specific command wrappers.
295 protected CommandLine
createCommandLine() {
296 // Check if an OS specific command overrides
297 String osName
= System
.getProperty("os.name");
298 List
<Object
> commandToUse
= null;
299 if (osCommands
.containsKey(osName
))
300 commandToUse
= osCommands
.get(osName
);
302 commandToUse
= command
;
303 String cmdToUse
= null;
304 if (osCmds
.containsKey(osName
))
305 cmdToUse
= osCmds
.get(osName
);
309 CommandLine commandLine
= null;
311 // Which command definition to use
312 if (commandToUse
== null && cmdToUse
== null)
313 throw new SlcException("Please specify a command.");
314 else if (commandToUse
!= null && cmdToUse
!= null)
315 throw new SlcException(
316 "Specify the command either as a line or as a list.");
317 else if (cmdToUse
!= null) {
318 if (chroot
!= null && !chroot
.trim().equals(""))
319 cmdToUse
= "chroot \"" + chroot
+ "\" " + cmdToUse
;
321 environmentVariables
.put("SUDO_ASKPASS", askPassProgram
);
322 if (!sudo
.trim().equals(""))
323 cmdToUse
= "sudo -p " + sudoPrompt
+ " -u " + sudo
+ " "
326 cmdToUse
= "sudo -p " + sudoPrompt
+ " " + cmdToUse
;
329 // GENERATE COMMAND LINE
330 commandLine
= CommandLine
.parse(cmdToUse
);
331 } else if (commandToUse
!= null) {
332 if (commandToUse
.size() == 0)
333 throw new SlcException("Command line is empty.");
335 if (chroot
!= null && sudo
!= null) {
336 commandToUse
.add(0, "chroot");
337 commandToUse
.add(1, chroot
);
341 environmentVariables
.put("SUDO_ASKPASS", askPassProgram
);
342 commandToUse
.add(0, "sudo");
343 commandToUse
.add(1, "-p");
344 commandToUse
.add(2, sudoPrompt
);
345 if (!sudo
.trim().equals("")) {
346 commandToUse
.add(3, "-u");
347 commandToUse
.add(4, sudo
);
351 // GENERATE COMMAND LINE
352 commandLine
= new CommandLine(commandToUse
.get(0).toString());
354 for (int i
= 1; i
< commandToUse
.size(); i
++) {
355 if (log
.isTraceEnabled())
356 log
.debug(commandToUse
.get(i
));
357 commandLine
.addArgument(commandToUse
.get(i
).toString());
360 // all cases covered previously
361 throw new UnsupportedException();
364 if (generateScript
!= null) {
365 File scriptFile
= new File(getExecDirToUse() + File
.separator
368 FileUtils
.writeStringToFile(scriptFile
,
369 (osConsole
!= null ? osConsole
+ " " : "")
370 + commandLine
.toString());
371 } catch (IOException e
) {
372 throw new SlcException("Could not generate script "
375 commandLine
= new CommandLine(scriptFile
);
377 if (osConsole
!= null)
378 commandLine
= CommandLine
.parse(osConsole
+ " "
379 + commandLine
.toString());
386 * Creates a {@link PumpStreamHandler} which redirects streams to the custom
389 protected ExecuteStreamHandler
createExecuteStreamHandler(
390 final Writer stdOutWriter
, final OutputStream stdOutputStream
,
391 final Writer stdErrWriter
, final InputStream stdInStream
) {
394 OutputStream stdout
= stdOutputStream
!= null ? stdOutputStream
395 : new LogOutputStream() {
396 protected void processLine(String line
, int level
) {
398 // if (sudo != null && callbackHandler != null
399 // && line.startsWith(sudoPrompt)) {
401 // PasswordCallback pc = new PasswordCallback(
402 // "sudo password", false);
403 // Callback[] cbs = { pc };
404 // callbackHandler.handle(cbs);
405 // char[] pwd = pc.getPassword();
406 // char[] arr = Arrays.copyOf(pwd,
408 // arr[arr.length - 1] = '\n';
409 // IOUtils.write(arr, stdInSink);
410 // stdInSink.flush();
411 // } catch (Exception e) {
412 // throw new SlcException(
413 // "Cannot retrieve sudo password", e);
416 // firstLine = false;
419 if (line
!= null && !line
.trim().equals(""))
422 if (stdOutWriter
!= null)
423 appendLineToFile(stdOutWriter
, line
);
427 OutputStream stderr
= new LogOutputStream() {
428 protected void processLine(String line
, int level
) {
429 if (line
!= null && !line
.trim().equals(""))
431 if (stdErrWriter
!= null)
432 appendLineToFile(stdErrWriter
, line
);
436 PumpStreamHandler pumpStreamHandler
= new PumpStreamHandler(stdout
,
437 stderr
, stdInStream
) {
440 public void stop() throws IOException
{
441 // prevents the method to block when joining stdin
442 if (stdInSink
!= null)
443 IOUtils
.closeQuietly(stdInSink
);
448 return pumpStreamHandler
;
451 /** Creates the default {@link ExecuteResultHandler}. */
452 protected ExecuteResultHandler
createExecuteResultHandler(
453 final CommandLine commandLine
) {
454 return new ExecuteResultHandler() {
456 public void onProcessComplete(int exitValue
) {
457 String msg
= "System call '" + commandLine
458 + "' properly completed.";
459 if (log
.isTraceEnabled())
461 if (testResult
!= null) {
462 forwardPath(testResult
);
463 testResult
.addResultPart(new SimpleResultPart(
464 TestStatus
.PASSED
, msg
));
469 public void onProcessFailed(ExecuteException e
) {
471 String msg
= "System call '" + commandLine
+ "' failed.";
472 if (testResult
!= null) {
473 forwardPath(testResult
);
474 testResult
.addResultPart(new SimpleResultPart(
475 TestStatus
.ERROR
, msg
, e
));
477 if (exceptionOnFailed
)
478 throw new SlcException(msg
, e
);
488 protected void forwardPath(TestResult testResult
) {
489 // TODO: allocate a TreeSPath
493 * Shortcut method getting the execDir to use
495 protected String
getExecDirToUse() {
497 if (execDir
!= null) {
500 return System
.getProperty("user.dir");
501 } catch (Exception e
) {
502 throw new SlcException("Cannot find exec dir", e
);
506 protected void logStdOut(String line
) {
507 for (SystemCallOutputListener outputListener
: outputListeners
)
508 outputListener
.newLine(this, line
, false);
509 log(stdOutLogLevel
, line
);
512 protected void logStdErr(String line
) {
513 for (SystemCallOutputListener outputListener
: outputListeners
)
514 outputListener
.newLine(this, line
, true);
515 log(stdErrLogLevel
, line
);
518 /** Log from the underlying streams. */
519 protected void log(String logLevel
, String line
) {
521 // if (SecurityContextHolder.getContext().getAuthentication() == null) {
522 // SecurityContextHolder.getContext()
523 // .setAuthentication(authentication);
526 if ("ERROR".equals(logLevel
))
528 else if ("WARN".equals(logLevel
))
530 else if ("INFO".equals(logLevel
))
532 else if ("DEBUG".equals(logLevel
))
534 else if ("TRACE".equals(logLevel
))
536 else if (LOG_STDOUT
.equals(logLevel
))
537 System
.out
.println(line
);
538 else if ("System.err".equals(logLevel
))
539 System
.err
.println(line
);
541 throw new SlcException("Unknown log level " + logLevel
);
544 /** Append line to a log file. */
545 protected void appendLineToFile(Writer writer
, String line
) {
547 writer
.append(line
).append('\n');
548 } catch (IOException e
) {
549 log
.error("Cannot write to log file", e
);
553 /** Creates the writer for the output/err files. */
554 protected Writer
createWriter(Resource target
, Boolean append
) {
555 FileWriter writer
= null;
559 if (executionResources
!= null)
560 file
= new File(executionResources
.getAsOsPath(target
, true));
562 file
= target
.getFile();
563 writer
= new FileWriter(file
, append
);
564 } catch (IOException e
) {
565 log
.error("Cannot get file for " + target
, e
);
566 IOUtils
.closeQuietly(writer
);
571 /** Creates an outputstream for the output/err files. */
572 protected OutputStream
createOutputStream(Resource target
) {
573 FileOutputStream out
= null;
577 if (executionResources
!= null)
578 file
= new File(executionResources
.getAsOsPath(target
, true));
580 file
= target
.getFile();
581 out
= new FileOutputStream(file
, false);
582 } catch (IOException e
) {
583 log
.error("Cannot get file for " + target
, e
);
584 IOUtils
.closeQuietly(out
);
589 /** Append the argument (for chaining) */
590 public SystemCall
arg(String arg
) {
592 command
= new ArrayList
<Object
>();
597 /** Append the argument (for chaining) */
598 public SystemCall
arg(String arg
, String value
) {
600 command
= new ArrayList
<Object
>();
607 public synchronized Boolean
isRunning() {
608 return currentWatchdog
!= null;
611 private synchronized ExecuteWatchdog
createWatchdog() {
612 // if (currentWatchdog != null)
613 // throw new SlcException("A process is already being monitored");
614 currentWatchdog
= new ExecuteWatchdog(watchdogTimeout
);
615 return currentWatchdog
;
618 private synchronized void releaseWatchdog() {
619 currentWatchdog
= null;
622 public synchronized void kill() {
623 if (currentWatchdog
!= null)
624 currentWatchdog
.destroyProcess();
628 public void setCmd(String command
) {
632 public void setCommand(List
<Object
> command
) {
633 this.command
= command
;
636 public void setExecDir(String execdir
) {
637 this.execDir
= execdir
;
640 public void setStdErrLogLevel(String stdErrLogLevel
) {
641 this.stdErrLogLevel
= stdErrLogLevel
;
644 public void setStdOutLogLevel(String stdOutLogLevel
) {
645 this.stdOutLogLevel
= stdOutLogLevel
;
648 public void setSynchronous(Boolean synchronous
) {
649 this.synchronous
= synchronous
;
652 public void setOsCommands(Map
<String
, List
<Object
>> osCommands
) {
653 this.osCommands
= osCommands
;
656 public void setOsCmds(Map
<String
, String
> osCmds
) {
657 this.osCmds
= osCmds
;
660 public void setEnvironmentVariables(Map
<String
, String
> environmentVariables
) {
661 this.environmentVariables
= environmentVariables
;
664 public Map
<String
, String
> getEnvironmentVariables() {
665 return environmentVariables
;
668 public void setWatchdogTimeout(Long watchdogTimeout
) {
669 this.watchdogTimeout
= watchdogTimeout
;
672 public void setStdOutFile(Resource stdOutFile
) {
673 this.stdOutFile
= stdOutFile
;
676 public void setStdErrFile(Resource stdErrFile
) {
677 this.stdErrFile
= stdErrFile
;
680 public void setStdInFile(Resource stdInFile
) {
681 this.stdInFile
= stdInFile
;
684 public void setTestResult(TestResult testResult
) {
685 this.testResult
= testResult
;
688 public void setLogCommand(Boolean logCommand
) {
689 this.logCommand
= logCommand
;
692 public void setRedirectStreams(Boolean redirectStreams
) {
693 this.redirectStreams
= redirectStreams
;
696 public void setExceptionOnFailed(Boolean exceptionOnFailed
) {
697 this.exceptionOnFailed
= exceptionOnFailed
;
700 public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables
) {
701 this.mergeEnvironmentVariables
= mergeEnvironmentVariables
;
704 public void setOsConsole(String osConsole
) {
705 this.osConsole
= osConsole
;
708 public void setGenerateScript(String generateScript
) {
709 this.generateScript
= generateScript
;
712 public void setExecutionResources(ExecutionResources executionResources
) {
713 this.executionResources
= executionResources
;
716 public void setRedirectStdOut(Boolean redirectStdOut
) {
717 this.redirectStdOut
= redirectStdOut
;
720 public void addOutputListener(SystemCallOutputListener outputListener
) {
721 outputListeners
.add(outputListener
);
724 public void removeOutputListener(SystemCallOutputListener outputListener
) {
725 outputListeners
.remove(outputListener
);
728 public void setOutputListeners(
729 List
<SystemCallOutputListener
> outputListeners
) {
730 this.outputListeners
= outputListeners
;
733 public void setExecutor(Executor executor
) {
734 this.executor
= executor
;
737 public void setSudo(String sudo
) {
741 public void setCallbackHandler(CallbackHandler callbackHandler
) {
742 this.callbackHandler
= callbackHandler
;
745 public void setChroot(String chroot
) {
746 this.chroot
= chroot
;
749 private class DummyexecuteStreamHandler
implements ExecuteStreamHandler
{
751 public void setProcessErrorStream(InputStream is
) throws IOException
{
754 public void setProcessInputStream(OutputStream os
) throws IOException
{
757 public void setProcessOutputStream(InputStream is
) throws IOException
{
760 public void start() throws IOException
{