List of usage examples for java.lang ProcessBuilder redirectError
public ProcessBuilder redirectError(File file)
From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java
private ProcessDescription start(final File jar) throws Exception { final ProcessDescription cfg = new ProcessDescription(this.configuration.getId(), this.configuration.getFolder()); final ProcessBuilder builder = new ProcessBuilder(); final List<String> args = new ArrayList<String>(); args.add("java"); add(args, this.configuration.getVmOpts()); add(args, this.configuration.getVmDebugOpts(this.environment.getDebug())); args.add("-cp"); args.add("bin"); args.add(Main.class.getName()); // first three arguments: jar, listener port, verbose args.add(jar.getPath());/*from w w w. j av a2 s . c o m*/ args.add(String.valueOf(cfg.getControlListener().getPort())); args.add("true"); // from here on launchpad properties add(args, this.configuration.getOpts()); final String contextPath = this.configuration.getContextPath(); if (contextPath != null && contextPath.length() > 0 && !contextPath.equals("/")) { args.add("-r"); args.add(contextPath); } if (this.configuration.getPort() != null) { args.add("-p"); args.add(this.configuration.getPort()); } if (this.configuration.getControlPort() != null) { args.add("-j"); args.add(this.configuration.getControlPort()); } if (this.configuration.getRunmode() != null && this.configuration.getRunmode().length() > 0) { args.add("-Dsling.run.modes=" + this.configuration.getRunmode()); } if (!this.environment.isShutdownOnExit()) { args.add("start"); } builder.command(args.toArray(new String[args.size()])); builder.directory(this.configuration.getFolder()); builder.redirectErrorStream(true); builder.redirectOutput(Redirect.INHERIT); builder.redirectError(Redirect.INHERIT); logger.info("Starting Launchpad " + this.configuration.getId() + "..."); logger.debug("Launchpad cmd: " + builder.command()); logger.debug("Launchpad dir: " + builder.directory()); try { cfg.setProcess(builder.start()); } catch (final IOException e) { if (cfg.getProcess() != null) { cfg.getProcess().destroy(); cfg.setProcess(null); } throw new Exception("Could not start the Launchpad", e); } return cfg; }
From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java
@SuppressFBWarnings(value = "COMMAND_INJECTION", justification = "mini runs in the same security context as user providing the args") private ProcessInfo _exec(Class<?> clazz, List<String> extraJvmOpts, String... args) throws IOException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = getClasspath(); String className = clazz.getName(); ArrayList<String> argList = new ArrayList<>(); argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath)); argList.addAll(extraJvmOpts);//from w w w .jav a 2 s . c o m for (Entry<String, String> sysProp : config.getSystemProperties().entrySet()) { argList.add(String.format("-D%s=%s", sysProp.getKey(), sysProp.getValue())); } // @formatter:off argList.addAll(Arrays.asList("-XX:+UseConcMarkSweepGC", "-XX:CMSInitiatingOccupancyFraction=75", "-Dapple.awt.UIElement=true", "-Djava.net.preferIPv4Stack=true", "-XX:+PerfDisableSharedMem", "-XX:+AlwaysPreTouch", Main.class.getName(), className)); // @formatter:on argList.addAll(Arrays.asList(args)); ProcessBuilder builder = new ProcessBuilder(argList); builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath()); builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath()); builder.environment().put("ACCUMULO_CLIENT_CONF_PATH", config.getClientConfFile().getAbsolutePath()); String ldLibraryPath = Joiner.on(File.pathSeparator).join(config.getNativeLibPaths()); builder.environment().put("LD_LIBRARY_PATH", ldLibraryPath); builder.environment().put("DYLD_LIBRARY_PATH", ldLibraryPath); // if we're running under accumulo.start, we forward these env vars String env = System.getenv("HADOOP_HOME"); if (env != null) builder.environment().put("HADOOP_HOME", env); env = System.getenv("ZOOKEEPER_HOME"); if (env != null) builder.environment().put("ZOOKEEPER_HOME", env); builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath()); if (config.getHadoopConfDir() != null) builder.environment().put("HADOOP_CONF_DIR", config.getHadoopConfDir().getAbsolutePath()); log.debug("Starting MiniAccumuloCluster process with class: " + clazz.getSimpleName() + "\n, jvmOpts: " + extraJvmOpts + "\n, classpath: " + classpath + "\n, args: " + argList + "\n, environment: " + builder.environment()); int hashcode = builder.hashCode(); File stdOut = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".out"); File stdErr = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".err"); Process process = builder.redirectError(stdErr).redirectOutput(stdOut).start(); cleanup.add(process); return new ProcessInfo(process, stdOut); }
From source file:io.snappydata.hydra.cluster.SnappyTest.java
public void executeProcess(ProcessBuilder pb, File logFile) { Process p = null;/*from w ww .ja v a2 s .com*/ try { pb.redirectErrorStream(true); pb.redirectError(ProcessBuilder.Redirect.PIPE); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); p = pb.start(); assert pb.redirectInput() == ProcessBuilder.Redirect.PIPE; assert pb.redirectOutput().file() == logFile; assert p.getInputStream().read() == -1; int rc = p.waitFor(); if (rc == 0) { Log.getLogWriter().info("Executed successfully"); } else { Log.getLogWriter().info("Failed with exit code: " + rc); } } catch (IOException e) { throw new TestException( "Exception occurred while starting the process:" + pb + "\nError Message:" + e.getMessage()); } catch (InterruptedException e) { throw new TestException("Exception occurred while waiting for the process execution:" + p + "\nError Message:" + e.getMessage()); } }
From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java
/** * {@inheritDoc}// w ww . j av a 2 s .c o m */ @Override public void launchProcess(final File jobDirectory, final Map<String, String> environmentVariablesMap, final List<String> commandLine, final boolean interactive) throws JobLaunchException { if (!launched.compareAndSet(false, true)) { throw new IllegalStateException("Job already launched"); } final ProcessBuilder processBuilder = new ProcessBuilder(); // Validate job running directory if (jobDirectory == null) { throw new JobLaunchException("Job directory is null"); } else if (!jobDirectory.exists()) { throw new JobLaunchException("Job directory does not exist: " + jobDirectory); } else if (!jobDirectory.isDirectory()) { throw new JobLaunchException("Job directory is not a directory: " + jobDirectory); } else if (!jobDirectory.canWrite()) { throw new JobLaunchException("Job directory is not writable: " + jobDirectory); } final Map<String, String> currentEnvironmentVariables = processBuilder.environment(); if (environmentVariablesMap == null) { throw new JobLaunchException("Job environment variables map is null"); } // Merge job environment variables into process inherited environment environmentVariablesMap.forEach((key, value) -> { final String replacedValue = currentEnvironmentVariables.put(key, value); if (StringUtils.isBlank(replacedValue)) { log.debug("Added job environment variable: {}={}", key, value); } else if (!replacedValue.equals(value)) { log.debug("Set job environment variable: {}={} (previous value: {})", key, value, replacedValue); } }); // Validate arguments if (commandLine == null) { throw new JobLaunchException("Job command-line arguments is null"); } else if (commandLine.isEmpty()) { throw new JobLaunchException("Job command-line arguments are empty"); } // Configure arguments log.info("Job command-line: {}", Arrays.toString(commandLine.toArray())); final List<String> expandedCommandLine; try { expandedCommandLine = expandCommandLineVariables(commandLine, Collections.unmodifiableMap(currentEnvironmentVariables)); } catch (final EnvUtils.VariableSubstitutionException e) { throw new JobLaunchException("Job command-line arguments variables could not be expanded"); } if (!commandLine.equals(expandedCommandLine)) { log.info("Job command-line with variables expanded: {}", Arrays.toString(expandedCommandLine.toArray())); } processBuilder.command(expandedCommandLine); if (interactive) { processBuilder.inheritIO(); } else { processBuilder.redirectError(PathUtils.jobStdErrPath(jobDirectory).toFile()); processBuilder.redirectOutput(PathUtils.jobStdOutPath(jobDirectory).toFile()); } if (killed.get()) { log.info("Job aborted, skipping launch"); } else { log.info("Launching job"); try { processReference.set(processBuilder.start()); } catch (final IOException | SecurityException e) { throw new JobLaunchException("Failed to launch job: ", e); } log.info("Process launched (pid: {})", getPid(processReference.get())); } }
From source file:com.kdmanalytics.toif.framework.toolAdaptor.ToolAdaptor.java
/** * Run the tool. A command needs to be constructed, the same as you would if * you were running it from the command line. * //from ww w .jav a2s.c o m * @return return the process which was created by running the tool. * @throws ToifException */ public java.io.File runTool() throws ToifException { ProcessBuilder process = null; java.io.File file = null; final String[] command = getCommands(); synchronized (this) { StringBuilder sb = new StringBuilder(); for (String cmd : command) { sb.append(cmd).append(" "); } } process = new ProcessBuilder(command); // DISABLED Nicing Windows. It seems that the cmd is dodgy and // occasionally loses the path that we set in the environment, // and it certainly does not like having absolute paths to // executables (at least ones with spaces). // Put the executable directory in path // if(SystemUtils.IS_OS_WINDOWS && execDir != null) // { // Map<String,String> env = process.environment(); // String envPath = env.get("PATH"); // if(envPath != null) // { // envPath = execDir.toString() + ";" + envPath; // } // else // { // envPath = execDir.toString(); // } // System.err.println("SETTING PATH: " + envPath); // env.put("PATH", envPath); // } // This doesn't work without spawning a bat or shell wrapper // // Extra path information // java.io.File paths = options.getPaths(); // if(paths != null) // { // Map<String,String> env = process.environment(); // String envPath = env.get("PATH"); // if(envPath != null) // { // envPath = paths + ";" + envPath; // } // else // { // envPath = paths.toString(); // } // System.err.println("SETTING PATH: " + envPath); // env.put("PATH", envPath); // } if (workingDirectory != null) { process.directory(workingDirectory); } java.io.File outputDirectory = options.getOutputDirectory(); outputDirectory.mkdirs(); file = null; if (adaptorImpl.getAdaptorName().equals("Splint")) { file = new java.io.File(outputDirectory, options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName()); java.io.File file2 = new java.io.File(outputDirectory, options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName()); java.io.File tmp = null; try { tmp = java.io.File.createTempFile("splint", ".tmp"); } catch (IOException e) { LOG.error("", e); throw new ToifException(); } if (tmp != null) { tmp.deleteOnExit(); process.redirectOutput(tmp); } process.redirectError(file2); } // if (adaptorImpl.getAdaptorName().equals("Cppcheck")) // { // file = new java.io.File(options.getOutputDirectory(), // options.getInputFile().getName() + "." + // adaptorImpl.getRuntoolName()); // java.io.File file2 = new java.io.File(options.getOutputDirectory(), // options.getInputFile().getName() + "-err." // + adaptorImpl.getRuntoolName()); // // process.redirectOutput(file2); // process.redirectError(file); // } else { file = new java.io.File(outputDirectory, options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName()); java.io.File file2 = new java.io.File(outputDirectory, options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName()); process.redirectOutput(file); process.redirectError(file2); } try { Process p = process.start(); p.waitFor(); // Check the exit value to ensure that process did not fail // except splint, splint is stupid and is always non-zero String name = adaptorImpl.getAdaptorName(); if ((p.exitValue() != 0) && (!"Splint".equals(name))) { int status = p.exitValue(); final String msg = "Adaptor process failure detected for '" + name + "': status=" + status + " " + options.getAdaptor().toString(); LOG.error(msg); throw new ToifException(msg); } return file; } catch (final IOException | InterruptedException e) { final String msg = options.getAdaptor().toString() + ": Could not write to output. " + e; LOG.error(msg); throw new ToifException(e); } }
From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java
@Override public void run() { Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile; // Path lockMarker; Process process;/*from ww w. j a va2 s.c o m*/ int exitValue; Set<JsonReportEntry> report; JsonReportEntry entry; String line; StringBuffer buf; Path srcPath, destPath; ProcessBuilder processBuilder; Ticket ticket; String script, stdOut, stdErr; long tic, toc; JSONObject obj; Message msg; Charset cs; int trial; boolean suc; Exception ex; if (log.isDebugEnabled()) log.debug("Starting up local thread for ticket " + invoc.getTicketId() + "."); if (invoc == null) throw new NullPointerException("Invocation must not be null."); ticket = invoc.getTicket(); process = null; stdOut = null; stdErr = null; // lockMarker = null; script = null; successMarker = null; cs = Charset.forName("UTF-8"); try { callLocation = Paths.get(System.getProperty("user.dir")); location = buildDir.resolve(String.valueOf(invoc.getTicketId())); // lockMarker = location.resolve( Invocation.LOCK_FILENAME ); successMarker = location.resolve(Invocation.SUCCESS_FILENAME); reportFile = location.resolve(Invocation.REPORT_FILENAME); script = invoc.toScript(); // if( Files.exists( lockMarker ) ) // throw new IOException( "Lock held on ticket "+invoc.getTicketId() ); if (!Files.exists(successMarker)) { deleteIfExists(location); Files.createDirectories(location); // Files.createFile( lockMarker ); scriptFile = invoc.getExecutablePath(location); Files.createFile(scriptFile, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"))); // write executable script try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) { writer.write(script); } // write executable log entry try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) { writer.write(ticket.getExecutableLogEntry().toString()); writer.write('\n'); } for (String filename : invoc.getStageInList()) { if (filename.charAt(0) == '/') throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'."); srcPath = centralRepo.resolve(filename); destPath = location.resolve(filename); if (!Files.exists(srcPath)) { srcPath = callLocation.resolve(filename); if (log.isTraceEnabled()) log.trace("Resolving relative path '" + srcPath + "'."); } else if (log.isTraceEnabled()) log.trace("Resolving path to central repository '" + srcPath + "'."); if (log.isTraceEnabled()) log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'."); if (!Files.exists(destPath.getParent())) Files.createDirectories(destPath.getParent()); Files.createSymbolicLink(destPath, srcPath); } // run script processBuilder = new ProcessBuilder(invoc.getCmd()); processBuilder.directory(location.toFile()); stdOutFile = location.resolve(Invocation.STDOUT_FILENAME); stdErrFile = location.resolve(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile.toFile()); processBuilder.redirectError(stdErrFile.toFile()); trial = 1; suc = false; ex = null; tic = System.currentTimeMillis(); do { try { process = processBuilder.start(); suc = true; } catch (IOException e) { ex = e; if (log.isWarnEnabled()) log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL + "ms: " + e.getMessage()); Thread.sleep(WAIT_INTERVAL); } } while (suc == false && trial <= MAX_TRIALS); if (process == null) { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null)); // Files.delete( lockMarker ); return; } exitValue = process.waitFor(); toc = System.currentTimeMillis(); try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) { obj = new JSONObject(); obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic); entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj); writer.write(entry.toString()); writer.write('\n'); try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdOut = buf.toString(); if (!stdOut.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut); writer.write(entry.toString()); writer.write('\n'); } } try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdErr = buf.toString(); if (!stdErr.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr); writer.write(entry.toString()); writer.write('\n'); } } if (exitValue == 0) Files.createFile(successMarker); else { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr)); // Files.delete( lockMarker ); return; } } } // gather report report = new HashSet<>(); try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) { while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; entry = new JsonReportEntry(line); // If the report comes from the hard cache then the run id // is different from the run id of this invocation. This is // corrected here. entry.setRunId(invoc.getRunId()); report.add(entry); } } invoc.evalReport(report); // create link in central data repository for (String f : invoc.getStageOutList()) { srcPath = location.resolve(f); destPath = centralRepo.resolve(f); if (Files.exists(destPath)) continue; if (log.isTraceEnabled()) log.trace("Creating link from " + srcPath + " to " + destPath + "."); Files.createSymbolicLink(destPath, srcPath); } ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report)); if (log.isTraceEnabled()) log.trace("Local thread ran through without exception."); // Files.deleteIfExists( lockMarker ); } catch (InterruptedException e) { if (log.isTraceEnabled()) log.trace("Local thread has been interrupted."); } catch (Exception e) { if (log.isTraceEnabled()) log.trace("Something went wrong. Deleting success marker if present."); if (successMarker != null) try { Files.deleteIfExists(successMarker); } catch (IOException e1) { e1.printStackTrace(); } msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr); ticketSrc.sendMsg(msg); } finally { if (process != null) { if (log.isDebugEnabled()) log.debug("Stopping local thread for ticket " + invoc.getTicketId() + "."); process.destroy(); } } }