List of usage examples for java.lang Runtime addShutdownHook
public void addShutdownHook(Thread hook)
From source file:it.sauronsoftware.jave.FFMPEGExecutor.java
/** * Executes the ffmpeg process with the previous given arguments. * // www. j a v a 2 s. c o m * @throws IOException * If the process call fails. */ public void execute() throws IOException { int argsSize = args.size(); String[] cmd = new String[argsSize + 1]; cmd[0] = ffmpegExecutablePath; for (int i = 0; i < argsSize; i++) { cmd[i + 1] = args.get(i); } if (_log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (String c : cmd) { sb.append(c); sb.append(' '); } _log.debug("About to execute " + sb.toString()); } Runtime runtime = Runtime.getRuntime(); ffmpeg = runtime.exec(cmd); ffmpegKiller = new ProcessKiller(ffmpeg); runtime.addShutdownHook(ffmpegKiller); inputStream = ffmpeg.getInputStream(); outputStream = ffmpeg.getOutputStream(); errorStream = ffmpeg.getErrorStream(); }
From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java
/** * Executes the ffmpeg process with the previous given arguments. * /*from w w w. j av a 2 s . co m*/ * @throws IOException * If the process call fails. */ public void execute(File directory) throws EncoderException { LOGGER.info("==========>>> ffmpeg ?..."); try { int argsSize = args.size(); String[] cmd = new String[argsSize + 1]; cmd[0] = executablePath; for (int i = 0; i < argsSize; i++) { cmd[i + 1] = args.get(i); } LOGGER.info("Ffmpeg ===>>> " + args); Runtime runtime = Runtime.getRuntime(); ffmpeg = runtime.exec(cmd, null, directory); ffmpegKiller = new ProcessKiller(ffmpeg); runtime.addShutdownHook(ffmpegKiller); inputStream = ffmpeg.getInputStream(); outputStream = ffmpeg.getOutputStream(); errorStream = ffmpeg.getErrorStream(); LOGGER.info("==========>>> ffmpeg ??."); } catch (IOException e) { LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage()); LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause()); e.printStackTrace(); } finally { destroy(); } }
From source file:com.nridge.core.app.mgr.AppMgr.java
/** * Executes one or more application tasks based on the the run/test command * line argument.// w w w .j a v a2 s . c o m * <p> * <b>Note:</b>If the word "all" is specified for the run/test argument * parameter, then all tasks defined for this application manager * will be executed in parallel. Otherwise, only the task that matches * the run/test name will be executed. * </p> * * @throws NSException Could be thrown by the executing task. */ public void execute() throws NSException { Thread appThread; Logger appLogger = getLogger(this, "execute"); appLogger.trace(LOGMSG_TRACE_ENTER); if (mTaskList == null) throw new NSException("The task list is undefined and cannot be executed."); if (mIsAbortHandlerEnabled) { Runtime osRuntime = Runtime.getRuntime(); osRuntime.addShutdownHook(new TaskAbort(this, mTaskList)); } // http://www.vogella.com/articles/JavaConcurrency/article.html if (mCmdLine.hasOption("run")) { String taskName = mCmdLine.getOptionValue("run"); if (taskName.equals(CMDARG_RUNALL_TASKS)) { ArrayList<Thread> threadList = new ArrayList<Thread>(); for (Task appTask : mTaskList) { appTask.init(this); appThread = new Thread(appTask); threadList.add(appThread); appThread.start(); } // Next, we will wait for each task thread to complete. for (Thread thread : threadList) { try { thread.join(); } catch (InterruptedException e) { appLogger.warn("Interrupted Thread: " + e.getMessage()); } } } else { Task appTask = getTaskByRunName(taskName); if (appTask != null) { appTask.init(this); appTask.run(); } } } else { if (mCmdLine.hasOption("test")) { String taskName = mCmdLine.getOptionValue("test"); if (taskName.equals(CMDARG_TESTALL_TASKS)) { for (Task appTask : mTaskList) { appTask.init(this); appTask.test(); } } else { Task appTask = getTaskByTestName(taskName); if (appTask != null) { appTask.init(this); appTask.test(); } } } } appLogger.trace(LOGMSG_TRACE_DEPART); }
From source file:de.huxhorn.lilith.swing.MainFrame.java
public MainFrame(ApplicationPreferences applicationPreferences, SplashScreen splashScreen, String appName, boolean enableBonjour) { super(appName); this.applicationPreferences = applicationPreferences; this.coloringWholeRow = this.applicationPreferences.isColoringWholeRow(); this.splashScreen = splashScreen; setSplashStatusText("Creating main frame."); groovyFormatter = new GroovyEventWrapperHtmlFormatter(applicationPreferences); thymeleafFormatter = new ThymeleafEventWrapperHtmlFormatter(applicationPreferences); smallProgressIcon = new ImageIcon(MainFrame.class.getResource("/otherGraphics/Progress16.gif")); ImageIcon frameIcon = new ImageIcon(MainFrame.class.getResource("/otherGraphics/Lilith16.jpg")); setIconImage(frameIcon.getImage());/* w w w. j av a 2 s . c om*/ //colorsReferenceQueue=new ReferenceQueue<Colors>(); //colorsCache=new ConcurrentHashMap<EventIdentifier, SoftColorsReference>(); application = new DefaultApplication(); autostartProcesses = new ArrayList<AutostartRunnable>(); addWindowListener(new MainWindowListener()); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // fixes ticket #79 Runtime runtime = Runtime.getRuntime(); Thread shutdownHook = new Thread(new ShutdownRunnable()); runtime.addShutdownHook(shutdownHook); senderService = new SenderService(this); this.enableBonjour = enableBonjour; /* if(application.isMac()) { setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); } else { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } */ longTaskManager = new TaskManager<Long>(); longTaskManager.setUsingEventQueue(true); longTaskManager.startUp(); longTaskManager.addTaskListener(new MainTaskListener()); startupApplicationPath = this.applicationPreferences.getStartupApplicationPath(); loggingFileFactory = new LogFileFactoryImpl(new File(startupApplicationPath, LOGGING_FILE_SUBDIRECTORY)); accessFileFactory = new LogFileFactoryImpl(new File(startupApplicationPath, ACCESS_FILE_SUBDIRECTORY)); Map<String, String> loggingMetaData = new HashMap<String, String>(); loggingMetaData.put(FileConstants.CONTENT_TYPE_KEY, FileConstants.CONTENT_TYPE_VALUE_LOGGING); loggingMetaData.put(FileConstants.CONTENT_FORMAT_KEY, FileConstants.CONTENT_FORMAT_VALUE_PROTOBUF); loggingMetaData.put(FileConstants.COMPRESSION_KEY, FileConstants.COMPRESSION_VALUE_GZIP); // TODO: configurable format and compressed loggingFileBufferFactory = new LoggingFileBufferFactory(loggingFileFactory, loggingMetaData); Map<String, String> accessMetaData = new HashMap<String, String>(); accessMetaData.put(FileConstants.CONTENT_TYPE_KEY, FileConstants.CONTENT_TYPE_VALUE_ACCESS); accessMetaData.put(FileConstants.CONTENT_FORMAT_KEY, FileConstants.CONTENT_FORMAT_VALUE_PROTOBUF); accessMetaData.put(FileConstants.COMPRESSION_KEY, FileConstants.COMPRESSION_VALUE_GZIP); // TODO: configurable format and compressed accessFileBufferFactory = new AccessFileBufferFactory(accessFileFactory, accessMetaData); rrdFileFilter = new RrdFileFilter(); loggingEventViewManager = new LoggingEventViewManager(this); accessEventViewManager = new AccessEventViewManager(this); this.applicationPreferences.addPropertyChangeListener(new PreferencesChangeListener()); loggingSourceListener = new LoggingEventSourceListener(); accessSourceListener = new AccessEventSourceListener(); // this.cleanupWindowChangeListener = new CleanupWindowChangeListener(); desktop = new JDesktopPane(); statusBar = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); statusLabel = new JLabel(); statusLabel.setText("Starting..."); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0.0; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(0, 5, 0, 0); statusBar.add(statusLabel, gbc); taskStatusLabel = new JLabel(); taskStatusLabel.setText(""); taskStatusLabel.setForeground(Color.BLUE); taskStatusLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent mouseEvent) { showTaskManager(); } @Override public void mouseEntered(MouseEvent mouseEvent) { taskStatusLabel.setForeground(Color.RED); } @Override public void mouseExited(MouseEvent mouseEvent) { taskStatusLabel.setForeground(Color.BLUE); } }); gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 1.0; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(0, 5, 0, 0); statusBar.add(taskStatusLabel, gbc); MemoryStatus memoryStatus = new MemoryStatus(); memoryStatus.setBackground(Color.WHITE); memoryStatus.setOpaque(true); memoryStatus.setUsingBinaryUnits(true); memoryStatus.setUsingTotal(false); memoryStatus.setBorder(new EtchedBorder(EtchedBorder.LOWERED)); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 2; gbc.gridy = 0; gbc.weightx = 0.0; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(0, 0, 0, 0); statusBar.add(memoryStatus, gbc); add(desktop, BorderLayout.CENTER); add(statusBar, BorderLayout.SOUTH); if (SystemUtils.IS_JAVA_1_6) { setSplashStatusText("Creating statistics dialog."); if (logger.isDebugEnabled()) logger.debug("Before creation of statistics-dialog..."); statisticsDialog = new StatisticsDialog(this); if (logger.isDebugEnabled()) logger.debug("After creation of statistics-dialog..."); } setSplashStatusText("Creating about dialog."); aboutDialog = new AboutDialog(this, "About " + appName + "...", appName); setSplashStatusText("Creating update dialog."); checkForUpdateDialog = new CheckForUpdateDialog(this); setSplashStatusText("Creating debug dialog."); debugDialog = new DebugDialog(this, this); setSplashStatusText("Creating preferences dialog."); if (logger.isDebugEnabled()) logger.debug("Before creation of preferences-dialog..."); preferencesDialog = new PreferencesDialog(this); if (logger.isDebugEnabled()) logger.debug("After creation of preferences-dialog..."); setSplashStatusText("Creating \"Open inactive\" dialog."); openInactiveLogsDialog = new OpenPreviousDialog(MainFrame.this); setSplashStatusText("Creating help frame."); helpFrame = new HelpFrame(this); helpFrame.setTitle("Help Topics"); openFileChooser = new JFileChooser(); openFileChooser.setFileFilter(new LilithFileFilter()); openFileChooser.setFileHidingEnabled(false); openFileChooser.setCurrentDirectory(this.applicationPreferences.getPreviousOpenPath()); importFileChooser = new JFileChooser(); importFileChooser.setFileFilter(new XmlImportFileFilter()); importFileChooser.setFileHidingEnabled(false); importFileChooser.setCurrentDirectory(this.applicationPreferences.getPreviousImportPath()); exportFileChooser = new JFileChooser(); exportFileChooser.setFileFilter(new LilithFileFilter()); exportFileChooser.setFileHidingEnabled(false); exportFileChooser.setCurrentDirectory(this.applicationPreferences.getPreviousExportPath()); setSplashStatusText("Creating task manager frame."); taskManagerFrame = new TaskManagerInternalFrame(this); taskManagerFrame.setTitle("Task Manager"); taskManagerFrame.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE); taskManagerFrame.setBounds(0, 0, 320, 240); desktop.add(taskManagerFrame); desktop.validate(); // the following code must be executed after desktop has been initialized... try { // try to use the 1.6 transfer handler... new MainFrameTransferHandler16(this).attach(); } catch (Throwable t) { // ... and use the basic 1.5 transfer handler if this fails. new MainFrameTransferHandler(this).attach(); } setSplashStatusText("Creating Tip of the Day dialog."); tipOfTheDayDialog = new TipOfTheDayDialog(this); setSplashStatusText("Creating actions and menus."); viewActions = new ViewActions(this, null); viewActions.getPopupMenu(); // initialize popup once in main frame only. JMenuBar menuBar = viewActions.getMenuBar(); toolbar = viewActions.getToolbar(); add(toolbar, BorderLayout.NORTH); setJMenuBar(menuBar); setShowingToolbar(applicationPreferences.isShowingToolbar()); setShowingStatusbar(applicationPreferences.isShowingStatusbar()); }
From source file:org.acmsl.queryj.api.AbstractTemplate.java
/** * Prints a log message displaying ClassLoader issues related * to ANTLR.jar and StringTemplate.jar./*from w w w.j av a 2 s . co m*/ */ @SuppressWarnings("unused") protected synchronized void traceClassLoaders() { @NotNull final FinalizingThread t_FinalizingThread = FinalizingThreadSingletonContainer.getInstance(); if (t_FinalizingThread.isNew()) { @Nullable final Runtime t_Runtime = Runtime.getRuntime(); if (t_Runtime != null) { t_Runtime.removeShutdownHook(t_FinalizingThread); t_Runtime.addShutdownHook(t_FinalizingThread); } } }
From source file:org.apache.juddi.v3.client.subscription.SubscriptionCallbackListener.java
/** * adds a shutdown hook to trap and warn about leaving the server * running on exit/*from ww w . ja va 2 s.c o m*/ */ public SubscriptionCallbackListener() { Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread(this)); }
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 . jav a 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 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.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; }/*from www.j a v a 2 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(); 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.minifi.bootstrap.RunMiNiFi.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void start() throws IOException, InterruptedException { final String confDir = getBootstrapProperties().getProperty(CONF_DIR_KEY); final File configFile = new File(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY)); try (InputStream inputStream = new FileInputStream(configFile)) { ByteBuffer tempConfigFile = performTransformation(inputStream, confDir); currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer()); } catch (ConfigurationChangeException e) { defaultLogger.error("The config file is malformed, unable to start.", e); return;//from w ww .j a va2 s . c o m } // Instantiate configuration listener and configured ingestors this.changeListener = new MiNiFiConfigurationChangeListener(this, defaultLogger); this.periodicStatusReporters = initializePeriodicNotifiers(); startPeriodicNotifiers(); try { this.changeCoordinator = initializeNotifier(this.changeListener); } catch (Exception e) { final String errorMsg = "Unable to start as {} is not properly configured due to: {}"; cmdLogger.error(errorMsg, this.changeListener.getDescriptor(), e.getMessage()); defaultLogger.error("Unable to initialize notifier.", e); // if we fail to initialize, exit without attempting to start System.exit(1); } Tuple<ProcessBuilder, Process> tuple = startMiNiFi(); if (tuple == null) { cmdLogger.info("Start method returned null, ending start command."); return; } ProcessBuilder builder = tuple.getKey(); Process process = tuple.getValue(); try { while (true) { final boolean alive = isAlive(process); if (alive) { try { Thread.sleep(1000L); if (reloading.get() && getNifiStarted()) { final File swapConfigFile = getSwapFile(defaultLogger); if (swapConfigFile.exists()) { defaultLogger.info( "MiNiFi has finished reloading successfully and swap file exists. Deleting old configuration."); if (swapConfigFile.delete()) { defaultLogger.info("Swap file was successfully deleted."); } else { defaultLogger .error("Swap file was not deleted. It should be deleted manually."); } } reloading.set(false); } } catch (final InterruptedException ie) { } } else { final Runtime runtime = Runtime.getRuntime(); try { runtime.removeShutdownHook(shutdownHook); } catch (final IllegalStateException ise) { // happens when already shutting down } if (autoRestartNiFi) { final File statusFile = getStatusFile(defaultLogger); if (!statusFile.exists()) { defaultLogger.info("Status File no longer exists. Will not restart MiNiFi"); return; } final File lockFile = getLockFile(defaultLogger); if (lockFile.exists()) { defaultLogger.info("A shutdown was initiated. Will not restart MiNiFi"); return; } final File reloadFile = getReloadFile(defaultLogger); if (reloadFile.exists()) { defaultLogger.info("Currently reloading configuration. Will wait to restart MiNiFi."); Thread.sleep(5000L); continue; } final boolean previouslyStarted = getNifiStarted(); if (!previouslyStarted) { final File swapConfigFile = getSwapFile(defaultLogger); if (swapConfigFile.exists()) { defaultLogger.info( "Swap file exists, MiNiFi failed trying to change configuration. Reverting to old configuration."); try { ByteBuffer tempConfigFile = performTransformation( new FileInputStream(swapConfigFile), confDir); currentConfigFileReference.set(tempConfigFile.asReadOnlyBuffer()); } catch (ConfigurationChangeException e) { defaultLogger.error( "The swap file is malformed, unable to restart from prior state. Will not attempt to restart MiNiFi. Swap File should be cleaned up manually."); return; } Files.copy(swapConfigFile.toPath(), Paths.get(getBootstrapProperties().getProperty(MINIFI_CONFIG_FILE_KEY)), REPLACE_EXISTING); defaultLogger.info("Replacing config file with swap file and deleting swap file"); if (!swapConfigFile.delete()) { defaultLogger.warn( "The swap file failed to delete after replacing using it to revert to the old configuration. It should be cleaned up manually."); } reloading.set(false); } else { defaultLogger.info( "MiNiFi either never started or failed to restart. Will not attempt to restart MiNiFi"); return; } } else { setNiFiStarted(false); } process = builder.start(); handleLogging(process); Long pid = getPid(process, defaultLogger); if (pid != null) { minifiPid = pid; final Properties minifiProps = new Properties(); minifiProps.setProperty(PID_KEY, String.valueOf(minifiPid)); saveProperties(minifiProps, defaultLogger); } shutdownHook = new ShutdownHook(process, this, secretKey, gracefulShutdownSeconds, loggingExecutor); runtime.addShutdownHook(shutdownHook); final boolean started = waitForStart(); if (started) { defaultLogger.info("Successfully spawned the thread to start Apache MiNiFi{}", (pid == null ? "" : " with PID " + pid)); } else { defaultLogger.error("Apache MiNiFi does not appear to have started"); } } else { return; } } } } finally { shutdownChangeNotifier(); shutdownPeriodicStatusReporters(); } }