├── .gitignore ├── src ├── main │ ├── resources │ │ └── META-INF │ │ │ └── services │ │ │ ├── io.dropwizard.jackson.Discoverable │ │ │ └── io.dropwizard.metrics.ReporterFactory │ └── java │ │ └── org │ │ └── dhatim │ │ └── dropwizard │ │ └── prometheus │ │ ├── TextFormat.java │ │ ├── MetricType.java │ │ ├── PrometheusBundle.java │ │ ├── PrometheusReporterFactory.java │ │ ├── PrometheusSender.java │ │ ├── PrometheusTextWriter.java │ │ ├── Pushgateway.java │ │ ├── PrometheusServlet.java │ │ ├── DropwizardMetricsExporter.java │ │ └── PrometheusReporter.java └── test │ └── java │ └── org │ └── dhatim │ └── dropwizard │ └── prometheus │ └── PrometheusTextWriterTest.java ├── renovate.json ├── .github ├── settings.xml └── workflows │ └── build.yml ├── README.md ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /.idea 3 | *.iml 4 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/io.dropwizard.jackson.Discoverable: -------------------------------------------------------------------------------- 1 | io.dropwizard.metrics.ReporterFactory -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/io.dropwizard.metrics.ReporterFactory: -------------------------------------------------------------------------------- 1 | org.dhatim.dropwizard.prometheus.PrometheusReporterFactory -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ], 6 | "packageRules": [ 7 | { 8 | "matchUpdateTypes": ["minor", "patch"], 9 | "automerge": true 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/TextFormat.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | final class TextFormat { 4 | 5 | public final static String REQUEST_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"; 6 | public final static String CONTENT_TYPE = "text/plain; version=0.0.4"; 7 | 8 | private TextFormat() { 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/MetricType.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | enum MetricType { 4 | COUNTER ("counter"), 5 | GAUGE ("gauge"), 6 | SUMMARY ("summary"), 7 | HISTOGRAM ("histogram"), 8 | UNTYPED ("untyped"); 9 | 10 | private final String text; 11 | 12 | MetricType(String text) { 13 | this.text = text; 14 | } 15 | 16 | public String getText() { 17 | return text; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusBundle.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import io.dropwizard.core.Configuration; 4 | import io.dropwizard.core.ConfiguredBundle; 5 | import io.dropwizard.core.setup.Bootstrap; 6 | import io.dropwizard.core.setup.Environment; 7 | 8 | public class PrometheusBundle implements ConfiguredBundle { 9 | 10 | @Override 11 | public void initialize(Bootstrap bootstrap) { 12 | } 13 | 14 | @Override 15 | public void run(Configuration configuration, Environment environment) { 16 | environment.admin().addServlet("prometheus-metrics", new PrometheusServlet(environment.metrics())).addMapping("/prometheus-metrics"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /.github/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ossrh 5 | ${env.SONATYPE_USERNAME} 6 | ${env.SONATYPE_PASSWORD} 7 | 8 | 9 | 10 | 11 | ossrh 12 | 13 | true 14 | 15 | 16 | ${env.GPG_PASSPHRASE} 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusReporterFactory.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.MetricRegistry; 4 | import com.codahale.metrics.ScheduledReporter; 5 | import com.fasterxml.jackson.annotation.JsonProperty; 6 | import com.fasterxml.jackson.annotation.JsonTypeName; 7 | import io.dropwizard.metrics.common.BaseReporterFactory; 8 | import jakarta.validation.constraints.NotNull; 9 | 10 | @JsonTypeName("prometheus") 11 | public class PrometheusReporterFactory extends BaseReporterFactory { 12 | 13 | @JsonProperty 14 | @NotNull 15 | public String url = null; 16 | 17 | @JsonProperty 18 | @NotNull 19 | public String prefix = ""; 20 | 21 | @JsonProperty 22 | @NotNull 23 | public String job = "prometheus"; 24 | 25 | @Override 26 | public ScheduledReporter build(MetricRegistry registry) { 27 | 28 | final Pushgateway pushgateway = new Pushgateway(url, job); 29 | 30 | final PrometheusReporter reporter = PrometheusReporter.forRegistry(registry) 31 | .prefixedWith(prefix) 32 | .filter(getFilter()) 33 | .build(pushgateway); 34 | return reporter; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusSender.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.Counter; 4 | import com.codahale.metrics.Gauge; 5 | import com.codahale.metrics.Histogram; 6 | import com.codahale.metrics.Meter; 7 | import com.codahale.metrics.Timer; 8 | import java.io.Closeable; 9 | import java.io.IOException; 10 | 11 | public interface PrometheusSender extends Closeable { 12 | 13 | /** 14 | * Connects to the server. 15 | * 16 | * @throws IllegalStateException if the client is already connected 17 | * @throws IOException if there is an error connecting 18 | */ 19 | public void connect() throws IllegalStateException, IOException; 20 | 21 | public void sendGauge(String name, Gauge gauge) throws IOException; 22 | public void sendCounter(String name, Counter counter) throws IOException; 23 | public void sendHistogram(String name, Histogram histogram) throws IOException; 24 | public void sendMeter(String name, Meter meter) throws IOException; 25 | public void sendTimer(String name, Timer timer) throws IOException; 26 | 27 | /** 28 | * Flushes buffer, if applicable 29 | * 30 | * @throws IOException if there is an error connecting 31 | */ 32 | void flush() throws IOException; 33 | 34 | /** 35 | * Returns true if ready to send data 36 | * @return connection status 37 | */ 38 | boolean isConnected(); 39 | 40 | } 41 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | push: 4 | branches: [ '*' ] 5 | tags: [ '*' ] 6 | pull_request: 7 | branches: [ '*' ] 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: actions/setup-java@v3 14 | with: 15 | distribution: 'zulu' 16 | java-version: '11' 17 | - name: maven build 18 | env: 19 | GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} 20 | GPG_OWNERTRUST: ${{ secrets.GPG_OWNERTRUST }} 21 | GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 22 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 23 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 24 | run: | 25 | if echo "${GITHUB_REF_NAME}" | egrep '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9]+)?$' 26 | then 27 | # the tag looks like a version number: proceed with release 28 | echo ${GPG_SECRET_KEY} | base64 --decode | gpg --import --no-tty --batch --yes 29 | echo ${GPG_OWNERTRUST} | base64 --decode | gpg --import-ownertrust --no-tty --batch --yes 30 | mvn -ntp versions:set -DnewVersion=${GITHUB_REF_NAME} 31 | mvn -ntp -s .github/settings.xml -Prelease deploy jacoco:report -DrepoToken=${COVERALLS_TOKEN} 32 | else 33 | # this is a regular build 34 | mvn -ntp install 35 | fi 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Dropwizard Prometheus module 2 | ======= 3 | [![Build Status](https://github.com/dhatim/dropwizard-prometheus/workflows/build/badge.svg)](https://github.com/dhatim/dropwizard-prometheus/actions) 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.dhatim/dropwizard-prometheus/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.dhatim/dropwizard-prometheus) 5 | [![Javadocs](https://www.javadoc.io/badge/org.dhatim/dropwizard-prometheus.svg)](https://www.javadoc.io/doc/org.dhatim/dropwizard-prometheus) 6 | 7 | Dropwizard bundle and reporter for [Prometheus](https://prometheus.io) 8 | 9 | ## Reporting to Prometheus Pushgateway 10 | 11 | This module provides `PrometheusReporter`, which allows your application to constantly stream metric values to a [Prometheus Pushway](https://prometheus.io/docs/instrumenting/pushing/) server: 12 | 13 | 14 | final Pushgateway pushgateway = new Pushgateway("localhost", 9091)); 15 | final PrometheusReporter reporter = PrometheusReporter.forRegistry(registry) 16 | .prefixedWith("web1.example.com") 17 | .filter(MetricFilter.ALL) 18 | .build(pushgateway); 19 | reporter.start(1, TimeUnit.MINUTES); 20 | 21 | ## Prometheus servlet 22 | 23 | You can also use `PrometheusBundle`, which starts a new admin servlet exposing metric values to a [Prometheus](https://prometheus.io) server. 24 | 25 | @Override 26 | public void initialize(Bootstrap bootstrap) { 27 | bootstrap.addBundle(new PrometheusBundle()); 28 | } 29 | 30 | After the Dropwizard application server start, a new endpoint `/prometheus-metrics` will be accessible with `admin` endpoint. 31 | 32 | -------------------------------------------------------------------------------- /src/test/java/org/dhatim/dropwizard/prometheus/PrometheusTextWriterTest.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import static org.assertj.core.api.Assertions.*; 4 | 5 | import java.io.IOException; 6 | import java.io.StringWriter; 7 | import java.util.Collections; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import org.junit.Test; 11 | 12 | public class PrometheusTextWriterTest { 13 | 14 | @Test 15 | public void testType() throws IOException { 16 | StringWriter buffer = new StringWriter(); 17 | try (PrometheusTextWriter writer = new PrometheusTextWriter(buffer)) { 18 | writer.writeType("lorem.ipsum", MetricType.GAUGE); 19 | } 20 | assertThat(buffer.toString()).isEqualTo("# TYPE lorem.ipsum gauge\n"); 21 | } 22 | 23 | @Test 24 | public void testHelp() throws IOException { 25 | StringWriter buffer = new StringWriter(); 26 | try (PrometheusTextWriter writer = new PrometheusTextWriter(buffer)) { 27 | writer.writeHelp("lorem.ipsum", "A\nB\nC"); 28 | } 29 | assertThat(buffer.toString()).isEqualTo("# HELP lorem.ipsum A\\nB\\nC\n"); 30 | } 31 | 32 | @Test 33 | public void testSample() throws IOException { 34 | StringWriter buffer = new StringWriter(); 35 | try (PrometheusTextWriter writer = new PrometheusTextWriter(buffer)) { 36 | writer.writeSample("lorem.ipsum", Collections.emptyMap(), 1.0D); 37 | } 38 | assertThat(buffer.toString()).isEqualTo("lorem.ipsum 1.0\n"); 39 | } 40 | 41 | @Test 42 | public void testLabelizedSample() throws IOException { 43 | StringWriter buffer = new StringWriter(); 44 | try (PrometheusTextWriter writer = new PrometheusTextWriter(buffer)) { 45 | writer.writeSample("lorem.ipsum", simpleMap(), 2.0D); 46 | } 47 | assertThat(buffer.toString()).isEqualTo("lorem.ipsum{quantile=\"1.0\",} 2.0\n"); 48 | } 49 | 50 | @Test 51 | public void testLabelizedSample2() throws IOException { 52 | StringWriter buffer = new StringWriter(); 53 | try (PrometheusTextWriter writer = new PrometheusTextWriter(buffer)) { 54 | writer.writeSample("lorem.ipsum", doubleMap(), 2.0D); 55 | } 56 | assertThat(buffer.toString()).isEqualTo("lorem.ipsum{quantile=\"1.0\",centile=\"3.0\",} 2.0\n"); 57 | } 58 | 59 | private static Map simpleMap() { 60 | HashMap map = new HashMap<>(); 61 | map.put("quantile", "1.0"); 62 | return map; 63 | } 64 | 65 | private static Map doubleMap() { 66 | Map map = simpleMap(); 67 | map.put("centile", "3.0"); 68 | return map; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusTextWriter.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import java.io.FilterWriter; 4 | import java.io.IOException; 5 | import java.io.Writer; 6 | import java.util.Map; 7 | 8 | class PrometheusTextWriter extends FilterWriter { 9 | 10 | public PrometheusTextWriter(Writer out) { 11 | super(out); 12 | } 13 | 14 | public void writeHelp(String name, String value) throws IOException { 15 | write("# HELP "); 16 | write(name); 17 | write(' '); 18 | writeEscapedHelp(value); 19 | write('\n'); 20 | } 21 | 22 | public void writeType(String name, MetricType type) throws IOException { 23 | write("# TYPE "); 24 | write(name); 25 | write(' '); 26 | write(type.getText()); 27 | write('\n'); 28 | } 29 | 30 | public void writeSample(String name, Map labels, double value) throws IOException { 31 | write(name); 32 | if (labels.size() > 0) { 33 | write('{'); 34 | for (Map.Entry entry : labels.entrySet()) { 35 | write(entry.getKey()); 36 | write("=\""); 37 | writeEscapedLabelValue(entry.getValue()); 38 | write("\","); 39 | } 40 | write('}'); 41 | } 42 | write(' '); 43 | write(doubleToGoString(value)); 44 | write('\n'); 45 | } 46 | 47 | private void writeEscapedHelp(String s) throws IOException { 48 | for (int i = 0; i < s.length(); i++) { 49 | char c = s.charAt(i); 50 | switch (c) { 51 | case '\\': 52 | append("\\\\"); 53 | break; 54 | case '\n': 55 | append("\\n"); 56 | break; 57 | default: 58 | append(c); 59 | } 60 | } 61 | } 62 | 63 | private void writeEscapedLabelValue(String s) throws IOException { 64 | for (int i = 0; i < s.length(); i++) { 65 | char c = s.charAt(i); 66 | switch (c) { 67 | case '\\': 68 | append("\\\\"); 69 | break; 70 | case '\"': 71 | append("\\\""); 72 | break; 73 | case '\n': 74 | append("\\n"); 75 | break; 76 | default: 77 | append(c); 78 | } 79 | } 80 | } 81 | 82 | private static String doubleToGoString(double d) { 83 | if (d == Double.POSITIVE_INFINITY) { 84 | return "+Inf"; 85 | } 86 | if (d == Double.NEGATIVE_INFINITY) { 87 | return "-Inf"; 88 | } 89 | if (Double.isNaN(d)) { 90 | return "NaN"; 91 | } 92 | return Double.toString(d); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/Pushgateway.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.*; 4 | import jakarta.ws.rs.HttpMethod; 5 | import jakarta.ws.rs.core.HttpHeaders; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.BufferedWriter; 10 | import java.io.IOException; 11 | import java.io.OutputStreamWriter; 12 | import java.net.HttpURLConnection; 13 | import java.net.URL; 14 | import java.net.URLEncoder; 15 | import java.nio.charset.StandardCharsets; 16 | 17 | public class Pushgateway implements PrometheusSender { 18 | 19 | private static final int SECONDS_PER_MILLISECOND = 1000; 20 | 21 | private static final Logger LOG = LoggerFactory.getLogger(Pushgateway.class); 22 | 23 | private final String url; 24 | private final String job; 25 | 26 | private volatile HttpURLConnection connection = null; 27 | private PrometheusTextWriter writer; 28 | private DropwizardMetricsExporter exporter; 29 | 30 | public Pushgateway(String url) { 31 | this(url, "prometheus"); 32 | } 33 | 34 | public Pushgateway(String url, String job) { 35 | this.url = url; 36 | this.job = job; 37 | } 38 | 39 | @Override 40 | public void close() throws IOException { 41 | try { 42 | if (writer != null) { 43 | writer.close(); 44 | } 45 | } catch (IOException e) { 46 | LOG.error("Error closing writer", e); 47 | } finally { 48 | this.writer = null; 49 | this.exporter = null; 50 | } 51 | 52 | int response = connection.getResponseCode(); 53 | if (response != HttpURLConnection.HTTP_ACCEPTED) { 54 | throw new IOException("Response code from " + url + " was " + response); 55 | } 56 | connection.disconnect(); 57 | this.connection = null; 58 | } 59 | 60 | @Override 61 | public void connect() throws IOException { 62 | if (!isConnected()) { 63 | String targetUrl = url + "/metrics/job/" + URLEncoder.encode(job, StandardCharsets.UTF_8.name()); 64 | HttpURLConnection conn = (HttpURLConnection) new URL(targetUrl).openConnection(); 65 | conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, TextFormat.REQUEST_CONTENT_TYPE); 66 | conn.setDoOutput(true); 67 | conn.setRequestMethod(HttpMethod.POST); 68 | 69 | conn.setConnectTimeout(10 * SECONDS_PER_MILLISECOND); 70 | conn.setReadTimeout(10 * SECONDS_PER_MILLISECOND); 71 | conn.connect(); 72 | this.writer = new PrometheusTextWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8))); 73 | this.exporter = new DropwizardMetricsExporter(writer); 74 | this.connection = conn; 75 | } 76 | } 77 | 78 | @Override 79 | public void sendGauge(String name, Gauge gauge) throws IOException { 80 | exporter.writeGauge(name, gauge); 81 | } 82 | 83 | @Override 84 | public void sendCounter(String name, Counter counter) throws IOException { 85 | exporter.writeCounter(name, counter); 86 | } 87 | 88 | @Override 89 | public void sendHistogram(String name, Histogram histogram) throws IOException { 90 | exporter.writeHistogram(name, histogram); 91 | } 92 | 93 | @Override 94 | public void sendMeter(String name, Meter meter) throws IOException { 95 | exporter.writeMeter(name, meter); 96 | } 97 | 98 | @Override 99 | public void sendTimer(String name, Timer timer) throws IOException { 100 | exporter.writeTimer(name, timer); 101 | } 102 | 103 | @Override 104 | public void flush() throws IOException { 105 | if (writer != null) { 106 | writer.flush(); 107 | } 108 | } 109 | 110 | @Override 111 | public boolean isConnected() { 112 | return connection != null; 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusServlet.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.Timer; 4 | import com.codahale.metrics.*; 5 | import io.dropwizard.metrics.servlets.MetricsServlet; 6 | import jakarta.servlet.ServletConfig; 7 | import jakarta.servlet.ServletContext; 8 | import jakarta.servlet.ServletException; 9 | import jakarta.servlet.http.HttpServlet; 10 | import jakarta.servlet.http.HttpServletRequest; 11 | import jakarta.servlet.http.HttpServletResponse; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | import java.io.IOException; 16 | import java.util.*; 17 | 18 | @SuppressWarnings("serial") 19 | class PrometheusServlet extends HttpServlet { 20 | 21 | public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry"; 22 | public static final String METRIC_FILTER = MetricsServlet.class.getCanonicalName() + ".metricFilter"; 23 | public static final String ALLOWED_ORIGIN = MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; 24 | private static final Logger LOG = LoggerFactory.getLogger(PrometheusServlet.class); 25 | 26 | private MetricRegistry registry; 27 | 28 | private String allowedOrigin; 29 | 30 | private MetricFilter filter; 31 | 32 | public PrometheusServlet(MetricRegistry registry) { 33 | this.registry = registry; 34 | } 35 | 36 | @Override 37 | public void init(ServletConfig config) throws ServletException { 38 | super.init(config); 39 | 40 | final ServletContext context = config.getServletContext(); 41 | if (null == registry) { 42 | final Object registryAttr = context.getAttribute(METRICS_REGISTRY); 43 | if (registryAttr instanceof MetricRegistry) { 44 | this.registry = (MetricRegistry) registryAttr; 45 | } else { 46 | throw new ServletException("Couldn't find a MetricRegistry instance."); 47 | } 48 | } 49 | 50 | filter = (MetricFilter) context.getAttribute(METRIC_FILTER); 51 | if (filter == null) { 52 | filter = MetricFilter.ALL; 53 | } 54 | 55 | this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); 56 | } 57 | 58 | @SuppressWarnings("rawtypes") 59 | @Override 60 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 61 | resp.setContentType(TextFormat.CONTENT_TYPE); 62 | if (allowedOrigin != null) { 63 | resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); 64 | } 65 | resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); 66 | resp.setStatus(HttpServletResponse.SC_OK); 67 | 68 | Set filtered = parse(req); 69 | 70 | PrometheusTextWriter writer = new PrometheusTextWriter(resp.getWriter()); 71 | try { 72 | DropwizardMetricsExporter exporter = new DropwizardMetricsExporter(writer); 73 | 74 | for (Map.Entry entry : registry.getGauges(filter).entrySet()) { 75 | String sanitizedName = DropwizardMetricsExporter.sanitizeMetricName(entry.getKey()); 76 | if (filtered.isEmpty() || filtered.contains(sanitizedName)) { 77 | exporter.writeGauge(entry.getKey(), entry.getValue()); 78 | } 79 | } 80 | for (Map.Entry entry : registry.getCounters(filter).entrySet()) { 81 | String sanitizedName = DropwizardMetricsExporter.sanitizeMetricName(entry.getKey()); 82 | if (filtered.isEmpty() || filtered.contains(sanitizedName)) { 83 | exporter.writeCounter(entry.getKey(), entry.getValue()); 84 | } 85 | } 86 | for (Map.Entry entry : registry.getHistograms(filter).entrySet()) { 87 | String sanitizedName = DropwizardMetricsExporter.sanitizeMetricName(entry.getKey()); 88 | if (filtered.isEmpty() || filtered.contains(sanitizedName)) { 89 | exporter.writeHistogram(entry.getKey(), entry.getValue()); 90 | } 91 | } 92 | for (Map.Entry entry : registry.getMeters(filter).entrySet()) { 93 | String sanitizedName = DropwizardMetricsExporter.sanitizeMetricName(entry.getKey()); 94 | if (filtered.isEmpty() || filtered.contains(sanitizedName)) { 95 | exporter.writeMeter(entry.getKey(), entry.getValue()); 96 | } 97 | } 98 | for (Map.Entry entry : registry.getTimers(filter).entrySet()) { 99 | String sanitizedName = DropwizardMetricsExporter.sanitizeMetricName(entry.getKey()); 100 | if (filtered.isEmpty() || filtered.contains(sanitizedName)) { 101 | exporter.writeTimer(entry.getKey(), entry.getValue()); 102 | } 103 | } 104 | 105 | writer.flush(); 106 | } catch (RuntimeException ex) { 107 | LOG.error("Unhandled exception", ex); 108 | resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 109 | } finally { 110 | writer.close(); 111 | } 112 | } 113 | 114 | private Set parse(HttpServletRequest req) { 115 | String[] includedParam = req.getParameterValues("name[]"); 116 | return includedParam == null ? Collections.emptySet() : new HashSet(Arrays.asList(includedParam)); 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/DropwizardMetricsExporter.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.Counter; 4 | import com.codahale.metrics.Gauge; 5 | import com.codahale.metrics.Histogram; 6 | import com.codahale.metrics.Meter; 7 | import com.codahale.metrics.Metered; 8 | import com.codahale.metrics.Metric; 9 | import com.codahale.metrics.Snapshot; 10 | import com.codahale.metrics.Timer; 11 | import java.io.IOException; 12 | import java.util.Collections; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | import java.util.concurrent.TimeUnit; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | 19 | class DropwizardMetricsExporter { 20 | 21 | private static final Logger LOG = LoggerFactory.getLogger(DropwizardMetricsExporter.class); 22 | 23 | private final PrometheusTextWriter writer; 24 | 25 | public DropwizardMetricsExporter(PrometheusTextWriter writer) { 26 | this.writer = writer; 27 | } 28 | 29 | public void writeGauge(String name, Gauge gauge) throws IOException { 30 | final String sanitizedName = sanitizeMetricName(name); 31 | writer.writeHelp(sanitizedName, getHelpMessage(name, gauge)); 32 | writer.writeType(sanitizedName, MetricType.GAUGE); 33 | 34 | Object obj = gauge.getValue(); 35 | double value; 36 | if (obj instanceof Number) { 37 | value = ((Number) obj).doubleValue(); 38 | } else if (obj instanceof Boolean) { 39 | value = ((Boolean) obj) ? 1 : 0; 40 | } else { 41 | LOG.warn("Invalid type for Gauge {}: {}", name, obj.getClass().getName()); 42 | return; 43 | } 44 | 45 | writer.writeSample(sanitizedName, emptyMap(), value); 46 | } 47 | 48 | /** 49 | * Export counter as Prometheus Gauge. 50 | */ 51 | public void writeCounter(String dropwizardName, Counter counter) throws IOException { 52 | String name = sanitizeMetricName(dropwizardName); 53 | writer.writeHelp(name, getHelpMessage(dropwizardName, counter)); 54 | writer.writeType(name, MetricType.GAUGE); 55 | writer.writeSample(name, emptyMap(), counter.getCount()); 56 | } 57 | 58 | 59 | /** 60 | * Export a histogram snapshot as a prometheus SUMMARY. 61 | * 62 | * @param dropwizardName metric name. 63 | * @param snapshot the histogram snapshot. 64 | * @param count the total sample count for this snapshot. 65 | * @param factor a factor to apply to histogram values. 66 | * @throws IOException 67 | * 68 | */ 69 | public void writeHistogram(String dropwizardName, Histogram histogram) throws IOException { 70 | writeSnapshotAndCount(dropwizardName, histogram.getSnapshot(), histogram.getCount(), 1.0, MetricType.SUMMARY, getHelpMessage(dropwizardName, histogram)); 71 | } 72 | 73 | 74 | private void writeSnapshotAndCount(String dropwizardName, Snapshot snapshot, long count, double factor, MetricType type, String helpMessage) throws IOException { 75 | String name = sanitizeMetricName(dropwizardName); 76 | writer.writeHelp(name, helpMessage); 77 | writer.writeType(name, type); 78 | writer.writeSample(name, mapOf("quantile", "0.5"), snapshot.getMedian() * factor); 79 | writer.writeSample(name, mapOf("quantile", "0.75"), snapshot.get75thPercentile() * factor); 80 | writer.writeSample(name, mapOf("quantile", "0.95"), snapshot.get95thPercentile() * factor); 81 | writer.writeSample(name, mapOf("quantile", "0.98"), snapshot.get98thPercentile() * factor); 82 | writer.writeSample(name, mapOf("quantile", "0.99"), snapshot.get99thPercentile() * factor); 83 | writer.writeSample(name, mapOf("quantile", "0.999"), snapshot.get999thPercentile() * factor); 84 | writer.writeSample(name + "_min", emptyMap(), snapshot.getMin()); 85 | writer.writeSample(name + "_max", emptyMap(), snapshot.getMax()); 86 | writer.writeSample(name + "_median", emptyMap(), snapshot.getMedian()); 87 | writer.writeSample(name + "_mean", emptyMap(), snapshot.getMean()); 88 | writer.writeSample(name + "_stddev", emptyMap(), snapshot.getStdDev()); 89 | writer.writeSample(name + "_count", emptyMap(), count); 90 | } 91 | 92 | private void writeMetered(String dropwizardName, Metered metered) throws IOException { 93 | String name = sanitizeMetricName(dropwizardName); 94 | writer.writeSample(name, mapOf("rate", "m1"), metered.getOneMinuteRate()); 95 | writer.writeSample(name, mapOf("rate", "m5"), metered.getFiveMinuteRate()); 96 | writer.writeSample(name, mapOf("rate", "m15"), metered.getFifteenMinuteRate()); 97 | writer.writeSample(name, mapOf("rate", "mean"), metered.getMeanRate()); 98 | } 99 | 100 | private Map mapOf(String key, String value) { 101 | HashMap result = new HashMap<>(); 102 | result.put(key, value); 103 | return result; 104 | } 105 | 106 | private Map emptyMap() { 107 | return Collections.emptyMap(); 108 | } 109 | 110 | public void writeTimer(String dropwizardName, Timer timer) throws IOException { 111 | writeSnapshotAndCount(dropwizardName, timer.getSnapshot(), timer.getCount(), 1.0D / TimeUnit.SECONDS.toNanos(1L), MetricType.SUMMARY, getHelpMessage(dropwizardName, timer)); 112 | writeMetered(dropwizardName, timer); 113 | } 114 | 115 | public void writeMeter(String dropwizardName, Meter meter) throws IOException { 116 | String name = sanitizeMetricName(dropwizardName) + "_total"; 117 | 118 | writer.writeHelp(name, getHelpMessage(dropwizardName, meter)); 119 | writer.writeType(name, MetricType.COUNTER); 120 | writer.writeSample(name, emptyMap(), meter.getCount()); 121 | 122 | writeMetered(dropwizardName, meter); 123 | } 124 | 125 | private static String getHelpMessage(String metricName, Metric metric) { 126 | return String.format("Generated from Dropwizard metric import (metric=%s, type=%s)", metricName, metric.getClass().getName()); 127 | } 128 | 129 | static String sanitizeMetricName(String dropwizardName) { 130 | return dropwizardName.replaceAll("[^a-zA-Z0-9:_]", "_"); 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | org.dhatim 6 | dropwizard-prometheus 7 | jar 8 | 0-SNAPSHOT 9 | Dropwizard Prometheus bridge 10 | https://github.com/dhatim/dropwizard-prometheus 11 | 12 | Dropwizard bundle and reporter for Prometheus. 13 | 14 | 15 | 16 | 11 17 | 11 18 | 11 19 | UTF-8 20 | false 21 | 22 | 23 | 24 | 25 | dev-oss@dhatim.com 26 | Dhatim 27 | http://dhatim.com/ 28 | 29 | 30 | Mathieu Ligocki 31 | mligocki@dhatim.com 32 | 33 | 34 | 35 | 36 | 37 | Apache License 2.0 38 | http://www.apache.org/licenses/LICENSE-2.0.html 39 | repo 40 | 41 | 42 | 43 | 44 | scm:git:git://github.com/dhatim/dropwizard-prometheus.git 45 | scm:git:git@github.com:dhatim/dropwizard-prometheus.git 46 | https://github.com/dhatim/dropwizard-prometheus 47 | HEAD 48 | 49 | 50 | 51 | GitHub 52 | https://github.com/dhatim/dropwizard-prometheus/issues 53 | 54 | 55 | 56 | 57 | release 58 | 59 | 60 | 61 | maven-gpg-plugin 62 | 63 | 64 | 65 | --pinentry-mode 66 | loopback 67 | 68 | 69 | 70 | 71 | sign-artifacts 72 | 73 | sign 74 | 75 | verify 76 | 77 | 78 | 79 | 80 | org.sonatype.plugins 81 | nexus-staging-maven-plugin 82 | true 83 | 84 | ossrh 85 | https://oss.sonatype.org 86 | true 87 | 60 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | io.dropwizard 99 | dropwizard-bom 100 | 4.0.16 101 | pom 102 | import 103 | 104 | 105 | 106 | 107 | 108 | 109 | io.dropwizard 110 | dropwizard-core 111 | 112 | 113 | junit 114 | junit 115 | 4.13.2 116 | test 117 | 118 | 119 | org.assertj 120 | assertj-core 121 | 3.27.6 122 | test 123 | 124 | 125 | 126 | 127 | 128 | 129 | maven-source-plugin 130 | 3.4.0 131 | 132 | 133 | attach-sources 134 | 135 | jar 136 | 137 | 138 | 139 | 140 | 141 | maven-javadoc-plugin 142 | 3.12.0 143 | 144 | true 145 | 146 | 147 | 148 | attach-javadocs 149 | 150 | jar 151 | 152 | 153 | 154 | 155 | 156 | maven-release-plugin 157 | 3.3.1 158 | 159 | true 160 | forked-path 161 | v@{project.version} 162 | clean test 163 | 164 | 165 | 166 | org.jacoco 167 | jacoco-maven-plugin 168 | 0.8.14 169 | 170 | 171 | prepare-agent 172 | 173 | prepare-agent 174 | 175 | 176 | 177 | 178 | 179 | maven-jar-plugin 180 | 3.5.0 181 | 182 | 183 | 184 | test-jar 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | -------------------------------------------------------------------------------- /src/main/java/org/dhatim/dropwizard/prometheus/PrometheusReporter.java: -------------------------------------------------------------------------------- 1 | package org.dhatim.dropwizard.prometheus; 2 | 3 | import com.codahale.metrics.Counter; 4 | import com.codahale.metrics.Gauge; 5 | import com.codahale.metrics.Histogram; 6 | import com.codahale.metrics.Meter; 7 | import com.codahale.metrics.MetricAttribute; 8 | import com.codahale.metrics.MetricFilter; 9 | import com.codahale.metrics.MetricRegistry; 10 | import com.codahale.metrics.ScheduledReporter; 11 | import com.codahale.metrics.Timer; 12 | import java.io.IOException; 13 | import java.util.Collections; 14 | import java.util.Map; 15 | import java.util.SortedMap; 16 | import java.util.concurrent.ScheduledExecutorService; 17 | import java.util.concurrent.TimeUnit; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | 21 | public class PrometheusReporter extends ScheduledReporter { 22 | 23 | /** 24 | * A builder for {@link PrometheusReporter} instances. Defaults to not using a prefix, and 25 | * not filtering metrics. 26 | */ 27 | 28 | public static class Builder { 29 | 30 | private final MetricRegistry registry; 31 | private String prefix; 32 | private MetricFilter filter; 33 | private ScheduledExecutorService executor; 34 | private boolean shutdownExecutorOnStop; 35 | 36 | private Builder(MetricRegistry registry) { 37 | this.registry = registry; 38 | this.prefix = null; 39 | this.filter = MetricFilter.ALL; 40 | this.executor = null; 41 | this.shutdownExecutorOnStop = true; 42 | } 43 | 44 | /** 45 | * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. 46 | * Default value is true. 47 | * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. 48 | * 49 | * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter 50 | * @return {@code this} 51 | */ 52 | public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { 53 | this.shutdownExecutorOnStop = shutdownExecutorOnStop; 54 | return this; 55 | } 56 | 57 | /** 58 | * Specifies the executor to use while scheduling reporting of metrics. 59 | * Default value is null. 60 | * Null value leads to executor will be auto created on start. 61 | * 62 | * @param executor the executor to use while scheduling reporting of metrics. 63 | * @return {@code this} 64 | */ 65 | public Builder scheduleOn(ScheduledExecutorService executor) { 66 | this.executor = executor; 67 | return this; 68 | } 69 | 70 | /** 71 | * Prefix all metric names with the given string. 72 | * 73 | * @param prefix the prefix for all metric names 74 | * @return {@code this} 75 | */ 76 | public Builder prefixedWith(String prefix) { 77 | this.prefix = prefix; 78 | return this; 79 | } 80 | 81 | /** 82 | * Only report metrics which match the given filter. 83 | * 84 | * @param filter a {@link MetricFilter} 85 | * @return {@code this} 86 | */ 87 | public Builder filter(MetricFilter filter) { 88 | this.filter = filter; 89 | return this; 90 | } 91 | 92 | /** 93 | * Builds a {@link PrometheusReporter} with the given properties, sending metrics using the 94 | * given {@link PrometheusSender}. 95 | * 96 | * Present for binary compatibility 97 | * 98 | * @param prometheus a {@link Pushgateway} 99 | * @return a {@link PrometheusReporter} 100 | */ 101 | public PrometheusReporter build(Pushgateway prometheus) { 102 | return build((PrometheusSender) prometheus); 103 | } 104 | 105 | /** 106 | * Builds a {@link PrometheusReporter} with the given properties, sending metrics using the 107 | * given {@link PrometheusSender}. 108 | * 109 | * @param prometheus a {@link PrometheusSender} 110 | * @return a {@link PrometheusReporter} 111 | */ 112 | public PrometheusReporter build(PrometheusSender prometheus) { 113 | return new PrometheusReporter(registry, 114 | prometheus, 115 | prefix, 116 | filter, 117 | executor, 118 | shutdownExecutorOnStop); 119 | } 120 | 121 | } 122 | 123 | private static final TimeUnit DURATION_UNIT = TimeUnit.MILLISECONDS; 124 | private static final TimeUnit RATE_UNIT = TimeUnit.SECONDS; 125 | 126 | private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusReporter.class); 127 | 128 | private final PrometheusSender prometheus; 129 | private final String prefix; 130 | 131 | 132 | /** 133 | * Creates a new {@link PrometheusReporter} instance. 134 | * 135 | * @param registry the {@link MetricRegistry} containing the metrics this 136 | * reporter will report 137 | * @param prometheus the {@link PrometheusSender} which is responsible for sending metrics to a Carbon server 138 | * via a transport protocol 139 | * @param prefix the prefix of all metric names (may be null) 140 | * @param filter the filter for which metrics to report 141 | * @param executor the executor to use while scheduling reporting of metrics (may be null). 142 | * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter 143 | */ 144 | protected PrometheusReporter(MetricRegistry registry, PrometheusSender prometheus, String prefix, MetricFilter filter, ScheduledExecutorService executor, boolean shutdownExecutorOnStop) { 145 | super(registry, "prometheus-reporter", filter, RATE_UNIT, DURATION_UNIT, executor, shutdownExecutorOnStop, Collections.emptySet()); 146 | this.prometheus = prometheus; 147 | this.prefix = prefix; 148 | } 149 | 150 | @Override 151 | public void stop() { 152 | try { 153 | super.stop(); 154 | } finally { 155 | try { 156 | prometheus.close(); 157 | } catch (IOException e) { 158 | LOGGER.debug("Error disconnecting from Prometheus", prometheus, e); 159 | } 160 | } 161 | } 162 | 163 | @Override 164 | @SuppressWarnings("rawtypes") 165 | public void report(SortedMap gauges, SortedMap counters, SortedMap histograms, SortedMap meters, SortedMap timers) { 166 | try { 167 | if (!prometheus.isConnected()) { 168 | prometheus.connect(); 169 | } 170 | 171 | for (Map.Entry entry : gauges.entrySet()) { 172 | prometheus.sendGauge(prefixed(entry.getKey()), entry.getValue()); 173 | } 174 | for (Map.Entry entry : counters.entrySet()) { 175 | prometheus.sendCounter(prefixed(entry.getKey()), entry.getValue()); 176 | } 177 | for (Map.Entry entry : histograms.entrySet()) { 178 | prometheus.sendHistogram(prefixed(entry.getKey()), entry.getValue()); 179 | } 180 | for (Map.Entry entry : meters.entrySet()) { 181 | prometheus.sendMeter(prefixed(entry.getKey()), entry.getValue()); 182 | } 183 | for (Map.Entry entry : timers.entrySet()) { 184 | prometheus.sendTimer(prefixed(entry.getKey()), entry.getValue()); 185 | } 186 | 187 | prometheus.flush(); 188 | } catch (IOException e) { 189 | LOGGER.warn("Unable to report to Prometheus", prometheus, e); 190 | } 191 | 192 | } 193 | 194 | private String prefixed(String name) { 195 | return prefix == null ? name : (prefix + name); 196 | } 197 | 198 | /** 199 | * Returns a new {@link Builder} for {@link PrometheusReporter}. 200 | * 201 | * @param registry the registry to report 202 | * @return a {@link Builder} instance for a {@link PrometheusReporter} 203 | */ 204 | public static Builder forRegistry(MetricRegistry registry) { 205 | return new Builder(registry); 206 | } 207 | 208 | } 209 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------