List of usage examples for java.lang ProcessBuilder environment
Map environment
To view the source code for java.lang ProcessBuilder environment.
Click Source Link
From source file:net.pms.configuration.DownloadPlugins.java
private void doExec(String args) throws IOException, InterruptedException, ConfigurationException { int pos = args.indexOf(','); if (pos == -1) { // weird stuff return;//from w w w . ja v a 2 s.co m } // Everything after the "," is what we're supposed to run // First make note of jars we got File[] oldJar = new File(configuration.getPluginDirectory()).listFiles(); // Before we start external installers better save the config configuration.save(); ProcessBuilder pb = new ProcessBuilder(args.substring(pos + 1)); pb.redirectErrorStream(true); Map<String, String> env = pb.environment(); env.put("PROFILE_PATH", configuration.getProfilePath()); env.put("UMS_VERSION", PMS.getVersion()); LOGGER.debug("running '" + args + "'"); Process pid = pb.start(); // Consume and log any output Scanner output = new Scanner(pid.getInputStream()); while (output.hasNextLine()) { LOGGER.debug("[" + args + "] " + output.nextLine()); } configuration.reload(); pid.waitFor(); File[] newJar = new File(configuration.getPluginDirectory()).listFiles(); for (File f : newJar) { if (!f.getAbsolutePath().endsWith(".jar")) { // skip non jar files continue; } for (File oldJar1 : oldJar) { if (f.getAbsolutePath().equals(oldJar1.getAbsolutePath())) { // old jar file break out, and set f to null to skip adding it f = null; break; } } // if f is null this is an jar that is old if (f != null) { jars.add(f.toURI().toURL()); } } }
From source file:com.hellblazer.process.impl.AbstractManagedProcess.java
/** * The actual execution process. Control will not return until the command * list execution has finished./*from w ww . j ava 2 s . c o m*/ * * @param commands * - the command list to execute * * @throws IOException * - if anything goes wrong during the execution. */ protected void primitiveExecute(List<String> commands) throws IOException { ProcessBuilder builder = new ProcessBuilder(); builder.directory(directory); if (environment != null) { builder.environment().putAll(environment); } builder.command(commands); builder.redirectErrorStream(true); // combine OUT and ERR into one // stream Process p = builder.start(); final BufferedReader shellReader = new BufferedReader(new InputStreamReader(p.getInputStream())); Runnable reader = new Runnable() { @Override public void run() { String line; try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage()) && !e.getMessage().contains("Bad file descriptor")) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } while (line != null) { if (log.isLoggable(Level.FINE) && line != null) { log.fine("[" + id + "] " + line); } try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage())) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } } } }; Thread readerThread = new Thread(reader, "Process reader for: " + getCommand()); readerThread.setDaemon(true); readerThread.start(); try { p.waitFor(); } catch (InterruptedException e) { return; } finally { readerThread.interrupt(); p.destroy(); } }
From source file:com.amazonaws.services.kinesis.producer.Daemon.java
private void startChildProcess() throws IOException, InterruptedException { log.info("Asking for trace"); List<String> args = new ArrayList<>(Arrays.asList(pathToExecutable, "-o", outPipe.getAbsolutePath(), "-i", inPipe.getAbsolutePath(), "-c", protobufToHex(config.toProtobufMessage()), "-k", protobufToHex(makeSetCredentialsMessage(config.getCredentialsProvider(), false)), "-t")); AWSCredentialsProvider metricsCreds = config.getMetricsCredentialsProvider(); if (metricsCreds == null) { metricsCreds = config.getCredentialsProvider(); }/*from ww w .j av a 2s . c om*/ args.add("-w"); args.add(protobufToHex(makeSetCredentialsMessage(metricsCreds, true))); final ProcessBuilder pb = new ProcessBuilder(args); for (Entry<String, String> e : environmentVariables.entrySet()) { pb.environment().put(e.getKey(), e.getValue()); } executor.submit(new Runnable() { @Override public void run() { try { connectToChild(); startLoops(); } catch (IOException e) { fatalError("Unexpected error connecting to child process", e, false); } } }); try { process = pb.start(); } catch (Exception e) { fatalError("Error starting child process", e, false); } stdOutReader = new LogInputStreamReader(process.getInputStream(), "StdOut", new LogInputStreamReader.DefaultLoggingFunction() { @Override public void apply(Logger logger, String message) { logger.info(message); } }); stdErrReader = new LogInputStreamReader(process.getErrorStream(), "StdErr", new LogInputStreamReader.DefaultLoggingFunction() { @Override public void apply(Logger logger, String message) { logger.warn(message); } }); executor.submit(stdOutReader); executor.submit(stdErrReader); try { int code = process.waitFor(); fatalError("Child process exited with code " + code, code != 1); } finally { stdOutReader.shutdown(); stdErrReader.shutdown(); deletePipes(); } }
From source file:edu.rice.dca.soaplabPBS.PBSJob.java
/************************************************************************** * Create and return a ProcessBuilder filled with the command-line * arguments and environment as defined in the metadata and user * input data for this job.//from w ww. ja v a2 s .c o m * * It throws an exception when it was not able to fill the * ProcessBuilder. **************************************************************************/ protected ProcessBuilder getProcessBuilder() throws SoaplabException { // command-line arguments ProcessBuilder pb = new ProcessBuilder(createArgs()); pb.command().add(0, getExecutableName()); // environment from several sources... Map<String, String> env = pb.environment(); // ...from the user (as defined by the service metadata) addProperties(env, createEnvs()); // ...from the service configuration addProperties(env, Config.getMatchingProperties(Config.PROP_ENVAR, getServiceName(), this)); // ...combine the current PATH and Soaplab's addtopath properties addToPath(env, Config.getStrings(Config.PROP_ADDTOPATH_DIR, null, getServiceName(), this)); // working directory pb.directory(getJobDir()); return pb; }
From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java
@Override public String startServiceForSimultion(String serviceId, String runtimeOptions, Map<String, Object> simulationContext) { String instanceId = serviceId + "-" + new Date().getTime(); // get execution path ServiceInfo serviceInfo = services.get(serviceId); if (serviceInfo == null) { //TODO: publish error on status topic throw new RuntimeException("Service not found: " + serviceId); }//from w ww. j a v a2 s .c o m // are multiple allowed? if not check to see if it is already running, if it is then fail if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) { throw new RuntimeException( "Service is already running and multiple instances are not allowed: " + serviceId); } File serviceDirectory = new File( getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId); ProcessBuilder processServiceBuilder = new ProcessBuilder(); Process process = null; List<String> commands = new ArrayList<String>(); Map<String, String> envVars = processServiceBuilder.environment(); //set environment variables List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables(); for (EnvironmentVariable envVar : envVarList) { String value = envVar.getEnvValue(); //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (value.contains("(")) { String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")"); for (String args : replaceValue) { value = value.replace("(" + args + ")", simulationContext.get(args).toString()); } } } envVars.put(envVar.getEnvName(), value); } //add executation command commands.add(serviceInfo.getExecution_path()); //Check if static args contain any replacement values List<String> staticArgsList = serviceInfo.getStatic_args(); for (String staticArg : staticArgsList) { if (staticArg != null) { //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (staticArg.contains("(")) { String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")"); for (String args : replaceArgs) { staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString()); } } } commands.add(staticArg); } } if (runtimeOptions != null) { commands.add(runtimeOptions); } try { if (serviceInfo.getType().equals(ServiceType.PYTHON)) { commands.add(0, "python"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.EXE)) { processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.JAVA)) { commands.add(0, "java -jar"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.WEB)) { } else { throw new RuntimeException("Type not recognized " + serviceInfo.getType()); } } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace); StringBuilder commandString = new StringBuilder(); for (String s : commands) { commandString.append(s); commandString.append(" "); } logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); } //create serviceinstance object ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId, process); serviceInstance.setService_info(serviceInfo); //add to service instances map serviceInstances.put(instanceId, serviceInstance); return instanceId; }
From source file:org.kiji.bento.box.tools.UpgradeInstallTool.java
/** * Perform an upgrade to the compatible version specified by the upgrade response. * * @param currentVersion of the BentoBox. * @param upgradeInfo from the checkin server specifying where the new version is. * @return an exit status code of 0 for success, nonzero for error. * @throws IOException if there's a problem downloading the package. * @throws InterruptedException if there's an interrupt while waiting for a script to run. *//*from w w w .j a v a 2 s . c o m*/ private int runUpgrade(String currentVersion, UpgradeResponse upgradeInfo) throws IOException, InterruptedException { // If the upgrade information refers to a later version than the one currently running, and // if it's time to give a reminder, do so. if (!upgradeInfo.isCompatibleNewer(currentVersion)) { System.out.println("You are already running the latest BentoBox."); return 0; // Nothing to do. } System.out.println("A new update is available!"); System.out.println("Current BentoBox version: " + currentVersion); System.out.println("Beginning upgrade to version: " + upgradeInfo.getCompatibleVersion()); final File workingDir = makeWorkDir(); final File targetFile = makeDownloadTarget(upgradeInfo, workingDir); final URL upgradeUrl = upgradeInfo.getCompatibleVersionURL(); LOG.info("Downloading: " + upgradeUrl.toString()); final HttpClient httpClient = new DefaultHttpClient(); final HttpGet getReq = new HttpGet(upgradeUrl.toString()); try { HttpResponse downloadResponse = httpClient.execute(getReq); int statusCode = downloadResponse.getStatusLine().getStatusCode(); LOG.debug("Status code: " + statusCode); if (statusCode != HttpStatus.SC_OK) { System.out.println("Received error from HTTP server:\n"); System.out.println(downloadResponse.getStatusLine().getReasonPhrase()); return 1; } HttpEntity entity = downloadResponse.getEntity(); if (null == entity) { System.out.println("Empty HTTP response when downloading from server."); System.out.println("Cannot automatically upgrade."); return 1; } OutputStream targetStream = new FileOutputStream(targetFile); try { entity.writeTo(targetStream); } finally { targetStream.close(); } } finally { getReq.releaseConnection(); httpClient.getConnectionManager().shutdown(); } // Run tar vzxf on the tarball. final String unzippedDirName = getUnzippedDir(targetFile); unzip(workingDir, targetFile); LOG.info("Running bootstrap command in new instance..."); // Run the upgrade bootstrap script from this tarball. final String[] command = { makeBootstrapCmd(workingDir, unzippedDirName).toString(), mBentoRootPath, currentVersion, }; debugLogStringArray("Bootstrap command:", command); final ProcessBuilder bootstrapProcBuilder = new ProcessBuilder(command).redirectErrorStream(true) .directory(workingDir); // Configure the environment for this process to run in. // We want to do so in as minimal an environment as possible. final Map<String, String> env = bootstrapProcBuilder.environment(); final String javaHome = env.get("JAVA_HOME"); env.clear(); // Run script in pure/empty environment. env.put("USER", System.getProperty("user.name")); env.put("HOME", System.getProperty("user.home")); if (javaHome != null) { env.put("JAVA_HOME", javaHome); } final Process bootstrapProcess = bootstrapProcBuilder.start(); printProcessOutput(bootstrapProcess); return bootstrapProcess.waitFor(); // Return its exit code. }
From source file:org.broadinstitute.sting.utils.runtime.ProcessController.java
/** * Executes a command line program with the settings and waits for it to return, * processing the output on a background thread. * * @param settings Settings to be run.// ww w . j a va2s . c om * @return The output of the command. */ public ProcessOutput exec(ProcessSettings settings) { if (destroyed) throw new IllegalStateException("This controller was destroyed"); ProcessBuilder builder = new ProcessBuilder(settings.getCommand()); builder.directory(settings.getDirectory()); Map<String, String> settingsEnvironment = settings.getEnvironment(); if (settingsEnvironment != null) { Map<String, String> builderEnvironment = builder.environment(); builderEnvironment.clear(); builderEnvironment.putAll(settingsEnvironment); } builder.redirectErrorStream(settings.isRedirectErrorStream()); StreamOutput stdout = null; StreamOutput stderr = null; // Start the process running. try { synchronized (toCapture) { process = builder.start(); } running.add(this); } catch (IOException e) { throw new ReviewedStingException( "Unable to start command: " + StringUtils.join(builder.command(), " ")); } int exitCode; try { // Notify the background threads to start capturing. synchronized (toCapture) { toCapture.put(ProcessStream.Stdout, new CapturedStreamOutput(settings.getStdoutSettings(), process.getInputStream(), System.out)); toCapture.put(ProcessStream.Stderr, new CapturedStreamOutput(settings.getStderrSettings(), process.getErrorStream(), System.err)); toCapture.notifyAll(); } // Write stdin content InputStreamSettings stdinSettings = settings.getStdinSettings(); Set<StreamLocation> streamLocations = stdinSettings.getStreamLocations(); if (!streamLocations.isEmpty()) { try { OutputStream stdinStream = process.getOutputStream(); for (StreamLocation location : streamLocations) { InputStream inputStream; switch (location) { case Buffer: inputStream = new ByteArrayInputStream(stdinSettings.getInputBuffer()); break; case File: try { inputStream = FileUtils.openInputStream(stdinSettings.getInputFile()); } catch (IOException e) { throw new UserException.BadInput(e.getMessage()); } break; case Standard: inputStream = System.in; break; default: throw new ReviewedStingException("Unexpected stream location: " + location); } try { IOUtils.copy(inputStream, stdinStream); } finally { if (location != StreamLocation.Standard) IOUtils.closeQuietly(inputStream); } } stdinStream.flush(); } catch (IOException e) { throw new ReviewedStingException( "Error writing to stdin on command: " + StringUtils.join(builder.command(), " "), e); } } // Wait for the process to complete. try { process.getOutputStream().close(); process.waitFor(); } catch (IOException e) { throw new ReviewedStingException( "Unable to close stdin on command: " + StringUtils.join(builder.command(), " "), e); } catch (InterruptedException e) { throw new ReviewedStingException("Process interrupted", e); } finally { while (!destroyed && stdout == null || stderr == null) { synchronized (fromCapture) { if (fromCapture.containsKey(ProcessStream.Stdout)) stdout = fromCapture.remove(ProcessStream.Stdout); if (fromCapture.containsKey(ProcessStream.Stderr)) stderr = fromCapture.remove(ProcessStream.Stderr); try { if (stdout == null || stderr == null) fromCapture.wait(); } catch (InterruptedException e) { // Log the error, ignore the interrupt and wait patiently // for the OutputCaptures to (via finally) return their // stdout and stderr. logger.error(e); } } } if (destroyed) { if (stdout == null) stdout = StreamOutput.EMPTY; if (stderr == null) stderr = StreamOutput.EMPTY; } } } finally { synchronized (toCapture) { exitCode = process.exitValue(); process = null; } running.remove(this); } return new ProcessOutput(exitCode, stdout, stderr); }
From source file:org.apache.kudu.client.MiniKuduCluster.java
/** * Starts a process using the provided command and configures it to be daemon, * redirects the stderr to stdout, and starts a thread that will read from the process' input * stream and redirect that to LOG./*w w w .ja v a 2s.c om*/ * @param port RPC port used to identify the process * @param command process and options * @return The started process * @throws Exception Exception if an error prevents us from starting the process, * or if we were able to start the process but noticed that it was then killed (in which case * we'll log the exit value). */ private Process configureAndStartProcess(int port, List<String> command) throws Exception { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); if (miniKdc != null) { processBuilder.environment().putAll(miniKdc.getEnvVars()); } Process proc = processBuilder.start(); ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable( proc.getInputStream()); Thread thread = new Thread(printer); thread.setDaemon(true); thread.setName(Iterables.getLast(Splitter.on(File.separatorChar).split(command.get(0))) + ":" + port); PROCESS_INPUT_PRINTERS.add(thread); thread.start(); Thread.sleep(300); try { int ev = proc.exitValue(); throw new Exception(String.format("We tried starting a process (%s) but it exited with value=%s", command.get(0), ev)); } catch (IllegalThreadStateException ex) { // This means the process is still alive, it's like reverse psychology. } return proc; }
From source file:com.anthemengineering.mojo.infer.InferMojo.java
/** * Executes infer once for each source file and writes the output to {@code inferOutputDir}. * * @param classpath classpath used as an argument to the javac command given to Infer. * @param inferOutputDir directory where Infer will write its output * @param sourceFiles collection of files for Infer to analyze * @param numSourceFiles number of source files to analyze; used to make sure every Infer execution finishes * before moving on./*from www .j av a2s. c o m*/ */ private void completeInferExecutions(final String classpath, final File inferOutputDir, Collection<File> sourceFiles, int numSourceFiles) throws MojoExecutionException { // temporary directory for storing .class files created by {@code javac}; placed in build directory final File buildTmpDir = new File(project.getBuild().getDirectory(), JAVAC_OUTPUT_DIRECTORY_NAME); try { FileUtils.forceMkdir(buildTmpDir); } catch (final IOException e) { final String errMsg = String.format("Unable to make temp directory %s!", buildTmpDir.getAbsolutePath()); getLog().error(errMsg, e); throw new MojoExecutionException(errMsg, e); } buildTmpDir.deleteOnExit(); // used to wait for all processes running infer to complete final CountDownLatch doneSignal = new CountDownLatch(numSourceFiles); // TODO: optionally allow debugging info? Output directory? // TODO: a better way to do this may be to determine if there is an entry point that takes a set of source // files and the classpath and use this. @See mvn, inferj and inferlib in the infer repository. ExecutorService pool = null; try { pool = Executors.newFixedThreadPool(4); for (final File sourceFile : sourceFiles) { final Runnable r = new Runnable() { @Override public void run() { Process proc = null; try { // infer final List<String> command = new ArrayList<String>(); command.add(inferPath); command.add("-i"); command.add("-o"); command.add(inferOutputDir.getAbsolutePath()); command.add("--"); // javac command.add("javac"); command.add(sourceFile.getAbsolutePath()); command.add("-d"); command.add(buildTmpDir.getAbsolutePath()); command.add("-classpath"); command.add(classpath); final ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(System.getenv()); if (consoleOut) { builder.redirectErrorStream(true); proc = builder.start(); InputStreamReader isr = null; BufferedReader br = null; InputStream pis = null; try { pis = proc.getInputStream(); isr = new InputStreamReader(pis); br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { getLog().info(line); } } catch (final IOException e) { getLog().error(String.format("Error writing process output for file: %s.", sourceFile.getAbsolutePath()), e); } finally { if (isr != null) { isr.close(); } if (br != null) { br.close(); } if (pis != null) { pis.close(); } } } else { // no logging. proc = builder.start(); } // NOTE: most/all executions end in failure during analysis, however, // supported java bugs are still reported proc.waitFor(); } catch (final IOException e) { getLog().error( "Exception occurred while trying to perform Infer execution; output not complete" + "", e); } catch (final InterruptedException e) { getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e); } finally { try { // currently they all fail, although java bugs are still reported if (proc != null && proc.exitValue() != 0) { FAILED_CHECKS.put(sourceFile, proc.exitValue()); } } catch (final Exception e) { FAILED_CHECKS.put(sourceFile, -1); } doneSignal.countDown(); } } }; pool.submit(r); } } finally { if (pool != null) { pool.shutdown(); } } try { doneSignal.await(); } catch (final InterruptedException e) { getLog().error(EARLY_EXECUTION_TERMINATION_EXCEPTION_MSG, e); } }
From source file:org.pepstock.jem.junit.init.submitters.AbstractSubmitter.java
/** * /*from www .j a v a 2s .co m*/ * @param command * @param args * @return * @throws NodeMessageException * @throws IOException * @throws InterruptedException */ int launch(String command, String[] args) throws NodeMessageException, IOException, InterruptedException { String osCommand = null; if (SystemUtils.IS_OS_WINDOWS) { osCommand = command + ".cmd"; } else { osCommand = command + ".sh"; } Process process = null; try { File logFile = File.createTempFile("junit", "log"); String redirect = "> " + FilenameUtils.normalize(logFile.getAbsolutePath(), true) + " 2>&1"; StringBuilder sb = new StringBuilder(osCommand); for (String arg : args) { sb.append(" ").append(arg); } System.err.println(sb.toString()); sb.append(" ").append(redirect); // create a process builder ProcessBuilder builder = new ProcessBuilder(); Shell shell = CurrentPlatform.getInstance().getShell(); builder.command(shell.getName(), shell.getParameters(), sb.toString()); // set directory where execute process builder.directory(new File(System.getenv("JEM_HOME") + "/bin")); // load variable environment from a temporary maps that you can use // inside of configure method. Map<String, String> env = System.getenv(); Map<String, String> map = builder.environment(); for (Map.Entry<String, String> e : env.entrySet()) { map.put(e.getKey(), e.getValue()); } // start process and save instance process = builder.start(); // wait for end of job execution int rc = process.waitFor(); FileInputStream fis = new FileInputStream(logFile); IOUtils.copy(fis, System.out); IOUtils.closeQuietly(fis); logFile.delete(); return rc; } finally { if (process != null) { process.destroy(); } } }