Lookup the server detectors and notify detector about the JVM startup

@param instrumentation
@see ServerDetector#jvmAgentStartup(Instrumentation)
769787
private static void awaitServerInitialization(JvmAgentConfig pConfig, final Instrumentation instrumentation) {
        List<ServerDetector> detectors = MBeanServerHandler.lookupDetectors();
        for (ServerDetector detector : detectors) {
            detector.jvmAgentStartup(instrumentation);
        }
    }
1004450
public void start() {
        if(started.compareAndSet(false, true)) {
            logger.info("Opening ServiceTracker to search for {} services...", serviceType.getCanonicalName());
            serviceTracker.open(true);
        } else {
            logger.warn("ServiceTracker already open, searching for {} services.", serviceType.getCanonicalName());
        }
    }
491506
private static void startServer() throws Exception {
          JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
          sf.setResourceClasses(TileFetcher.class);

          List<Object> providers = new ArrayList<Object>();
          // add custom providers if any
          providers.add(new org.apache.cxf.jaxrs.provider.JAXBElementProvider());
          providers.add(new org.apache.cxf.jaxrs.provider.json.JSONProvider());
          sf.setProviders(providers);

          sf.setResourceProvider(TileFetcher.class,
                  new SingletonResourceProvider(new TileFetcher(), true));
          sf.setAddress(ENDPOINT_ADDRESS);

          server = sf.create();

     }
40211
private void startFolderMonitor() {
    if (serverConfiguration.getAppFolderToMonitor() != null) {
      try {
        folderMonitor = new FolderMonitor(this, serverConfiguration);
        folderMonitor.start();
      } catch (IOException e) {
        log.warning("Could not monitor the given folder: "
            + serverConfiguration.getAppFolderToMonitor());
      }
    }
  }
506954
public static Instrumentation initAgentAtRuntimeAndReportSuccess() {
        try {
            setSystemClassLoaderClassPath();
        } catch (Exception e) {
            Log.e("Could not set classpath. Tool will be off.", e);
            return null;
        }
        try {
            return addClassfileTransformer();
        } catch (Exception e) {
            Log.e("Could not add transformer. Tool will be off.", e);
            return null;
        }
    }
8376
private static void startServer() {

    try {

      JdcpUtil.initialize();

      Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
      EmbeddedDataSource ds = new EmbeddedDataSource();
      ds.setConnectionAttributes("create=true");
      ds.setDatabaseName("classes");

      System.err.print("Initializing progress monitor...");
      ProgressPanel panel = new ProgressPanel();
      panel.setPreferredSize(new Dimension(500, 350));
      System.err.println("OK");

      System.err.print("Initializing folders...");
      Preferences pref = Preferences
          .userNodeForPackage(JobServer.class);
      String path = pref.get("rootDirectory", "./server");
      File rootDirectory = new File(path);
      File jobsDirectory = new File(rootDirectory, "jobs");

      rootDirectory.mkdir();
      jobsDirectory.mkdir();
      System.err.println("OK");

      System.err.print("Initializing service...");
      DbClassManager classManager = new DbClassManager(ds);
      classManager.prepareDataSource();

      TaskScheduler scheduler = new PrioritySerialTaskScheduler();
      Executor executor = Executors.newCachedThreadPool();
      JobServer jobServer = new JobServer(jobsDirectory, panel, scheduler, classManager, executor);
      AuthenticationServer authServer = new AuthenticationServer(jobServer, JdcpUtil.DEFAULT_PORT);
      System.err.println("OK");

      System.err.print("Exporting service stubs...");
//      JobService jobStub = (JobService) UnicastRemoteObject.exportObject(
//          jobServer, 0);
      System.err.println("OK");

      System.err.print("Binding service...");
      final Registry registry = LocateRegistry.createRegistry(JdcpUtil.DEFAULT_PORT);
      registry.bind("AuthenticationService", authServer);
      System.err.println("OK");

      System.err.println("Server ready");

      JFrame frame = new JFrame("JDCP Server");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

      frame.getContentPane().add(panel);
      frame.pack();

      frame.addWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent event) {
          System.err.print("Shutting down...");
          try {
            registry.unbind("AuthenticationService");
            System.err.println("OK");
          } catch (Exception e) {
            e.printStackTrace();
          }
          System.exit(0);
        }
      });

      frame.setVisible(true);

    } catch (Exception e) {

      System.err.println("Server exception:");
      e.printStackTrace();

    }

  }
1301059
@PostConstruct
    void init(TracingRunnableInstrumenter instrumenter) {
        if (instrumenter != null) {
            Func1<Action0, Action0> existing = RxJavaHooks.getOnScheduleAction();
            if (existing != null && !(existing instanceof InstrumentScheduleAction)) {
                RxJavaHooks.setOnScheduleAction(action0 ->
                        new InstrumentScheduleAction(instrumenter).call(existing.call(action0))
                );
            } else {
                RxJavaHooks.setOnScheduleAction(new InstrumentScheduleAction(instrumenter));
            }
        }
    }
1260020
protected void handleStartupException(Environment environment, Throwable exception) {
        Function<Throwable, Integer> exitCodeMapper = exitHandlers.computeIfAbsent(exception.getClass(), exceptionType -> (throwable -> 1));
        Integer code = exitCodeMapper.apply(exception);
        if (code > 0) {
            if (!environment.getActiveNames().contains(Environment.TEST)) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Error starting Micronaut server: " + exception.getMessage(), exception);
                }
                System.exit(code);
            }
        }
        throw new ApplicationStartupException("Error starting Micronaut server: " + exception.getMessage(), exception);
    }
854913
void startEngine() throws ServerStartException {

		// setting up the server
		final boolean isDaemon = true;
		final boolean isSilent = false;

		final HsqlProperties hsqlProp = new HsqlProperties();

		// gives the chance to the descriptors to contribute to the server configuration.
		final AtomicInteger dbCounter = new AtomicInteger(0);
		for (HsqlDatabaseDescriptor db : dbs) {
			
			db.contributeToServerConfiguration(new LocationConfiguration() {

				@Override
				public void setLocation(String dbName, String location) {

					log.info("Registering db #{} : '{}' stored on '{}'", dbCounter, dbName, location);
					int dbIndex = dbCounter.getAndAdd(1);
					if (!(location.startsWith("file:") || location.startsWith("res:") || location
							.startsWith("mem:"))) {
						throw new IllegalArgumentException(location);
					}
					
					hsqlProp.setProperty("server.database." + dbIndex, location);
					hsqlProp.setProperty("server.dbname." + dbIndex, dbName);
				}

			});

		}
		// avoid to open a db remotely
		server = new Server();
		hsqlProp.setProperty("server.remote_open", false);
		try {
			server.setProperties(hsqlProp);
		} catch (IOException | AclFormatException e1) {
			throw new ServerStartException(e1);
		}

		server.setLogWriter(lubricantLoggerWriter.asPrintWriter());
		server.setDaemon(isDaemon);
		server.setSilent(isSilent);
		server.setTrace(false);
		server.setNoSystemExit(true);

		if (definedPort != null) {
			server.setPort(definedPort);
		}
		if (this.address != null) {
			server.setAddress(this.address);
		}

		for (int i = 0; i < this.dbs.size(); i++) {
			log.info("db " + i);
			log.info(server.getDatabaseType(i));
			log.info(server.getDatabaseName(i, true));
			log.info(server.getDatabasePath(i, true));
		}

		// dump config
		log.info("Starting HSQL standalone DBMS...");
		log.info("is daemon: {}", isDaemon);
		log.info("is silent: {}", isSilent);
		log.info("port: {} ", (definedPort != null ? definedPort
				: "HSQL default"));
		log.info("address: {} ", (address != null ? address : "HSQL default"));

		log.info("Waiting for hsql engine to start...");
		
		
		Integer state = server.start();
		Throwable serverError = server.getServerError();
		if(serverError!=null){
			throw new ServerStartException(serverError);
		}			
		do {
			state = server.getState();
			Thread.yield();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// nothing special
			}			
		}while(state != 1);
		
		log.info("Hsql engine started.");

		try{
			log.info("Starting databases post setup...");
			for (int i = 0; i < dbs.size(); i++) {
				final HsqlDatabaseDescriptor db = dbs.get(i);
				log.info("Post start up for db '{}', {}/{}.", db.getDbName(), i+1, dbs.size());
				db.postStartSetUp();
				db.goReady();
			}
			log.info("Post setup completed.");			
		}catch(Exception e){
			throw new ServerStartException("An error occurred during post setup.", e);
		}

		log.info("Dump connection strings:");
		for (HsqlDatabaseDescriptor db : dbs) {
			log.info("Connection to db {}: {}, account {}/{} ", db.getDbName(),
					db.getUrl(), db.getDbName(), db.getPassword());
		}

		log.info("HSQL standalone DBMS is ready");

	}
276146
public final void serverStarted() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "serverStarted", this);

        if (okayToSendServerStarted()) {

            Iterator<ComponentList> vIter = jmeComponents.iterator();
            while (vIter.hasNext()) {
                vIter.next().getRef().serverStarted();
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "serverStarted");
    }
627282
protected void initNode() {
        /**
         * quick fix for integration tests. if hosts property set to "embedded" then a local node is start.
         * maven dependencies need to be defined correctly for this to work
         */
        ClassLoader cl = Thread.currentThread().getContextClassLoader();

        try {
            // Need to use the classloader for Elasticsearch to pick up the property files when
            // running in an OSGi environment
            Thread.currentThread().setContextClassLoader(TransportClient.class.getClassLoader());

            final Properties properties = new Properties();
            try {
                InputStream stream = null;

                if (System.getProperties().containsKey("jboss.server.config.dir")) {
                    File file = new File(System.getProperty("jboss.server.config.dir") + File.separatorChar +
                            HAWKULAR_ELASTICSEARCH_PROPERTIES);
                    stream = new FileInputStream(file);
                } else {
                    stream = this.getClass().getResourceAsStream(File.separatorChar +
                                    HAWKULAR_ELASTICSEARCH_PROPERTIES);
                }
                properties.load(stream);
                stream.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Failed to load elasticsearch properties", e);
            }

            node = NodeBuilder.nodeBuilder()
                    .settings(ImmutableSettings.settingsBuilder()
                            .put(properties)).node();

            node.start();
            client = node.client();
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }

        if (log.isLoggable(Level.FINEST)) {
            log.finest("Initialized Elasticsearch node=" + node + " client=" + client);
        }
    }
8333
private void tryInit() {
    try {
      Configuration conf = getSnapshotConfiguration();
      if (conf != null) {
        // Since this is only used for background loading of transaction snapshots, we use the no-op metrics collector,
        // as there are no relevant metrics to report
        this.storage = new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf),
                                                       new TxMetricsCollector());
        this.storage.startAndWait();
        this.snapshotRefreshFrequency = conf.getLong(TxConstants.Manager.CFG_TX_SNAPSHOT_INTERVAL,
                                                     TxConstants.Manager.DEFAULT_TX_SNAPSHOT_INTERVAL) * 1000;
        this.initialized = true;
      } else {
        LOG.info("Could not load configuration");
      }
    } catch (Exception e) {
      LOG.info("Failed to initialize TransactionStateCache due to: " + e.getMessage());
    }
  }
744546
public static void agentmain(String agentArgs, Instrumentation instrumentation) {
        JvmAgentConfig config = new JvmAgentConfig(agentArgs);
        if (!config.isModeStop()) {
            startAgent(config,false, instrumentation);
        } else {
            stopAgent();
        }
    }
355160
public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println(STARTUP_NOTICE) ;
        JMXetricAgent a = null ;
        try {
            a = new JMXetricAgent();
            XMLConfigurationService.configure(a, agentArgs);
            a.start();
        } catch ( Exception ex ) {
            // log.severe("Exception starting JMXetricAgent");
            ex.printStackTrace();
        }
    }
210427
@Override
    public void start(StartContext context) throws StartException {
        Set<KeytabService> services = keytabServices.getValue();

        hostServiceMap = new HashMap<String, KeytabService>(services.size()); // Assume at least one per service.
        /*
         * Iterate the services and find the first one to offer default resolution, also create a hostname to KeytabService map
         * for the first one that claims each host.
         */
        for (KeytabService current : services) {
            for (String currentHost : current.getForHosts()) {
                if ("*".equals(currentHost)) {
                    if (defaultService == null) {
                        defaultService = current;
                    }
                } else if (currentHost != null) {
                    int idx = currentHost.indexOf("/");
                    String hostKey = idx > -1 ? currentHost.substring(0, idx) + "/" + currentHost.substring(idx + 1).toLowerCase(Locale.ENGLISH) :
                        currentHost.toLowerCase(Locale.ENGLISH);
                    if (hostServiceMap.containsKey(hostKey) == false) {
                        hostServiceMap.put(hostKey, current);
                    }
                }
            }
        }

        /*
         * Iterate the services again and attempt to identify host names from the principal name and add to the map if there is
         * not already a mapping for that host name.
         */
        for (KeytabService current : services) {
            String principal = current.getPrincipal();
            int start = principal.indexOf('/');
            int end = principal.indexOf('@');

            String currentHost = principal.substring(start > -1 ? start + 1 : 0, end > -1 ? end : principal.length() - 1);
            if (hostServiceMap.containsKey(currentHost.toLowerCase(Locale.ENGLISH)) == false) {
                hostServiceMap.put(currentHost.toLowerCase(Locale.ENGLISH), current);
            }
            principal = principal.substring(0, end > -1 ? end : principal.length() - 1);
            if (principal.equals(currentHost) == false) {
                String principalKey = principal.substring(0, start) + "/" + currentHost.toLowerCase(Locale.ENGLISH);
                if (hostServiceMap.containsKey(principalKey) == false) {
                    hostServiceMap.put(principalKey, current);
                }
            }
        }
    }
823539
@Override
    public void start() throws Exception {

        String thisMethodName = CLASS_NAME + ".start()";

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            // SibTr.entry(tc, thisMethodName);
        }

        Enumeration meEnum = _messagingEngines.elements();

        while (meEnum.hasMoreElements()) {
            Object o = meEnum.nextElement();
            Object c = ((MessagingEngine) o).getRuntime();
            try {

                ((BaseMessagingEngineImpl) c).startConditional();
                Dictionary<String, Object> properties = new Hashtable<String, Object>();
                properties.put("service.vendor", "IBM");
                properties.put("jmx.objectname", "WebSphere:feature=wasJmsServer,type=MessagingEngine,name=" + ((BaseMessagingEngineImpl) c)._name);
                mbeanServiceReg = (ServiceRegistration<MessagingEngineMBean>) this.bContext.registerService(MessagingEngineMBean.class.getName(), c, properties);

            } catch (Exception w) {
                // Not serious enough to warrant server stop.
                FFDCFilter.processException(w, thisMethodName, "1:725:1.108",
                                            this);
                SibTr.exception(tc, w);
                SibTr.error(tc, "INTERNAL_ERROR_SIAS0003", w);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            SibTr.exit(tc, thisMethodName);
        }
    }
601896
public void watchStartup(int startingTimeout, int startupTimeout)
            throws Exception {

        // use this for timeout checks later
        long startTime = System.currentTimeMillis();

        ServerStatusMessage[] messages = getAllMessages();

        ServerStatusMessage lastMessage = messages[messages.length - 1];

        boolean starting = false;
        boolean started = false;
        while (!started) {

            showStartup(messages);

            // update started and starting flags, and
            // throw a startup exception if startup failed
            // is encountered
            for (ServerStatusMessage element : messages) {
                ServerState state = element.getState();
                if (state == ServerState.STARTING) {
                    starting = true;
                } else if (state == ServerState.STARTED) {
                    started = true;
                } else if (state == ServerState.STARTUP_FAILED) {
                    throw new Exception("Fedora startup failed (see above)");
                }
            }

            if (!started) {

                // wait half a second
                try {
                    Thread.sleep(500);
                } catch (Throwable th) {
                }

                // throw an exception if either timeout has been
                // exceeded
                long now = System.currentTimeMillis();
                if (!starting) {
                    if ((now - startTime) / 1000 > startingTimeout) {
                        throw new Exception("Server startup did not begin within "
                                + startingTimeout + " seconds");
                    }
                }
                if ((now - startTime) / 1000 > startupTimeout) {
                    throw new Exception("Server startup did not complete within "
                            + startupTimeout + " seconds");
                }

                // get next batch of messages
                messages = _statusFile.getMessages(lastMessage);
                if (messages.length > 0) {
                    lastMessage = messages[messages.length - 1];
                }
            }

        }

    }