/**
   * Initializes the Graphite reporter based on the current configuration.
   *
   * @param config the graphite reporter configuration
   */
  private void configureGraphiteReporter(GraphiteReporterConfig config) {
    if (config.isEnabled()) {
      Graphite graphite =
          new Graphite(new InetSocketAddress(config.getServerUri(), config.getServerPort()));

      String nodeName;

      try {
        InetAddress localhost = InetAddress.getLocalHost();
        nodeName = localhost.getHostName();
      } catch (UnknownHostException e) {
        nodeName = "UNKNOWN";
      }

      graphiteReporter =
          GraphiteReporter.forRegistry(metricRegistry)
              .prefixedWith(String.format("motech.%s", nodeName))
              .convertRatesTo(config.getConvertRates())
              .convertDurationsTo(config.getConvertDurations())
              .filter(MetricFilter.ALL)
              .build(graphite);

      graphiteReporter.start(config.getFrequency(), config.getFrequencyUnit());
    }
  }
 @Bean
 public GraphiteReporter graphiteReporter() {
   LOGGER.debug("Creating graphite reporter");
   final Graphite graphite = new Graphite(new InetSocketAddress("192.168.10.120", 2003));
   final GraphiteReporter reporter =
       GraphiteReporter.forRegistry(metricRegistry)
           .prefixedWith("KillrAuction")
           .convertRatesTo(TimeUnit.SECONDS)
           .convertDurationsTo(TimeUnit.MILLISECONDS)
           .filter(MetricFilter.ALL)
           .build(graphite);
   reporter.start(30, TimeUnit.SECONDS);
   return reporter;
 }
 @PostConstruct
 private void init() {
   if (jHipsterProperties.getMetrics().getGraphite().isEnabled()) {
     log.info("Initializing Metrics Graphite reporting");
     String graphiteHost = jHipsterProperties.getMetrics().getGraphite().getHost();
     Integer graphitePort = jHipsterProperties.getMetrics().getGraphite().getPort();
     String graphitePrefix = jHipsterProperties.getMetrics().getGraphite().getPrefix();
     Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort));
     GraphiteReporter graphiteReporter =
         GraphiteReporter.forRegistry(metricRegistry)
             .convertRatesTo(TimeUnit.SECONDS)
             .convertDurationsTo(TimeUnit.MILLISECONDS)
             .prefixedWith(graphitePrefix)
             .build(graphite);
     graphiteReporter.start(1, TimeUnit.MINUTES);
   }
 }
 /** Stop the reporter threads. */
 @PreDestroy
 public void stopReporters() {
   if (consoleReporter != null) {
     consoleReporter.stop();
   }
   if (graphiteReporter != null) {
     graphiteReporter.stop();
   }
 }
  private void reportToGraphite(
      MetricRegistry metricRegistry,
      long reportingInterval,
      MeasurementSession measurementSession,
      MetricFilter filter) {
    String graphiteHostName = getGraphiteHostName();
    if (isReportToGraphite()) {
      final GraphiteReporter graphiteReporter =
          GraphiteReporter.forRegistry(metricRegistry)
              .prefixedWith(getGraphitePrefix(measurementSession))
              .convertRatesTo(TimeUnit.SECONDS)
              .convertDurationsTo(TimeUnit.MILLISECONDS)
              .filter(filter)
              .build(new Graphite(new InetSocketAddress(graphiteHostName, getGraphitePort())));

      graphiteReporter.start(reportingInterval, TimeUnit.SECONDS);
      reporters.add(graphiteReporter);
    }
  }
 private MetricRegistry buildMetricRegistry() {
   metricRegistry = new MetricRegistry();
   // set graphite reporter
   final MovieTimeConfig.GraphiteConfig graphiteConfig = configuration.getGraphite();
   if (graphiteConfig.isActivate()) {
     final Graphite graphite =
         new Graphite(new InetSocketAddress(graphiteConfig.getHost(), graphiteConfig.getPort()));
     final GraphiteReporter graphiteReporter =
         GraphiteReporter.forRegistry(metricRegistry)
             .prefixedWith(graphiteConfig.getApiKey())
             .convertRatesTo(TimeUnit.SECONDS)
             .convertDurationsTo(TimeUnit.MILLISECONDS)
             .filter(MetricFilter.ALL)
             .build(graphite);
     graphiteReporter.start(1, TimeUnit.MINUTES);
     log.info("Metrics graphite reporter bootstrapped");
   } else {
     log.info("Metrics reporter not running");
   }
   return metricRegistry;
 }
    @PostConstruct
    private void init() {
      Boolean graphiteEnabled =
          propertyResolver.getProperty(PROP_GRAPHITE_ENABLED, Boolean.class, false);
      if (graphiteEnabled) {
        log.info("Initializing Metrics Graphite reporting");
        String graphiteHost = propertyResolver.getRequiredProperty(PROP_HOST);
        Integer graphitePort = propertyResolver.getRequiredProperty(PROP_PORT, Integer.class);
        String graphitePrefix =
            propertyResolver.getProperty(PROP_GRAPHITE_PREFIX, String.class, "");

        Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort));
        GraphiteReporter graphiteReporter =
            GraphiteReporter.forRegistry(metricRegistry)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .prefixedWith(graphitePrefix)
                .build(graphite);
        graphiteReporter.start(1, TimeUnit.MINUTES);
      }
    }
Exemple #8
0
  static {
    Configuration config = Configuration.getInstance();

    // register jvm metrics
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    if (!System.getProperty("java.version").split("\\.")[1].equals("6")) {
      // if not running 1.6
      registry.registerAll(
          new PrefixedMetricSet(new BufferPoolMetricSet(mbs), JVM_PREFIX, "buffer-pool"));
    }
    registry.registerAll(new PrefixedMetricSet(new GarbageCollectorMetricSet(), JVM_PREFIX, "gc"));
    registry.registerAll(new PrefixedMetricSet(new MemoryUsageGaugeSet(), JVM_PREFIX, "memory"));
    registry.registerAll(
        new PrefixedMetricSet(new ThreadStatesGaugeSet(), JVM_PREFIX, "thread-states"));

    // instrument log4j
    InstrumentedAppender appender = new InstrumentedAppender(registry);
    appender.activateOptions();
    LogManager.getRootLogger().addAppender(appender);

    if (!config.getStringProperty(CoreConfig.RIEMANN_HOST).equals("")) {
      RiemannReporter tmpreporter;
      try {
        Riemann riemann =
            new Riemann(
                config.getStringProperty(CoreConfig.RIEMANN_HOST),
                config.getIntegerProperty(CoreConfig.RIEMANN_PORT));

        RiemannReporter.Builder builder =
            RiemannReporter.forRegistry(registry)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .convertRatesTo(TimeUnit.SECONDS);
        if (!config.getStringProperty(CoreConfig.RIEMANN_SEPARATOR).isEmpty()) {
          builder.useSeparator(config.getStringProperty(CoreConfig.RIEMANN_SEPARATOR));
        }
        if (!config.getStringProperty(CoreConfig.RIEMANN_TTL).isEmpty()) {
          builder.withTtl(config.getFloatProperty(CoreConfig.RIEMANN_TTL));
        }
        if (!config.getStringProperty(CoreConfig.RIEMANN_LOCALHOST).isEmpty()) {
          builder.localHost(config.getStringProperty(CoreConfig.RIEMANN_LOCALHOST));
        }
        if (!config.getStringProperty(CoreConfig.RIEMANN_PREFIX).isEmpty()) {
          builder.prefixedWith(config.getStringProperty(CoreConfig.RIEMANN_PREFIX));
        }
        if (!config.getStringProperty(CoreConfig.RIEMANN_TAGS).isEmpty()) {
          builder.tags(config.getListProperty(CoreConfig.RIEMANN_TAGS));
        }
        tmpreporter = builder.build(riemann);

        tmpreporter.start(30l, TimeUnit.SECONDS);
      } catch (IOException e) {
        tmpreporter = null;
      }
      reporter1 = tmpreporter;
    } else {
      reporter1 = null;
    }

    if (!config.getStringProperty(CoreConfig.GRAPHITE_HOST).equals("")) {
      Graphite graphite =
          new Graphite(
              new InetSocketAddress(
                  config.getStringProperty(CoreConfig.GRAPHITE_HOST),
                  config.getIntegerProperty(CoreConfig.GRAPHITE_PORT)));

      reporter =
          GraphiteReporter.forRegistry(registry)
              .convertDurationsTo(TimeUnit.MILLISECONDS)
              .convertRatesTo(TimeUnit.SECONDS)
              .prefixedWith(config.getStringProperty(CoreConfig.GRAPHITE_PREFIX))
              .build(graphite);

      reporter.start(30l, TimeUnit.SECONDS);
    } else {
      reporter = null;
    }

    reporter2 =
        JmxReporter.forRegistry(registry)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .convertRatesTo(TimeUnit.SECONDS)
            .build();
    reporter2.start();
  }
  @Override
  public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
    SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
    environment
        .getObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    DBIFactory dbiFactory = new DBIFactory();
    DBI database = dbiFactory.build(environment, config.getDataSourceFactory(), "accountdb");
    DBI messagedb =
        dbiFactory.build(environment, config.getMessageStoreConfiguration(), "messagedb");

    Accounts accounts = database.onDemand(Accounts.class);
    PendingAccounts pendingAccounts = database.onDemand(PendingAccounts.class);
    PendingDevices pendingDevices = database.onDemand(PendingDevices.class);
    Keys keys = database.onDemand(Keys.class);
    Messages messages = messagedb.onDemand(Messages.class);

    RedisClientFactory cacheClientFactory =
        new RedisClientFactory(config.getCacheConfiguration().getUrl());
    JedisPool cacheClient = cacheClientFactory.getRedisClientPool();
    JedisPool directoryClient =
        new RedisClientFactory(config.getDirectoryConfiguration().getUrl()).getRedisClientPool();
    Client httpClient = initializeHttpClient(environment, config);

    DirectoryManager directory = new DirectoryManager(directoryClient);
    PendingAccountsManager pendingAccountsManager =
        new PendingAccountsManager(pendingAccounts, cacheClient);
    PendingDevicesManager pendingDevicesManager =
        new PendingDevicesManager(pendingDevices, cacheClient);
    AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheClient);
    FederatedClientManager federatedClientManager =
        new FederatedClientManager(
            environment,
            config.getJerseyClientConfiguration(),
            config.getFederationConfiguration());
    MessagesManager messagesManager = new MessagesManager(messages);
    DeadLetterHandler deadLetterHandler = new DeadLetterHandler(messagesManager);
    DispatchManager dispatchManager =
        new DispatchManager(cacheClientFactory, Optional.<DispatchChannel>of(deadLetterHandler));
    PubSubManager pubSubManager = new PubSubManager(cacheClient, dispatchManager);
    PushServiceClient pushServiceClient =
        new PushServiceClient(httpClient, config.getPushConfiguration());
    WebsocketSender websocketSender = new WebsocketSender(messagesManager, pubSubManager);
    AccountAuthenticator deviceAuthenticator = new AccountAuthenticator(accountsManager);
    FederatedPeerAuthenticator federatedPeerAuthenticator =
        new FederatedPeerAuthenticator(config.getFederationConfiguration());
    RateLimiters rateLimiters = new RateLimiters(config.getLimitsConfiguration(), cacheClient);

    ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushServiceClient);
    TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration());
    Optional<NexmoSmsSender> nexmoSmsSender =
        initializeNexmoSmsSender(config.getNexmoConfiguration());
    SmsSender smsSender =
        new SmsSender(
            twilioSmsSender, nexmoSmsSender, config.getTwilioConfiguration().isInternational());
    UrlSigner urlSigner = new UrlSigner(config.getS3Configuration());
    PushSender pushSender = new PushSender(apnFallbackManager, pushServiceClient, websocketSender);
    ReceiptSender receiptSender =
        new ReceiptSender(accountsManager, pushSender, federatedClientManager);
    FeedbackHandler feedbackHandler = new FeedbackHandler(pushServiceClient, accountsManager);
    Optional<byte[]> authorizationKey = config.getRedphoneConfiguration().getAuthorizationKey();

    environment.lifecycle().manage(apnFallbackManager);
    environment.lifecycle().manage(pubSubManager);
    environment.lifecycle().manage(feedbackHandler);

    AttachmentController attachmentController =
        new AttachmentController(rateLimiters, federatedClientManager, urlSigner);
    KeysControllerV1 keysControllerV1 =
        new KeysControllerV1(rateLimiters, keys, accountsManager, federatedClientManager);
    KeysControllerV2 keysControllerV2 =
        new KeysControllerV2(rateLimiters, keys, accountsManager, federatedClientManager);
    MessageController messageController =
        new MessageController(
            rateLimiters,
            pushSender,
            receiptSender,
            accountsManager,
            messagesManager,
            federatedClientManager);

    environment
        .jersey()
        .register(
            new AuthDynamicFeature(
                new BasicCredentialAuthFilter.Builder<Account>()
                    .setAuthenticator(deviceAuthenticator)
                    .setPrincipal(Account.class)
                    .buildAuthFilter(),
                new BasicCredentialAuthFilter.Builder<FederatedPeer>()
                    .setAuthenticator(federatedPeerAuthenticator)
                    .setPrincipal(FederatedPeer.class)
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder());

    environment
        .jersey()
        .register(
            new AccountController(
                pendingAccountsManager,
                accountsManager,
                rateLimiters,
                smsSender,
                messagesManager,
                new TimeProvider(),
                authorizationKey,
                config.getTestDevices()));
    environment
        .jersey()
        .register(new DeviceController(pendingDevicesManager, accountsManager, rateLimiters));
    environment.jersey().register(new DirectoryController(rateLimiters, directory));
    environment
        .jersey()
        .register(
            new FederationControllerV1(
                accountsManager, attachmentController, messageController, keysControllerV1));
    environment
        .jersey()
        .register(
            new FederationControllerV2(
                accountsManager, attachmentController, messageController, keysControllerV2));
    environment.jersey().register(new ReceiptController(receiptSender));
    environment.jersey().register(new ProvisioningController(rateLimiters, pushSender));
    environment.jersey().register(attachmentController);
    environment.jersey().register(keysControllerV1);
    environment.jersey().register(keysControllerV2);
    environment.jersey().register(messageController);

    if (config.getWebsocketConfiguration().isEnabled()) {
      WebSocketEnvironment webSocketEnvironment =
          new WebSocketEnvironment(environment, config, 90000);
      webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(deviceAuthenticator));
      webSocketEnvironment.setConnectListener(
          new AuthenticatedConnectListener(
              accountsManager,
              pushSender,
              receiptSender,
              messagesManager,
              pubSubManager,
              apnFallbackManager));
      webSocketEnvironment.jersey().register(new KeepAliveController(pubSubManager));

      WebSocketEnvironment provisioningEnvironment = new WebSocketEnvironment(environment, config);
      provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(pubSubManager));
      provisioningEnvironment.jersey().register(new KeepAliveController(pubSubManager));

      WebSocketResourceProviderFactory webSocketServlet =
          new WebSocketResourceProviderFactory(webSocketEnvironment);
      WebSocketResourceProviderFactory provisioningServlet =
          new WebSocketResourceProviderFactory(provisioningEnvironment);

      ServletRegistration.Dynamic websocket =
          environment.servlets().addServlet("WebSocket", webSocketServlet);
      ServletRegistration.Dynamic provisioning =
          environment.servlets().addServlet("Provisioning", provisioningServlet);

      websocket.addMapping("/v1/websocket/");
      websocket.setAsyncSupported(true);

      provisioning.addMapping("/v1/websocket/provisioning/");
      provisioning.setAsyncSupported(true);

      webSocketServlet.start();
      provisioningServlet.start();

      FilterRegistration.Dynamic filter =
          environment.servlets().addFilter("CORS", CrossOriginFilter.class);
      filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
      filter.setInitParameter("allowedOrigins", "*");
      filter.setInitParameter(
          "allowedHeaders",
          "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
      filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS");
      filter.setInitParameter("preflightMaxAge", "5184000");
      filter.setInitParameter("allowCredentials", "true");
    }

    environment.healthChecks().register("directory", new RedisHealthCheck(directoryClient));
    environment.healthChecks().register("cache", new RedisHealthCheck(cacheClient));

    environment.jersey().register(new IOExceptionMapper());
    environment.jersey().register(new RateLimitExceededExceptionMapper());
    environment.jersey().register(new InvalidWebsocketAddressExceptionMapper());
    environment.jersey().register(new DeviceLimitExceededExceptionMapper());

    environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge());
    environment
        .metrics()
        .register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
    environment
        .metrics()
        .register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge());
    environment
        .metrics()
        .register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge());

    if (config.getGraphiteConfiguration().isEnabled()) {
      GraphiteReporterFactory graphiteReporterFactory = new GraphiteReporterFactory();
      graphiteReporterFactory.setHost(config.getGraphiteConfiguration().getHost());
      graphiteReporterFactory.setPort(config.getGraphiteConfiguration().getPort());

      GraphiteReporter graphiteReporter =
          (GraphiteReporter) graphiteReporterFactory.build(environment.metrics());
      graphiteReporter.start(15, TimeUnit.SECONDS);
    }
  }