コード例 #1
0
 private void registerJvmMetrics() {
   // add JVM gauges
   metrics.register(
       "variable.jvm.free.memory",
       new Gauge<Long>() {
         @Override
         public Long getValue() {
           return Runtime.getRuntime().freeMemory();
         }
       });
   metrics.register(
       "variable.jvm.max.memory",
       new Gauge<Long>() {
         @Override
         public Long getValue() {
           return Runtime.getRuntime().maxMemory();
         }
       });
   metrics.register(
       "variable.jvm.total.memory",
       new Gauge<Long>() {
         @Override
         public Long getValue() {
           return Runtime.getRuntime().totalMemory();
         }
       });
 }
コード例 #2
0
 @Test
 public void test() throws Exception {
   Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
   JobExecution jobExecution = jobLauncherTestUtils.launchJob(new JobParameters(parameters));
   Assert.assertEquals(
       jobExecution.getExitStatus().getExitDescription(),
       BatchStatus.COMPLETED,
       jobExecution.getStatus());
   Map<String, Meter> meters = metricRegistry.getMeters();
   assertThat(meters).hasSize(2);
   assertThat(meters)
       .containsKey("batch.sampleJob.job.metered")
       .containsKey("batch.sampleJob.step.chunkStep.step.metered");
   assertThat(extractProperty("count", Number.class).from(meters.values()))
       .contains(1L)
       .doesNotContain(0L);
   Map<String, Timer> timers = metricRegistry.getTimers();
   assertThat(timers).hasSize(6);
   assertThat(timers)
       .containsKey("batch.sampleJob.job.timed")
       .containsKey("batch.sampleJob.step.chunkStep.chunk.timed")
       .containsKey("batch.sampleJob.step.chunkStep.step.timed")
       .containsKey("batch.sampleJob.step.chunkStep.read.timed")
       .containsKey("batch.sampleJob.step.chunkStep.process.timed")
       .containsKey("batch.sampleJob.step.chunkStep.write.timed");
   assertThat(extractProperty("count", Number.class).from(timers.values()))
       .contains(1L, 3L, 4L)
       .doesNotContain(0L);
   Map<String, Gauge> gauges = metricRegistry.getGauges();
   assertThat(gauges).hasSize(0);
 }
コード例 #3
0
  @Test
  public void publishReceivedCountsIncomingMessages() {
    assumeThat(metricRegistry.getMeters().get("test.incomingMessages").getCount(), is(0l));
    listener.publishReceived(client, new PublishMessage("test", QoS.AT_LEAST_ONCE));

    assertThat(metricRegistry.getMeters().get("test.incomingMessages").getCount(), is(1l));
  }
コード例 #4
0
  /**
   * @summary get the worker metrics
   * @return the response object
   */
  @GET
  @Path(GET_METRICS)
  @ReturnType("java.util.SortedMap<String, Long>")
  public Response getMetrics() {
    MetricRegistry metricRegistry = mWorker.getWorkerMetricsSystem().getMetricRegistry();

    // Get all counters.
    Map<String, Counter> counters = metricRegistry.getCounters();

    // Only the gauge for cached blocks is retrieved here, other gauges are statistics of free/used
    // spaces, those statistics can be gotten via other REST apis.
    String blocksCachedProperty =
        CommonUtils.argsToString(
            ".", WorkerContext.getWorkerSource().getName(), WorkerSource.BLOCKS_CACHED);
    @SuppressWarnings("unchecked")
    Gauge<Integer> blocksCached =
        (Gauge<Integer>) metricRegistry.getGauges().get(blocksCachedProperty);

    // Get values of the counters and gauges and put them into a metrics map.
    SortedMap<String, Long> metrics = new TreeMap<>();
    for (Map.Entry<String, Counter> counter : counters.entrySet()) {
      metrics.put(counter.getKey(), counter.getValue().getCount());
    }
    metrics.put(blocksCachedProperty, blocksCached.getValue().longValue());

    return RestUtils.createResponse(metrics);
  }
コード例 #5
0
 private void registerContainerAppNumMetrics() {
   metrics.register(
       "variable.running.application",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAppsRunning();
           }
         }
       });
   metrics.register(
       "variable.running.container",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAllocatedContainers();
           }
         }
       });
 }
コード例 #6
0
ファイル: Hash.java プロジェクト: wealdtech/wealdtech
  static {
    // TODO where to obtain this from?
    CONFIGURATION = new HashConfiguration();

    LOOKUPS =
        WealdMetrics.getMetricRegistry()
            .meter(com.codahale.metrics.MetricRegistry.name(Hash.class, "lookups"));
    MISSES =
        WealdMetrics.getMetricRegistry()
            .meter(com.codahale.metrics.MetricRegistry.name(Hash.class, "misses"));
    GETS =
        WealdMetrics.getMetricRegistry()
            .timer(com.codahale.metrics.MetricRegistry.name(Hash.class, "gets"));
    final CacheBuilder<Object, Object> cb =
        CacheBuilder.newBuilder()
            .maximumSize(CONFIGURATION.getCacheConfiguration().getMaxEntries())
            .expireAfterWrite(
                CONFIGURATION.getCacheConfiguration().getMaxDuration(), TimeUnit.SECONDS);
    CACHE =
        cb.recordStats()
            .build(
                new CacheLoader<TwoTuple<String, String>, Boolean>() {
                  @Override
                  public Boolean load(final TwoTuple<String, String> input) {
                    MISSES.mark();
                    return calculateMatches(input.getS(), input.getT());
                  }
                });
  }
コード例 #7
0
ファイル: MetricContextTest.java プロジェクト: ronwxy/gobblin
  @Test
  public void testTaggableGauge() {
    ContextAwareGauge<Long> queueSize =
        this.context.newContextAwareGauge(
            QUEUE_SIZE,
            new Gauge<Long>() {
              @Override
              public Long getValue() {
                return 1000l;
              }
            });
    this.context.register(QUEUE_SIZE, queueSize);

    Assert.assertEquals(queueSize.getValue().longValue(), 1000l);

    Assert.assertEquals(
        this.context
            .getGauges()
            .get(MetricRegistry.name(this.context.metricNamePrefix(false), queueSize.getName())),
        queueSize);
    Assert.assertEquals(queueSize.getContext(), this.context);
    Assert.assertEquals(queueSize.getName(), QUEUE_SIZE);

    Assert.assertTrue(queueSize.getTags().isEmpty());
    queueSize.addTag(new Tag<String>(METRIC_GROUP_KEY, INPUT_RECORDS_GROUP));
    Assert.assertEquals(queueSize.getTags().size(), 1);
    Assert.assertEquals(queueSize.getTags().get(0).getKey(), METRIC_GROUP_KEY);
    Assert.assertEquals(queueSize.getTags().get(0).getValue(), INPUT_RECORDS_GROUP);
    Assert.assertEquals(
        queueSize.getFullyQualifiedName(false),
        MetricRegistry.name(INPUT_RECORDS_GROUP, QUEUE_SIZE));
  }
コード例 #8
0
ファイル: MetricContextTest.java プロジェクト: ronwxy/gobblin
    @Override
    protected void reportInContext(
        MetricContext context,
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

      Assert.assertEquals(context.getName(), CONTEXT_NAME);

      Assert.assertEquals(gauges.size(), 1);
      Assert.assertTrue(
          gauges.containsKey(MetricRegistry.name(context.metricNamePrefix(false), QUEUE_SIZE)));

      Assert.assertEquals(counters.size(), 1);
      Assert.assertTrue(
          counters.containsKey(
              MetricRegistry.name(context.metricNamePrefix(false), RECORDS_PROCESSED)));

      Assert.assertEquals(histograms.size(), 1);
      Assert.assertTrue(
          histograms.containsKey(
              MetricRegistry.name(context.metricNamePrefix(false), RECORD_SIZE_DISTRIBUTION)));

      Assert.assertEquals(meters.size(), 1);
      Assert.assertTrue(
          meters.containsKey(
              MetricRegistry.name(context.metricNamePrefix(false), RECORD_PROCESS_RATE)));

      Assert.assertEquals(timers.size(), 2);
      Assert.assertTrue(
          timers.containsKey(MetricRegistry.name(context.metricNamePrefix(false), TOTAL_DURATION)));
    }
コード例 #9
0
ファイル: MetricContextTest.java プロジェクト: ronwxy/gobblin
  @Test
  public void testContextAwareTimer() {
    ContextAwareTimer jobTotalDuration = this.context.contextAwareTimer(TOTAL_DURATION);
    Assert.assertEquals(
        this.context
            .getTimers()
            .get(
                MetricRegistry.name(
                    this.context.metricNamePrefix(false), jobTotalDuration.getName())),
        jobTotalDuration);
    Assert.assertEquals(jobTotalDuration.getContext(), this.context);
    Assert.assertEquals(jobTotalDuration.getName(), TOTAL_DURATION);

    Assert.assertTrue(jobTotalDuration.getTags().isEmpty());
    jobTotalDuration.addTag(new Tag<String>(METRIC_GROUP_KEY, INPUT_RECORDS_GROUP));
    Assert.assertEquals(jobTotalDuration.getTags().size(), 1);
    Assert.assertEquals(jobTotalDuration.getTags().get(0).getKey(), METRIC_GROUP_KEY);
    Assert.assertEquals(jobTotalDuration.getTags().get(0).getValue(), INPUT_RECORDS_GROUP);
    Assert.assertEquals(
        jobTotalDuration.getFullyQualifiedName(false),
        MetricRegistry.name(INPUT_RECORDS_GROUP, TOTAL_DURATION));

    jobTotalDuration.update(50, TimeUnit.SECONDS);
    jobTotalDuration.update(100, TimeUnit.SECONDS);
    jobTotalDuration.update(150, TimeUnit.SECONDS);
    Assert.assertEquals(jobTotalDuration.getCount(), 3l);
    Assert.assertEquals(jobTotalDuration.getSnapshot().getMin(), TimeUnit.SECONDS.toNanos(50l));
    Assert.assertEquals(jobTotalDuration.getSnapshot().getMax(), TimeUnit.SECONDS.toNanos(150l));

    Assert.assertTrue(jobTotalDuration.time().stop() >= 0l);
  }
コード例 #10
0
  private ExtractorSummary toSummary(Extractor extractor) {
    final ExtractorMetrics metrics =
        ExtractorMetrics.create(
            MetricUtils.buildTimerMap(
                metricRegistry.getTimers().get(extractor.getTotalTimerName())),
            MetricUtils.buildTimerMap(
                metricRegistry.getTimers().get(extractor.getConverterTimerName())));

    return ExtractorSummary.create(
        extractor.getId(),
        extractor.getTitle(),
        extractor.getType().toString().toLowerCase(),
        extractor.getCursorStrategy().toString().toLowerCase(),
        extractor.getSourceField(),
        extractor.getTargetField(),
        extractor.getExtractorConfig(),
        extractor.getCreatorUserId(),
        extractor.converterConfigMap(),
        extractor.getConditionType().toString().toLowerCase(),
        extractor.getConditionValue(),
        extractor.getOrder(),
        extractor.getExceptionCount(),
        extractor.getConverterExceptionCount(),
        metrics);
  }
コード例 #11
0
  @Test
  public void publishReceivedCountsEmptyMessages() {
    assumeThat(metricRegistry.getMeters().get("test.incompleteMessages").getCount(), is(0l));
    listener.publishReceived(client, new PublishMessage("test", QoS.AT_LEAST_ONCE, (byte[]) null));
    listener.publishReceived(client, new PublishMessage("test", QoS.AT_LEAST_ONCE, new byte[0]));

    assertThat(metricRegistry.getMeters().get("test.incompleteMessages").getCount(), is(2l));
  }
コード例 #12
0
  @Test
  @InSequence(1)
  public void countedMethodNotCalledYet() {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter hasn't been called yet
    assertThat("Counter count is incorrect", counter.getCount(), is(equalTo(COUNTER_COUNT.get())));
  }
コード例 #13
0
  @Test
  @InSequence(2)
  public void countedMethodNotCalledYet(
      @Metric(name = "countedMethod", absolute = true) Counter instance) {
    assertThat("Counter is not registered correctly", registry.getCounters(), hasKey(COUNTER_NAME));
    Counter counter = registry.getCounters().get(COUNTER_NAME);

    // Make sure that the counter registered and the bean instance are the same
    assertThat("Counter and bean instance are not equal", instance, is(equalTo(counter)));
  }
コード例 #14
0
  @Test
  @InSequence(1)
  public void gaugeCalledWithDefaultValue() {
    assertThat("Gauge is not registered correctly", registry.getGauges(), hasKey(GAUGE_NAME));
    @SuppressWarnings("unchecked")
    Gauge<Long> gauge = registry.getGauges().get(GAUGE_NAME);

    // Make sure that the gauge has the expected value
    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(0L)));
  }
コード例 #15
0
  @Test
  public void publishReceivedCountsDiscardedMessages()
      throws BufferOutOfCapacityException, ProcessingDisabledException {
    final PublishMessage message = new PublishMessage("test", QoS.AT_LEAST_ONCE, "");

    assumeThat(metricRegistry.getMeters().get("test.incompleteMessages").getCount(), is(0l));
    listener.publishReceived(client, message);

    assertThat(metricRegistry.getMeters().get("test.incompleteMessages").getCount(), is(1l));
  }
コード例 #16
0
ファイル: MetricManager.java プロジェクト: nickman/nash
 /**
  * Removes all the metrics for the named data source
  *
  * @param name the sub registry name
  * @param metricNames The metrics to remove
  */
 public void closeDataSource(final String name, final Collection<String> metricNames) {
   if (name == null || name.trim().isEmpty())
     throw new IllegalArgumentException("Metric registry name was null");
   final String mname = name.trim();
   MetricRegistry m = subRegistries.get(mname);
   if (m != null) {
     for (String s : metricNames) {
       m.remove(s);
     }
   }
 }
コード例 #17
0
  /**
   * package metrics information for one tracked queue/app only support FairScheduler currently
   *
   * @throws java.io.IOException
   */
  private void printJsonTrack(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/json");
    response.setStatus(HttpServletResponse.SC_OK);

    StringBuilder sb = new StringBuilder();
    if (schedulerMetrics instanceof FairSchedulerMetrics) {
      String para = request.getParameter("t");
      if (para.startsWith("Job ")) {
        String appId = para.substring("Job ".length());

        sb.append("{");
        sb.append("\"time\": ").append(System.currentTimeMillis()).append(",");
        sb.append("\"appId\": \"").append(appId).append("\"");
        for (String metric : this.schedulerMetrics.getAppTrackedMetrics()) {
          String key = "variable.app." + appId + "." + metric;
          sb.append(",\"").append(metric).append("\": ");
          if (metrics.getGauges().containsKey(key)) {
            double memoryGB =
                Double.parseDouble(metrics.getGauges().get(key).getValue().toString()) / 1024;
            sb.append(memoryGB);
          } else {
            sb.append(-1);
          }
        }
        sb.append("}");

      } else if (para.startsWith("Queue ")) {
        String queueName = para.substring("Queue ".length());
        sb.append("{");
        sb.append("\"time\": ").append(System.currentTimeMillis()).append(",");
        sb.append("\"queueName\": \"").append(queueName).append("\"");
        for (String metric : this.schedulerMetrics.getQueueTrackedMetrics()) {
          String key = "variable.queue." + queueName + "." + metric;
          sb.append(",\"").append(metric).append("\": ");
          if (metrics.getGauges().containsKey(key)) {
            double memoryGB =
                Double.parseDouble(metrics.getGauges().get(key).getValue().toString()) / 1024;
            sb.append(memoryGB);
          } else {
            sb.append(-1);
          }
        }
        sb.append("}");
      }
    }
    String output = sb.toString();
    if (output.isEmpty()) {
      output = "[]";
    }
    response.getWriter().println(output);
    // package result
    ((Request) request).setHandled(true);
  }
コード例 #18
0
  public void init(FilterConfig filterConfig) throws ServletException {
    final MetricRegistry metricsRegistry = Metrics.metricRegistry();

    this.metersByStatusCode = new ConcurrentHashMap<Integer, Meter>(meterNamesByStatusCode.size());
    for (Map.Entry<Integer, String> entry : meterNamesByStatusCode.entrySet()) {
      metersByStatusCode.put(entry.getKey(), metricsRegistry.meter(name("http", entry.getValue())));
    }
    this.otherMeter = metricsRegistry.meter(name("http", otherMetricName));
    this.activeRequests = metricsRegistry.counter(name("http", "activeRequests"));
    this.requestTimer = metricsRegistry.timer(name("http", "requests"));
  }
コード例 #19
0
ファイル: MetricContextTest.java プロジェクト: ronwxy/gobblin
  @Test(dependsOnMethods = "testChildContext")
  public void testContextAwareCounter() {
    ContextAwareCounter jobRecordsProcessed = this.context.contextAwareCounter(RECORDS_PROCESSED);
    Assert.assertEquals(
        this.context
            .getCounters()
            .get(
                MetricRegistry.name(
                    this.context.metricNamePrefix(false), jobRecordsProcessed.getName())),
        jobRecordsProcessed);
    Assert.assertEquals(jobRecordsProcessed.getContext(), this.context);
    Assert.assertEquals(jobRecordsProcessed.getName(), RECORDS_PROCESSED);

    Assert.assertTrue(jobRecordsProcessed.getTags().isEmpty());
    jobRecordsProcessed.addTag(new Tag<String>(METRIC_GROUP_KEY, INPUT_RECORDS_GROUP));
    Assert.assertEquals(jobRecordsProcessed.getTags().size(), 1);
    Assert.assertEquals(jobRecordsProcessed.getTags().get(0).getKey(), METRIC_GROUP_KEY);
    Assert.assertEquals(jobRecordsProcessed.getTags().get(0).getValue(), INPUT_RECORDS_GROUP);
    Assert.assertEquals(
        jobRecordsProcessed.getFullyQualifiedName(false),
        MetricRegistry.name(INPUT_RECORDS_GROUP, RECORDS_PROCESSED));

    jobRecordsProcessed.inc();
    Assert.assertEquals(jobRecordsProcessed.getCount(), 1l);
    jobRecordsProcessed.inc(5);
    Assert.assertEquals(jobRecordsProcessed.getCount(), 6l);
    jobRecordsProcessed.dec();
    Assert.assertEquals(jobRecordsProcessed.getCount(), 5l);
    jobRecordsProcessed.dec(3);
    Assert.assertEquals(jobRecordsProcessed.getCount(), 2l);

    ContextAwareCounter taskRecordsProcessed =
        this.childContext.contextAwareCounter(RECORDS_PROCESSED);
    Assert.assertEquals(
        this.childContext
            .getCounters()
            .get(
                MetricRegistry.name(
                    this.childContext.metricNamePrefix(false), taskRecordsProcessed.getName())),
        taskRecordsProcessed);
    Assert.assertEquals(taskRecordsProcessed.getContext(), this.childContext);
    Assert.assertEquals(taskRecordsProcessed.getName(), RECORDS_PROCESSED);

    taskRecordsProcessed.inc();
    Assert.assertEquals(taskRecordsProcessed.getCount(), 1l);
    Assert.assertEquals(jobRecordsProcessed.getCount(), 3l);
    taskRecordsProcessed.inc(3);
    Assert.assertEquals(taskRecordsProcessed.getCount(), 4l);
    Assert.assertEquals(jobRecordsProcessed.getCount(), 6l);
    taskRecordsProcessed.dec(4);
    Assert.assertEquals(taskRecordsProcessed.getCount(), 0l);
    Assert.assertEquals(jobRecordsProcessed.getCount(), 2l);
  }
 @Test
 public void metricMethodsWithDefaultNamingConvention() {
   assertThat(
       "Shared metric registry is not created",
       SharedMetricRegistries.names(),
       hasItem(REGISTRY_NAME));
   MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
   assertThat(
       "Metrics are not registered correctly",
       registry.getMetrics().keySet(),
       is(equalTo(metricNames())));
 }
コード例 #21
0
ファイル: MetricContextTest.java プロジェクト: ronwxy/gobblin
  @Test
  public void testContextAwareHistogram() {
    ContextAwareHistogram jobRecordSizeDist =
        this.context.contextAwareHistogram(RECORD_SIZE_DISTRIBUTION);
    Assert.assertEquals(
        this.context
            .getHistograms()
            .get(
                MetricRegistry.name(
                    this.context.metricNamePrefix(false), jobRecordSizeDist.getName())),
        jobRecordSizeDist);
    Assert.assertEquals(jobRecordSizeDist.getContext(), this.context);
    Assert.assertEquals(jobRecordSizeDist.getName(), RECORD_SIZE_DISTRIBUTION);

    Assert.assertTrue(jobRecordSizeDist.getTags().isEmpty());
    jobRecordSizeDist.addTag(new Tag<String>(METRIC_GROUP_KEY, INPUT_RECORDS_GROUP));
    Assert.assertEquals(jobRecordSizeDist.getTags().size(), 1);
    Assert.assertEquals(jobRecordSizeDist.getTags().get(0).getKey(), METRIC_GROUP_KEY);
    Assert.assertEquals(jobRecordSizeDist.getTags().get(0).getValue(), INPUT_RECORDS_GROUP);
    Assert.assertEquals(
        jobRecordSizeDist.getFullyQualifiedName(false),
        MetricRegistry.name(INPUT_RECORDS_GROUP, RECORD_SIZE_DISTRIBUTION));

    jobRecordSizeDist.update(2);
    jobRecordSizeDist.update(4);
    jobRecordSizeDist.update(7);
    Assert.assertEquals(jobRecordSizeDist.getCount(), 3l);
    Assert.assertEquals(jobRecordSizeDist.getSnapshot().getMin(), 2l);
    Assert.assertEquals(jobRecordSizeDist.getSnapshot().getMax(), 7l);

    ContextAwareHistogram taskRecordSizeDist =
        this.childContext.contextAwareHistogram(RECORD_SIZE_DISTRIBUTION);
    Assert.assertEquals(
        this.childContext
            .getHistograms()
            .get(
                MetricRegistry.name(
                    this.childContext.metricNamePrefix(false), taskRecordSizeDist.getName())),
        taskRecordSizeDist);
    Assert.assertEquals(taskRecordSizeDist.getContext(), this.childContext);
    Assert.assertEquals(taskRecordSizeDist.getName(), RECORD_SIZE_DISTRIBUTION);

    taskRecordSizeDist.update(3);
    taskRecordSizeDist.update(14);
    taskRecordSizeDist.update(11);
    Assert.assertEquals(taskRecordSizeDist.getCount(), 3l);
    Assert.assertEquals(taskRecordSizeDist.getSnapshot().getMin(), 3l);
    Assert.assertEquals(taskRecordSizeDist.getSnapshot().getMax(), 14l);
    Assert.assertEquals(jobRecordSizeDist.getCount(), 6l);
    Assert.assertEquals(jobRecordSizeDist.getSnapshot().getMin(), 2l);
    Assert.assertEquals(jobRecordSizeDist.getSnapshot().getMax(), 14l);
  }
  @Override
  protected MetricRegistry getMetricRegistry() {

    METRIC_REGISTRY.register(name("jvm", "gc"), new GarbageCollectorMetricSet());
    METRIC_REGISTRY.register(name("jvm", "memory"), new MemoryUsageGaugeSet());
    METRIC_REGISTRY.register(name("jvm", "thread-states"), new ThreadStatesGaugeSet());

    HystrixCodaHaleMetricsPublisher hystrixCodaHaleMetricsPublisher =
        new HystrixCodaHaleMetricsPublisher(METRIC_REGISTRY);
    HystrixPlugins.getInstance().registerMetricsPublisher(hystrixCodaHaleMetricsPublisher);

    return METRIC_REGISTRY;
  }
コード例 #23
0
 private void registerClusterResourceMetrics() {
   metrics.register(
       "variable.cluster.allocated.memory",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAllocatedMB();
           }
         }
       });
   metrics.register(
       "variable.cluster.allocated.vcores",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAllocatedVirtualCores();
           }
         }
       });
   metrics.register(
       "variable.cluster.available.memory",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAvailableMB();
           }
         }
       });
   metrics.register(
       "variable.cluster.available.vcores",
       new Gauge<Integer>() {
         @Override
         public Integer getValue() {
           if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
             return 0;
           } else {
             return scheduler.getRootQueueMetrics().getAvailableVirtualCores();
           }
         }
       });
 }
コード例 #24
0
 private Timer timer(String name) {
   Timer timer = metricRegistry.getTimers().get(name);
   if (timer != null) {
     return timer;
   }
   try {
     return metricRegistry.register(
         name,
         new Timer(new SlidingTimeWindowReservoir(timerReservoirSeconds.get(), TimeUnit.SECONDS)));
   } catch (IllegalArgumentException e) {
     // timer already exists. this happens due to race condition. its fine.
     return metricRegistry.getTimers().get(name);
   }
 }
コード例 #25
0
  @Override
  public void process(Request request) {
    String name = getRouteName(request);

    if (name == null || name.isEmpty()) return;

    if (!ROUTE_TIMERS.containsKey(name)) {
      ROUTE_TIMERS.putIfAbsent(name, metrics.timer(getTimerName(name)));
    }

    if (!EXCEPTION_COUNTERS_BY_ROUTE.containsKey(name)) {
      EXCEPTION_COUNTERS_BY_ROUTE.putIfAbsent(name, metrics.counter(getExceptionCounterName(name)));
    }
  }
コード例 #26
0
 @PostConstruct
 public void init() {
   log.debug("Registering JVM gauges");
   metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
   metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
   metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
   metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
   metricRegistry.register(
       PROP_METRIC_REG_JVM_BUFFERS,
       new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
   if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
     log.debug("Initializing Metrics JMX reporting");
     JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
     jmxReporter.start();
   }
 }
コード例 #27
0
 protected BaseAttributeResolver(AttributeResolverDescriptor descriptor) {
   checkNotNull(descriptor);
   this.descriptor =
       new AttributeResolverDescriptorDelegate(descriptor) {
         @Override
         public int getPreferredCacheTTL() {
           return (preferredCacheTTL == null)
               ? super.getPreferredCacheTTL()
               : preferredCacheTTL.get();
         }
       };
   final MetricRegistry registry = getOrCreate();
   this.timer = registry.timer(name("pip.AttributeResolver", descriptor.getId(), "timer"));
   this.histogram =
       registry.histogram(name("pip.AttributeResolver", descriptor.getId(), "histogram"));
 }
コード例 #28
0
  @Test
  public void createsMetricsForTheHandler() throws Exception {
    final ContentResponse response =
        client.GET("http://localhost:" + connector.getLocalPort() + "/hello");

    assertThat(response.getStatus()).isEqualTo(404);

    assertThat(registry.getNames())
        .containsOnly(
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.1xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.2xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.3xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.4xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.5xx-responses",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-suspended",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.async-dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.async-timeouts",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.get-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.put-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.trace-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.other-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.connect-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.dispatches",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.head-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.post-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.options-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.active-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.delete-requests",
            "org.eclipse.jetty.server.handler.DefaultHandler.handler.move-requests");
  }
コード例 #29
0
  @Override
  public Connector build(
      Server server, MetricRegistry metrics, String name, ThreadPool threadPool) {
    logSupportedParameters();

    final HttpConfiguration httpConfig = buildHttpConfiguration();

    final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig);

    final SslContextFactory sslContextFactory = buildSslContextFactory();
    server.addBean(sslContextFactory);

    final SslConnectionFactory sslConnectionFactory =
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString());

    final Scheduler scheduler = new ScheduledExecutorScheduler();

    final ByteBufferPool bufferPool = buildBufferPool();

    final String timerName =
        name(
            HttpConnectionFactory.class, getBindHost(), Integer.toString(getPort()), "connections");

    return buildConnector(
        server,
        scheduler,
        bufferPool,
        name,
        threadPool,
        new InstrumentedConnectionFactory(sslConnectionFactory, metrics.timer(timerName)),
        httpConnectionFactory);
  }
コード例 #30
0
  @Override
  protected void onComplete(Request request, Response response) {
    activeRequestsCounter.dec();
    Long duration =
        computeDurationMillis(START_TIMES_BY_CORRELATION_ID.remove(request.getCorrelationId()));

    if (duration != null && duration.longValue() > 0) {
      allTimesTimer.update(duration, TimeUnit.MILLISECONDS);

      String name = getRouteName(request);
      if (name == null || name.isEmpty()) return;

      ROUTE_TIMERS.get(name).update(duration, TimeUnit.MILLISECONDS);
    }

    Counter responseCounter = COUNTERS_BY_RESPONSE.get(response.getResponseStatus().getCode());

    if (responseCounter == null) {
      responseCounter = metrics.counter(getResponseCounterName(response.getResponseStatus()));
      COUNTERS_BY_RESPONSE.putIfAbsent(response.getResponseStatus().getCode(), responseCounter);
    }

    responseCounter.inc();
    publish(request, response, duration);
  }