]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.core/src/main/java/org/argeo/slc/core/execution/tasks/SystemCall.java
Reduce log verbosity
[gpl/argeo-slc.git] / runtime / org.argeo.slc.core / src / main / java / org / argeo / slc / core / execution / tasks / SystemCall.java
1 /*
2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 package org.argeo.slc.core.execution.tasks;
18
19 import java.io.File;
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;
30 import java.util.Map;
31
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;
53
54 /** Execute an OS specific system call. */
55 public class SystemCall implements Runnable {
56 public final static String LOG_STDOUT = "System.out";
57
58 private final Log log = LogFactory.getLog(getClass());
59
60 private String execDir;
61
62 private String cmd = null;
63 private List<Object> command = null;
64
65 private Boolean synchronous = true;
66
67 private String stdErrLogLevel = "ERROR";
68 private String stdOutLogLevel = "INFO";
69
70 private Resource stdOutFile = null;
71 private Resource stdErrFile = null;
72 private Resource stdInFile = null;
73 private Boolean redirectStdOut = false;
74
75 private List<SystemCallOutputListener> outputListeners = Collections
76 .synchronizedList(new ArrayList<SystemCallOutputListener>());
77
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>();
81
82 private Boolean logCommand = false;
83 private Boolean redirectStreams = true;
84 private Boolean exceptionOnFailed = true;
85 private Boolean mergeEnvironmentVariables = true;
86
87 private String osConsole = null;
88 private String generateScript = null;
89
90 private Long watchdogTimeout = 24 * 60 * 60 * 1000l;
91
92 private TestResult testResult;
93
94 private ExecutionResources executionResources;
95
96 /** Empty constructor */
97 public SystemCall() {
98
99 }
100
101 /**
102 * Constructor based on the provided command list.
103 *
104 * @param command
105 * the command list
106 */
107 public SystemCall(List<Object> command) {
108 this.command = command;
109 }
110
111 /**
112 * Constructor based on the provided command.
113 *
114 * @param cmd
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)
118 */
119 public SystemCall(String cmd) {
120 if (cmd.indexOf(' ') < 0) {
121 command = new ArrayList<Object>();
122 command.add(cmd);
123 } else {
124 this.cmd = cmd;
125 }
126 }
127
128 /** Executes the system call. */
129 public void run() {
130 // Manage streams
131 Writer stdOutWriter = null;
132 OutputStream stdOutputStream = null;
133 Writer stdErrWriter = null;
134 InputStream stdInStream = null;
135 if (stdOutFile != null)
136 if (redirectStdOut)
137 stdOutputStream = createOutputStream(stdOutFile);
138 else
139 stdOutWriter = createWriter(stdOutFile, true);
140
141 if (stdErrFile != null) {
142 stdErrWriter = createWriter(stdErrFile, true);
143 } else {
144 if (stdOutFile != null && !redirectStdOut)
145 stdErrWriter = createWriter(stdOutFile, true);
146 }
147
148 if (stdInFile != null)
149 try {
150 stdInStream = stdInFile.getInputStream();
151 } catch (IOException e2) {
152 throw new SlcException("Cannot open a stream for " + stdInFile,
153 e2);
154 }
155
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"));
160 }
161
162 // Execution directory
163 File dir = new File(getExecDirToUse());
164 if (!dir.exists())
165 dir.mkdirs();
166
167 // Watchdog to check for lost processes
168 Executor executor = new DefaultExecutor();
169 executor.setWatchdog(new ExecuteWatchdog(watchdogTimeout));
170
171 if (redirectStreams) {
172 // Redirect standard streams
173 executor.setStreamHandler(createExecuteStreamHandler(stdOutWriter,
174 stdOutputStream, stdErrWriter, stdInStream));
175 } else {
176 // Dummy stream handler (otherwise pump is used)
177 executor.setStreamHandler(new DummyexecuteStreamHandler());
178 }
179
180 executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
181 executor.setWorkingDirectory(dir);
182
183 // Command line to use
184 final CommandLine commandLine = createCommandLine();
185 if (logCommand)
186 log.info("Execute command:\n" + commandLine
187 + "\n in working directory: \n" + dir + "\n");
188
189 // Env variables
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);
196 }
197
198 // Execute
199 ExecuteResultHandler executeResultHandler = createExecuteResultHandler(commandLine);
200
201 //
202 // THE EXECUTION PROPER
203 //
204 try {
205 if (synchronous)
206 try {
207 int exitValue = executor.execute(commandLine,
208 environmentVariablesToUse);
209 executeResultHandler.onProcessComplete(exitValue);
210 } catch (ExecuteException e1) {
211 executeResultHandler.onProcessFailed(e1);
212 }
213 else
214 executor.execute(commandLine, environmentVariablesToUse,
215 executeResultHandler);
216 } catch (SlcException e) {
217 throw e;
218 } catch (Exception e) {
219 throw new SlcException("Could not execute command " + commandLine,
220 e);
221 } finally {
222 IOUtils.closeQuietly(stdOutWriter);
223 IOUtils.closeQuietly(stdErrWriter);
224 IOUtils.closeQuietly(stdInStream);
225 }
226
227 }
228
229 public synchronized String function() {
230 final StringBuffer buf = new StringBuffer("");
231 SystemCallOutputListener tempOutputListener = new SystemCallOutputListener() {
232 public void newLine(SystemCall systemCall, String line,
233 Boolean isError) {
234 if (!isError)
235 buf.append(line);
236 }
237 };
238 addOutputListener(tempOutputListener);
239 run();
240 removeOutputListener(tempOutputListener);
241 return buf.toString();
242 }
243
244 public String asCommand() {
245 return createCommandLine().toString();
246 }
247
248 @Override
249 public String toString() {
250 return asCommand();
251 }
252
253 /**
254 * Build a command line based on the properties. Can be overridden by
255 * specific command wrappers.
256 */
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);
263 else
264 commandToUse = command;
265 String cmdToUse = null;
266 if (osCmds.containsKey(osName))
267 cmdToUse = osCmds.get(osName);
268 else
269 cmdToUse = cmd;
270
271 CommandLine commandLine = null;
272
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.");
284
285 commandLine = new CommandLine(commandToUse.get(0).toString());
286
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());
291 }
292 } else {
293 // all cases covered previously
294 throw new UnsupportedException();
295 }
296
297 if (generateScript != null) {
298 File scriptFile = new File(getExecDirToUse() + File.separator
299 + generateScript);
300 try {
301 FileUtils.writeStringToFile(scriptFile,
302 (osConsole != null ? osConsole + " " : "")
303 + commandLine.toString());
304 } catch (IOException e) {
305 throw new SlcException("Could not generate script "
306 + scriptFile, e);
307 }
308 commandLine = new CommandLine(scriptFile);
309 } else {
310 if (osConsole != null)
311 commandLine = CommandLine.parse(osConsole + " "
312 + commandLine.toString());
313 }
314
315 return commandLine;
316 }
317
318 /**
319 * Creates a {@link PumpStreamHandler} which redirects streams to the custom
320 * logging mechanism.
321 */
322 protected ExecuteStreamHandler createExecuteStreamHandler(
323 final Writer stdOutWriter, final OutputStream stdOutputStream,
324 final Writer stdErrWriter, final InputStream stdInStream) {
325
326 // Log writers
327
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(""))
333 logStdOut(line);
334 if (stdOutWriter != null)
335 appendLineToFile(stdOutWriter, line);
336 }
337 }, new LogOutputStream() {
338 protected void processLine(String line, int level) {
339 if (line != null && !line.trim().equals(""))
340 logStdErr(line);
341 if (stdErrWriter != null)
342 appendLineToFile(stdErrWriter, line);
343 }
344 }, stdInStream);
345 return pumpStreamHandler;
346 }
347
348 /** Creates the default {@link ExecuteResultHandler}. */
349 protected ExecuteResultHandler createExecuteResultHandler(
350 final CommandLine commandLine) {
351 return new ExecuteResultHandler() {
352
353 public void onProcessComplete(int exitValue) {
354 String msg = "System call '" + commandLine
355 + "' properly completed.";
356 if (log.isTraceEnabled())
357 log.trace(msg);
358 if (testResult != null) {
359 forwardPath(testResult);
360 testResult.addResultPart(new SimpleResultPart(
361 TestStatus.PASSED, msg));
362 }
363 }
364
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));
371 } else {
372 if (exceptionOnFailed)
373 throw new SlcException(msg, e);
374 else
375 log.error(msg, e);
376 }
377 }
378 };
379 }
380
381 protected void forwardPath(TestResult testResult) {
382 // TODO: allocate a TreeSPath
383 }
384
385 /**
386 * Shortcut method getting the execDir to use
387 */
388 protected String getExecDirToUse() {
389 try {
390 File dir = null;
391 if (execDir != null) {
392 // Replace '/' by local file separator, for portability
393 execDir.replace('/', File.separatorChar);
394 dir = new File(execDir).getCanonicalFile();
395 }
396
397 if (dir == null)
398 return System.getProperty("user.dir");
399 else
400 return dir.getPath();
401 } catch (Exception e) {
402 throw new SlcException("Cannot find exec dir", e);
403 }
404 }
405
406 protected void logStdOut(String line) {
407 for (SystemCallOutputListener outputListener : outputListeners)
408 outputListener.newLine(this, line, false);
409 log(stdOutLogLevel, line);
410 }
411
412 protected void logStdErr(String line) {
413 for (SystemCallOutputListener outputListener : outputListeners)
414 outputListener.newLine(this, line, true);
415 log(stdErrLogLevel, line);
416 }
417
418 /** Log from the underlying streams. */
419 protected void log(String logLevel, String line) {
420 if ("ERROR".equals(logLevel))
421 log.error(line);
422 else if ("WARN".equals(logLevel))
423 log.warn(line);
424 else if ("INFO".equals(logLevel))
425 log.info(line);
426 else if ("DEBUG".equals(logLevel))
427 log.debug(line);
428 else if ("TRACE".equals(logLevel))
429 log.trace(line);
430 else if (LOG_STDOUT.equals(logLevel))
431 System.out.println(line);
432 else if ("System.err".equals(logLevel))
433 System.err.println(line);
434 else
435 throw new SlcException("Unknown log level " + logLevel);
436 }
437
438 /** Append line to a log file. */
439 protected void appendLineToFile(Writer writer, String line) {
440 try {
441 writer.append(line).append('\n');
442 } catch (IOException e) {
443 log.error("Cannot write to log file", e);
444 }
445 }
446
447 /** Creates the writer for the output/err files. */
448 protected Writer createWriter(Resource target, Boolean append) {
449 FileWriter writer = null;
450 try {
451
452 final File file;
453 if (executionResources != null)
454 file = new File(executionResources.getAsOsPath(target, true));
455 else
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);
461 }
462 return writer;
463 }
464
465 /** Creates an outputstream for the output/err files. */
466 protected OutputStream createOutputStream(Resource target) {
467 FileOutputStream out = null;
468 try {
469
470 final File file;
471 if (executionResources != null)
472 file = new File(executionResources.getAsOsPath(target, true));
473 else
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);
479 }
480 return out;
481 }
482
483 /** Append the argument (for chaining) */
484 public SystemCall arg(String arg) {
485 if (command == null)
486 command = new ArrayList<Object>();
487 command.add(arg);
488 return this;
489 }
490
491 /** Append the argument (for chaining) */
492 public SystemCall arg(String arg, String value) {
493 if (command == null)
494 command = new ArrayList<Object>();
495 command.add(arg);
496 command.add(value);
497 return this;
498 }
499
500 /** */
501 public void setCmd(String command) {
502 this.cmd = command;
503 }
504
505 public void setCommand(List<Object> command) {
506 this.command = command;
507 }
508
509 public void setExecDir(String execdir) {
510 this.execDir = execdir;
511 }
512
513 public void setStdErrLogLevel(String stdErrLogLevel) {
514 this.stdErrLogLevel = stdErrLogLevel;
515 }
516
517 public void setStdOutLogLevel(String stdOutLogLevel) {
518 this.stdOutLogLevel = stdOutLogLevel;
519 }
520
521 public void setSynchronous(Boolean synchronous) {
522 this.synchronous = synchronous;
523 }
524
525 public void setOsCommands(Map<String, List<Object>> osCommands) {
526 this.osCommands = osCommands;
527 }
528
529 public void setOsCmds(Map<String, String> osCmds) {
530 this.osCmds = osCmds;
531 }
532
533 public void setEnvironmentVariables(Map<String, String> environmentVariables) {
534 this.environmentVariables = environmentVariables;
535 }
536
537 public void setWatchdogTimeout(Long watchdogTimeout) {
538 this.watchdogTimeout = watchdogTimeout;
539 }
540
541 public void setStdOutFile(Resource stdOutFile) {
542 this.stdOutFile = stdOutFile;
543 }
544
545 public void setStdErrFile(Resource stdErrFile) {
546 this.stdErrFile = stdErrFile;
547 }
548
549 public void setStdInFile(Resource stdInFile) {
550 this.stdInFile = stdInFile;
551 }
552
553 public void setTestResult(TestResult testResult) {
554 this.testResult = testResult;
555 }
556
557 public void setLogCommand(Boolean logCommand) {
558 this.logCommand = logCommand;
559 }
560
561 public void setRedirectStreams(Boolean redirectStreams) {
562 this.redirectStreams = redirectStreams;
563 }
564
565 public void setExceptionOnFailed(Boolean exceptionOnFailed) {
566 this.exceptionOnFailed = exceptionOnFailed;
567 }
568
569 public void setMergeEnvironmentVariables(Boolean mergeEnvironmentVariables) {
570 this.mergeEnvironmentVariables = mergeEnvironmentVariables;
571 }
572
573 public void setOsConsole(String osConsole) {
574 this.osConsole = osConsole;
575 }
576
577 public void setGenerateScript(String generateScript) {
578 this.generateScript = generateScript;
579 }
580
581 public void setExecutionResources(ExecutionResources executionResources) {
582 this.executionResources = executionResources;
583 }
584
585 public void setRedirectStdOut(Boolean redirectStdOut) {
586 this.redirectStdOut = redirectStdOut;
587 }
588
589 public void addOutputListener(SystemCallOutputListener outputListener) {
590 outputListeners.add(outputListener);
591 }
592
593 public void removeOutputListener(SystemCallOutputListener outputListener) {
594 outputListeners.remove(outputListener);
595 }
596
597 public void setOutputListeners(
598 List<SystemCallOutputListener> outputListeners) {
599 this.outputListeners = outputListeners;
600 }
601
602 private class DummyexecuteStreamHandler implements ExecuteStreamHandler {
603
604 public void setProcessErrorStream(InputStream is) throws IOException {
605 }
606
607 public void setProcessInputStream(OutputStream os) throws IOException {
608 }
609
610 public void setProcessOutputStream(InputStream is) throws IOException {
611 }
612
613 public void start() throws IOException {
614 }
615
616 public void stop() {
617 }
618
619 }
620
621 }