public synchronized GoTimer buildTimer() { String name = generateName("timing"); GoTimer timer = getExistingTimer(name); if (timer == null) { timer = new GoTimer(name); Map<String, Metric> map = new HashMap<>(1); map.put(name, timer); MetricSet set = () -> map; try { registry.registerAll(set); } catch (Exception ex) { //I haven't figured out a good solution around this... } } return timer; }
/** * Given a {@link Metric}, registers it under the given name. * * @param name the name of the metric * @param metric the metric * @param <T> the type of the metric * @return {@code metric} * @throws IllegalArgumentException if the name is already registered */ @SuppressWarnings("unchecked") public final <T extends Metric> T register(final String name, final T metric) throws IllegalArgumentException { if(metric instanceof MetricSet) { registerAll(name, (MetricSet) metric); } else { final Metric existing = metrics.putIfAbsent(name, metric); if(existing == null) { onMetricAdded(name, metric); } else { throw new IllegalArgumentException("A metric named " + name + " already exists"); } } return metric; }
private void registerMetricSetImpl(MetricSet metricSet, String namespace) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() == null) { continue; } if (MetricSet.class.isInstance(entry.getValue())) { MetricSet innerMetricSet = MetricSet.class.cast(entry.getValue()); if (namespace == null) { registerMetricSet(innerMetricSet, entry.getKey()); } else { registerMetricSetImpl(innerMetricSet, MetricNamingUtil.join(namespace, entry.getKey())); } } else { String name = null; if (namespace == null) { name = entry.getKey(); } else { name = MetricNamingUtil.join(namespace, entry.getKey()); } name = addPostfixIfNeeded(name, getPostfixForMetric(entry.getValue())); metricRegistry.register(name, entry.getValue()); } } }
private void removeMetricSetImpl(MetricSet metricSet, String namespace) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() == null) { continue; } if (MetricSet.class.isInstance(entry.getValue())) { MetricSet innerMetricSet = MetricSet.class.cast(entry.getValue()); if (namespace == null) { removeMetricSet(innerMetricSet, entry.getKey()); } else { removeMetricSetImpl(innerMetricSet, MetricNamingUtil.join(namespace, entry.getKey())); } } else { String name = null; if (namespace == null) { name = entry.getKey(); } else { name = MetricNamingUtil.join(namespace, entry.getKey()); } name = addPostfixIfNeeded(name, getPostfixForMetric(entry.getValue())); metricRegistry.remove(name); } } }
/** * {@inheritDoc} */ @NonNull @Override public MetricSet getMetricSet() { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new AssertionError("Jenkins is missing"); } HealthChecker c = jenkins.getExtensionList(PeriodicWork.class).get(HealthChecker.class); if (c == null) { throw new AssertionError("HealthChecker is missing"); } return metrics( metric(name("jenkins", "health-check", "duration"), c.getHealthCheckDuration()), metric(name("jenkins", "health-check", "count"), c.getHealthCheckCount()), metric(name("jenkins", "health-check", "score"), c.getHealthCheckScore()), metric(name("jenkins", "health-check", "inverse-score"), new DerivativeGauge<Double, Double>(c.getHealthCheckScore()) { @Override protected Double transform(Double value) { return value == null ? null : 1.0 - value; } }) ); }
/** * {@inheritDoc} */ @NonNull @Override public MetricSet getMetricSet() { if (set == null || nextRefresh < System.currentTimeMillis()) { Map<String, Metric> metrics = new LinkedHashMap<String, Metric>(); metrics.put(name("jenkins", "versions", "core"), new VersionGauge(Jenkins.VERSION)); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { final PluginManager pluginManager = jenkins.getPluginManager(); for (PluginWrapper p : pluginManager.getPlugins()) { if (p.isActive()) { metrics.put(name("jenkins", "versions", "plugin", p.getShortName()), new VersionGauge(p.getVersion())); } } } set = metrics(metrics); // idempotent nextRefresh = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(15); } return set; }
public static Metric2Set convert(final MetricSet metricSet, final MetricNameConverter converter) { return new Metric2Set() { @Override public Map<MetricName, Metric> getMetrics() { final HashMap<MetricName, Metric> result = new HashMap<MetricName, Metric>(); for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { final MetricName convertedName; try { convertedName = converter.convert(entry.getKey()); result.put(convertedName, entry.getValue()); } catch (Exception e) { e.printStackTrace(); logger.warn("Invalid name " + entry.getKey()); logger.debug(e.getMessage(), e); } } return result; } }; }
/** * Given a {@link Metric}, registers it under the given name. * * @param name the name of the metric * @param metric the metric * @param <T> the type of the metric * @return {@code metric} * @throws IllegalArgumentException if the name is already registered */ @SuppressWarnings("unchecked") public <T extends Metric> T register(MetricName name, T metric) throws IllegalArgumentException { if (metric instanceof MetricSet) { throw new IllegalArgumentException("This metrics registry is not compatible with MetricSets. Use a Metric2Set instead."); } else { final Metric existing = metrics.putIfAbsent(name, metric); if (existing != null) { throw new IllegalArgumentException("A metric named " + name + " already exists"); } else { // This is a new metric - we have to register the Metric with // the legacy Dropwizard Metric registry as // well to support existing reports and listeners metricRegistry.register(name.toGraphiteName(), metric); } } return metric; }
private void configuration(@Observes AfterDeploymentValidation adv, BeanManager manager) { // Fire configuration event manager.fireEvent(configuration); configuration.unmodifiable(); // Produce and register custom metrics MetricRegistry registry = getReference(manager, MetricRegistry.class); MetricName name = getReference(manager, MetricName.class); for (Map.Entry<Bean<?>, AnnotatedMember<?>> bean : metrics.entrySet()) { // TODO: add MetricSet metrics into the metric registry if (bean.getKey().getTypes().contains(MetricSet.class) // skip non @Default beans || !bean.getKey().getQualifiers().contains(DEFAULT) // skip producer methods with injection point || hasInjectionPoints(bean.getValue())) continue; registry.register(name.of(bean.getValue()), (Metric) getReference(manager, bean.getValue().getBaseType(), bean.getKey())); } // Let's clear the collected metric producers metrics.clear(); }
private void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry); } else { registry.register(prefix + "." + entry.getKey(), entry.getValue()); } } }
public synchronized GoCounter buildCounter() { String name = generateName("counter"); GoCounter counter = getExistingCounter(name); if (counter == null) { counter = new GoCounter(name); Map<String, Metric> map = new HashMap<>(); map.put(name, counter); MetricSet set = () -> map; registry.registerAll(set); } return counter; }
public synchronized GoGauge buildGauge() { String name = generateName("gauge"); GoGauge gauge = getExistingGauge(name); if (gauge == null) { gauge = new GoGauge(name); Map<String, Metric> map = new HashMap<>(); map.put(name, gauge); MetricSet set = () -> map; registry.registerAll(set); } return gauge; }
private static void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) { for (Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry); } else { registry.register(prefix + "." + entry.getKey(), entry.getValue()); } } }
private static MetricSet scoped(final String name, final MetricSet metricSet) { return new MetricSet() { @Override public Map<String, Metric> getMetrics() { ImmutableMap.Builder<String, Metric> scopedMetrics = ImmutableMap.builder(); for(Map.Entry<String, Metric> entry: metricSet.getMetrics().entrySet()) { scopedMetrics.put(MetricRegistry.name(name, entry.getKey()), entry.getValue()); } return scopedMetrics.build(); } }; }
@PostConstruct public void init() { // ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry) // .convertRatesTo(TimeUnit.SECONDS) // .convertDurationsTo(TimeUnit.MILLISECONDS) // .build(); // // consoleReporter.start(10, TimeUnit.SECONDS); // Graphite graphite = new Graphite(new InetSocketAddress("192.168.99.100", 2003)); // GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(metricRegistry) // .prefixedWith("com.packt.microservices.geolocation") // .convertRatesTo(TimeUnit.SECONDS) // .convertDurationsTo(TimeUnit.MILLISECONDS) // .filter(MetricFilter.ALL) // .build(graphite); // graphiteReporter.start(60, TimeUnit.SECONDS); geolocationWriteRequestCount = metricRegistry.counter("geolocationWriteRequestCount"); metricRegistry.register("geolocationLastWriteTime", new Gauge<Long>() { @Override public Long getValue() { return geolocationLastWriteTime; } }); metricRegistry.registerAll(new MetricSet() { @Override public Map<String, Metric> getMetrics() { Map<String, Metric> metrics = new HashMap<>(); metrics.put("geolocationMemoryUsage", new MemoryUsageGaugeSet()); metrics.put("geolocationClassLoading", new ClassLoadingGaugeSet()); metrics.put("geolocationGarbageCollector", new GarbageCollectorMetricSet()); return metrics; } }); }
public CodahaleMetricsCollector registerAll(String prefix, MetricSet metricSet) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue()); } else { registerNamedMetric(prefix + "." + entry.getKey(), entry.getValue()); } } return this; }
private void registerAll(final String prefix, final MetricSet metrics) throws IllegalArgumentException { for(final Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if(entry.getValue() instanceof MetricSet) { registerAll(name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { register(name(prefix, entry.getKey()), entry.getValue()); } } }
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric instanceof MetricSet) { registerAll(name, (MetricSet) metric); } else { delegate.register(getTaggedName(name, metric.getClass()), metric); } return metric; }
@Override public void registerMetric(Metric metric, String topLevelName, String... additionalNames) { Preconditions.checkNotNull(metric, "metric cannot be null"); if (MetricSet.class.isAssignableFrom(metric.getClass())) { if (StringUtils.isNotBlank(topLevelName)) { registerMetricSet(MetricSet.class.cast(metric), MetricNamingUtil.join(topLevelName, additionalNames)); } else { registerMetricSet(MetricSet.class.cast(metric)); } } else { metricRegistry.register(buildFullName(topLevelName, additionalNames, getPostfixForMetric(metric)), metric); } }
@Override public void registerMetricSet(MetricSet metricSet, String... names) { Preconditions.checkNotNull(metricSet, "metricSet cannot be null"); String namespace = null; if (names != null && names.length > 0) { namespace = buildFullName(names[0], Arrays.copyOfRange(names, 1, names.length), null); } else { namespace = collectorNamespace; } registerMetricSetImpl(metricSet, namespace); }
@Override public void removeMetric(Metric metric, String topLevelName, String... additionalNames) { Preconditions.checkNotNull(metric, "metric cannot be null"); if (MetricSet.class.isAssignableFrom(metric.getClass())) { if (StringUtils.isNotBlank(topLevelName)) { removeMetricSet(MetricSet.class.cast(metric), MetricNamingUtil.join(topLevelName, additionalNames)); } else { removeMetricSet(MetricSet.class.cast(metric)); } } else { metricRegistry.remove(buildFullName(topLevelName, additionalNames, getPostfixForMetric(metric))); } }
@Override public void removeMetricSet(MetricSet metricSet, String... names) { Preconditions.checkNotNull(metricSet, "metricSet cannot be null"); String namespace = null; if (names != null && names.length > 0) { namespace = buildFullName(names[0], Arrays.copyOfRange(names, 1, names.length), null); } removeMetricSetImpl(metricSet, namespace); }
/** * TODO add javadocs * * @param namePrefix * @param monitor * @return */ public static MetricSet toMetricSet(String namePrefix, GcMonitor monitor) { Map<String, Metric> metrics = new TreeMap<>(); GcMonitorConfiguration configuration = monitor.getConfiguration(); for (String collectorName : configuration.getCollectorNames()) { for (String windowName : configuration.getWindowNames()) { addHistogram(namePrefix, metrics, collectorName, windowName, monitor); addPercentageGauge(namePrefix, metrics, collectorName, windowName, monitor); addGcDurationGauge(namePrefix, metrics, collectorName, windowName, monitor); } } return () -> metrics; }
private void registerMetrics( final String prefix, final MetricSet metricSet, final MetricRegistry registry) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerMetrics(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry); } else { registry.register(prefix + "." + entry.getKey(), entry.getValue()); } } }
public static void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException { for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(MetricRegistry.name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { register(MetricRegistry.name(prefix, entry.getKey()), entry.getValue()); } } }
/** * Register a given metric under a given name. * * <p> * This method does not support registering {@link com.codahale.metrics.MetricSet}s. * See{@link #registerAll(com.codahale.metrics.MetricSet)}. * </p> * * <p> * This method will not register a metric with the same name in the parent context (if it exists). * </p> */ @Override public synchronized <T extends Metric> T register(String name, T metric) throws IllegalArgumentException { if (metric instanceof MetricSet) { registerAll((MetricSet) metric); } if (this.contextAwareMetrics.putIfAbsent(name, metric) != null) { throw new IllegalArgumentException("A metric named " + name + " already exists"); } // Also register the metric with the MetricRegistry using its fully-qualified name return super.register(MetricRegistry.name(metricNamePrefix(this.includeTagKeys), name), metric); }
@Override @SuppressWarnings("unchecked") public MetricAdapter createMetricAdapterFor(String originalMetricName, Metric metric) { Preconditions.checkArgument(!(metric instanceof MetricSet), "Metric Sets cannot be adapted!!"); String translatedName = translate(originalMetricName); MetricDescriptor descriptor = metricDescriptorLookup.getDescriptorFor(translatedName); if (metric instanceof Timer) { return new TimerAdapter((Timer) metric, translatedName, descriptor.getDescription()); } if (metric instanceof Histogram) { return new HistogramAdapter((Histogram) metric, translatedName, descriptor.getDescription(), descriptor.getUnit()); } if (metric instanceof Counter) { return new CountingAdapter((Counter) metric, translatedName, descriptor.getDescription(), descriptor.getSemantics()); } if (metric instanceof Gauge) { return new GaugeAdapter<>((Gauge) metric, translatedName, descriptor.getDescription(), descriptor.getUnit(), descriptor.getSemantics()); } if (metric instanceof Metered) { return new MeteredAdapter((Metered) metric, translatedName, descriptor.getDescription()); } throw new UnsupportedOperationException(String.format("Unable to produce a monitorable adapter for metrics of class %s (%s)", metric.getClass().getName(), originalMetricName)); }
private void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException { for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(MetricRegistry.name(prefix, entry.getKey()), (MetricSet) entry.getValue()); } else { metricRegistry.register(MetricRegistry.name(prefix, entry.getKey()), entry.getValue()); } } }
private void registerAllJVMMetrics(Level level, String prefix, MetricSet metrics) throws IllegalArgumentException { metrics.getMetrics().entrySet().stream().filter(entry -> filterJVMMetric(entry.getKey())).forEach(entry -> { String name = MetricRegistry.name(prefix, entry.getKey()); com.codahale.metrics.Metric metric = entry.getValue(); com.codahale.metrics.Gauge<?> gauge = (com.codahale.metrics.Gauge<?>) metric; gauge(name, level, new JVMGaugeWrapper(gauge)); }); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof MetricSet) { metricRegistry.registerAll((MetricSet) bean); LOG.debug("Registering MetricSet bean {}", beanName); } return bean; }
@RequestMapping(value = "/metrics/reset", method = RequestMethod.POST) public ModelAndView reset(HttpServletRequest request) { metricRegistry.removeMatching(MetricFilter.ALL); LOGGER.debug("Metrics Reset"); Map<String,MetricSet> metricSets = applicationContext.getBeansOfType(MetricSet.class); for (MetricSet metricSet: metricSets.values()) { metricRegistry.registerAll(metricSet); } return ModelAndViewFactory.contentNegotiatingModelAndView(JsonCResponse.create(request, singletonMap("message", "Metrics Reset"))); }
private void registerAll(String prefix, MetricSet metricSet) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue()); } else { metricRegistry.register(prefix + "." + entry.getKey(), entry.getValue()); } } }
private void registerJvmMetrics() { registerMetricSetWithPrefix("jvm.gc", new GarbageCollectorMetricSet()); registerMetricSetWithPrefix("jvm.memory", new MemoryUsageGaugeSet()); registerMetricSetWithPrefix("jvm.threads", new ThreadStatesGaugeSet()); this.metricRegistry.register("jvm.fileDescriptorRatio", new FileDescriptorRatioGauge()); for (Map.Entry<String, MetricSet> metricSet : this.additionalMetricSets.entrySet()) { registerMetricSetWithPrefix(metricSet.getKey(), metricSet.getValue()); } }
@NonNull @Override public MetricSet getMetricSet() { final DiskUsagePlugin plugin = Jenkins.getInstance().getPlugin(DiskUsagePlugin.class); return metrics( metric(name("jenkins", "job", "disk-usage", "total"), new Gauge<Long>() { public Long getValue() { return plugin.getCashedGlobalJobsDiskUsage(); } }), metric(name("jenkins", "job", "disk-usage", "without-builds"), new Gauge<Long>() { public Long getValue() { return plugin.getCashedGlobalJobsWithoutBuildsDiskUsage(); } }), metric(name("jenkins", "job", "disk-usage", "workspaces"), new Gauge<Long>() { public Long getValue() { return plugin.getCashedGlobalWorkspacesDiskUsage(); } }), metric(name("jenkins", "job", "disk-usage", "builds", "total"), new Gauge<Long>() { public Long getValue() { return plugin.getCashedGlobalBuildsDiskUsage(); } }), metric(name("jenkins", "job", "disk-usage", "builds", "locked"), new Gauge<Long>() { public Long getValue() { return plugin.getCashedGlobalLockedBuildsDiskUsage(); } }) ); }
private void registerAll(String prefix, MetricSet metrics, MetricRegistry registry) { for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) { String name = MetricRegistry.name(prefix, entry.getKey()); if (entry.getValue() instanceof MetricSet) { registerAll(name, (MetricSet) entry.getValue(), registry); } else { register(name, entry.getValue(), registry); } } }
private void registerMetricSet(String prefix, MetricSet metricSet, MetricRegistry registry) { for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) { if (entry.getValue() instanceof MetricSet) { registerMetricSet(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry); } else { registry.register(prefix + "." + entry.getKey(), entry.getValue()); } } }