1 package org
.argeo
.slc
.runtime
.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
.nio
.file
.Files
;
13 import java
.nio
.file
.Path
;
14 import java
.util
.ArrayList
;
15 import java
.util
.Collections
;
16 import java
.util
.HashMap
;
17 import java
.util
.List
;
19 import java
.util
.UUID
;
21 import javax
.security
.auth
.callback
.CallbackHandler
;
23 import org
.apache
.commons
.exec
.CommandLine
;
24 import org
.apache
.commons
.exec
.DefaultExecutor
;
25 import org
.apache
.commons
.exec
.ExecuteException
;
26 import org
.apache
.commons
.exec
.ExecuteResultHandler
;
27 import org
.apache
.commons
.exec
.ExecuteStreamHandler
;
28 import org
.apache
.commons
.exec
.ExecuteWatchdog
;
29 import org
.apache
.commons
.exec
.Executor
;
30 import org
.apache
.commons
.exec
.LogOutputStream
;
31 import org
.apache
.commons
.exec
.PumpStreamHandler
;
32 import org
.apache
.commons
.exec
.ShutdownHookProcessDestroyer
;
33 import org
.apache
.commons
.io
.FileUtils
;
34 import org
.apache
.commons
.io
.IOUtils
;
35 import org
.apache
.commons
.logging
.Log
;
36 import org
.apache
.commons
.logging
.LogFactory
;
37 import org
.argeo
.slc
.SlcException
;
38 import org
.argeo
.slc
.UnsupportedException
;
39 import org
.argeo
.slc
.execution
.ExecutionResources
;
40 import org
.argeo
.slc
.runtime
.test
.SimpleResultPart
;
41 import org
.argeo
.slc
.test
.TestResult
;
42 import org
.argeo
.slc
.test
.TestStatus
;
44 /** Execute an OS specific system call. */
45 public class SystemCall
implements Runnable
{
46 public final static String LOG_STDOUT
= "System.out";
48 private final Log log
= LogFactory
.getLog(getClass());
50 private String execDir
;
52 private String cmd
= null;
53 private List
<Object
> command
= null;
55 private Executor executor
= new DefaultExecutor();
56 private Boolean synchronous
= true;
58 private String stdErrLogLevel
= "ERROR";
59 private String stdOutLogLevel
= "INFO";
61 private Path stdOutFile
= null;
62 private Path stdErrFile
= null;
64 private Path stdInFile
= null;
66 * If no {@link #stdInFile} provided, writing to this stream will write to the
67 * stdin of the process.
69 private OutputStream stdInSink
= null;
71 private Boolean redirectStdOut
= false;
73 private List
<SystemCallOutputListener
> outputListeners
= Collections
74 .synchronizedList(new ArrayList
<SystemCallOutputListener
>());
76 private Map
<String
, List
<Object
>> osCommands
= new HashMap
<String
, List
<Object
>>();
77 private Map
<String
, String
> osCmds
= new HashMap
<String
, String
>();
78 private Map
<String
, String
> environmentVariables
= new HashMap
<String
, String
>();
80 private Boolean logCommand
= false;
81 private Boolean redirectStreams
= true;
82 private Boolean exceptionOnFailed
= true;
83 private Boolean mergeEnvironmentVariables
= true;
85 // private Authentication authentication;
87 private String osConsole
= null;
88 private String generateScript
= null;
91 private Long watchdogTimeout
= 24 * 60 * 60 * 1000l;
93 private TestResult testResult
;
95 private ExecutionResources executionResources
;
97 /** Sudo the command, as root if empty or as user if not. */
98 private String sudo
= null;
99 // TODO make it more secure and robust, test only once
100 private final String sudoPrompt
= UUID
.randomUUID().toString();
101 private String askPassProgram
= "/usr/libexec/openssh/ssh-askpass";
102 @SuppressWarnings("unused")
103 private boolean firstLine
= true;
104 @SuppressWarnings("unused")
105 private CallbackHandler callbackHandler
;
106 /** Chroot to the this path (must not be empty) */
107 private String chroot
= null;
110 /** Current watchdog, null if process is completed */
111 ExecuteWatchdog currentWatchdog
= null;
113 /** Empty constructor */
114 public SystemCall() {
119 * Constructor based on the provided command list.
121 * @param command the command list
123 public SystemCall(List
<Object
> command
) {
124 this.command
= command
;
128 * Constructor based on the provided command.
130 * @param cmd the command. If the provided string contains no space a command
131 * list is initialized with the argument as first component (useful
132 * for chained construction)
134 public SystemCall(String cmd
) {
135 if (cmd
.indexOf(' ') < 0) {
136 command
= new ArrayList
<Object
>();
143 /** Executes the system call. */
145 // authentication = SecurityContextHolder.getContext().getAuthentication();
148 Writer stdOutWriter
= null;
149 OutputStream stdOutputStream
= null;
150 Writer stdErrWriter
= null;
151 InputStream stdInStream
= null;
152 if (stdOutFile
!= null)
154 stdOutputStream
= createOutputStream(stdOutFile
);
156 stdOutWriter
= createWriter(stdOutFile
, true);
158 if (stdErrFile
!= null) {
159 stdErrWriter
= createWriter(stdErrFile
, true);
161 if (stdOutFile
!= null && !redirectStdOut
)
162 stdErrWriter
= createWriter(stdOutFile
, true);
166 if (stdInFile
!= null)
167 stdInStream
= Files
.newInputStream(stdInFile
);
169 stdInStream
= new PipedInputStream();
170 stdInSink
= new PipedOutputStream((PipedInputStream
) stdInStream
);
172 } catch (IOException e2
) {
173 throw new SlcException("Cannot open a stream for " + stdInFile
, e2
);
176 if (log
.isTraceEnabled()) {
177 log
.debug("os.name=" + System
.getProperty("os.name"));
178 log
.debug("os.arch=" + System
.getProperty("os.arch"));
179 log
.debug("os.version=" + System
.getProperty("os.version"));
182 // Execution directory
183 File dir
= new File(getExecDirToUse());
184 // if (!dir.exists())
187 // Watchdog to check for lost processes
188 Executor executorToUse
;
189 if (executor
!= null)
190 executorToUse
= executor
;
192 executorToUse
= new DefaultExecutor();
193 executorToUse
.setWatchdog(createWatchdog());
195 if (redirectStreams
) {
196 // Redirect standard streams
197 executorToUse
.setStreamHandler(
198 createExecuteStreamHandler(stdOutWriter
, stdOutputStream
, stdErrWriter
, stdInStream
));
200 // Dummy stream handler (otherwise pump is used)
201 executorToUse
.setStreamHandler(new DummyexecuteStreamHandler());
204 executorToUse
.setProcessDestroyer(new ShutdownHookProcessDestroyer());
205 executorToUse
.setWorkingDirectory(dir
);
207 // Command line to use
208 final CommandLine commandLine
= createCommandLine();
210 log
.info("Execute command:\n" + commandLine
+ "\n in working directory: \n" + dir
+ "\n");
213 Map
<String
, String
> environmentVariablesToUse
= null;
214 environmentVariablesToUse
= new HashMap
<String
, String
>();
215 if (mergeEnvironmentVariables
)
216 environmentVariablesToUse
.putAll(System
.getenv());
217 if (environmentVariables
.size() > 0)
218 environmentVariablesToUse
.putAll(environmentVariables
);
221 ExecuteResultHandler executeResultHandler
= createExecuteResultHandler(commandLine
);
224 // THE EXECUTION PROPER
229 int exitValue
= executorToUse
.execute(commandLine
, environmentVariablesToUse
);
230 executeResultHandler
.onProcessComplete(exitValue
);
231 } catch (ExecuteException e1
) {
232 if (e1
.getExitValue() == Executor
.INVALID_EXITVALUE
) {
233 Thread
.currentThread().interrupt();
236 // Sleep 1s in order to make sure error logs are flushed
238 executeResultHandler
.onProcessFailed(e1
);
241 executorToUse
.execute(commandLine
, environmentVariablesToUse
, executeResultHandler
);
242 } catch (SlcException e
) {
244 } catch (Exception e
) {
245 throw new SlcException("Could not execute command " + commandLine
, e
);
247 IOUtils
.closeQuietly(stdOutWriter
);
248 IOUtils
.closeQuietly(stdErrWriter
);
249 IOUtils
.closeQuietly(stdInStream
);
250 IOUtils
.closeQuietly(stdInSink
);
255 public synchronized String
function() {
256 final StringBuffer buf
= new StringBuffer("");
257 SystemCallOutputListener tempOutputListener
= new SystemCallOutputListener() {
258 private Long lineCount
= 0l;
260 public void newLine(SystemCall systemCall
, String line
, Boolean isError
) {
269 addOutputListener(tempOutputListener
);
271 removeOutputListener(tempOutputListener
);
272 return buf
.toString();
275 public String
asCommand() {
276 return createCommandLine().toString();
280 public String
toString() {
285 * Build a command line based on the properties. Can be overridden by specific
288 protected CommandLine
createCommandLine() {
289 // Check if an OS specific command overrides
290 String osName
= System
.getProperty("os.name");
291 List
<Object
> commandToUse
= null;
292 if (osCommands
.containsKey(osName
))
293 commandToUse
= osCommands
.get(osName
);
295 commandToUse
= command
;
296 String cmdToUse
= null;
297 if (osCmds
.containsKey(osName
))
298 cmdToUse
= osCmds
.get(osName
);
302 CommandLine commandLine
= null;
304 // Which command definition to use
305 if (commandToUse
== null && cmdToUse
== null)
306 throw new SlcException("Please specify a command.");
307 else if (commandToUse
!= null && cmdToUse
!= null)
308 throw new SlcException("Specify the command either as a line or as a list.");
309 else if (cmdToUse
!= null) {
310 if (chroot
!= null && !chroot
.trim().equals(""))
311 cmdToUse
= "chroot \"" + chroot
+ "\" " + cmdToUse
;
313 environmentVariables
.put("SUDO_ASKPASS", askPassProgram
);
314 if (!sudo
.trim().equals(""))
315 cmdToUse
= "sudo -p " + sudoPrompt
+ " -u " + sudo
+ " " + cmdToUse
;
317 cmdToUse
= "sudo -p " + sudoPrompt
+ " " + cmdToUse
;
320 // GENERATE COMMAND LINE
321 commandLine
= CommandLine
.parse(cmdToUse
);
322 } else if (commandToUse
!= null) {
323 if (commandToUse
.size() == 0)
324 throw new SlcException("Command line is empty.");
326 if (chroot
!= null && sudo
!= null) {
327 commandToUse
.add(0, "chroot");
328 commandToUse
.add(1, chroot
);
332 environmentVariables
.put("SUDO_ASKPASS", askPassProgram
);
333 commandToUse
.add(0, "sudo");
334 commandToUse
.add(1, "-p");
335 commandToUse
.add(2, sudoPrompt
);
336 if (!sudo
.trim().equals("")) {
337 commandToUse
.add(3, "-u");
338 commandToUse
.add(4, sudo
);
342 // GENERATE COMMAND LINE
343 commandLine
= new CommandLine(commandToUse
.get(0).toString());
345 for (int i
= 1; i
< commandToUse
.size(); i
++) {
346 if (log
.isTraceEnabled())
347 log
.debug(commandToUse
.get(i
));
348 commandLine
.addArgument(commandToUse
.get(i
).toString());
351 // all cases covered previously
352 throw new UnsupportedException();
355 if (generateScript
!= null) {
356 File scriptFile
= new File(getExecDirToUse() + File
.separator
+ generateScript
);
358 FileUtils
.writeStringToFile(scriptFile
,
359 (osConsole
!= null ? osConsole
+ " " : "") + commandLine
.toString());
360 } catch (IOException e
) {
361 throw new SlcException("Could not generate script " + scriptFile
, e
);
363 commandLine
= new CommandLine(scriptFile
);
365 if (osConsole
!= null)
366 commandLine
= CommandLine
.parse(osConsole
+ " " + commandLine
.toString());
373 * Creates a {@link PumpStreamHandler} which redirects streams to the custom
376 protected ExecuteStreamHandler
createExecuteStreamHandler(final Writer stdOutWriter
,
377 final OutputStream stdOutputStream
, final Writer stdErrWriter
, final InputStream stdInStream
) {
380 OutputStream stdout
= stdOutputStream
!= null ? stdOutputStream
: new LogOutputStream() {
381 protected void processLine(String line
, int level
) {
383 // if (sudo != null && callbackHandler != null
384 // && line.startsWith(sudoPrompt)) {
386 // PasswordCallback pc = new PasswordCallback(
387 // "sudo password", false);
388 // Callback[] cbs = { pc };
389 // callbackHandler.handle(cbs);
390 // char[] pwd = pc.getPassword();
391 // char[] arr = Arrays.copyOf(pwd,
393 // arr[arr.length - 1] = '\n';
394 // IOUtils.write(arr, stdInSink);
395 // stdInSink.flush();
396 // } catch (Exception e) {
397 // throw new SlcException(
398 // "Cannot retrieve sudo password", e);
401 // firstLine = false;
404 if (line
!= null && !line
.trim().equals(""))
407 if (stdOutWriter
!= null)
408 appendLineToFile(stdOutWriter
, line
);
412 OutputStream stderr
= new LogOutputStream() {
413 protected void processLine(String line
, int level
) {
414 if (line
!= null && !line
.trim().equals(""))
416 if (stdErrWriter
!= null)
417 appendLineToFile(stdErrWriter
, line
);
421 PumpStreamHandler pumpStreamHandler
= new PumpStreamHandler(stdout
, stderr
, stdInStream
) {
424 public void stop() throws IOException
{
425 // prevents the method to block when joining stdin
426 if (stdInSink
!= null)
427 IOUtils
.closeQuietly(stdInSink
);
432 return pumpStreamHandler
;
435 /** Creates the default {@link ExecuteResultHandler}. */
436 protected ExecuteResultHandler
createExecuteResultHandler(final CommandLine commandLine
) {
437 return new ExecuteResultHandler() {
439 public void onProcessComplete(int exitValue
) {
440 String msg
= "System call '" + commandLine
+ "' properly completed.";
441 if (log
.isTraceEnabled())
443 if (testResult
!= null) {
444 forwardPath(testResult
);
445 testResult
.addResultPart(new SimpleResultPart(TestStatus
.PASSED
, msg
));
450 public void onProcessFailed(ExecuteException e
) {
452 String msg
= "System call '" + commandLine
+ "' failed.";
453 if (testResult
!= null) {
454 forwardPath(testResult
);
455 testResult
.addResultPart(new SimpleResultPart(TestStatus
.ERROR
, msg
, e
));
457 if (exceptionOnFailed
)
458 throw new SlcException(msg
, e
);
468 protected void forwardPath(TestResult testResult
) {
469 // TODO: allocate a TreeSPath
473 * Shortcut method getting the execDir to use
475 protected String
getExecDirToUse() {
477 if (execDir
!= null) {
480 return System
.getProperty("user.dir");
481 } catch (Exception e
) {
482 throw new SlcException("Cannot find exec dir", e
);
486 protected void logStdOut(String line
) {
487 for (SystemCallOutputListener outputListener
: outputListeners
)
488 outputListener
.newLine(this, line
, false);
489 log(stdOutLogLevel
, line
);
492 protected void logStdErr(String line
) {
493 for (SystemCallOutputListener outputListener
: outputListeners
)
494 outputListener
.newLine(this, line
, true);
495 log(stdErrLogLevel
, line
);
498 /** Log from the underlying streams. */
499 protected void log(String logLevel
, String line
) {
501 // if (SecurityContextHolder.getContext().getAuthentication() == null) {
502 // SecurityContextHolder.getContext()
503 // .setAuthentication(authentication);
506 if ("ERROR".equals(logLevel
))
508 else if ("WARN".equals(logLevel
))
510 else if ("INFO".equals(logLevel
))
512 else if ("DEBUG".equals(logLevel
))
514 else if ("TRACE".equals(logLevel
))
516 else if (LOG_STDOUT
.equals(logLevel
))
517 System
.out
.println(line
);
518 else if ("System.err".equals(logLevel
))
519 System
.err
.println(line
);
521 throw new SlcException("Unknown log level " + logLevel
);
524 /** Append line to a log file. */
525 protected void appendLineToFile(Writer writer
, String line
) {
527 writer
.append(line
).append('\n');
528 } catch (IOException e
) {
529 log
.error("Cannot write to log file", e
);
533 /** Creates the writer for the output/err files. */
534 protected Writer
createWriter(Path target
, Boolean append
) {
535 FileWriter writer
= null;
539 if (executionResources
!= null)
540 file
= new File(executionResources
.getAsOsPath(target
, true));
542 file
= target
.toFile();
543 writer
= new FileWriter(file
, append
);
544 } catch (IOException e
) {
545 log
.error("Cannot get file for " + target
, e
);
546 IOUtils
.closeQuietly(writer
);
551 /** Creates an outputstream for the output/err files. */
552 protected OutputStream
createOutputStream(Path target
) {
553 FileOutputStream out
= null;
557 if (executionResources
!= null)
558 file
= new File(executionResources
.getAsOsPath(target
, true));
560 file
= target
.toFile();
561 out
= new FileOutputStream(file
, false);
562 } catch (IOException e
) {
563 log
.error("Cannot get file for " + target
, e
);
564 IOUtils
.closeQuietly(out
);
569 /** Append the argument (for chaining) */
570 public SystemCall
arg(String arg
) {
572 command
= new ArrayList
<Object
>();
577 /** Append the argument (for chaining) */
578 public SystemCall
arg(String arg
, String value
) {
580 command
= new ArrayList
<Object
>();
587 public synchronized Boolean
isRunning() {
588 return currentWatchdog
!= null;
591 private synchronized ExecuteWatchdog
createWatchdog() {
592 // if (currentWatchdog != null)
593 // throw new SlcException("A process is already being monitored");
594 currentWatchdog
= new ExecuteWatchdog(watchdogTimeout
);
595 return currentWatchdog
;
598 private synchronized void releaseWatchdog() {
599 currentWatchdog
= null;
602 public synchronized void kill() {
603 if (currentWatchdog
!= null)
604 currentWatchdog
.destroyProcess();
608 public void setCmd(String command
) {
612 public void setCommand(List
<Object
> command
) {
613 this.command
= command
;
616 public void setExecDir(String execdir
) {
617 this.execDir
= execdir
;
620 public void setStdErrLogLevel(String stdErrLogLevel
) {
621 this.stdErrLogLevel
= stdErrLogLevel
;
624 public void setStdOutLogLevel(String stdOutLogLevel
) {
625 this.stdOutLogLevel
= stdOutLogLevel
;
628 public void setSynchronous(Boolean synchronous
) {
629 this.synchronous
= synchronous
;
632 public void setOsCommands(Map
<String
, List
<Object
>> osCommands
) {
633 this.osCommands
= osCommands
;
636 public void setOsCmds(Map
<String
, String
> osCmds
) {
637 this.osCmds
= osCmds
;
640 public void setEnvironmentVariables(Map
<String
, String
> environmentVariables
) {
641 this.environmentVariables
= environmentVariables
;
644 public Map
<String
, String
> getEnvironmentVariables() {
645 return environmentVariables
;
648 public void setWatchdogTimeout(Long watchdogTimeout
) {
649 this.watchdogTimeout
= watchdogTimeout
;
652 public void setStdOutFile(Path stdOutFile
) {
653 this.stdOutFile
= stdOutFile
;
656 public void setStdErrFile(Path stdErrFile
) {
657 this.stdErrFile
= stdErrFile
;
660 public void setStdInFile(Path stdInFile
) {
661 this.stdInFile
= stdInFile
;
664 public void setTestResult(TestResult testResult
) {
665 this.testResult
= testResult
;
668 public void setLogCommand(Boolean logCommand
) {
669 this.logCommand
= logCommand
;
672 public void setRedirectStreams(Boolean redirectStreams
) {
673 this.redirectStreams
= redirectStreams
;
676 public void setExceptionOnFailed(Boolean exceptionOnFailed
) {
677 this.exceptionOnFailed
= exceptionOnFailed
;
680 public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables
) {
681 this.mergeEnvironmentVariables
= mergeEnvironmentVariables
;
684 public void setOsConsole(String osConsole
) {
685 this.osConsole
= osConsole
;
688 public void setGenerateScript(String generateScript
) {
689 this.generateScript
= generateScript
;
692 public void setExecutionResources(ExecutionResources executionResources
) {
693 this.executionResources
= executionResources
;
696 public void setRedirectStdOut(Boolean redirectStdOut
) {
697 this.redirectStdOut
= redirectStdOut
;
700 public void addOutputListener(SystemCallOutputListener outputListener
) {
701 outputListeners
.add(outputListener
);
704 public void removeOutputListener(SystemCallOutputListener outputListener
) {
705 outputListeners
.remove(outputListener
);
708 public void setOutputListeners(List
<SystemCallOutputListener
> outputListeners
) {
709 this.outputListeners
= outputListeners
;
712 public void setExecutor(Executor executor
) {
713 this.executor
= executor
;
716 public void setSudo(String sudo
) {
720 public void setCallbackHandler(CallbackHandler callbackHandler
) {
721 this.callbackHandler
= callbackHandler
;
724 public void setChroot(String chroot
) {
725 this.chroot
= chroot
;
728 private class DummyexecuteStreamHandler
implements ExecuteStreamHandler
{
730 public void setProcessErrorStream(InputStream is
) throws IOException
{
733 public void setProcessInputStream(OutputStream os
) throws IOException
{
736 public void setProcessOutputStream(InputStream is
) throws IOException
{
739 public void start() throws IOException
{