/* This should initialise the prometheus metrics when the
server starts up instead of the first time /metrics is
queried.
500347
@Override
    public void contextInitialized(ServletContextEvent event) {
        // Uncomment the next line to enable the default hotspot events.
        // DefaultExports.initialize();

        metrics = new Metrics();
        ServletContext context = event.getServletContext();
        context.addServlet("Metrics", new MetricsServlet()).addMapping("");
    }
769787
private static void awaitServerInitialization(JvmAgentConfig pConfig, final Instrumentation instrumentation) {
        List<ServerDetector> detectors = MBeanServerHandler.lookupDetectors();
        for (ServerDetector detector : detectors) {
            detector.jvmAgentStartup(instrumentation);
        }
    }
848940
function MetricsServer(port) {
  this.servedMetrics = [];
  this.sorted = true;
  this.startTime = new Date();
  this.server = http.createServer(this._handleRequest.bind(this));
  this.server.listen(port);
  debug('Serving metrics on localhost:%d/eyes', port);
}
62370
private void startMetricsCacheChecker() {
    final int checkIntervalSec =
        TypeUtils.getInteger(sinkConfig.get(KEY_TMASTER_LOCATION_CHECK_INTERVAL_SEC));

    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        TopologyMaster.MetricsCacheLocation location =
            (TopologyMaster.MetricsCacheLocation) SingletonRegistry.INSTANCE.getSingleton(
                MetricsManagerServer.METRICSCACHE_LOCATION_BEAN_NAME);

        if (location != null) {
          if (currentMetricsCacheLocation == null
              || !location.equals(currentMetricsCacheLocation)) {
            LOG.info("Update current MetricsCacheLocation to: " + location);
            currentMetricsCacheLocation = location;
            metricsCacheClientService.updateMetricsCacheLocation(currentMetricsCacheLocation);
            metricsCacheClientService.startNewMasterClient();

            // Update Metrics
            sinkContext.exportCountMetric(METRICSMGR_LOCATION_UPDATE_COUNT, 1);
          }
        }

        // Schedule itself in future
        tMasterLocationStarter.schedule(this, checkIntervalSec, TimeUnit.SECONDS);
      }
    };

    // First Entry
    tMasterLocationStarter.schedule(runnable, checkIntervalSec, TimeUnit.SECONDS);
    LOG.info("MetricsCacheChecker started with interval: " + checkIntervalSec);
  }
949116
@Override
  public void reportMetric(final IMetric<?> metric) throws MetricException {
    final String metricName = metric.getName();
    if (!this.historyListMapping.containsKey(metricName)) {
      logger.info("First time capturing metric: " + metricName);
      this.historyListMapping.put(metricName, new LinkedBlockingDeque<>());
    }
    synchronized (this.historyListMapping.get(metricName)) {
      logger.debug("Ingesting metric: " + metricName);
      this.historyListMapping.get(metricName).add(new InMemoryHistoryNode(metric.getValue()));
      cleanUsingTime(metricName, this.historyListMapping.get(metricName).peekLast().getTimestamp());
    }
  }
1364909
@Override
    public void initialize(Integer pollingPeriodMs) {
        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {
                /* (non-Javadoc)
                 * @see java.util.TimerTask#run()
                 */
                @Override
                public void run() {
                    try {
                        log.info("Launching periodic finalization...");
                        snapshotManager.finalizeSnapshots();
                        restoreManager.finalizeRestores();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            };

            if (pollingPeriodMs == null || pollingPeriodMs < 1) {
                pollingPeriodMs = DEFAULT_POLLING_PERIOD_MS;
            }

            timer.schedule(task, new Date(), pollingPeriodMs);
            log.info("Finalization scheduled to run every "
                     + pollingPeriodMs + " milliseconds.");
        }
    }
519138
public void start() throws Exception {
        Exceptions.checkNotClosed(this.closed, this);

        log.info("Initializing metrics provider ...");
        MetricsProvider.initialize(builderConfig.getConfig(MetricsConfig::builder));
        statsProvider = MetricsProvider.getMetricsProvider();
        statsProvider.start();

        log.info("Initializing ZooKeeper Client ...");
        this.zkClient = createZKClient();

        log.info("Initializing Service Builder ...");
        this.serviceBuilder.initialize();

        log.info("Creating StreamSegmentService ...");
        StreamSegmentStore service = this.serviceBuilder.createStreamSegmentService();

        log.info("Creating TableStoreService ...");
        TableStore tableStoreService = this.serviceBuilder.createTableStoreService();

        log.info("Creating Segment Stats recorder ...");
        autoScaleMonitor = new AutoScaleMonitor(service, builderConfig.getConfig(AutoScalerConfig::builder));

        TokenVerifierImpl tokenVerifier = new TokenVerifierImpl(builderConfig.getConfig(AutoScalerConfig::builder));

        // Log the configuration
        log.info(serviceConfig.toString());
        log.info(builderConfig.getConfig(AutoScalerConfig::builder).toString());

        this.listener = new PravegaConnectionListener(this.serviceConfig.isEnableTls(), this.serviceConfig.getListeningIPAddress(),
                                                      this.serviceConfig.getListeningPort(), service, tableStoreService,
                                                      autoScaleMonitor.getStatsRecorder(), autoScaleMonitor.getTableSegmentStatsRecorder(),
                                                      tokenVerifier, this.serviceConfig.getCertFile(), this.serviceConfig.getKeyFile(),
                                                      this.serviceConfig.isReplyWithStackTraceOnError());

        this.listener.startListening();
        log.info("PravegaConnectionListener started successfully.");
        log.info("StreamSegmentService started.");
    }
387171
private void serverInventoryInitialized()
  {
    long start = System.currentTimeMillis();
    long serverSyncWaitTimeout = config.getServerTimeout() + 2 * ChangeRequestHttpSyncer.HTTP_TIMEOUT_EXTRA_MS;

    List<DruidServerHolder> uninitializedServers = new ArrayList<>();
    for (DruidServerHolder server : servers.values()) {
      if (!server.isSyncedSuccessfullyAtleastOnce()) {
        uninitializedServers.add(server);
      }
    }

    while (!uninitializedServers.isEmpty() && ((System.currentTimeMillis() - start) < serverSyncWaitTimeout)) {
      try {
        Thread.sleep(5000);
      }
      catch (InterruptedException ex) {
        throw new RE(ex, "Interrupted while waiting for queryable server initial successful sync.");
      }

      log.info("Checking whether all servers have been synced at least once yet....");
      Iterator<DruidServerHolder> iter = uninitializedServers.iterator();
      while (iter.hasNext()) {
        if (iter.next().isSyncedSuccessfullyAtleastOnce()) {
          iter.remove();
        }
      }
    }

    if (uninitializedServers.isEmpty()) {
      log.info("All servers have been synced successfully at least once.");
    } else {
      for (DruidServerHolder server : uninitializedServers) {
        log.warn(
            "Server[%s] might not yet be synced successfully. We will continue to retry that in the background.",
            server.druidServer.getName()
        );
      }
    }

    log.info("Calling SegmentCallback.segmentViewInitialized() for all callbacks.");

    runSegmentCallbacks(
        new Function<SegmentCallback, CallbackAction>()
        {
          @Override
          public CallbackAction apply(SegmentCallback input)
          {
            return input.segmentViewInitialized();
          }
        }
    );
  }
974787
@Override
    void start() throws InitializationException {
        if (hsqlServer == null) {
            hsqlServer = new Server();
            hsqlServer.setLogWriter(null);
            hsqlServer.setSilent(true);
            hsqlServer.setDatabaseName(0, EMBEDED_DB_NAME);
            hsqlServer.setDatabasePath(0, "file:" + EMBEDED_DB_FILE_NAME + ";user=" + getUname() + ";password="
                    + getPassword());
            hsqlServer.start();
        }
    }
547113
private static void startIfNeeded()
   {
      if (!STARTED)
      {
         synchronized (JCRStatisticsManager.class)
         {
            if (!STARTED)
            {
               addTriggers();
               ExoContainer container = ExoContainerContext.getTopContainer();
               ManagementContext ctx = null;
               if (container != null)
               {
                  ctx = container.getManagementContext();
               }
               if (ctx == null)
               {
                  LOG.warn("Cannot register the statistics");
               }
               else
               {
                  ctx.register(new JCRStatisticsManager());
               }
               STARTED = true;
            }
         }
      }
   }
156145
public void initialise()
  {
    super.initialise();
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "initialise");
      
    _deletedQueuePoints = new HashMap();

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "initialise");
  }
903248
def _setup_metrics(self):
        
        path = os.environ.get("prometheus_multiproc_dir")
        if not os.path.exists(self.metrics_dir):
            try:
                log.info("Creating metrics directory")
                os.makedirs(self.metrics_dir)
            except OSError:
                log.error("Failed to create metrics directory!")
                raise ConfigurationException("Failed to create metrics directory!")
            path = self.metrics_dir
        elif path != self.metrics_dir:
            path = self.metrics_dir
        os.environ['prometheus_multiproc_dir'] = path
        log.info("Cleaning metrics collection directory")
        log.debug("Metrics directory set to: {}".format(path))
        files = os.listdir(path)
        for f in files:
            if f.endswith(".db"):
                os.remove(os.path.join(path, f))
            log.debug("Starting metrics exposition")
        if self.metrics_enabled:
            registry = CollectorRegistry()
            multiprocess.MultiProcessCollector(registry)
            start_http_server(
                port=self.metrics_port,
                addr=self.metrics_address,
                registry=registry
            )
266863
private AbstractSigarMetricSet<?> init(AbstractSigarMetricSet<?> metrics) {
		try {
			metrics.getSnapshot();
			return metrics;
		} catch (RuntimeException e) {
			logger.warn(e.getMessage() + ". (This exception is ignored)", e);
			return new EmptySigarMetricSet();
		}
	}
131144
function init(endPoint, accessKeyId, accessKeySecret, securityToken = null, project) {
  return AliyunLog && AliyunLog.initAliyunLog && AliyunLog.initAliyunLog(endPoint, accessKeyId, accessKeySecret, securityToken, project);
}
12728
private void initialize(Configuration conf) throws IOException {
    // initiate Java VM metrics
    JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
    
    // Create connection to the namenode.
    shouldRun = true;
    nameNodeAddr = NameNode.getClientProtocolAddress(conf);

    this.conf = conf;
    this.namenode =
        (NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
            NamenodeProtocol.versionID, nameNodeAddr, conf);
    this.namenode.register();

    // initialize checkpoint directories
    fsName = getInfoServer();
    checkpointDirs = getFileStorageDirs(NNStorageConfiguration
        .getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary"));
    checkpointEditsDirs = getFileStorageDirs(NNStorageConfiguration
        .getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary")); 
    checkpointImage = new CheckpointStorage(conf);
    checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);

    // Initialize other scheduling parameters from the configuration
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointTxnCount = NNStorageConfiguration.getCheckpointTxnCount(conf);

    // initialize the webserver for uploading files.
    String infoAddr = 
      NetUtils.getServerAddress(conf, 
                                "dfs.secondary.info.bindAddress",
                                "dfs.secondary.info.port",
                                "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    String infoBindIpAddress = infoSocAddr.getAddress().getHostAddress();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("secondary", infoBindIpAddress, tmpInfoPort,
        tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", checkpointImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindIpAddress + ":" +infoPort); 
    LOG.info("Secondary Web-server up at: " + infoBindIpAddress + ":" +infoPort);
    LOG.warn("Checkpoint Period   :" + checkpointPeriod + " secs " +
             "(" + checkpointPeriod/60 + " min)");
    LOG.warn("Log Size Trigger    :" + checkpointTxnCount  + " transactions ");
  }
617793
function _doLaunchAfterServerReady(initialDoc) {
        // update status
        _setStatus(STATUS_CONNECTING);
        _createLiveDocumentForFrame(initialDoc);

        // start listening for requests
        _server.start();

        // Install a one-time event handler when connected to the launcher page
        Inspector.one("connect", _onConnect);

        // open browser to the interstitial page to prepare for loading agents
        _openInterstitialPage();

        // Once all agents loaded (see _onInterstitialPageLoad()), begin Live Highlighting for preprocessor documents
        _openDeferred.done(function () {
            // Setup activeEditorChange event listener so that we can track cursor positions in
            // CSS preprocessor files and perform live preview highlighting on all elements with
            // the current selector in the preprocessor file.
            EditorManager.on("activeEditorChange", onActiveEditorChange);

            // Explicitly trigger onActiveEditorChange so that live preview highlighting
            // can be set up for the preprocessor files.
            onActiveEditorChange(null, EditorManager.getActiveEditor(), null);
        });
    }
121456
static synchronized boolean restartSingleton(CloudWatchMetricConfig config) {
        if (singleton == null) {
            throw new IllegalStateException(MetricCollectorSupport.class.getSimpleName()
                + " has neven been initialized");
        }
        log.info("Re-initializing " + MetricCollectorSupport.class.getSimpleName());
        singleton.stop();
        // singleton is set to null at this point via the stop method
        return createAndStartCollector(config);
    }