2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
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.
17 package org
.argeo
.slc
.core
.execution
.tasks
;
20 import java
.io
.FileOutputStream
;
21 import java
.io
.FileWriter
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.io
.OutputStream
;
25 import java
.io
.Writer
;
26 import java
.util
.ArrayList
;
27 import java
.util
.Collections
;
28 import java
.util
.HashMap
;
29 import java
.util
.List
;
32 import org
.apache
.commons
.exec
.CommandLine
;
33 import org
.apache
.commons
.exec
.DefaultExecutor
;
34 import org
.apache
.commons
.exec
.ExecuteException
;
35 import org
.apache
.commons
.exec
.ExecuteResultHandler
;
36 import org
.apache
.commons
.exec
.ExecuteStreamHandler
;
37 import org
.apache
.commons
.exec
.ExecuteWatchdog
;
38 import org
.apache
.commons
.exec
.Executor
;
39 import org
.apache
.commons
.exec
.LogOutputStream
;
40 import org
.apache
.commons
.exec
.PumpStreamHandler
;
41 import org
.apache
.commons
.exec
.ShutdownHookProcessDestroyer
;
42 import org
.apache
.commons
.io
.FileUtils
;
43 import org
.apache
.commons
.io
.IOUtils
;
44 import org
.apache
.commons
.logging
.Log
;
45 import org
.apache
.commons
.logging
.LogFactory
;
46 import org
.argeo
.slc
.SlcException
;
47 import org
.argeo
.slc
.UnsupportedException
;
48 import org
.argeo
.slc
.core
.execution
.ExecutionResources
;
49 import org
.argeo
.slc
.core
.test
.SimpleResultPart
;
50 import org
.argeo
.slc
.test
.TestResult
;
51 import org
.argeo
.slc
.test
.TestStatus
;
52 import org
.springframework
.core
.io
.Resource
;
54 /** Execute an OS specific system call. */
55 public class SystemCall
implements Runnable
{
56 public final static String LOG_STDOUT
= "System.out";
58 private final Log log
= LogFactory
.getLog(getClass());
60 private String execDir
;
62 private String cmd
= null;
63 private List
<Object
> command
= null;
65 private Boolean synchronous
= true;
67 private String stdErrLogLevel
= "ERROR";
68 private String stdOutLogLevel
= "INFO";
70 private Resource stdOutFile
= null;
71 private Resource stdErrFile
= null;
72 private Resource stdInFile
= null;
73 private Boolean redirectStdOut
= false;
75 private List
<SystemCallOutputListener
> outputListeners
= Collections
76 .synchronizedList(new ArrayList
<SystemCallOutputListener
>());
78 private Map
<String
, List
<Object
>> osCommands
= new HashMap
<String
, List
<Object
>>();
79 private Map
<String
, String
> osCmds
= new HashMap
<String
, String
>();
80 private Map
<String
, String
> environmentVariables
= new HashMap
<String
, String
>();
82 private Boolean logCommand
= false;
83 private Boolean redirectStreams
= true;
84 private Boolean exceptionOnFailed
= true;
85 private Boolean mergeEnvironmentVariables
= true;
87 private String osConsole
= null;
88 private String generateScript
= null;
90 private Long watchdogTimeout
= 24 * 60 * 60 * 1000l;
92 private TestResult testResult
;
94 private ExecutionResources executionResources
;
96 /** Empty constructor */
102 * Constructor based on the provided command list.
107 public SystemCall(List
<Object
> command
) {
108 this.command
= command
;
112 * Constructor based on the provided command.
115 * the command. If the provided string contains no space a
116 * command list is initialized with the argument as first
117 * component (useful for chained construction)
119 public SystemCall(String cmd
) {
120 if (cmd
.indexOf(' ') < 0) {
121 command
= new ArrayList
<Object
>();
128 /** Executes the system call. */
131 Writer stdOutWriter
= null;
132 OutputStream stdOutputStream
= null;
133 Writer stdErrWriter
= null;
134 InputStream stdInStream
= null;
135 if (stdOutFile
!= null)
137 stdOutputStream
= createOutputStream(stdOutFile
);
139 stdOutWriter
= createWriter(stdOutFile
, true);
141 if (stdErrFile
!= null) {
142 stdErrWriter
= createWriter(stdErrFile
, true);
144 if (stdOutFile
!= null && !redirectStdOut
)
145 stdErrWriter
= createWriter(stdOutFile
, true);
148 if (stdInFile
!= null)
150 stdInStream
= stdInFile
.getInputStream();
151 } catch (IOException e2
) {
152 throw new SlcException("Cannot open a stream for " + stdInFile
,
156 if (log
.isTraceEnabled()) {
157 log
.debug("os.name=" + System
.getProperty("os.name"));
158 log
.debug("os.arch=" + System
.getProperty("os.arch"));
159 log
.debug("os.version=" + System
.getProperty("os.version"));
162 // Execution directory
163 File dir
= new File(getExecDirToUse());
167 // Watchdog to check for lost processes
168 Executor executor
= new DefaultExecutor();
169 executor
.setWatchdog(new ExecuteWatchdog(watchdogTimeout
));
171 if (redirectStreams
) {
172 // Redirect standard streams
173 executor
.setStreamHandler(createExecuteStreamHandler(stdOutWriter
,
174 stdOutputStream
, stdErrWriter
, stdInStream
));
176 // Dummy stream handler (otherwise pump is used)
177 executor
.setStreamHandler(new DummyexecuteStreamHandler());
180 executor
.setProcessDestroyer(new ShutdownHookProcessDestroyer());
181 executor
.setWorkingDirectory(dir
);
183 // Command line to use
184 final CommandLine commandLine
= createCommandLine();
186 log
.info("Execute command:\n" + commandLine
187 + "\n in working directory: \n" + dir
+ "\n");
190 Map
<String
, String
> environmentVariablesToUse
= null;
191 if (environmentVariables
.size() > 0) {
192 environmentVariablesToUse
= new HashMap
<String
, String
>();
193 if (mergeEnvironmentVariables
)
194 environmentVariablesToUse
.putAll(System
.getenv());
195 environmentVariablesToUse
.putAll(environmentVariables
);
199 ExecuteResultHandler executeResultHandler
= createExecuteResultHandler(commandLine
);
202 // THE EXECUTION PROPER
207 int exitValue
= executor
.execute(commandLine
,
208 environmentVariablesToUse
);
209 executeResultHandler
.onProcessComplete(exitValue
);
210 } catch (ExecuteException e1
) {
211 executeResultHandler
.onProcessFailed(e1
);
214 executor
.execute(commandLine
, environmentVariablesToUse
,
215 executeResultHandler
);
216 } catch (SlcException e
) {
218 } catch (Exception e
) {
219 throw new SlcException("Could not execute command " + commandLine
,
222 IOUtils
.closeQuietly(stdOutWriter
);
223 IOUtils
.closeQuietly(stdErrWriter
);
224 IOUtils
.closeQuietly(stdInStream
);
229 public synchronized String
function() {
230 final StringBuffer buf
= new StringBuffer("");
231 SystemCallOutputListener tempOutputListener
= new SystemCallOutputListener() {
232 public void newLine(SystemCall systemCall
, String line
,
238 addOutputListener(tempOutputListener
);
240 removeOutputListener(tempOutputListener
);
241 return buf
.toString();
244 public String
asCommand() {
245 return createCommandLine().toString();
249 public String
toString() {
254 * Build a command line based on the properties. Can be overridden by
255 * specific command wrappers.
257 protected CommandLine
createCommandLine() {
258 // Check if an OS specific command overrides
259 String osName
= System
.getProperty("os.name");
260 List
<Object
> commandToUse
= null;
261 if (osCommands
.containsKey(osName
))
262 commandToUse
= osCommands
.get(osName
);
264 commandToUse
= command
;
265 String cmdToUse
= null;
266 if (osCmds
.containsKey(osName
))
267 cmdToUse
= osCmds
.get(osName
);
271 CommandLine commandLine
= null;
273 // Which command definition to use
274 if (commandToUse
== null && cmdToUse
== null)
275 throw new SlcException("Please specify a command.");
276 else if (commandToUse
!= null && cmdToUse
!= null)
277 throw new SlcException(
278 "Specify the command either as a line or as a list.");
279 else if (cmdToUse
!= null) {
280 commandLine
= CommandLine
.parse(cmdToUse
);
281 } else if (commandToUse
!= null) {
282 if (commandToUse
.size() == 0)
283 throw new SlcException("Command line is empty.");
285 commandLine
= new CommandLine(commandToUse
.get(0).toString());
287 for (int i
= 1; i
< commandToUse
.size(); i
++) {
288 if (log
.isTraceEnabled())
289 log
.debug(commandToUse
.get(i
));
290 commandLine
.addArgument(commandToUse
.get(i
).toString());
293 // all cases covered previously
294 throw new UnsupportedException();
297 if (generateScript
!= null) {
298 File scriptFile
= new File(getExecDirToUse() + File
.separator
301 FileUtils
.writeStringToFile(scriptFile
,
302 (osConsole
!= null ? osConsole
+ " " : "")
303 + commandLine
.toString());
304 } catch (IOException e
) {
305 throw new SlcException("Could not generate script "
308 commandLine
= new CommandLine(scriptFile
);
310 if (osConsole
!= null)
311 commandLine
= CommandLine
.parse(osConsole
+ " "
312 + commandLine
.toString());
319 * Creates a {@link PumpStreamHandler} which redirects streams to the custom
322 protected ExecuteStreamHandler
createExecuteStreamHandler(
323 final Writer stdOutWriter
, final OutputStream stdOutputStream
,
324 final Writer stdErrWriter
, final InputStream stdInStream
) {
328 PumpStreamHandler pumpStreamHandler
= new PumpStreamHandler(
329 stdOutputStream
!= null ? stdOutputStream
330 : new LogOutputStream() {
331 protected void processLine(String line
, int level
) {
332 if (line
!= null && !line
.trim().equals(""))
334 if (stdOutWriter
!= null)
335 appendLineToFile(stdOutWriter
, line
);
337 }, new LogOutputStream() {
338 protected void processLine(String line
, int level
) {
339 if (line
!= null && !line
.trim().equals(""))
341 if (stdErrWriter
!= null)
342 appendLineToFile(stdErrWriter
, line
);
345 return pumpStreamHandler
;
348 /** Creates the default {@link ExecuteResultHandler}. */
349 protected ExecuteResultHandler
createExecuteResultHandler(
350 final CommandLine commandLine
) {
351 return new ExecuteResultHandler() {
353 public void onProcessComplete(int exitValue
) {
354 String msg
= "System call '" + commandLine
355 + "' properly completed.";
356 if (log
.isTraceEnabled())
358 if (testResult
!= null) {
359 forwardPath(testResult
);
360 testResult
.addResultPart(new SimpleResultPart(
361 TestStatus
.PASSED
, msg
));
365 public void onProcessFailed(ExecuteException e
) {
366 String msg
= "System call '" + commandLine
+ "' failed.";
367 if (testResult
!= null) {
368 forwardPath(testResult
);
369 testResult
.addResultPart(new SimpleResultPart(
370 TestStatus
.ERROR
, msg
, e
));
372 if (exceptionOnFailed
)
373 throw new SlcException(msg
, e
);
381 protected void forwardPath(TestResult testResult
) {
382 // TODO: allocate a TreeSPath
386 * Shortcut method getting the execDir to use
388 protected String
getExecDirToUse() {
391 if (execDir
!= null) {
392 // Replace '/' by local file separator, for portability
393 execDir
.replace('/', File
.separatorChar
);
394 dir
= new File(execDir
).getCanonicalFile();
398 return System
.getProperty("user.dir");
400 return dir
.getPath();
401 } catch (Exception e
) {
402 throw new SlcException("Cannot find exec dir", e
);
406 protected void logStdOut(String line
) {
407 for (SystemCallOutputListener outputListener
: outputListeners
)
408 outputListener
.newLine(this, line
, false);
409 log(stdOutLogLevel
, line
);
412 protected void logStdErr(String line
) {
413 for (SystemCallOutputListener outputListener
: outputListeners
)
414 outputListener
.newLine(this, line
, true);
415 log(stdErrLogLevel
, line
);
418 /** Log from the underlying streams. */
419 protected void log(String logLevel
, String line
) {
420 if ("ERROR".equals(logLevel
))
422 else if ("WARN".equals(logLevel
))
424 else if ("INFO".equals(logLevel
))
426 else if ("DEBUG".equals(logLevel
))
428 else if ("TRACE".equals(logLevel
))
430 else if (LOG_STDOUT
.equals(logLevel
))
431 System
.out
.println(line
);
432 else if ("System.err".equals(logLevel
))
433 System
.err
.println(line
);
435 throw new SlcException("Unknown log level " + logLevel
);
438 /** Append line to a log file. */
439 protected void appendLineToFile(Writer writer
, String line
) {
441 writer
.append(line
).append('\n');
442 } catch (IOException e
) {
443 log
.error("Cannot write to log file", e
);
447 /** Creates the writer for the output/err files. */
448 protected Writer
createWriter(Resource target
, Boolean append
) {
449 FileWriter writer
= null;
453 if (executionResources
!= null)
454 file
= new File(executionResources
.getAsOsPath(target
, true));
456 file
= target
.getFile();
457 writer
= new FileWriter(file
, append
);
458 } catch (IOException e
) {
459 log
.error("Cannot get file for " + target
, e
);
460 IOUtils
.closeQuietly(writer
);
465 /** Creates an outputstream for the output/err files. */
466 protected OutputStream
createOutputStream(Resource target
) {
467 FileOutputStream out
= null;
471 if (executionResources
!= null)
472 file
= new File(executionResources
.getAsOsPath(target
, true));
474 file
= target
.getFile();
475 out
= new FileOutputStream(file
, false);
476 } catch (IOException e
) {
477 log
.error("Cannot get file for " + target
, e
);
478 IOUtils
.closeQuietly(out
);
483 /** Append the argument (for chaining) */
484 public SystemCall
arg(String arg
) {
486 command
= new ArrayList
<Object
>();
491 /** Append the argument (for chaining) */
492 public SystemCall
arg(String arg
, String value
) {
494 command
= new ArrayList
<Object
>();
501 public void setCmd(String command
) {
505 public void setCommand(List
<Object
> command
) {
506 this.command
= command
;
509 public void setExecDir(String execdir
) {
510 this.execDir
= execdir
;
513 public void setStdErrLogLevel(String stdErrLogLevel
) {
514 this.stdErrLogLevel
= stdErrLogLevel
;
517 public void setStdOutLogLevel(String stdOutLogLevel
) {
518 this.stdOutLogLevel
= stdOutLogLevel
;
521 public void setSynchronous(Boolean synchronous
) {
522 this.synchronous
= synchronous
;
525 public void setOsCommands(Map
<String
, List
<Object
>> osCommands
) {
526 this.osCommands
= osCommands
;
529 public void setOsCmds(Map
<String
, String
> osCmds
) {
530 this.osCmds
= osCmds
;
533 public void setEnvironmentVariables(Map
<String
, String
> environmentVariables
) {
534 this.environmentVariables
= environmentVariables
;
537 public void setWatchdogTimeout(Long watchdogTimeout
) {
538 this.watchdogTimeout
= watchdogTimeout
;
541 public void setStdOutFile(Resource stdOutFile
) {
542 this.stdOutFile
= stdOutFile
;
545 public void setStdErrFile(Resource stdErrFile
) {
546 this.stdErrFile
= stdErrFile
;
549 public void setStdInFile(Resource stdInFile
) {
550 this.stdInFile
= stdInFile
;
553 public void setTestResult(TestResult testResult
) {
554 this.testResult
= testResult
;
557 public void setLogCommand(Boolean logCommand
) {
558 this.logCommand
= logCommand
;
561 public void setRedirectStreams(Boolean redirectStreams
) {
562 this.redirectStreams
= redirectStreams
;
565 public void setExceptionOnFailed(Boolean exceptionOnFailed
) {
566 this.exceptionOnFailed
= exceptionOnFailed
;
569 public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables
) {
570 this.mergeEnvironmentVariables
= mergeEnvironmentVariables
;
573 public void setOsConsole(String osConsole
) {
574 this.osConsole
= osConsole
;
577 public void setGenerateScript(String generateScript
) {
578 this.generateScript
= generateScript
;
581 public void setExecutionResources(ExecutionResources executionResources
) {
582 this.executionResources
= executionResources
;
585 public void setRedirectStdOut(Boolean redirectStdOut
) {
586 this.redirectStdOut
= redirectStdOut
;
589 public void addOutputListener(SystemCallOutputListener outputListener
) {
590 outputListeners
.add(outputListener
);
593 public void removeOutputListener(SystemCallOutputListener outputListener
) {
594 outputListeners
.remove(outputListener
);
597 public void setOutputListeners(
598 List
<SystemCallOutputListener
> outputListeners
) {
599 this.outputListeners
= outputListeners
;
602 private class DummyexecuteStreamHandler
implements ExecuteStreamHandler
{
604 public void setProcessErrorStream(InputStream is
) throws IOException
{
607 public void setProcessInputStream(OutputStream os
) throws IOException
{
610 public void setProcessOutputStream(InputStream is
) throws IOException
{
613 public void start() throws IOException
{