use of org.apache.commons.exec.DefaultExecutor in project cloudstack by apache.
the class HeatMojo method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
CommandLine commandLine = new CommandLine("heat");
if (dir != null && !dir.trim().isEmpty()) {
commandLine.addArgument("dir");
commandLine.addArgument(dir);
}
commandLine.addArgument("-gg");
commandLine.addArgument("-cg");
commandLine.addArgument(componentGroup);
commandLine.addArgument("-ke");
commandLine.addArgument("-sfrag");
if (template == null || template.trim().isEmpty()) {
commandLine.addArgument("-template");
commandLine.addArgument("fragment");
} else {
commandLine.addArgument("-template");
commandLine.addArgument(template);
}
if (outputFile != null) {
commandLine.addArgument("-out");
commandLine.addArgument(outputFile.getAbsolutePath());
}
if (directoryName != null) {
commandLine.addArgument("-dr");
commandLine.addArgument(directoryName);
}
if (vars != null) {
commandLine.addArguments(vars, false);
}
DefaultExecutor executor = new DefaultExecutor();
getLog().debug("working directory " + commandLine.toString());
executor.setWorkingDirectory(getWorkingDirectory(workingDirectory));
int exitValue = executor.execute(commandLine);
if (exitValue != 0) {
throw new MojoExecutionException("Problem executing heat, return code " + exitValue);
}
} catch (ExecuteException e) {
throw new MojoExecutionException("Problem executing heat", e);
} catch (IOException e) {
throw new MojoExecutionException("Problem executing heat", e);
}
}
use of org.apache.commons.exec.DefaultExecutor in project lucene-solr by apache.
the class TestSolrCLIRunExample method testFailExecuteScript.
@Test
public void testFailExecuteScript() throws Exception {
File solrHomeDir = new File(ExternalPaths.SERVER_HOME);
if (!solrHomeDir.isDirectory())
fail(solrHomeDir.getAbsolutePath() + " not found and is required to run this test!");
Path tmpDir = createTempDir();
File solrExampleDir = tmpDir.toFile();
File solrServerDir = solrHomeDir.getParentFile();
// need a port to start the example server on
int bindPort = -1;
try (ServerSocket socket = new ServerSocket(0)) {
bindPort = socket.getLocalPort();
}
File toExecute = new File(tmpDir.toString(), "failExecuteScript");
assertTrue("Should have been able to create file '" + toExecute.getAbsolutePath() + "' ", toExecute.createNewFile());
String[] toolArgs = new String[] { "-e", "techproducts", "-serverDir", solrServerDir.getAbsolutePath(), "-exampleDir", solrExampleDir.getAbsolutePath(), "-p", String.valueOf(bindPort), "-script", toExecute.getAbsolutePath().toString() };
// capture tool output to stdout
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
DefaultExecutor executor = new DefaultExecutor();
SolrCLI.RunExampleTool tool = new SolrCLI.RunExampleTool(executor, System.in, stdoutSim);
int code = tool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(tool.getOptions()), toolArgs));
assertTrue("Execution should have failed with return code 1", code == 1);
}
use of org.apache.commons.exec.DefaultExecutor in project sling by apache.
the class JarExecutor method start.
/** Start the jar if not done yet, and setup runtime hook
* to stop it.
*/
public void start() throws Exception {
final ExecuteResultHandler h = new ExecuteResultHandler() {
public void onProcessFailed(ExecuteException ex) {
log.error("Process execution failed:" + ex, ex);
}
public void onProcessComplete(int result) {
log.info("Process execution complete, exit code=" + result);
}
};
final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
executor = new DefaultExecutor();
final CommandLine cl = new CommandLine(jvmFullPath);
if (vmOptions != null && vmOptions.length() > 0) {
cl.addArguments(vmOptions);
}
cl.addArgument("-jar");
cl.addArgument(jarToExecute.getAbsolutePath());
// Additional options for the jar that's executed.
// $JAREXEC_SERVER_PORT$ is replaced our serverPort value
String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
if (jarOptions != null && jarOptions.length() > 0) {
jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
log.info("Executable jar options: {}", jarOptions);
cl.addArguments(jarOptions);
}
final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
if (workFolderOption != null && workFolderOption.length() > 0) {
final File workFolder = new File(workFolderOption);
if (!workFolder.isDirectory()) {
throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: " + workFolder.getAbsolutePath());
}
log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
executor.setWorkingDirectory(workFolder);
}
String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);
if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
final long start = System.currentTimeMillis();
log.info("Executing and waiting for result: " + cl);
final int result = executor.execute(cl);
final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
if (result != expected) {
throw new ExecutorException("Expected result code " + expected + ", got " + result);
}
} else {
log.info("Executing asynchronously: " + cl);
executor.setStreamHandler(new PumpStreamHandler());
final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer("java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
pd.setWaitOnShutdown(waitOnShutdown);
executor.setProcessDestroyer(pd);
executor.execute(cl, h);
}
}
use of org.apache.commons.exec.DefaultExecutor in project sling by apache.
the class JarExecutor method start.
/** Start the jar if not done yet, and setup runtime hook
* to stop it.
*/
public void start() throws Exception {
final ExecuteResultHandler h = new ExecuteResultHandler() {
public void onProcessFailed(ExecuteException ex) {
log.error("Process execution failed:" + ex, ex);
}
public void onProcessComplete(int result) {
log.info("Process execution complete, exit code=" + result);
}
};
final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
executor = new DefaultExecutor();
final CommandLine cl = new CommandLine(jvmFullPath);
if (vmOptions != null && vmOptions.length() > 0) {
cl.addArguments(vmOptions);
}
cl.addArgument("-jar");
cl.addArgument(jarToExecute.getAbsolutePath());
// Additional options for the jar that's executed.
// $JAREXEC_SERVER_PORT$ is replaced our serverPort value
String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
if (jarOptions != null && jarOptions.length() > 0) {
jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
log.info("Executable jar options: {}", jarOptions);
cl.addArguments(jarOptions);
}
final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
if (workFolderOption != null && workFolderOption.length() > 0) {
final File workFolder = new File(workFolderOption);
if (!workFolder.isDirectory()) {
throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: " + workFolder.getAbsolutePath());
}
log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
executor.setWorkingDirectory(workFolder);
}
String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);
if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
final long start = System.currentTimeMillis();
log.info("Executing and waiting for result: " + cl);
final int result = executor.execute(cl);
final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
if (result != expected) {
throw new ExecutorException("Expected result code " + expected + ", got " + result);
}
} else {
log.info("Executing asynchronously: " + cl);
executor.setStreamHandler(new PumpStreamHandler());
final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer("java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
pd.setWaitOnShutdown(waitOnShutdown);
executor.setProcessDestroyer(pd);
executor.execute(cl, h);
}
}
use of org.apache.commons.exec.DefaultExecutor in project Saturn by vipshop.
the class ScriptJobRunner method execute.
private SaturnJobReturn execute(long timeoutSeconds) {
SaturnJobReturn saturnJobReturn;
ProcessOutputStream processOutputStream = new ProcessOutputStream(1);
DefaultExecutor executor = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(processOutputStream);
// 关闭线程等待时间, (注意commons-exec会固定增加2秒的addition)
streamHandler.setStopTimeout(timeoutSeconds * 1000);
executor.setExitValue(0);
executor.setStreamHandler(streamHandler);
executor.setWatchdog(getWatchdog());
// filter env key in execParameter. like cd ${mypath} -> cd /root/my.
Map<String, String> env = ScriptPidUtils.loadEnv();
CommandLine commandLine = createCommandLine(env);
try {
long start = System.currentTimeMillis();
log.info("[{}] msg=Begin executing {}-{} {}", jobName, jobName, item, commandLine);
int exitValue = executor.execute(commandLine, env);
long end = System.currentTimeMillis();
log.info("[{}] msg=Finish executing {}-{} {}, the exit value is {}, cost={}ms", jobName, jobName, item, commandLine, exitValue, (end - start));
SaturnJobReturn tmp = readSaturnJobReturn();
if (tmp == null) {
tmp = new SaturnJobReturn("the exit value is " + exitValue);
}
saturnJobReturn = tmp;
} catch (Exception e) {
saturnJobReturn = handleException(timeoutSeconds, e);
} finally {
try {
// 将日志set进jobLog, 写不写zk再由ExecutionService控制
handleJobLog(processOutputStream.getJobLog());
processOutputStream.close();
} catch (Exception ex) {
log.error("[{}] msg={}-{} Error at closing output stream. Should not be concern: {}", jobName, jobName, item, ex);
}
stopStreamHandler(streamHandler);
ScriptPidUtils.removePidFile(job.getExecutorName(), jobName, "" + item, watchdog.getPid());
}
return saturnJobReturn;
}
Aggregations