List of usage examples for org.apache.commons.exec DefaultExecutor setWatchdog
public void setWatchdog(final ExecuteWatchdog watchDog)
From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java
protected Set<Integer> getOpenNMSProcesses() { LOG.trace("getOpenNMSProcesses()"); final Set<Integer> processes = new HashSet<Integer>(); final String jps = getResourceLocator().findBinary("jps"); LOG.trace("jps = {}", jps); DataInputStream input = null; PsParser parser = null;// ww w .j av a 2 s .c om PipedInputStream pis = null; PipedOutputStream output = new PipedOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5000)); if (jps != null) { CommandLine command = CommandLine.parse(jps + " -v"); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("Failed to run '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } LOG.trace("looking for ps"); final String ps = getResourceLocator().findBinary("ps"); if (ps != null) { // try Linux/Mac style CommandLine command = CommandLine.parse(ps + " aww -o pid -o args"); output = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("error running '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } if (processes.size() == 0) { // try Solaris style command = CommandLine.parse(ps + " -ea -o pid -o args"); output = new PipedOutputStream(); streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("error running '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } } if (processes.size() == 0) { LOG.warn("Unable to find any OpenNMS processes."); } return processes; }
From source file:org.opennms.systemreport.system.ThreadReportPlugin.java
private void triggerThreadDump() { String kill = findBinary("kill"); if (kill != null) { for (final Integer pid : getOpenNMSProcesses()) { LOG.debug("pid = {}", pid); CommandLine command = CommandLine.parse(kill + " -3 " + pid.toString()); try { LOG.trace("running '{}'", command); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5000)); int exitValue = executor.execute(command); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.warn("'{}' exited non-zero: {}", command, exitValue); }//w w w. jav a2s . c o m } catch (final Exception e) { LOG.warn("Unable to run kill -3 on '{}': you might need to run system-report as root.", pid, e); } } } }
From source file:org.opennms.systemreport.SystemReportResourceLocator.java
@Override public String slurpOutput(final String commandString, final boolean ignoreExitCode) { final CommandLine command = CommandLine.parse(commandString); LOG.debug("running: {}", commandString); final Map<String, String> environment = new HashMap<String, String>(System.getenv()); environment.put("COLUMNS", "2000"); DataInputStream input = null; PipedInputStream pis = null;// www.j a v a2s. co m OutputSuckingParser parser = null; String outputText = null; final DefaultExecutor executor = new DefaultExecutor(); final PipedOutputStream output = new PipedOutputStream(); final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output); executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait)); executor.setStreamHandler(streamHandler); if (ignoreExitCode) { executor.setExitValues(null); } try { LOG.trace("executing '{}'", commandString); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new OutputSuckingParser(input); parser.start(); final int exitValue = executor.execute(command, environment); IOUtils.closeQuietly(output); parser.join(m_maxProcessWait); if (!ignoreExitCode && exitValue != 0) { LOG.debug("error running '{}': exit value was {}", commandString, exitValue); } else { outputText = parser.getOutput(); } LOG.trace("finished '{}'", commandString); } catch (final Exception e) { LOG.debug("Failed to run '{}'", commandString, e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); } return outputText; }
From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}//from ww w. j a va2s . co m */ @Override protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException { String rrdBinary = System.getProperty("rrd.binary"); if (rrdBinary == null) { throw new RrdException("No RRD binary is set."); } final long startInSeconds = (long) Math.floor(start / 1000); final long endInSeconds = (long) Math.floor(end / 1000); long stepInSeconds = (long) Math.floor(step / 1000); // The step must be strictly positive if (stepInSeconds <= 0) { stepInSeconds = 1; } final CommandLine cmdLine = new CommandLine(rrdBinary); cmdLine.addArgument("xport"); cmdLine.addArgument("--step"); cmdLine.addArgument("" + stepInSeconds); cmdLine.addArgument("--start"); cmdLine.addArgument("" + startInSeconds); cmdLine.addArgument("--end"); cmdLine.addArgument("" + endInSeconds); if (maxrows > 0) { cmdLine.addArgument("--maxrows"); cmdLine.addArgument("" + maxrows); } // Use labels without spaces when executing the xport command // These are mapped back to the requested labels in the response final Map<String, String> labelMap = Maps.newHashMap(); int k = 0; for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) { final Source source = entry.getKey(); final String rrdFile = entry.getValue(); final String tempLabel = Integer.toString(++k); labelMap.put(tempLabel, source.getLabel()); cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, rrdFile, source.getAttribute(), source.getAggregation())); cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel)); } // Use commons-exec to execute rrdtool final DefaultExecutor executor = new DefaultExecutor(); // Capture stdout/stderr final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null)); // Fail if we get a non-zero exit code executor.setExitValue(0); // Fail if the process takes too long final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS); executor.setWatchdog(watchdog); // Export RrdXport rrdXport; try { executor.execute(cmdLine); final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString()))); final JAXBContext jc = JAXBContext.newInstance(RrdXport.class); final Unmarshaller u = jc.createUnmarshaller(); rrdXport = (RrdXport) u.unmarshal(source); } catch (IOException e) { throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e); } catch (SAXException | JAXBException e) { throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e); } final int numRows = rrdXport.getRows().size(); final int numColumns = rrdXport.getMeta().getLegends().size(); final long timestamps[] = new long[numRows]; final double values[][] = new double[numColumns][numRows]; // Convert rows to columns int i = 0; for (final XRow row : rrdXport.getRows()) { timestamps[i] = row.getTimestamp() * 1000; for (int j = 0; j < numColumns; j++) { if (row.getValues() == null) { // NMS-7710: Avoid NPEs, in certain cases the list of values may be null throw new RrdException( "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries."); } values[j][i] = row.getValues().get(j); } i++; } // Map the columns by label // The legend entries are in the same order as the column values final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns); i = 0; for (String label : rrdXport.getMeta().getLegends()) { columns.put(labelMap.get(label), values[i++]); } return new FetchResults(timestamps, columns, rrdXport.getMeta().getStep() * 1000, constants); }
From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java
@Override protected void startApplication() { File bundleDirectory = getBundleDirectory(); List<String> javaOptions = getConfiguration().getJavaOptions(); List<String> javaAgentOptions = getJavaAgentOptions(); CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java")); if (javaAgentOptions.size() > 0) { cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()])); }/* ww w.j ava2s.com*/ if (javaOptions.size() > 0) { cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()])); } cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments()) .addArgument("config.yaml"); log.debug("Launching: {}", cmdLine.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(bundleDirectory); executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis())); try { executor.setStreamHandler(streamHandler = new PumpStreamHandler( new FileOutputStream(new File(bundleDirectory, "output.log")))); executor.execute(cmdLine, new DefaultExecuteResultHandler()); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:org.waarp.commandexec.server.LocalExecServerHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { answered = false;/*from w w w.java2 s .c om*/ String request = msg; // Generate and write a response. String response; response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result; ExecuteWatchdog watchdog = null; try { if (request.length() == 0) { // No command response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result; } else { String[] args = request.split(" "); int cpt = 0; long tempDelay; try { tempDelay = Long.parseLong(args[0]); cpt++; } catch (NumberFormatException e) { tempDelay = delay; } if (tempDelay < 0) { // Shutdown Order isShutdown = true; logger.warn("Shutdown order received"); response = LocalExecDefaultResult.ShutdownOnGoing.status + " " + LocalExecDefaultResult.ShutdownOnGoing.result; Thread thread = new GGLEThreadShutdown(factory); thread.start(); return; } String binary = args[cpt++]; File exec = new File(binary); if (exec.isAbsolute()) { // If true file, is it executable if (!exec.canExecute()) { logger.error("Exec command is not executable: " + request); response = LocalExecDefaultResult.NotExecutable.status + " " + LocalExecDefaultResult.NotExecutable.result; return; } } // Create command with parameters CommandLine commandLine = new CommandLine(binary); for (; cpt < args.length; cpt++) { commandLine.addArgument(args[cpt]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); ByteArrayOutputStream outputStream; outputStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); if (tempDelay > 0) { // If delay (max time), then setup Watchdog watchdog = new ExecuteWatchdog(tempDelay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { // Execute the command status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(LocalExecDefaultResult.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } catch (IOException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } else { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error( "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } try { pumpStreamHandler.stop(); } catch (IOException e3) { } if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); response = LocalExecDefaultResult.TimeOutExecution.status + " " + LocalExecDefaultResult.TimeOutExecution.result; try { outputStream.close(); } catch (IOException e2) { } } else { try { response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name()); } catch (UnsupportedEncodingException e) { response = status + " " + outputStream.toString(); } try { outputStream.close(); } catch (IOException e2) { } } } } finally { // We do not need to write a ByteBuf here. // We know the encoder inserted at LocalExecInitializer will do the // conversion. ctx.channel().writeAndFlush(response + "\n"); answered = true; if (watchdog != null) { watchdog.stop(); } logger.info("End of Command: " + request + " : " + response); ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n"); } }
From source file:org.waarp.gateway.kernel.exec.ExecuteExecutor.java
public void run() throws Reply421Exception { // Check if the execution will be done through LocalExec daemon if (AbstractExecutor.useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(arg, delay, futureCompletion); localExecClient.disconnect(); return; } // else continue }/*w w w.j a v a 2s .co m*/ // Execution is done internally File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + args[0]); throw new Reply421Exception("Pre Exec command is not executable"); } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(10); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("System Exception: " + e.getMessage() + "\n Exec cannot execute command " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } catch (IOException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error( "Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } logger.info("System Exception: " + e.getMessage() + " but finally get the command executed " + commandLine.toString()); } else { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } try { pumpStreamHandler.stop(); } catch (IOException e1) { } if (watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); status = -1; } if (status == 0) { futureCompletion.setSuccess(); logger.info("Exec OK with {}", commandLine); } else if (status == 1) { logger.warn("Exec in warning with {}", commandLine); futureCompletion.setSuccess(); } else { logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with " + commandLine.toString()); throw new Reply421Exception("Pre command executed in error"); } }
From source file:org.waarp.openr66.context.task.ExecMoveTask.java
@Override public void run() { /*//from ww w. j a v a2 s . c o m * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last * line of stdout will be the new name given to the R66File in case of status 0. The * previous file should be deleted by the script or will be deleted in case of status 0. If * the status is 1, no change is made to the file. */ logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); move(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } LastLineReader lastLineReader = new LastLineReader(inputStream); Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } catch (IOException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = lastLineReader.getLastLine(); if (status == 0 && (newname == null || newname.isEmpty())) { status = 1; } } move(status, newname, commandLine.toString()); }
From source file:org.waarp.openr66.context.task.ExecOutputTask.java
@Override public void run() { /*//from w w w .j a v a 2 s. c o m * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of * an error (> 0), all the line from output will be send back to the partner with the Error * code. No change is made to the file. */ logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); finalize(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } AllLineReader allLineReader = new AllLineReader(inputStream); Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } catch (IOException e1) { try { outputStream.flush(); } catch (IOException e2) { } try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = allLineReader.getLastLine().toString(); } finalize(status, newname, commandLine.toString()); }
From source file:org.waarp.openr66.context.task.ExecTask.java
@Override public void run() { /*//from w w w .ja v a 2 s . c o m * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change * should be done in the FILENAME */ logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Check if the execution will be done through LocalExec daemon if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); localExecClient.disconnect(); return; } // else continue } // Execution is done internally String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0 && waitForValidation) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } if (!waitForValidation) { // Do not wait for validation futureCompletion.setSuccess(); logger.info("Exec will start but no WAIT with {}", commandLine); } int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } catch (IOException e1) { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } } else { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } try { pumpStreamHandler.stop(); } catch (IOException e2) { } if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); status = -1; } if (status == 0) { if (waitForValidation) { futureCompletion.setSuccess(); } logger.info("Exec OK with {}", commandLine); } else if (status == 1) { logger.warn("Exec in warning with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setSuccess(); } } else { logger.error("Status: " + status + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.cancel(); } } }