Esempio n. 1
0
 public void register(Runtime runtime) {
   runtime.addShutdownHook(
       new Thread() {
         @Override
         public void run() {
           StateKeeper.this.end();
         }
       });
 }
Esempio n. 2
0
  @Override
  protected void startUp() {
    _cellShell.addCommandListener(this);
    _cellShell.addCommandListener(new LogbackShell());
    _cellShell.addCommandListener(new FilterShell(_nucleus.getLoggingThresholds()));
    _cellShell.addCommandListener(_cellShell.new HelpCommands());
    useInterpreter(false);

    _runtime.addShutdownHook(new TheKiller());
  }
  public void start() {
    Runtime runtime = Runtime.getRuntime();

    try {
      process = runtime.exec(command);
      reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
      writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream()), true);
      runtime.addShutdownHook(
          new Thread() {
            @Override
            public void run() {
              cleanup();
            }
          });
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 4
0
 public static void startDerby(int port) throws IOException {
   Runtime runtime = Runtime.getRuntime();
   runtime.addShutdownHook(
       new Thread() {
         public void run() {
           if (derbyProcess != null) derbyProcess.destroy();
         }
       });
   System.out.print("Start embedded database...");
   String cmd =
       String.format(
           "java -Dderby.drda.portNumber=%d -jar out/bin/derbyrun.jar server start -noSecurityManager",
           port);
   derbyProcess = runtime.exec(cmd);
   if (!CommonTools.waitForService(port)) {
     System.out.println("FAILED");
     System.exit(1);
   }
   System.out.println("OK");
 }
Esempio n. 5
0
  protected void doRun(String[] ids) throws Exception {

    // Print release information

    System.out.println("Starting " + ReleaseInfo.getReleaseInfo());

    // Portal resiliency

    DistributedRegistry.registerDistributed(
        ComponentConstants.COMPONENT_CONTEXT, Direction.DUPLEX, MatchType.POSTFIX);
    DistributedRegistry.registerDistributed(
        MimeResponse.MARKUP_HEAD_ELEMENT, Direction.DUPLEX, MatchType.EXACT);
    DistributedRegistry.registerDistributed(
        PortletRequest.LIFECYCLE_PHASE, Direction.DUPLEX, MatchType.EXACT);
    DistributedRegistry.registerDistributed(WebKeys.class);

    Intraband intraband = MPIHelperUtil.getIntraband();

    intraband.registerDatagramReceiveHandler(
        SystemDataType.MAILBOX.getValue(), new MailboxDatagramReceiveHandler());

    MessageBus messageBus = (MessageBus) PortalBeanLocatorUtil.locate(MessageBus.class.getName());

    intraband.registerDatagramReceiveHandler(
        SystemDataType.MESSAGE.getValue(), new MessageDatagramReceiveHandler(messageBus));

    intraband.registerDatagramReceiveHandler(
        SystemDataType.PROXY.getValue(), new IntrabandProxyDatagramReceiveHandler());

    intraband.registerDatagramReceiveHandler(
        SystemDataType.RPC.getValue(), new RPCDatagramReceiveHandler());

    // Shutdown hook

    if (_log.isDebugEnabled()) {
      _log.debug("Add shutdown hook");
    }

    Runtime runtime = Runtime.getRuntime();

    runtime.addShutdownHook(new Thread(new ShutdownHook()));

    // Template manager

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize template manager");
    }

    TemplateManagerUtil.init();

    // Indexers

    IndexerRegistryUtil.register(new MBMessageIndexer());
    IndexerRegistryUtil.register(new PluginPackageIndexer());

    // Upgrade

    if (_log.isDebugEnabled()) {
      _log.debug("Upgrade database");
    }

    DBUpgrader.upgrade();

    // Clear locks

    if (_log.isDebugEnabled()) {
      _log.debug("Clear locks");
    }

    try {
      LockLocalServiceUtil.clear();
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Unable to clear locks because Lock table does not exist");
      }
    }

    // Messaging

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize message bus");
    }

    MessageSender messageSender =
        (MessageSender) PortalBeanLocatorUtil.locate(MessageSender.class.getName());
    SynchronousMessageSender synchronousMessageSender =
        (SynchronousMessageSender)
            PortalBeanLocatorUtil.locate(SynchronousMessageSender.class.getName());

    MessageBusUtil.init(
        DoPrivilegedUtil.wrap(messageBus),
        DoPrivilegedUtil.wrap(messageSender),
        DoPrivilegedUtil.wrap(synchronousMessageSender));

    // Cluster executor

    ClusterExecutorUtil.initialize();

    if (!SPIUtil.isSPI()) {
      ClusterMasterExecutorUtil.initialize();
    }

    // Ehache bootstrap

    EhcacheStreamBootstrapCacheLoader.start();

    // Scheduler

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize scheduler engine lifecycle");
    }

    SchedulerEngineHelperUtil.initialize();

    // Verify

    if (_log.isDebugEnabled()) {
      _log.debug("Verify database");
    }

    DBUpgrader.verify();

    // Background tasks

    if (!ClusterMasterExecutorUtil.isEnabled()) {
      BackgroundTaskLocalServiceUtil.cleanUpBackgroundTasks();
    }

    // Liferay JspFactory

    JspFactorySwapper.swap();

    // Jericho

    CachedLoggerProvider.install();
  }
Esempio n. 6
0
  @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;
    }

    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 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("org.apache.nifi.NiFi");

    builder.command(cmd);

    final StringBuilder cmdBuilder = new StringBuilder();
    for (final String s : cmd) {
      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) {
      nifiPid = pid;
      final Properties nifiProps = new Properties();
      nifiProps.setProperty("pid", String.valueOf(nifiPid));
      saveProperties(nifiProps, cmdLogger);
    }

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

    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
        }

        if (autoRestartNiFi) {
          final File statusFile = getStatusFile(defaultLogger);
          if (!statusFile.exists()) {
            defaultLogger.info("Status File no longer exists. 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) {
            nifiPid = pid;
            final Properties nifiProps = new Properties();
            nifiProps.setProperty("pid", String.valueOf(nifiPid));
            saveProperties(nifiProps, defaultLogger);
          }

          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));
          } else {
            defaultLogger.error("Apache NiFi does not appear to have started");
          }
        } else {
          return;
        }
      }
    }
  }
  public static synchronized void premain(String agentArguments, Instrumentation instrumentation) {

    String[] arguments = agentArguments.split(";");

    String[] includes = arguments[0].split(",");
    String[] excludes = arguments[1].split(",");

    if (Boolean.getBoolean("junit.code.coverage")) {
      final CoberturaClassFileTransformer coberturaClassFileTransformer =
          new CoberturaClassFileTransformer(includes, excludes);

      instrumentation.addTransformer(coberturaClassFileTransformer);

      Runtime runtime = Runtime.getRuntime();

      runtime.addShutdownHook(
          new Thread() {

            @Override
            public void run() {
              ProjectDataUtil.runMergeHooks();
            }
          });
    } else if (instrumentation.isRedefineClassesSupported()
        && instrumentation.isRetransformClassesSupported()) {

      _instrumentation = instrumentation;
      _includes = includes;
      _excludes = excludes;

      // Forcibly clear the data file to make sure that the coverage
      // assert is based on the current test

      File dataFile = CoverageDataFileHandler.getDefaultDataFile();

      dataFile.delete();
    } else {
      StringBuilder sb = new StringBuilder();

      sb.append("Current JVM is not capable for dynamic ");
      sb.append("instrumententation. Instrumentation ");

      if (instrumentation.isRetransformClassesSupported()) {
        sb.append("supports ");
      } else {
        sb.append("does not support ");
      }

      sb.append("restranforming classes. Instrumentation ");

      if (instrumentation.isRedefineClassesSupported()) {
        sb.append("supports ");
      } else {
        sb.append("does not support ");
      }

      sb.append("redefining classes. Dynamic instrumententation is ");
      sb.append("disabled.");

      System.out.println(sb.toString());
    }
  }
  protected void processStartupEvents() throws Exception {

    // Print release information

    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    try (InputStream inputStream =
        classLoader.getResourceAsStream("com/liferay/portal/events/dependencies/startup.txt")) {

      System.out.println(_toString(inputStream));
    }

    System.out.println("Starting " + ReleaseInfo.getReleaseInfo() + "\n");

    if (_log.isDebugEnabled()) {
      _log.debug("Portal Resiliency - NOT SUPPORTED");
    }

    // Shutdown hook

    if (_log.isDebugEnabled()) {
      _log.debug("Add shutdown hook");
    }

    Runtime runtime = Runtime.getRuntime();

    runtime.addShutdownHook(new Thread(new ShutdownHook()));

    // MySQL version

    DB db = DBManagerUtil.getDB();

    if ((db.getDBType() == DBType.MYSQL) && GetterUtil.getFloat(db.getVersionString()) < 5.6F) {

      throw new ServletException(
          "Please upgrade to at least MySQL 5.6.4. The portal no "
              + "longer supports older versions of MySQL.");
    }

    // Check required build number

    if (_log.isDebugEnabled()) {
      _log.debug("Check required build number");
    }

    DBUpgrader.checkRequiredBuildNumber(ReleaseInfo.getParentBuildNumber());

    Registry registry = RegistryUtil.getRegistry();

    Map<String, Object> properties = new HashMap<>();

    properties.put("module.service.lifecycle", "database.initialized");
    properties.put("service.vendor", ReleaseInfo.getVendor());
    properties.put("service.version", ReleaseInfo.getVersion());

    _dbModuleServiceLifecycleServiceRegistration =
        registry.registerService(
            ModuleServiceLifecycle.class, new ModuleServiceLifecycle() {}, properties);

    // Check class names

    if (_log.isDebugEnabled()) {
      _log.debug("Check class names");
    }

    ClassNameLocalServiceUtil.checkClassNames();
  }