List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler hasResult
boolean hasResult
To view the source code for org.apache.commons.exec DefaultExecuteResultHandler hasResult.
Click Source Link
From source file:com.stratio.ingestion.IngestionInterpreter.java
@Override public InterpreterResult interpret(String st) { if (ingestionHome.isEmpty()) { open();/* w ww . j a v a2 s . c o m*/ if (ingestionHome.isEmpty()) { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text Ingestion is not installed correctly. " + "INGESTION_HOME Is not set"); } } IngestionSyntaxParser parser = new IngestionSyntaxParser(); IngestionParserResult parserResult = null; try { parserResult = parser.parse(st); } catch (IngestionParserException e) { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage()); } StringBuilder shellCommand = new StringBuilder(); StringBuilder interpreterResult = new StringBuilder(); String bashResult; interpreterResult.append("%text "); switch (parserResult.getCommand()) { case AGENT_START: try { IngestionAgent agentStart = parserResult.getAgent(); String agentName = agentStart.getName(); String agentFilepath = agentStart.getFilepath(); int agentPort = agentStart.getPort(); logger.info("Ingestion interpreter @ agent start $INGESTION_HOME -> " + ingestionHome); logger.info("Ingestion interpreter @ agent start agent filepath -> " + agentFilepath); logger.info("Ingestion interpreter @ agent start agent name -> " + agentName); logger.info("Ingestion interpreter @ agent start agent port -> " + agentPort); shellCommand.append("exec \"").append(ingestionHome).append("/bin/flume-ng\" agent --conf ") .append(ingestionHome).append("/conf --conf-file ").append(agentFilepath).append(" --name ") .append(agentName).append(" -Dflume.monitoring.type=http -Dflume.monitoring.port=") .append(String.valueOf(agentPort)).append("> /dev/null & "); logger.info("Ingestion interpreter @ agent start command -> " + shellCommand.toString()); DefaultExecuteResultHandler handler = IngestionUtils.executeBash(shellCommand.toString()); long initTime = System.currentTimeMillis(); while (!handler.hasResult()) { if (System.currentTimeMillis() > (initTime + CMD_TIMEOUT)) { handler.onProcessComplete(999); } } if (handler.getException() != null) { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + handler.getExitValue() + " " + handler.getException().getMessage()); } bashResult = "Agent started"; return new InterpreterResult(InterpreterResult.Code.SUCCESS, bashResult); } catch (IOException e) { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage()); } case AGENT_STOP: try { IngestionAgent agentStop = parserResult.getAgent(); shellCommand.append("ps auxww | grep flume | grep ").append(agentStop.getPort()) .append("| awk '{ print $2 }' | xargs kill -15 "); IngestionUtils.executeBash(shellCommand.toString()); return new InterpreterResult(InterpreterResult.Code.SUCCESS, interpreterResult.append("Agent " + "apparently stopped ").toString()); } catch (IOException e) { if (e.getMessage().contains("143")) { //after kill a process always 143 exit code return new InterpreterResult(InterpreterResult.Code.SUCCESS, interpreterResult.append("Agent " + "apparently stopped ").toString()); } else { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage()); } } case CHANNELS_STATUS: try { String json = IngestionUtils.getAgentStatus(parserResult.getAgent().getPort()); if (json.length() > 3) { Map<String, String> channelsStatus = IngestionUtils.getChannelsStatus(json); String channelStatusResult = ""; for (String channel : channelsStatus.keySet()) { channelStatusResult += "Channel ".concat(channel).concat(": ") .concat(channelsStatus.get(channel)).concat("\n"); } return new InterpreterResult(InterpreterResult.Code.SUCCESS, "%text " + channelStatusResult); } } catch (IOException e) { return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage()); } break; case LIST_PROPERTIES: List<String> files = new ArrayList<>(); StringBuilder listResult = new StringBuilder(); IngestionUtils.getIngestionPropertiesFiles(files, ingestionHome); if (!files.isEmpty()) { for (String file : files) { listResult.append(file).append("\n"); } return new InterpreterResult(InterpreterResult.Code.SUCCESS, "%text ".concat(listResult.toString())); } return new InterpreterResult(InterpreterResult.Code.ERROR, "%text No .properties files found"); case HELP: return new InterpreterResult(InterpreterResult.Code.SUCCESS, interpreterResult.append(IngestionUtils.help()).toString()); } return new InterpreterResult(InterpreterResult.Code.ERROR, "%text Ingestion command not recognized, type help" + " for more info"); }
From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java
@Override public JobStatus updateJob(String jobId) { try {//from w w w. j a va 2s . c o m log.info("Polling state for " + jobId + "..."); ExecutionHandler handler = jobIdToHandlerMap.get(jobId); if (handler == null) { return null; } JobStatus jobStatus = new JobStatus().setId(jobId); DefaultExecuteResultHandler resultHandler; ByteArrayOutputStream stdOutStream; ByteArrayOutputStream stdErrStream; stdOutStream = handler.getStdOut(); stdErrStream = handler.getStdErr(); resultHandler = handler.getResultHandler(); jobStatus.setStdOut(new String(stdOutStream.toByteArray())); jobStatus.setStdErr(new String(stdErrStream.toByteArray())); if (resultHandler.hasResult()) { jobStatus.setState(State.COMPLETED); int exitValue = resultHandler.getExitValue(); log.info(jobId + " has terminated with exit code " + exitValue); if (exitValue == 0) { jobStatus.setResult(Result.SUCCESS); } else { jobStatus.setResult(Result.FAILURE); } jobIdToHandlerMap.remove(jobId); } else { jobStatus.setState(State.RUNNING); } return jobStatus; } catch (Exception e) { log.warn("Failed to retrieve status of " + jobId); return null; } }
From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java
@Override public JobStatus updateJob(String jobId) { try {// w w w .ja va 2s .co m log.debug("Polling state for " + jobId + "..."); ExecutionHandler handler = jobIdToHandlerMap.get(jobId); if (handler == null) { return null; } JobStatus jobStatus = new JobStatus().setId(jobId); DefaultExecuteResultHandler resultHandler; ByteArrayOutputStream stdOutStream; ByteArrayOutputStream stdErrStream; stdOutStream = handler.getStdOut(); stdErrStream = handler.getStdErr(); resultHandler = handler.getResultHandler(); stdOutStream.flush(); stdErrStream.flush(); jobStatus.setStdOut(new String(stdOutStream.toByteArray())); jobStatus.setStdErr(new String(stdErrStream.toByteArray())); if (resultHandler.hasResult()) { jobStatus.setState(JobStatus.State.COMPLETED); int exitValue = resultHandler.getExitValue(); log.info(jobId + " has terminated with exit code " + exitValue); if (exitValue == 0) { jobStatus.setResult(JobStatus.Result.SUCCESS); } else { jobStatus.setResult(JobStatus.Result.FAILURE); } jobIdToHandlerMap.remove(jobId); } else { jobStatus.setState(JobStatus.State.RUNNING); } return jobStatus; } catch (Exception e) { log.warn("Failed to retrieve status of " + jobId); return null; } }
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/* w ww . ja v a2 s . c o m*/ getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.fuin.esmp.EventStoreStartMojo.java
private List<String> waitForHttpServer(final DefaultExecuteResultHandler resultHandler, final ByteArrayOutputStream bos) throws MojoExecutionException { // Wait for result int wait = 0; while ((wait++ < maxWaitCycles) && !resultHandler.hasResult() && !bos.toString().contains(upMessage)) { sleep(sleepMs);//from ww w .j a v a 2 s .c o m } if (bos.toString().contains(upMessage)) { // Success return asList(bos.toString()); } // Failure final List<String> messages = asList(bos.toString()); logError(messages); // Exception if (resultHandler.hasResult()) { throw new MojoExecutionException("Error starting the server. Exit code=" + resultHandler.getExitValue(), resultHandler.getException()); } // Timeout throw new MojoExecutionException("Waited too long for the server to start!"); }
From source file:ro.cosu.vampires.client.executors.fork.ForkExecutor.java
@Override public Result execute(Computation computation) { acquireResources();/*from ww w. j a v a 2 s . com*/ CommandLine commandLine = getCommandLine(computation.command()); CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream(); PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream); executor.setStreamHandler(handler); executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS)); executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile()); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); LocalDateTime start = LocalDateTime.now(); int exitCode; try { executor.execute(commandLine, resultHandler); } catch (IOException e) { LOG.error("failed to exec", resultHandler.getException()); } try { resultHandler.waitFor(); } catch (InterruptedException e) { LOG.error("failed to exec", resultHandler.getException()); } exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1; //TODO take different action for failed commands so we can collect the output (stderr or java exception) LocalDateTime stop = LocalDateTime.now(); long duration = Duration.between(start, stop).toMillis(); releaseResources(); return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop)) .output(collectingLogOutputStream.getLines()).build(); }