Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

In this page you can find the example usage for java.lang ProcessBuilder command.

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Tuple<ProcessBuilder, Process> startMiNiFi() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache MiNiFi is already running, listening to Bootstrap on port " + port);
        return null;
    }//w  ww.ja v a 2  s .  co 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();

    final Map<String, String> props = readProperties();

    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 minifiLogDir = replaceNull(
            System.getProperty("org.apache.nifi.minifi.bootstrap.config.log.dir"), DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);

    final String confFilename = replaceNull(props.get(CONF_DIR_KEY), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String minifiPropsFilename = props.get("props.file");
    if (minifiPropsFilename == null) {
        if (confDir.exists()) {
            minifiPropsFilename = new File(confDir, "nifi.properties").getAbsolutePath();
        } else {
            minifiPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    minifiPropsFilename = minifiPropsFilename.trim();

    final List<String> javaAdditionalArgs = new ArrayList<>();
    for (final 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[] 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);
    cpFiles.add(confDir.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 MiNiFiListener listener = new MiNiFiListener();
    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.properties.file.path=" + minifiPropsFilename);
    cmd.add("-Dnifi.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=MiNiFi");
    cmd.add("-Dorg.apache.nifi.minifi.bootstrap.config.log.dir=" + minifiLogDir);
    cmd.add("org.apache.nifi.minifi.MiNiFi");

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        cmdBuilder.append(s).append(" ");
    }

    cmdLogger.info("Starting Apache MiNiFi...");
    cmdLogger.info("Working Directory: {}", workingDir.getAbsolutePath());
    cmdLogger.info("Command: {}", cmdBuilder.toString());

    Process process = builder.start();
    handleLogging(process);
    Long pid = getPid(process, cmdLogger);
    if (pid != null) {
        minifiPid = pid;
        final Properties minifiProps = new Properties();
        minifiProps.setProperty(PID_KEY, String.valueOf(minifiPid));
        saveProperties(minifiProps, cmdLogger);
    }

    gracefulShutdownSeconds = getGracefulShutdownSeconds(props, bootstrapConfigAbsoluteFile);
    shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor);
    final Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(shutdownHook);

    return new Tuple<ProcessBuilder, Process>(builder, process);
}

From source file:org.apache.nifi.bootstrap.RunNiFi.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() throws IOException, InterruptedException {
    final Integer port = getCurrentPort(cmdLogger);
    if (port != null) {
        cmdLogger.info("Apache NiFi is already running, listening to Bootstrap on port " + port);
        return;//from  w  w w .  ja  v  a2  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 nifiLogDir = replaceNull(System.getProperty("org.apache.nifi.bootstrap.config.log.dir"),
            DEFAULT_LOG_DIR).trim();

    final String libFilename = replaceNull(props.get("lib.dir"), "./lib").trim();
    File libDir = getFile(libFilename, workingDir);

    final String confFilename = replaceNull(props.get("conf.dir"), "./conf").trim();
    File confDir = getFile(confFilename, workingDir);

    String nifiPropsFilename = props.get("props.file");
    if (nifiPropsFilename == null) {
        if (confDir.exists()) {
            nifiPropsFilename = new File(confDir, "nifi.properties").getAbsolutePath();
        } else {
            nifiPropsFilename = DEFAULT_CONFIG_FILE;
        }
    }

    nifiPropsFilename = nifiPropsFilename.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[] 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);
    cpFiles.add(confDir.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 NiFiListener listener = new NiFiListener();
    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.properties.file.path=" + nifiPropsFilename);
    cmd.add("-Dnifi.bootstrap.listen.port=" + listenPort);
    cmd.add("-Dapp=NiFi");
    cmd.add("-Dorg.apache.nifi.bootstrap.config.log.dir=" + nifiLogDir);
    cmd.add("org.apache.nifi.NiFi");
    if (props.containsKey(NIFI_BOOTSTRAP_SENSITIVE_KEY)
            && !StringUtils.isBlank(props.get(NIFI_BOOTSTRAP_SENSITIVE_KEY))) {
        cmd.add("-k " + props.get(NIFI_BOOTSTRAP_SENSITIVE_KEY));
    }

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
        // Mask the key
        if (s.startsWith("-k ")) {
            cmdBuilder.append("-k ****");
        } else {
            cmdBuilder.append(s).append(" ");
        }
    }

    cmdLogger.info("Starting Apache NiFi...");
    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 = getPid(process, cmdLogger);
    if (pid == null) {
        cmdLogger.info("Launched Apache NiFi but could not determined the Process ID");
    } else {
        nifiPid = pid;
        final Properties pidProperties = new Properties();
        pidProperties.setProperty(PID_KEY, String.valueOf(nifiPid));
        savePidProperties(pidProperties, cmdLogger);
        cmdLogger.info("Launched Apache NiFi 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";
    }
    serviceManager.notify(NotificationType.NIFI_STARTED, "NiFi Started on Host " + hostname,
            "Hello,\n\nApache NiFi has been started on host " + hostname + " at " + now + " by user " + 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 (autoRestartNiFi) {
                final File statusFile = getStatusFile(defaultLogger);
                if (!statusFile.exists()) {
                    defaultLogger.info("Status File no longer exists. Will not restart NiFi");
                    return;
                }

                final File lockFile = getLockFile(defaultLogger);
                if (lockFile.exists()) {
                    defaultLogger.info("A shutdown was initiated. Will not restart NiFi");
                    return;
                }

                final boolean previouslyStarted = getNifiStarted();
                if (!previouslyStarted) {
                    defaultLogger.info("NiFi never started. Will not restart NiFi");
                    return;
                } else {
                    setNiFiStarted(false);
                }

                defaultLogger.warn("Apache NiFi appears to have died. Restarting...");
                process = builder.start();
                handleLogging(process);

                pid = getPid(process, defaultLogger);
                if (pid == null) {
                    cmdLogger.info("Launched Apache NiFi but could not obtain the Process ID");
                } else {
                    nifiPid = pid;
                    final Properties pidProperties = new Properties();
                    pidProperties.setProperty(PID_KEY, String.valueOf(nifiPid));
                    savePidProperties(pidProperties, defaultLogger);
                    cmdLogger.info("Launched Apache NiFi 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{}",
                            (pid == null ? "" : " with PID " + pid));
                    // We are expected to restart nifi, so send a notification that it died. If we are not restarting nifi,
                    // then this means that we are intentionally stopping the service.
                    serviceManager.notify(NotificationType.NIFI_DIED, "NiFi Died on Host " + hostname,
                            "Hello,\n\nIt appears that Apache NiFi has died on host " + hostname + " at " + now
                                    + "; automatically restarting NiFi");
                } else {
                    defaultLogger.error("Apache NiFi does not appear to have started");
                    // We are expected to restart nifi, so send a notification that it died. If we are not restarting nifi,
                    // then this means that we are intentionally stopping the service.
                    serviceManager.notify(NotificationType.NIFI_DIED, "NiFi Died on Host " + hostname,
                            "Hello,\n\nIt appears that Apache NiFi has died on host " + hostname + " at " + now
                                    + ". Attempted to restart NiFi but the services does not appear to have restarted!");
                }
            } else {
                return;
            }
        }
    }
}

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  ww.j  av a2 s . c  om*/
    }

    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;
            }
        }
    }
}