2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.slc
.core
.execution
.tasks
;
19 import java
.io
.FileOutputStream
;
20 import java
.io
.FileWriter
;
21 import java
.io
.IOException
;
22 import java
.io
.InputStream
;
23 import java
.io
.OutputStream
;
24 import java
.io
.PipedInputStream
;
25 import java
.io
.PipedOutputStream
;
26 import java
.io
.Writer
;
27 import java
.util
.ArrayList
;
28 import java
.util
.Collections
;
29 import java
.util
.HashMap
;
30 import java
.util
.List
;
33 import org
.apache
.commons
.exec
.CommandLine
;
34 import org
.apache
.commons
.exec
.DefaultExecutor
;
35 import org
.apache
.commons
.exec
.ExecuteException
;
36 import org
.apache
.commons
.exec
.ExecuteResultHandler
;
37 import org
.apache
.commons
.exec
.ExecuteStreamHandler
;
38 import org
.apache
.commons
.exec
.ExecuteWatchdog
;
39 import org
.apache
.commons
.exec
.Executor
;
40 import org
.apache
.commons
.exec
.LogOutputStream
;
41 import org
.apache
.commons
.exec
.PumpStreamHandler
;
42 import org
.apache
.commons
.exec
.ShutdownHookProcessDestroyer
;
43 import org
.apache
.commons
.io
.FileUtils
;
44 import org
.apache
.commons
.io
.IOUtils
;
45 import org
.apache
.commons
.logging
.Log
;
46 import org
.apache
.commons
.logging
.LogFactory
;
47 import org
.argeo
.slc
.SlcException
;
48 import org
.argeo
.slc
.UnsupportedException
;
49 import org
.argeo
.slc
.core
.execution
.ExecutionResources
;
50 import org
.argeo
.slc
.core
.test
.SimpleResultPart
;
51 import org
.argeo
.slc
.test
.TestResult
;
52 import org
.argeo
.slc
.test
.TestStatus
;
53 import org
.springframework
.core
.io
.Resource
;
55 /** Execute an OS specific system call. */
56 public class SystemCall
implements Runnable
{
57 public final static String LOG_STDOUT
= "System.out";
59 private final Log log
= LogFactory
.getLog(getClass());
61 private String execDir
;
63 private String cmd
= null;
64 private List
<Object
> command
= null;
66 private Executor executor
= new DefaultExecutor();
67 private Boolean synchronous
= true;
69 private String stdErrLogLevel
= "ERROR";
70 private String stdOutLogLevel
= "INFO";
72 private Resource stdOutFile
= null;
73 private Resource stdErrFile
= null;
75 private Resource stdInFile
= null;
77 * If no {@link #stdInFile} provided, writing to this stream will write to
78 * the stdin of the process.
80 private OutputStream stdInSink
= null;
82 private Boolean redirectStdOut
= false;
84 private List
<SystemCallOutputListener
> outputListeners
= Collections
85 .synchronizedList(new ArrayList
<SystemCallOutputListener
>());
87 private Map
<String
, List
<Object
>> osCommands
= new HashMap
<String
, List
<Object
>>();
88 private Map
<String
, String
> osCmds
= new HashMap
<String
, String
>();
89 private Map
<String
, String
> environmentVariables
= new HashMap
<String
, String
>();
91 private Boolean logCommand
= false;
92 private Boolean redirectStreams
= true;
93 private Boolean exceptionOnFailed
= true;
94 private Boolean mergeEnvironmentVariables
= true;
96 private String osConsole
= null;
97 private String generateScript
= null;
100 private Long watchdogTimeout
= 24 * 60 * 60 * 1000l;
102 private TestResult testResult
;
104 private ExecutionResources executionResources
;
106 /** Empty constructor */
107 public SystemCall() {
112 * Constructor based on the provided command list.
117 public SystemCall(List
<Object
> command
) {
118 this.command
= command
;
122 * Constructor based on the provided command.
125 * the command. If the provided string contains no space a
126 * command list is initialized with the argument as first
127 * component (useful for chained construction)
129 public SystemCall(String cmd
) {
130 if (cmd
.indexOf(' ') < 0) {
131 command
= new ArrayList
<Object
>();
138 /** Executes the system call. */
141 Writer stdOutWriter
= null;
142 OutputStream stdOutputStream
= null;
143 Writer stdErrWriter
= null;
144 InputStream stdInStream
= null;
145 if (stdOutFile
!= null)
147 stdOutputStream
= createOutputStream(stdOutFile
);
149 stdOutWriter
= createWriter(stdOutFile
, true);
151 if (stdErrFile
!= null) {
152 stdErrWriter
= createWriter(stdErrFile
, true);
154 if (stdOutFile
!= null && !redirectStdOut
)
155 stdErrWriter
= createWriter(stdOutFile
, true);
159 if (stdInFile
!= null)
160 stdInStream
= stdInFile
.getInputStream();
162 stdInStream
= new PipedInputStream();
163 stdInSink
= new PipedOutputStream(
164 (PipedInputStream
) stdInStream
);
166 } catch (IOException e2
) {
167 throw new SlcException("Cannot open a stream for " + stdInFile
, e2
);
170 if (log
.isTraceEnabled()) {
171 log
.debug("os.name=" + System
.getProperty("os.name"));
172 log
.debug("os.arch=" + System
.getProperty("os.arch"));
173 log
.debug("os.version=" + System
.getProperty("os.version"));
176 // Execution directory
177 File dir
= new File(getExecDirToUse());
178 // if (!dir.exists())
181 // Watchdog to check for lost processes
182 Executor executorToUse
;
183 if (executor
!= null)
184 executorToUse
= executor
;
186 executorToUse
= new DefaultExecutor();
187 executorToUse
.setWatchdog(new ExecuteWatchdog(watchdogTimeout
));
189 if (redirectStreams
) {
190 // Redirect standard streams
191 executorToUse
.setStreamHandler(createExecuteStreamHandler(
192 stdOutWriter
, stdOutputStream
, stdErrWriter
, stdInStream
));
194 // Dummy stream handler (otherwise pump is used)
195 executorToUse
.setStreamHandler(new DummyexecuteStreamHandler());
198 executorToUse
.setProcessDestroyer(new ShutdownHookProcessDestroyer());
199 executorToUse
.setWorkingDirectory(dir
);
201 // Command line to use
202 final CommandLine commandLine
= createCommandLine();
204 log
.info("Execute command:\n" + commandLine
205 + "\n in working directory: \n" + dir
+ "\n");
208 Map
<String
, String
> environmentVariablesToUse
= null;
209 environmentVariablesToUse
= new HashMap
<String
, String
>();
210 if (mergeEnvironmentVariables
)
211 environmentVariablesToUse
.putAll(System
.getenv());
212 if (environmentVariables
.size() > 0)
213 environmentVariablesToUse
.putAll(environmentVariables
);
216 ExecuteResultHandler executeResultHandler
= createExecuteResultHandler(commandLine
);
219 // THE EXECUTION PROPER
224 int exitValue
= executorToUse
.execute(commandLine
,
225 environmentVariablesToUse
);
226 executeResultHandler
.onProcessComplete(exitValue
);
227 } catch (ExecuteException e1
) {
228 if (e1
.getExitValue() == Executor
.INVALID_EXITVALUE
) {
229 Thread
.currentThread().interrupt();
232 // Sleep 1s in order to make sure error logs are flushed
234 executeResultHandler
.onProcessFailed(e1
);
237 executorToUse
.execute(commandLine
, environmentVariablesToUse
,
238 executeResultHandler
);
239 } catch (SlcException e
) {
241 } catch (Exception e
) {
242 throw new SlcException("Could not execute command " + commandLine
,
245 IOUtils
.closeQuietly(stdOutWriter
);
246 IOUtils
.closeQuietly(stdErrWriter
);
247 IOUtils
.closeQuietly(stdInStream
);
248 IOUtils
.closeQuietly(stdInSink
);
253 public synchronized String
function() {
254 final StringBuffer buf
= new StringBuffer("");
255 SystemCallOutputListener tempOutputListener
= new SystemCallOutputListener() {
256 public void newLine(SystemCall systemCall
, String line
,
262 addOutputListener(tempOutputListener
);
264 removeOutputListener(tempOutputListener
);
265 return buf
.toString();
268 public String
asCommand() {
269 return createCommandLine().toString();
273 public String
toString() {
278 * Build a command line based on the properties. Can be overridden by
279 * specific command wrappers.
281 protected CommandLine
createCommandLine() {
282 // Check if an OS specific command overrides
283 String osName
= System
.getProperty("os.name");
284 List
<Object
> commandToUse
= null;
285 if (osCommands
.containsKey(osName
))
286 commandToUse
= osCommands
.get(osName
);
288 commandToUse
= command
;
289 String cmdToUse
= null;
290 if (osCmds
.containsKey(osName
))
291 cmdToUse
= osCmds
.get(osName
);
295 CommandLine commandLine
= null;
297 // Which command definition to use
298 if (commandToUse
== null && cmdToUse
== null)
299 throw new SlcException("Please specify a command.");
300 else if (commandToUse
!= null && cmdToUse
!= null)
301 throw new SlcException(
302 "Specify the command either as a line or as a list.");
303 else if (cmdToUse
!= null) {
304 commandLine
= CommandLine
.parse(cmdToUse
);
305 } else if (commandToUse
!= null) {
306 if (commandToUse
.size() == 0)
307 throw new SlcException("Command line is empty.");
309 commandLine
= new CommandLine(commandToUse
.get(0).toString());
311 for (int i
= 1; i
< commandToUse
.size(); i
++) {
312 if (log
.isTraceEnabled())
313 log
.debug(commandToUse
.get(i
));
314 commandLine
.addArgument(commandToUse
.get(i
).toString());
317 // all cases covered previously
318 throw new UnsupportedException();
321 if (generateScript
!= null) {
322 File scriptFile
= new File(getExecDirToUse() + File
.separator
325 FileUtils
.writeStringToFile(scriptFile
,
326 (osConsole
!= null ? osConsole
+ " " : "")
327 + commandLine
.toString());
328 } catch (IOException e
) {
329 throw new SlcException("Could not generate script "
332 commandLine
= new CommandLine(scriptFile
);
334 if (osConsole
!= null)
335 commandLine
= CommandLine
.parse(osConsole
+ " "
336 + commandLine
.toString());
343 * Creates a {@link PumpStreamHandler} which redirects streams to the custom
346 protected ExecuteStreamHandler
createExecuteStreamHandler(
347 final Writer stdOutWriter
, final OutputStream stdOutputStream
,
348 final Writer stdErrWriter
, final InputStream stdInStream
) {
352 PumpStreamHandler pumpStreamHandler
= new PumpStreamHandler(
353 stdOutputStream
!= null ? stdOutputStream
354 : new LogOutputStream() {
355 protected void processLine(String line
, int level
) {
356 if (line
!= null && !line
.trim().equals(""))
358 if (stdOutWriter
!= null)
359 appendLineToFile(stdOutWriter
, line
);
361 }, new LogOutputStream() {
362 protected void processLine(String line
, int level
) {
363 if (line
!= null && !line
.trim().equals(""))
365 if (stdErrWriter
!= null)
366 appendLineToFile(stdErrWriter
, line
);
372 // prevents the method to block when joining stdin
373 if (stdInSink
!= null)
374 IOUtils
.closeQuietly(stdInSink
);
379 return pumpStreamHandler
;
382 /** Creates the default {@link ExecuteResultHandler}. */
383 protected ExecuteResultHandler
createExecuteResultHandler(
384 final CommandLine commandLine
) {
385 return new ExecuteResultHandler() {
387 public void onProcessComplete(int exitValue
) {
388 String msg
= "System call '" + commandLine
389 + "' properly completed.";
390 if (log
.isTraceEnabled())
392 if (testResult
!= null) {
393 forwardPath(testResult
);
394 testResult
.addResultPart(new SimpleResultPart(
395 TestStatus
.PASSED
, msg
));
399 public void onProcessFailed(ExecuteException e
) {
401 String msg
= "System call '" + commandLine
+ "' failed.";
402 if (testResult
!= null) {
403 forwardPath(testResult
);
404 testResult
.addResultPart(new SimpleResultPart(
405 TestStatus
.ERROR
, msg
, e
));
407 if (exceptionOnFailed
)
408 throw new SlcException(msg
, e
);
416 protected void forwardPath(TestResult testResult
) {
417 // TODO: allocate a TreeSPath
421 * Shortcut method getting the execDir to use
423 protected String
getExecDirToUse() {
425 if (execDir
!= null) {
428 return System
.getProperty("user.dir");
429 } catch (Exception e
) {
430 throw new SlcException("Cannot find exec dir", e
);
434 protected void logStdOut(String line
) {
435 for (SystemCallOutputListener outputListener
: outputListeners
)
436 outputListener
.newLine(this, line
, false);
437 log(stdOutLogLevel
, line
);
440 protected void logStdErr(String line
) {
441 for (SystemCallOutputListener outputListener
: outputListeners
)
442 outputListener
.newLine(this, line
, true);
443 log(stdErrLogLevel
, line
);
446 /** Log from the underlying streams. */
447 protected void log(String logLevel
, String line
) {
448 if ("ERROR".equals(logLevel
))
450 else if ("WARN".equals(logLevel
))
452 else if ("INFO".equals(logLevel
))
454 else if ("DEBUG".equals(logLevel
))
456 else if ("TRACE".equals(logLevel
))
458 else if (LOG_STDOUT
.equals(logLevel
))
459 System
.out
.println(line
);
460 else if ("System.err".equals(logLevel
))
461 System
.err
.println(line
);
463 throw new SlcException("Unknown log level " + logLevel
);
466 /** Append line to a log file. */
467 protected void appendLineToFile(Writer writer
, String line
) {
469 writer
.append(line
).append('\n');
470 } catch (IOException e
) {
471 log
.error("Cannot write to log file", e
);
475 /** Creates the writer for the output/err files. */
476 protected Writer
createWriter(Resource target
, Boolean append
) {
477 FileWriter writer
= null;
481 if (executionResources
!= null)
482 file
= new File(executionResources
.getAsOsPath(target
, true));
484 file
= target
.getFile();
485 writer
= new FileWriter(file
, append
);
486 } catch (IOException e
) {
487 log
.error("Cannot get file for " + target
, e
);
488 IOUtils
.closeQuietly(writer
);
493 /** Creates an outputstream for the output/err files. */
494 protected OutputStream
createOutputStream(Resource target
) {
495 FileOutputStream out
= null;
499 if (executionResources
!= null)
500 file
= new File(executionResources
.getAsOsPath(target
, true));
502 file
= target
.getFile();
503 out
= new FileOutputStream(file
, false);
504 } catch (IOException e
) {
505 log
.error("Cannot get file for " + target
, e
);
506 IOUtils
.closeQuietly(out
);
511 /** Append the argument (for chaining) */
512 public SystemCall
arg(String arg
) {
514 command
= new ArrayList
<Object
>();
519 /** Append the argument (for chaining) */
520 public SystemCall
arg(String arg
, String value
) {
522 command
= new ArrayList
<Object
>();
529 public void setCmd(String command
) {
533 public void setCommand(List
<Object
> command
) {
534 this.command
= command
;
537 public void setExecDir(String execdir
) {
538 this.execDir
= execdir
;
541 public void setStdErrLogLevel(String stdErrLogLevel
) {
542 this.stdErrLogLevel
= stdErrLogLevel
;
545 public void setStdOutLogLevel(String stdOutLogLevel
) {
546 this.stdOutLogLevel
= stdOutLogLevel
;
549 public void setSynchronous(Boolean synchronous
) {
550 this.synchronous
= synchronous
;
553 public void setOsCommands(Map
<String
, List
<Object
>> osCommands
) {
554 this.osCommands
= osCommands
;
557 public void setOsCmds(Map
<String
, String
> osCmds
) {
558 this.osCmds
= osCmds
;
561 public void setEnvironmentVariables(Map
<String
, String
> environmentVariables
) {
562 this.environmentVariables
= environmentVariables
;
565 public void setWatchdogTimeout(Long watchdogTimeout
) {
566 this.watchdogTimeout
= watchdogTimeout
;
569 public void setStdOutFile(Resource stdOutFile
) {
570 this.stdOutFile
= stdOutFile
;
573 public void setStdErrFile(Resource stdErrFile
) {
574 this.stdErrFile
= stdErrFile
;
577 public void setStdInFile(Resource stdInFile
) {
578 this.stdInFile
= stdInFile
;
581 public void setTestResult(TestResult testResult
) {
582 this.testResult
= testResult
;
585 public void setLogCommand(Boolean logCommand
) {
586 this.logCommand
= logCommand
;
589 public void setRedirectStreams(Boolean redirectStreams
) {
590 this.redirectStreams
= redirectStreams
;
593 public void setExceptionOnFailed(Boolean exceptionOnFailed
) {
594 this.exceptionOnFailed
= exceptionOnFailed
;
597 public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables
) {
598 this.mergeEnvironmentVariables
= mergeEnvironmentVariables
;
601 public void setOsConsole(String osConsole
) {
602 this.osConsole
= osConsole
;
605 public void setGenerateScript(String generateScript
) {
606 this.generateScript
= generateScript
;
609 public void setExecutionResources(ExecutionResources executionResources
) {
610 this.executionResources
= executionResources
;
613 public void setRedirectStdOut(Boolean redirectStdOut
) {
614 this.redirectStdOut
= redirectStdOut
;
617 public void addOutputListener(SystemCallOutputListener outputListener
) {
618 outputListeners
.add(outputListener
);
621 public void removeOutputListener(SystemCallOutputListener outputListener
) {
622 outputListeners
.remove(outputListener
);
625 public void setOutputListeners(
626 List
<SystemCallOutputListener
> outputListeners
) {
627 this.outputListeners
= outputListeners
;
630 public void setExecutor(Executor executor
) {
631 this.executor
= executor
;
634 private class DummyexecuteStreamHandler
implements ExecuteStreamHandler
{
636 public void setProcessErrorStream(InputStream is
) throws IOException
{
639 public void setProcessInputStream(OutputStream os
) throws IOException
{
642 public void setProcessOutputStream(InputStream is
) throws IOException
{
645 public void start() throws IOException
{