001/* 002 * (C) Copyright 2020 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bdelbosc 018 */ 019package org.nuxeo.runtime.metrics.reporter; 020 021import java.io.IOException; 022import java.util.Collections; 023import java.util.Map; 024import java.util.Set; 025 026import org.apache.logging.log4j.LogManager; 027import org.apache.logging.log4j.Logger; 028import org.nuxeo.runtime.metrics.AbstractMetricsReporter; 029 030import io.dropwizard.metrics5.MetricAttribute; 031import io.dropwizard.metrics5.MetricFilter; 032import io.dropwizard.metrics5.MetricRegistry; 033import io.opencensus.contrib.dropwizard5.DropWizardMetrics; 034import io.opencensus.exporter.stats.prometheus.PrometheusStatsCollector; 035import io.opencensus.metrics.Metrics; 036import io.prometheus.client.exporter.HTTPServer; 037 038/** 039 * Reports metrics to Prometheus. 040 * 041 * @since 11.1 042 */ 043public class PrometheusReporter extends AbstractMetricsReporter { 044 045 private static final Logger log = LogManager.getLogger(PrometheusReporter.class); 046 047 protected static final int DEFAULT_PORT = 9090; 048 049 protected int port; 050 051 protected int zPort; 052 053 protected HTTPServer server; 054 055 @Override 056 public void init(long pollInterval, Map<String, String> options) { 057 super.init(pollInterval, options); 058 port = getOptionAsInt("port", DEFAULT_PORT); 059 } 060 061 @Override 062 public void start(MetricRegistry registry, MetricFilter filter, Set<MetricAttribute> deniedExpansions) { 063 log.warn("Creating Prometheus endpoint on port {}", port); 064 DropWizardMetrics registries = new DropWizardMetrics(Collections.singletonList(registry), filter); 065 Metrics.getExportComponent().getMetricProducerManager().add(registries); 066 try { 067 PrometheusStatsCollector.createAndRegister(); 068 } catch (IllegalArgumentException e) { 069 log.warn("Prometheus collector already registered"); 070 } 071 try { 072 server = new HTTPServer(port, true); 073 } catch (IOException e) { 074 throw new IllegalArgumentException("Cannot start Prometheus on port " + port, e); 075 } 076 } 077 078 @Override 079 public void stop() { 080 log.debug("Stop reporting"); 081 server.stop(); 082 server = null; 083 } 084 085}