List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { final Path chrootRoot = this.storage.getPath().resolve("chroot"); final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString()); FileAccess.createDirectories(chrootedProgram); FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory"); final Path policyFile = this.storage.getPath().resolve("olymp.policy"); try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) { paths.forEach(path -> {//from w w w . j a v a2 s . c o m try { Files.setPosixFilePermissions(path, new HashSet<PosixFilePermission>( Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ))); } catch (Exception e) { throw new RuntimeException(e); } }); } this.buildPolicy(chrootRoot, policyFile); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument("--security=0"); commandLine.addArgument("--jail=/"); commandLine.addArgument("--"); commandLine.addArgument("/usr/bin/java"); commandLine.addArgument("-classpath"); commandLine.addArgument(chrootedProgram.toAbsolutePath().toString()); commandLine.addArgument("-Djava.security.manager"); commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString()); commandLine.addArgument("-Xmx" + this.getMemoryLimit()); commandLine.addArgument("-Xms" + this.getMemoryLimit()); commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}", outOfMemoryFile.toAbsolutePath().toString()), false); commandLine.addArgument("Main"); final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the // sandbox to // complete executor.setWorkingDirectory(chrootRoot.toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); try { executor.execute(commandLine); } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt")); if (FileAccess.exists(outOfMemoryFile)) { readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT); } readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit()); return readOlrunnerVerdict; }
From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java
private static String callNativeId(boolean group) throws IOException { OpenOlympusWatchdogExecutor.ensureUserAndGroupExists(); final CommandLine commandLine = new CommandLine("id"); commandLine.addArgument(group ? "-g" : "-u"); commandLine.addArgument("olympuswatchdogchild"); final DefaultExecutor executor = new DefaultExecutor(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(out)); executor.setWatchdog(new ExecuteWatchdog(1000)); try {//from w w w . ja v a 2 s . co m executor.execute(commandLine); return out.toString(StandardCharsets.UTF_8.name()); } catch (final ExecuteException e) { throw new ExecuteException( "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?", e.getExitValue(), e); } }
From source file:org.ng200.openolympus.cerberus.executors.OpenOlympusWatchdogExecutor.java
private static void ensureUserAndGroupExists() throws IOException { if (alreadyEnsuredUserExists) return;//from w ww.j a v a 2s . c o m final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("useradd"); commandLine.addArgument("-U"); commandLine.addArgument("-M"); // Don't create home directory commandLine.addArgument("-s"); commandLine.addArgument("/bin/false"); commandLine.addArgument("olympuswatchdogchild"); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, /* Added user */ 9 /* User already exists */ }); executor.setWatchdog(new ExecuteWatchdog(1000)); try { executor.execute(commandLine); alreadyEnsuredUserExists = true; } catch (final ExecuteException e) { throw new ExecuteException( "Couldn't find user/group id of the olympuswatchdogchild user/group: does it even exist?", e.getExitValue(), e); } }
From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { SandboxedExecutor.logger.debug("Copying program into jail"); final Path chrootedProgram = this.storage.getPath().resolve("chroot") .resolve(program.getFileName().toString()); chrootedProgram.getParent().toFile().mkdirs(); FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument(MessageFormat.format("--jail={0}", this.storage.getPath().resolve("chroot").toAbsolutePath().toString())); commandLine.addArgument("--"); commandLine// ww w.j a va2 s . com .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString()); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the // sandbox to // complete executor.setWorkingDirectory(this.storage.getPath().toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString()); try { executor.execute(commandLine); } catch (final ExecuteException e) { SandboxedExecutor.logger.info("Execution failed: {}", e); throw e; } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt")); }
From source file:org.ng200.openolympus.controller.admin.DiagnosticsController.java
private File which(final String applicationName) { try {//from ww w. j a v a 2 s .c o m final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(20000)); final CommandLine commandLine = new CommandLine("which"); commandLine.addArgument(applicationName); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(byteArrayOutputStream)); executor.execute(commandLine); final String fileName = byteArrayOutputStream.toString().trim(); if (fileName.isEmpty()) { return null; } return new File(fileName); } catch (final IOException e) { return null; } }
From source file:org.ng200.openolympus.FileAccess.java
public static void rsync(final Path from, final Path to) throws IOException { final CommandLine commandLine = new CommandLine("/usr/bin/rsync"); commandLine.addArgument("-r"); commandLine.addArgument("--ignore-errors"); commandLine.addArgument(from.toAbsolutePath().toString()); commandLine.addArgument(to.toAbsolutePath().toString()); final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the // sandbox to // complete//w w w . j a v a 2s .c o m final ByteArrayOutputStream outAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outAndErr)); executor.setExitValues(new int[] { 0 }); try { executor.execute(commandLine); } catch (final ExecuteException e) { throw new IOException("Rsync failed:\n" + outAndErr.toString(), e); } }
From source file:org.nps.autopsypycaffe.NPSPyCaffeFactory.java
public NPSPyCaffeFactory() { IngestServices services = IngestServices.getInstance(); props = new Properties(); //The user directory is where the plugin got installed File userDir = PlatformUtil.getUserDirectory(); basePath = userDir.toString();/* www.j av a 2 s . c o m*/ // Search for all directories in the detectors directory. This is the list // of all the detector types. if (new File(basePath + "/NPSPyCaffe/detectors").exists() == false) { // When we run in the netbeans debugger basePath is up two directories basePath = basePath + "/../../release/NPSPyCaffe/detectors/"; } else basePath = basePath + "/NPSPyCaffe/detectors/"; String[] dlist = new File(basePath).list(); for (String name : dlist) { if (new File(basePath + name).isDirectory()) { detectorTypes.add(name); } } if (detectorTypes.size() == 0) { IngestMessage msg = IngestMessage.createErrorMessage(NPSPyCaffeFactory.getModuleName(), "Congigure Error!", "No Detector types found!"); services.postMessage(msg); } else for (String det : detectorTypes) { String[] plist = new File(basePath + det).list(); for (String name : plist) { if (name.endsWith(".properties")) { // Read anything that ends with .properties File propfile = new File(basePath + det + "/" + name); if (propfile.exists() == true) { try { FileInputStream in = new FileInputStream(propfile); props.load(in); in.close(); if (name.equals("detector.properties")) { // main property file describing the detector type boolean gpu = checkForGPU(det); hasGPU.put(det, gpu); } else { // specific detector property file so use name of file as detector name int idx = name.indexOf(".properties"); String detName = name.substring(0, idx); detectorNames.add(det + "." + detName); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Could not Find detector.properties file"); } catch (IOException ex) { logger.log(Level.SEVERE, ex.getMessage()); } } } } for (String name : plist) { if (name.endsWith(".properties")) { } } } // Find Python Exec try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); CommandLine args = CommandLine.parse("where.exe"); args.addArgument("python"); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler stdpump = new PumpStreamHandler(outStream); exec.setStreamHandler(stdpump); exec.execute(args); String whereOut = outStream.toString(); String[] lines = StringUtils.split(whereOut, "\r\n"); pythonExec = lines[0]; } catch (IOException ex) { } }
From source file:org.nuxeo.webpage.archiver.WebpageToBlob.java
protected Blob buildCommandLineAndRun(String inCommandLine, CmdParameters inParams, String inFileName, boolean inUseAllParams) throws IOException, CommandNotAvailable, NuxeoException { // Create a temp. File handled by Nuxeo Blob resultPdf = Blobs.createBlobWithExtension(".pdf"); // Build the full, resolved command line String resolvedParameterString = CommandLineParameters.buildParameterString(inCommandLine, inParams.getParameter(CommandLineParameters.COOKIE_JAR), inParams.getParameter(CommandLineParameters.URL), resultPdf.getFile().getAbsolutePath()); // Mainly during test, we may have uncjecked parameters (safe because everything is hard-coded server side) if (inUseAllParams) { if (!Framework.isTestModeSet()) { throw new NuxeoException("A call to buildCommandLineAndRun(..., true) is for test only."); }//w ww . ja v a 2 s . c o m Map<String, ParameterValue> allParams = inParams.getParameters(); String key, value; for (Entry<String, ParameterValue> entry : allParams.entrySet()) { key = entry.getKey(); value = entry.getValue().getValue(); if (!CommandLineParameters.isHandledParameter(key)) { resolvedParameterString = StringUtils.replace(resolvedParameterString, "#{" + key + "}", value); } } } // Get the exact command line and build the line CommandLineDescriptor desc = CommandLineExecutorComponent.getCommandDescriptor(inCommandLine); String line = desc.getCommand() + " " + resolvedParameterString; // Run the thing Exception exception = null; CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); // We don't want a check on exit values, because a PDF can still be created with errors // (can't get a font, ...) executor.setExitValues(null); executor.setWatchdog(watchdog); int exitValue = 0; try { exitValue = executor.execute(cmdLine); } catch (IOException e) { exception = e; } // Even if we had no error catched, we must check if the pdf is valid. // Exit value may be 1, or non zero while the pdf was created. But maybe // a font could not be correctly rendered, etc. Let's check if we have // something in the pdf and it looks valid if (!pdfLooksValid(resultPdf.getFile())) { resultPdf = null; String msg = "Failed to execute the command line [" + cmdLine.toString() + " ]. No valid PDF generated. exitValue: " + exitValue; if (exitValue == 143) { // On Linux: Timeout, wkhtmltopdf was SIGTERM msg += " (time out reached. The timeout was " + timeout + "ms)"; } if (exception == null) { throw new NuxeoException(msg); } else { throw new NuxeoException(msg, exception); } } resultPdf.setMimeType("application/pdf"); String url = inParams.getParameter(CommandLineParameters.URL); // Url parameter can be blank (hard coded url in the command line XML for example) if (StringUtils.isBlank(inFileName) && StringUtils.isNotBlank(url)) { try { URL urlObj = new URL(url); inFileName = StringUtils.replace(urlObj.getHost(), ".", "-") + ".pdf"; } finally { // Nothing. Default name has been set by nuxeo } } if (StringUtils.isNotBlank(inFileName)) { resultPdf.setFilename(inFileName); } return resultPdf; }
From source file:org.obm.push.mail.greenmail.ExternalProcess.java
private Executor buildExecutor() { Executor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); setTimeoutWatchdog(executor);// w w w . j a v a 2 s . co m return executor; }
From source file:org.onehippo.forge.gallerymagick.core.command.AbstractMagickCommand.java
/** * Execute the Magick command with the sub-command and arguments. * @param stdOut standard output stream/*from w w w.j av a 2 s .co m*/ * @throws MagickExecuteException if an execution exception occurs * @throws IOException if IO exception occurs */ public void execute(final OutputStream stdOut) throws IOException { CommandLine cmdLine = createCommandLine(); ByteArrayOutputStream errStream = null; int exitValue = 0; DefaultExecuteResultHandler resultHandler = null; try { errStream = new ByteArrayOutputStream(512); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler streamHandler; if (stdOut != null) { streamHandler = new PumpStreamHandler(stdOut, errStream); } else { streamHandler = new PumpStreamHandler(System.out, errStream); } executor.setStreamHandler(streamHandler); if (getWorkingDirectory() != null) { executor.setWorkingDirectory(getWorkingDirectory()); } long timeout = NumberUtils.toLong(System.getProperty(PROP_TIMEOUT), DEFAULT_COMMAND_TIMEOUT); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(DEFAULT_COMMAND_TIMEOUT); executor.setWatchdog(watchdog); resultHandler = new DefaultExecuteResultHandler(); executor.execute(cmdLine, resultHandler); log.debug("Executed with watchdog: {}", cmdLine); resultHandler.waitFor(); } else { exitValue = executor.execute(cmdLine); log.debug("Executed without watchdog: {}", cmdLine); } } catch (ExecuteException | InterruptedException e) { if (resultHandler != null) { exitValue = resultHandler.getExitValue(); } if (e.getCause() == null) { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue); } else { throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue, e.getCause()); } } finally { IOUtils.closeQuietly(errStream); } }