List of usage examples for java.lang Runtime addShutdownHook
public void addShutdownHook(Thread hook)
From source file:org.apache.nifi.registry.bootstrap.RunNiFiRegistry.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void start() throws IOException, InterruptedException { final Integer port = getCurrentPort(cmdLogger); if (port != null) { cmdLogger.info("Apache NiFi Registry is already running, listening to Bootstrap on port " + port); return;// w w w .j a va 2 s . c o m } final File prevLockFile = getLockFile(cmdLogger); if (prevLockFile.exists() && !prevLockFile.delete()) { cmdLogger.warn("Failed to delete previous lock file {}; this file should be cleaned up manually", prevLockFile); } final ProcessBuilder builder = new ProcessBuilder(); if (!bootstrapConfigFile.exists()) { throw new FileNotFoundException(bootstrapConfigFile.getAbsolutePath()); } final Properties properties = new Properties(); try (final FileInputStream fis = new FileInputStream(bootstrapConfigFile)) { properties.load(fis); } final Map<String, String> props = new HashMap<>(); props.putAll((Map) properties); final String specifiedWorkingDir = props.get("working.dir"); if (specifiedWorkingDir != null) { builder.directory(new File(specifiedWorkingDir)); } final File bootstrapConfigAbsoluteFile = bootstrapConfigFile.getAbsoluteFile(); final File binDir = bootstrapConfigAbsoluteFile.getParentFile(); final File workingDir = binDir.getParentFile(); if (specifiedWorkingDir == null) { builder.directory(workingDir); } final String nifiRegistryLogDir = replaceNull( System.getProperty("org.apache.nifi.registry.bootstrap.config.log.dir"), DEFAULT_LOG_DIR).trim(); final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim(); File libDir = getFile(libFilename, workingDir); File libSharedDir = getFile(libFilename + "/shared", workingDir); final String confFilename = replaceNull(props.get("conf.dir"), "./conf").trim(); File confDir = getFile(confFilename, workingDir); String nifiRegistryPropsFilename = props.get("props.file"); if (nifiRegistryPropsFilename == null) { if (confDir.exists()) { nifiRegistryPropsFilename = new File(confDir, "nifi-registry.properties").getAbsolutePath(); } else { nifiRegistryPropsFilename = DEFAULT_CONFIG_FILE; } } nifiRegistryPropsFilename = nifiRegistryPropsFilename.trim(); final List<String> javaAdditionalArgs = new ArrayList<>(); for (final Map.Entry<String, String> entry : props.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (key.startsWith("java.arg")) { javaAdditionalArgs.add(value); } } final File[] libSharedFiles = libSharedDir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.toLowerCase().endsWith(".jar"); } }); if (libSharedFiles == null || libSharedFiles.length == 0) { throw new RuntimeException("Could not find lib shared directory at " + libSharedDir.getAbsolutePath()); } final File[] libFiles = libDir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String filename) { return filename.toLowerCase().endsWith(".jar"); } }); if (libFiles == null || libFiles.length == 0) { throw new RuntimeException("Could not find lib directory at " + libDir.getAbsolutePath()); } final File[] confFiles = confDir.listFiles(); if (confFiles == null || confFiles.length == 0) { throw new RuntimeException("Could not find conf directory at " + confDir.getAbsolutePath()); } final List<String> cpFiles = new ArrayList<>(confFiles.length + libFiles.length + libSharedFiles.length); cpFiles.add(confDir.getAbsolutePath()); for (final File file : libSharedFiles) { cpFiles.add(file.getAbsolutePath()); } for (final File file : libFiles) { cpFiles.add(file.getAbsolutePath()); } final StringBuilder classPathBuilder = new StringBuilder(); for (int i = 0; i < cpFiles.size(); i++) { final String filename = cpFiles.get(i); classPathBuilder.append(filename); if (i < cpFiles.size() - 1) { classPathBuilder.append(File.pathSeparatorChar); } } final String classPath = classPathBuilder.toString(); String javaCmd = props.get("java"); if (javaCmd == null) { javaCmd = DEFAULT_JAVA_CMD; } if (javaCmd.equals(DEFAULT_JAVA_CMD)) { String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { String fileExtension = isWindows() ? ".exe" : ""; File javaFile = new File( javaHome + File.separatorChar + "bin" + File.separatorChar + "java" + fileExtension); if (javaFile.exists() && javaFile.canExecute()) { javaCmd = javaFile.getAbsolutePath(); } } } final NiFiRegistryListener listener = new NiFiRegistryListener(); final int listenPort = listener.start(this); final List<String> cmd = new ArrayList<>(); cmd.add(javaCmd); cmd.add("-classpath"); cmd.add(classPath); cmd.addAll(javaAdditionalArgs); cmd.add("-Dnifi.registry.properties.file.path=" + nifiRegistryPropsFilename); cmd.add("-Dnifi.registry.bootstrap.config.file.path=" + bootstrapConfigFile.getAbsolutePath()); cmd.add("-Dnifi.registry.bootstrap.listen.port=" + listenPort); cmd.add("-Dapp=NiFiRegistry"); cmd.add("-Dorg.apache.nifi.registry.bootstrap.config.log.dir=" + nifiRegistryLogDir); cmd.add("org.apache.nifi.registry.NiFiRegistry"); builder.command(cmd); final StringBuilder cmdBuilder = new StringBuilder(); for (final String s : cmd) { cmdBuilder.append(s).append(" "); } cmdLogger.info("Starting Apache NiFi Registry..."); cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath()); cmdLogger.info("Command: {}", cmdBuilder.toString()); String gracefulShutdown = props.get(GRACEFUL_SHUTDOWN_PROP); if (gracefulShutdown == null) { gracefulShutdown = DEFAULT_GRACEFUL_SHUTDOWN_VALUE; } final int gracefulShutdownSeconds; try { gracefulShutdownSeconds = Integer.parseInt(gracefulShutdown); } catch (final NumberFormatException nfe) { throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath() + " has an invalid value. Must be a non-negative integer"); } if (gracefulShutdownSeconds < 0) { throw new NumberFormatException("The '" + GRACEFUL_SHUTDOWN_PROP + "' property in Bootstrap Config File " + bootstrapConfigAbsoluteFile.getAbsolutePath() + " has an invalid value. Must be a non-negative integer"); } Process process = builder.start(); handleLogging(process); Long pid = OSUtils.getProcessId(process, cmdLogger); if (pid == null) { cmdLogger.warn("Launched Apache NiFi Registry but could not determined the Process ID"); } else { nifiRegistryPid = pid; final Properties pidProperties = new Properties(); pidProperties.setProperty(PID_KEY, String.valueOf(nifiRegistryPid)); savePidProperties(pidProperties, cmdLogger); cmdLogger.info("Launched Apache NiFi Registry with Process ID " + pid); } shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor); final Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(shutdownHook); final String hostname = getHostname(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); String now = sdf.format(System.currentTimeMillis()); String user = System.getProperty("user.name"); if (user == null || user.trim().isEmpty()) { user = "Unknown User"; } while (true) { final boolean alive = isAlive(process); if (alive) { try { Thread.sleep(1000L); } catch (final InterruptedException ie) { } } else { try { runtime.removeShutdownHook(shutdownHook); } catch (final IllegalStateException ise) { // happens when already shutting down } now = sdf.format(System.currentTimeMillis()); if (autoRestartNiFiRegistry) { final File statusFile = getStatusFile(defaultLogger); if (!statusFile.exists()) { defaultLogger.info("Status File no longer exists. Will not restart NiFi Registry "); return; } final File lockFile = getLockFile(defaultLogger); if (lockFile.exists()) { defaultLogger.info("A shutdown was initiated. Will not restart NiFi Registry "); return; } final boolean previouslyStarted = getNifiRegistryStarted(); if (!previouslyStarted) { defaultLogger.info("NiFi Registry never started. Will not restart NiFi Registry "); return; } else { setNiFiRegistryStarted(false); } defaultLogger.warn("Apache NiFi Registry appears to have died. Restarting..."); process = builder.start(); handleLogging(process); pid = OSUtils.getProcessId(process, defaultLogger); if (pid == null) { cmdLogger.warn("Launched Apache NiFi Registry but could not obtain the Process ID"); } else { nifiRegistryPid = pid; final Properties pidProperties = new Properties(); pidProperties.setProperty(PID_KEY, String.valueOf(nifiRegistryPid)); savePidProperties(pidProperties, defaultLogger); cmdLogger.info("Launched Apache NiFi Registry with Process ID " + pid); } shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor); runtime.addShutdownHook(shutdownHook); final boolean started = waitForStart(); if (started) { defaultLogger.info("Successfully started Apache NiFi Registry {}", (pid == null ? "" : " with PID " + pid)); } else { defaultLogger.error("Apache NiFi Registry does not appear to have started"); } } else { return; } } } }
From source file:org.formic.util.CommandExecutor.java
/** * Run the thread./*from www. j ava2 s . c om*/ */ public void run() { logger.info(this.toString()); Runtime runtime = Runtime.getRuntime(); try { process = runtime.exec(cmd); shutdownHook = new ShutdownHook(); try { runtime.addShutdownHook(shutdownHook); } catch (IllegalStateException ignore) { // happens if this is called during shutdown } ByteArrayOutputStream out = new ByteArrayOutputStream(); Thread outThread = createOutThread(out); outThread.start(); ByteArrayOutputStream err = new ByteArrayOutputStream(); Thread errThread = createErrThread(err); errThread.start(); returnCode = process.waitFor(); outThread.join(1000); errThread.join(1000); if (result == null) { result = out.toString(); } if (error == null) { error = err.toString(); } } catch (Exception e) { returnCode = 12; error = e.getMessage(); e.printStackTrace(); } finally { if (shutdownHook != null) { try { runtime.removeShutdownHook(shutdownHook); } catch (IllegalStateException ignore) { // happens if this is called during shutdown } } } }