diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..b33efbd87 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +max_line_length = 100 +indent_size = 2 + +[pom.xml] +indent_size = 4 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3d8c766ec..c27647e49 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,6 +27,7 @@ If you're getting errors when running tests: - Use `-Dspotless.check.skip=true` to skip the formatting check during development. - Use `-Dcoverage.skip=true` to skip the coverage check during development. +- Use `-Dcheckstyle.skip=true` to skip the checkstyle check during development. - Use `-Dwarnings=-nowarn` to skip the warnings during development. ## Updating the Protobuf Java Classes diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml new file mode 100644 index 000000000..5f632c578 --- /dev/null +++ b/checkstyle-suppressions.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 000000000..ef205414d --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,375 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/example-exemplars-tail-sampling/example-greeting-service/pom.xml b/examples/example-exemplars-tail-sampling/example-greeting-service/pom.xml index 9b58c9707..803fcb1e3 100644 --- a/examples/example-exemplars-tail-sampling/example-greeting-service/pom.xml +++ b/examples/example-exemplars-tail-sampling/example-greeting-service/pom.xml @@ -57,7 +57,7 @@ - io.prometheus.metrics.examples.otel_exemplars.greeting.Main + io.prometheus.metrics.examples.otel.exemplars.greeting.Main diff --git a/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/GreetingServlet.java b/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/GreetingServlet.java similarity index 95% rename from examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/GreetingServlet.java rename to examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/GreetingServlet.java index a2b16f5f5..8b80268df 100644 --- a/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/GreetingServlet.java +++ b/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/GreetingServlet.java @@ -1,4 +1,4 @@ -package io.prometheus.metrics.examples.otel_exemplars.greeting; +package io.prometheus.metrics.examples.otel.exemplars.greeting; import static io.prometheus.metrics.model.snapshots.Unit.nanosToSeconds; diff --git a/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/Main.java b/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/Main.java similarity index 93% rename from examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/Main.java rename to examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/Main.java index c0cf09830..99ba1084c 100644 --- a/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel_exemplars/greeting/Main.java +++ b/examples/example-exemplars-tail-sampling/example-greeting-service/src/main/java/io/prometheus/metrics/examples/otel/exemplars/greeting/Main.java @@ -1,4 +1,4 @@ -package io.prometheus.metrics.examples.otel_exemplars.greeting; +package io.prometheus.metrics.examples.otel.exemplars.greeting; import io.prometheus.metrics.exporter.servlet.jakarta.PrometheusMetricsServlet; import io.prometheus.metrics.instrumentation.jvm.JvmMetrics; diff --git a/examples/example-exemplars-tail-sampling/example-hello-world-app/pom.xml b/examples/example-exemplars-tail-sampling/example-hello-world-app/pom.xml index deb15f4fe..e89809ff8 100644 --- a/examples/example-exemplars-tail-sampling/example-hello-world-app/pom.xml +++ b/examples/example-exemplars-tail-sampling/example-hello-world-app/pom.xml @@ -57,7 +57,7 @@ - io.prometheus.metrics.examples.otel_exemplars.app.Main + io.prometheus.metrics.examples.otel.exemplars.app.Main diff --git a/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/HelloWorldServlet.java b/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/HelloWorldServlet.java similarity index 97% rename from examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/HelloWorldServlet.java rename to examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/HelloWorldServlet.java index 988f63819..b770c29fb 100644 --- a/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/HelloWorldServlet.java +++ b/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/HelloWorldServlet.java @@ -1,4 +1,4 @@ -package io.prometheus.metrics.examples.otel_exemplars.app; +package io.prometheus.metrics.examples.otel.exemplars.app; import static io.prometheus.metrics.model.snapshots.Unit.nanosToSeconds; import static java.net.http.HttpResponse.BodyHandlers.ofString; diff --git a/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/Main.java b/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/Main.java similarity index 94% rename from examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/Main.java rename to examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/Main.java index dc58256cb..25ea8a1c6 100644 --- a/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel_exemplars/app/Main.java +++ b/examples/example-exemplars-tail-sampling/example-hello-world-app/src/main/java/io/prometheus/metrics/examples/otel/exemplars/app/Main.java @@ -1,4 +1,4 @@ -package io.prometheus.metrics.examples.otel_exemplars.app; +package io.prometheus.metrics.examples.otel.exemplars.app; import io.prometheus.metrics.exporter.servlet.jakarta.PrometheusMetricsServlet; import io.prometheus.metrics.instrumentation.jvm.JvmMetrics; diff --git a/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java b/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java index 7a2715647..b2aa8950f 100644 --- a/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java +++ b/examples/example-exporter-opentelemetry/src/main/java/io/prometheus/metrics/examples/opentelemetry/ManualCompleteMetricsTest.java @@ -59,7 +59,8 @@ public static void main(String[] args) throws Exception { histogram.labelValues("200").observe(random.nextGaussian()); } - // Explicitly use a classic-only histogram to have an example of a classic histogram in OpenTelemetry + // Explicitly use a classic-only histogram to have an example of a classic + // histogram in OpenTelemetry Histogram classicHistogram = Histogram.newBuilder() .withName("request_size_bytes") .withHelp("Request size in Bytes") diff --git a/integration-tests/it-exporter/it-exporter-httpserver-sample/src/main/java/io/prometheus/metrics/it/exporter/httpserver/HTTPServerSample.java b/integration-tests/it-exporter/it-exporter-httpserver-sample/src/main/java/io/prometheus/metrics/it/exporter/httpserver/HTTPServerSample.java index 4c665dd81..8490cd64e 100644 --- a/integration-tests/it-exporter/it-exporter-httpserver-sample/src/main/java/io/prometheus/metrics/it/exporter/httpserver/HTTPServerSample.java +++ b/integration-tests/it-exporter/it-exporter-httpserver-sample/src/main/java/io/prometheus/metrics/it/exporter/httpserver/HTTPServerSample.java @@ -26,7 +26,10 @@ public static void main(String[] args) throws IOException, InterruptedException int port = parsePortOrExit(args[0]); Mode mode = parseModeOrExit(args[1]); + run(mode, port); + } + private static void run(Mode mode, int port) throws IOException, InterruptedException { Counter counter = Counter.builder() .name("uptime_seconds_total") diff --git a/integration-tests/it-exporter/it-exporter-servlet-jetty-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/jetty/ExporterServletJettySample.java b/integration-tests/it-exporter/it-exporter-servlet-jetty-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/jetty/ExporterServletJettySample.java index 8c899b4ad..c694eda02 100644 --- a/integration-tests/it-exporter/it-exporter-servlet-jetty-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/jetty/ExporterServletJettySample.java +++ b/integration-tests/it-exporter/it-exporter-servlet-jetty-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/jetty/ExporterServletJettySample.java @@ -29,7 +29,10 @@ public static void main(String[] args) throws Exception { int port = parsePortOrExit(args[0]); Mode mode = parseModeOrExit(args[1]); + run(mode, port); + } + private static void run(Mode mode, int port) throws Exception { Counter counter = Counter.builder() .name("uptime_seconds_total") diff --git a/integration-tests/it-exporter/it-exporter-servlet-tomcat-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/tomcat/ExporterServletTomcatSample.java b/integration-tests/it-exporter/it-exporter-servlet-tomcat-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/tomcat/ExporterServletTomcatSample.java index ead2ee88f..fa470b306 100644 --- a/integration-tests/it-exporter/it-exporter-servlet-tomcat-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/tomcat/ExporterServletTomcatSample.java +++ b/integration-tests/it-exporter/it-exporter-servlet-tomcat-sample/src/main/java/io/prometheus/metrics/it/exporter/servlet/tomcat/ExporterServletTomcatSample.java @@ -32,7 +32,10 @@ public static void main(String[] args) throws LifecycleException, IOException { int port = parsePortOrExit(args[0]); Mode mode = parseModeOrExit(args[1]); + run(mode, port); + } + private static void run(Mode mode, int port) throws IOException, LifecycleException { Counter counter = Counter.builder() .name("uptime_seconds_total") diff --git a/pom.xml b/pom.xml index 37f1fdbfe..dfc5a427e 100644 --- a/pom.xml +++ b/pom.xml @@ -21,6 +21,7 @@ 2.9.0-alpha 8 0.70 + false false -Werror @@ -224,6 +225,28 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.5.0 + + true + google_checks.xml + checkstyle.xml + warning + true + ${checkstyle.skip} + checkstyle-suppressions.xml + **/generated/**,**/jmh_generated/* + + + + + check + + + + org.jacoco jacoco-maven-plugin diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/datapoints/StateSetDataPoint.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/datapoints/StateSetDataPoint.java index 61b458ba8..bf13b5214 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/datapoints/StateSetDataPoint.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/datapoints/StateSetDataPoint.java @@ -14,12 +14,6 @@ public interface StateSetDataPoint extends DataPoint { */ void setTrue(String state); - /** - * {@code state} must be one of the states from when the {@code StateSet} was created with {@link - * io.prometheus.metrics.core.metrics.StateSet.Builder#states(String...)}. - */ - void setFalse(String state); - /** * {@code state} must be one of the states from when the {@code StateSet} was created with {@link * io.prometheus.metrics.core.metrics.StateSet.Builder#states(Class)}. @@ -28,6 +22,12 @@ default void setTrue(Enum state) { setTrue(state.toString()); } + /** + * {@code state} must be one of the states from when the {@code StateSet} was created with {@link + * io.prometheus.metrics.core.metrics.StateSet.Builder#states(String...)}. + */ + void setFalse(String state); + /** * {@code state} must be one of the states from when the {@code StateSet} was created with {@link * io.prometheus.metrics.core.metrics.StateSet.Builder#states(Class)}. diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSampler.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSampler.java index 0e1c49f8c..15b0355cd 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSampler.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/exemplars/ExemplarSampler.java @@ -130,6 +130,16 @@ private long doObserveSingleExemplar(double value) { return 0; } + private long doObserveSingleExemplar(double amount, Labels labels) { + long now = System.currentTimeMillis(); + Exemplar current = customExemplars[0]; + if (current == null + || now - current.getTimestampMillis() > config.getMinRetentionPeriodMillis()) { + return updateCustomExemplar(0, amount, labels, now); + } + return 0; + } + private long doObserveWithUpperBounds(double value) { long now = System.currentTimeMillis(); double[] upperBounds = config.getHistogramClassicUpperBounds(); @@ -212,16 +222,6 @@ private long doObserveWithExemplar(double amount, Labels labels) { } } - private long doObserveSingleExemplar(double amount, Labels labels) { - long now = System.currentTimeMillis(); - Exemplar current = customExemplars[0]; - if (current == null - || now - current.getTimestampMillis() > config.getMinRetentionPeriodMillis()) { - return updateCustomExemplar(0, amount, labels, now); - } - return 0; - } - private long doObserveWithExemplarWithUpperBounds(double value, Labels labels) { long now = System.currentTimeMillis(); double[] upperBounds = config.getHistogramClassicUpperBounds(); diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CKMSQuantiles.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CKMSQuantiles.java index 9fc1e9634..74ce18e72 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CKMSQuantiles.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CKMSQuantiles.java @@ -26,6 +26,8 @@ import java.util.LinkedList; import java.util.ListIterator; +// CHECKSTYLE:OFF: checkstyle + /** * Algorithm solving the "Targeted Quantile Problem" as described in "Effective Computation of * Biased Quantiles over Data Streams" by Cormode, Korn, Muthukrishnan, and Srivastava. @@ -273,3 +275,5 @@ public String toString() { } } } + +// CHECKSTYLE:ON: checkstyle diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CallbackMetric.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CallbackMetric.java index cf25e6527..2afaffae7 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CallbackMetric.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CallbackMetric.java @@ -28,7 +28,8 @@ protected Labels makeLabels(String... labelValues) { if (labelValues == null) { throw new IllegalArgumentException( this.getClass().getSimpleName() - + " was created with label names, but the callback was called without label values."); + + " was created with label names, " + + "but the callback was called without label values."); } if (labelValues.length != labelNames.length) { throw new IllegalArgumentException( diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Counter.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Counter.java index 2e84b6ade..8ed9b0001 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Counter.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Counter.java @@ -82,6 +82,15 @@ public CounterSnapshot collect() { return (CounterSnapshot) super.collect(); } + @Override + protected CounterSnapshot collect(List labels, List metricData) { + List data = new ArrayList<>(labels.size()); + for (int i = 0; i < labels.size(); i++) { + data.add(metricData.get(i).collect(labels.get(i))); + } + return new CounterSnapshot(getMetadata(), data); + } + @Override protected boolean isExemplarsEnabled() { return exemplarsEnabled; @@ -96,15 +105,6 @@ protected DataPoint newDataPoint() { } } - @Override - protected CounterSnapshot collect(List labels, List metricData) { - List data = new ArrayList<>(labels.size()); - for (int i = 0; i < labels.size(); i++) { - data.add(metricData.get(i).collect(labels.get(i))); - } - return new CounterSnapshot(getMetadata(), data); - } - static String stripTotalSuffix(String name) { if (name != null && (name.endsWith("_total") || name.endsWith(".total"))) { name = name.substring(0, name.length() - 6); diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CounterWithCallback.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CounterWithCallback.java index 5dc533d58..f8c1b162c 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CounterWithCallback.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/CounterWithCallback.java @@ -15,7 +15,7 @@ * * CounterWithCallback.builder() * .name("classes_loaded_total") - * .help("The total number of classes that have been loaded since the JVM has started execution") + * .help("The total number of classes since the JVM has started execution") * .callback(callback -> callback.call(classLoadingMXBean.getLoadedClassCount())) * .register(); * } diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Histogram.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Histogram.java index bf70bec7c..8f76819f1 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Histogram.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Histogram.java @@ -63,7 +63,7 @@ public class Histogram extends StatefulMetric max ? min : max; + max == Builder.DEFAULT_NATIVE_MAX_ZERO_THRESHOLD && min > max ? min : max; nativeMinZeroThreshold = Math.min(min, nativeMaxZeroThreshold); nativeMaxBuckets = getConfigProperty(properties, MetricsProperties::getHistogramNativeMaxNumberOfBuckets); @@ -447,9 +447,9 @@ private void maybeScaleDown(AtomicBoolean wasReset) { // Now we are in the synchronized block while new observations go into the buffer. // Check again if we need to limit the bucket size, because another thread might // have limited it in the meantime. - int nBuckets = + int numBuckets = nativeBucketsForPositiveValues.size() + nativeBucketsForNegativeValues.size(); - if (nBuckets <= nativeMaxBuckets || nativeSchema == -4) { + if (numBuckets <= nativeMaxBuckets || nativeSchema == -4) { return null; } if (maybeReset()) { @@ -668,11 +668,11 @@ public static class Builder extends StatefulMetric.Builder labels, List metricDataList) { List data = new ArrayList<>(labels.size()); @@ -97,6 +87,16 @@ protected StateSetSnapshot collect(List labels, List metricDa return new StateSetSnapshot(getMetadata(), data); } + @Override + public void setTrue(String state) { + getNoLabels().setTrue(state); + } + + @Override + public void setFalse(String state) { + getNoLabels().setFalse(state); + } + @Override protected DataPoint newDataPoint() { return new DataPoint(); diff --git a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java index 5a838c649..d7fb3afd0 100644 --- a/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java +++ b/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java @@ -105,7 +105,8 @@ public D labelValues(String... labelValues) { getClass().getSimpleName() + " " + getMetadata().getName() - + " was created with label names, so you must call labelValues(...) when using it."); + + " was created with label names, so you must call labelValues(...)" + + " when using it."); } else { throw new IllegalArgumentException( "Expected " + labelNames.length + " label values, but got " + labelValues.length + "."); diff --git a/prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java b/prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java index dee7098fb..f871addfd 100644 --- a/prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java +++ b/prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java @@ -46,7 +46,6 @@ public PrometheusScrapeHandler(PrometheusProperties config, PrometheusRegistry r public void handleRequest(PrometheusHttpExchange exchange) throws IOException { try { PrometheusHttpRequest request = exchange.getRequest(); - PrometheusHttpResponse response = exchange.getResponse(); MetricSnapshots snapshots = scrape(request); if (writeDebugResponse(snapshots, exchange)) { return; @@ -57,6 +56,7 @@ public void handleRequest(PrometheusHttpExchange exchange) throws IOException { ExpositionFormatWriter writer = expositionFormats.findWriter(acceptHeader); writer.write(responseBuffer, snapshots); lastResponseSize.set(responseBuffer.size()); + PrometheusHttpResponse response = exchange.getResponse(); response.setHeader("Content-Type", writer.getContentType()); if (shouldUseCompression(request)) { @@ -106,16 +106,6 @@ private Predicate makeNameFilter(ExporterFilterProperties props) { } } - private MetricSnapshots scrape(PrometheusHttpRequest request) { - - Predicate filter = makeNameFilter(request.getParameterValues("name[]")); - if (filter != null) { - return registry.scrape(filter, request); - } else { - return registry.scrape(request); - } - } - private Predicate makeNameFilter(String[] includedNames) { Predicate result = null; if (includedNames != null && includedNames.length > 0) { @@ -129,6 +119,16 @@ private Predicate makeNameFilter(String[] includedNames) { return result; } + private MetricSnapshots scrape(PrometheusHttpRequest request) { + + Predicate filter = makeNameFilter(request.getParameterValues("name[]")); + if (filter != null) { + return registry.scrape(filter, request); + } else { + return registry.scrape(request); + } + } + private boolean writeDebugResponse(MetricSnapshots snapshots, PrometheusHttpExchange exchange) throws IOException { String debugParam = exchange.getRequest().getParameter("debug"); @@ -157,7 +157,8 @@ private boolean writeDebugResponse(MetricSnapshots snapshots, PrometheusHttpExch body.write( ("debug=" + debugParam - + ": Unsupported query parameter. Valid values are 'openmetrics', 'text', and 'prometheus-protobuf'.") + + ": Unsupported query parameter. Valid values are 'openmetrics', " + + "'text', and 'prometheus-protobuf'.") .getBytes(StandardCharsets.UTF_8)); break; } diff --git a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/DefaultHandler.java b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/DefaultHandler.java index eeb2f70f6..506da12bc 100644 --- a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/DefaultHandler.java +++ b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/DefaultHandler.java @@ -21,15 +21,19 @@ public DefaultHandler() { + "

Metrics Path

\n" + "The metrics path is /metrics.\n" + "

Name Filter

\n" - + "If you want to scrape only specific metrics, use the name[] parameter like this:\n" + + "If you want to scrape only specific metrics, " + + "use the name[] parameter like this:\n" + "\n" + "You can also use multiple name[] parameters to query multiple metrics:\n" + "\n" - + "The name[] parameter can be used by the Prometheus server for scraping. Add the following snippet to your scrape job configuration in prometheus.yaml:\n" + + "The name[] parameter can be used by the Prometheus server for scraping. " + + "Add the following snippet to your scrape job configuration in " + + "prometheus.yaml:\n" + "
\n"
             + "params:\n"
             + "    name[]:\n"
@@ -38,16 +42,28 @@ public DefaultHandler() {
             + "
\n" + "

Debug Parameter

\n" + "The Prometheus Java metrics library supports multiple exposition formats.\n" - + "The Prometheus server sends the Accept header to indicate which format it accepts.\n" - + "By default, the Prometheus server accepts OpenMetrics text format, unless the Prometheus server is started with feature flag --enable-feature=native-histograms,\n" + + "The Prometheus server sends the Accept header " + + "to indicate which format it accepts.\n" + + "By default, the Prometheus server accepts OpenMetrics text format, " + + "unless the Prometheus server is started with feature flag " + + "--enable-feature=native-histograms,\n" + "in which case the default is Prometheus protobuf.\n" - + "The Prometheus Java metrics library supports a debug query parameter for viewing the different formats in a Web browser:\n" + + "The Prometheus Java metrics library supports a debug query parameter " + + "for viewing the different formats in a Web browser:\n" + "\n" - + "Note that the debug parameter is only for viewing different formats in a Web browser, it should not be used by the Prometheus server for scraping. The Prometheus server uses the Accept header for indicating which format it accepts.\n" + + "Note that the debug parameter is only for viewing different formats in a " + + "Web browser, it should not be used by the Prometheus server for scraping. " + + "The Prometheus server uses the Accept " + + "header for indicating which format it accepts.\n" + "\n" + "\n"; this.responseBytes = responseString.getBytes(StandardCharsets.UTF_8); diff --git a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HTTPServer.java b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HTTPServer.java index 5702a0b21..90aaf9d42 100644 --- a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HTTPServer.java +++ b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HTTPServer.java @@ -117,7 +117,9 @@ public void handle(HttpExchange exchange) throws IOException { } catch (PrivilegedActionException e) { if (e.getException() != null) { throw new IOException(e.getException()); - } else throw new IOException(e); + } else { + throw new IOException(e); + } } } else { drainInputAndClose(exchange); @@ -130,8 +132,9 @@ public void handle(HttpExchange exchange) throws IOException { private void drainInputAndClose(HttpExchange httpExchange) throws IOException { InputStream inputStream = httpExchange.getRequestBody(); byte[] b = new byte[4096]; - while (inputStream.read(b) != -1) - ; + while (inputStream.read(b) != -1) { + // nop + } inputStream.close(); } diff --git a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HttpExchangeAdapter.java b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HttpExchangeAdapter.java index e7d33d310..3e0322309 100644 --- a/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HttpExchangeAdapter.java +++ b/prometheus-metrics-exporter-httpserver/src/main/java/io/prometheus/metrics/exporter/httpserver/HttpExchangeAdapter.java @@ -120,7 +120,8 @@ private void sendErrorResponseWithStackTrace(Exception requestHandlerException) Logger.getLogger(this.getClass().getName()) .log( Level.SEVERE, - "The Prometheus metrics HTTPServer caught an Exception during scrape and failed to send an error response to the client.", + "The Prometheus metrics HTTPServer caught an Exception during scrape and " + + "failed to send an error response to the client.", errorWriterException); Logger.getLogger(this.getClass().getName()) .log( @@ -134,7 +135,8 @@ private void sendErrorResponseWithStackTrace(Exception requestHandlerException) Logger.getLogger(this.getClass().getName()) .log( Level.SEVERE, - "The Prometheus metrics HTTPServer caught an Exception while trying to send the metrics response.", + "The Prometheus metrics HTTPServer caught an Exception while trying to send " + + "the metrics response.", requestHandlerException); } } diff --git a/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusMetricProducer.java b/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusMetricProducer.java index 39a293640..ff9be1cf8 100644 --- a/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusMetricProducer.java +++ b/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/PrometheusMetricProducer.java @@ -44,7 +44,7 @@ public Collection collectAllMetrics() { // registry.scrape(filter) if a filter is configured, like in the Servlet exporter. MetricSnapshots snapshots = registry.scrape(); Resource resourceWithTargetInfo = resource.merge(resourceFromTargetInfo(snapshots)); - InstrumentationScopeInfo scopeFromInfo = instrumentationScopeFromOTelScopeInfo(snapshots); + InstrumentationScopeInfo scopeFromInfo = instrumentationScopeFromOtelScopeInfo(snapshots); List result = new ArrayList<>(snapshots.size()); MetricDataFactory factory = new MetricDataFactory( @@ -93,7 +93,7 @@ private Resource resourceFromTargetInfo(MetricSnapshots snapshots) { return result.build(); } - private InstrumentationScopeInfo instrumentationScopeFromOTelScopeInfo( + private InstrumentationScopeInfo instrumentationScopeFromOtelScopeInfo( MetricSnapshots snapshots) { for (MetricSnapshot snapshot : snapshots) { if (snapshot.getMetadata().getPrometheusName().equals("otel_scope") diff --git a/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusData.java b/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusData.java index 64b82bd8b..9d2cff6a8 100644 --- a/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusData.java +++ b/prometheus-metrics-exporter-opentelemetry/src/main/java/io/prometheus/metrics/exporter/opentelemetry/otelmodel/PrometheusData.java @@ -10,7 +10,11 @@ import io.opentelemetry.sdk.metrics.data.MetricDataType; import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.prometheus.metrics.model.snapshots.*; +import io.prometheus.metrics.model.snapshots.DataPointSnapshot; +import io.prometheus.metrics.model.snapshots.Exemplar; +import io.prometheus.metrics.model.snapshots.Exemplars; +import io.prometheus.metrics.model.snapshots.Label; +import io.prometheus.metrics.model.snapshots.Labels; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; diff --git a/prometheus-metrics-exporter-pushgateway/src/main/java/io/prometheus/metrics/exporter/pushgateway/PushGateway.java b/prometheus-metrics-exporter-pushgateway/src/main/java/io/prometheus/metrics/exporter/pushgateway/PushGateway.java index 2b986adb4..2bafc6aa2 100644 --- a/prometheus-metrics-exporter-pushgateway/src/main/java/io/prometheus/metrics/exporter/pushgateway/PushGateway.java +++ b/prometheus-metrics-exporter-pushgateway/src/main/java/io/prometheus/metrics/exporter/pushgateway/PushGateway.java @@ -10,10 +10,24 @@ import io.prometheus.metrics.model.registry.Collector; import io.prometheus.metrics.model.registry.MultiCollector; import io.prometheus.metrics.model.registry.PrometheusRegistry; -import java.io.*; -import java.net.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLEncoder; +import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; /** * Export metrics via the Prometheus diff --git a/prometheus-metrics-exposition-formats/generate-protobuf.sh b/prometheus-metrics-exposition-formats/generate-protobuf.sh index 9e5dd9d09..866da038d 100755 --- a/prometheus-metrics-exposition-formats/generate-protobuf.sh +++ b/prometheus-metrics-exposition-formats/generate-protobuf.sh @@ -29,6 +29,8 @@ curl -sL https://raw.githubusercontent.com/prometheus/client_model/master/io/pro sed -i "s/java_package = \"io.prometheus.client\"/java_package = \"$PACKAGE\"/" $PROTO_DIR/metrics.proto protoc --java_out $TARGET_DIR $PROTO_DIR/metrics.proto +sed -i '1 i\//CHECKSTYLE:OFF: checkstyle' $(find src/main/generated/io -type f) +sed -i -e $'$a\\\n//CHECKSTYLE:ON: checkstyle' $(find src/main/generated/io -type f) GENERATED_WITH=$(grep -oP '\/\/ Protobuf Java Version: \K.*' "$TARGET_DIR/${PACKAGE//\.//}"/Metrics.java) diff --git a/prometheus-metrics-exposition-formats/src/main/generated/io/prometheus/metrics/expositionformats/generated/com_google_protobuf_4_28_3/Metrics.java b/prometheus-metrics-exposition-formats/src/main/generated/io/prometheus/metrics/expositionformats/generated/com_google_protobuf_4_28_3/Metrics.java index 0f74014ed..ffa9b1d87 100644 --- a/prometheus-metrics-exposition-formats/src/main/generated/io/prometheus/metrics/expositionformats/generated/com_google_protobuf_4_28_3/Metrics.java +++ b/prometheus-metrics-exposition-formats/src/main/generated/io/prometheus/metrics/expositionformats/generated/com_google_protobuf_4_28_3/Metrics.java @@ -1,3 +1,4 @@ +//CHECKSTYLE:OFF: checkstyle // Generated by the protocol buffer compiler. DO NOT EDIT! // NO CHECKED-IN PROTOBUF GENCODE // source: src/main/protobuf/metrics.proto @@ -15114,3 +15115,4 @@ public io.prometheus.metrics.expositionformats.generated.com_google_protobuf_4_2 // @@protoc_insertion_point(outer_class_scope) } +//CHECKSTYLE:ON: checkstyle diff --git a/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/PrometheusProtobufWriter.java b/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/PrometheusProtobufWriter.java index fc5ac874e..fb3b9412d 100644 --- a/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/PrometheusProtobufWriter.java +++ b/prometheus-metrics-exposition-formats/src/main/java/io/prometheus/metrics/expositionformats/PrometheusProtobufWriter.java @@ -33,7 +33,8 @@ public class PrometheusProtobufWriter implements ExpositionFormatWriter { public static final String CONTENT_TYPE = - "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"; + "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; " + + "encoding=delimited"; @Override public boolean accepts(String acceptHeader) { @@ -53,7 +54,7 @@ public String getContentType() { public String toDebugString(MetricSnapshots metricSnapshots) { StringBuilder stringBuilder = new StringBuilder(); for (MetricSnapshot snapshot : metricSnapshots) { - if (snapshot.getDataPoints().size() > 0) { + if (!snapshot.getDataPoints().isEmpty()) { stringBuilder.append(TextFormat.printer().printToString(convert(snapshot))); } } @@ -63,7 +64,7 @@ public String toDebugString(MetricSnapshots metricSnapshots) { @Override public void write(OutputStream out, MetricSnapshots metricSnapshots) throws IOException { for (MetricSnapshot snapshot : metricSnapshots) { - if (snapshot.getDataPoints().size() > 0) { + if (!snapshot.getDataPoints().isEmpty()) { convert(snapshot).writeDelimitedTo(out); } } @@ -122,32 +123,13 @@ public Metrics.MetricFamily convert(MetricSnapshot snapshot) { return builder.build(); } - private void setMetadataUnlessEmpty( - Metrics.MetricFamily.Builder builder, - MetricMetadata metadata, - String nameSuffix, - Metrics.MetricType type) { - if (builder.getMetricCount() == 0) { - return; - } - if (nameSuffix == null) { - builder.setName(metadata.getPrometheusName()); - } else { - builder.setName(metadata.getPrometheusName() + nameSuffix); - } - if (metadata.getHelp() != null) { - builder.setHelp(metadata.getHelp()); - } - builder.setType(type); - } - private Metrics.Metric.Builder convert(CounterDataPointSnapshot data) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); Metrics.Counter.Builder counterBuilder = Metrics.Counter.newBuilder(); counterBuilder.setValue(data.getValue()); if (data.getExemplar() != null) { counterBuilder.setExemplar(convert(data.getExemplar())); } + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); addLabels(metricBuilder, data.getLabels()); metricBuilder.setCounter(counterBuilder.build()); setScrapeTimestamp(metricBuilder, data); @@ -155,9 +137,9 @@ private Metrics.Metric.Builder convert(CounterDataPointSnapshot data) { } private Metrics.Metric.Builder convert(GaugeSnapshot.GaugeDataPointSnapshot data) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); Metrics.Gauge.Builder gaugeBuilder = Metrics.Gauge.newBuilder(); gaugeBuilder.setValue(data.getValue()); + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); addLabels(metricBuilder, data.getLabels()); metricBuilder.setGauge(gaugeBuilder); setScrapeTimestamp(metricBuilder, data); @@ -219,6 +201,94 @@ private Metrics.Metric.Builder convert(HistogramSnapshot.HistogramDataPointSnaps return metricBuilder; } + private Metrics.Metric.Builder convert(SummarySnapshot.SummaryDataPointSnapshot data) { + Metrics.Summary.Builder summaryBuilder = Metrics.Summary.newBuilder(); + if (data.hasCount()) { + summaryBuilder.setSampleCount(data.getCount()); + } + if (data.hasSum()) { + summaryBuilder.setSampleSum(data.getSum()); + } + Quantiles quantiles = data.getQuantiles(); + for (int i = 0; i < quantiles.size(); i++) { + summaryBuilder.addQuantile( + Metrics.Quantile.newBuilder() + .setQuantile(quantiles.get(i).getQuantile()) + .setValue(quantiles.get(i).getValue()) + .build()); + } + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); + addLabels(metricBuilder, data.getLabels()); + metricBuilder.setSummary(summaryBuilder.build()); + setScrapeTimestamp(metricBuilder, data); + return metricBuilder; + } + + private Metrics.Metric.Builder convert(InfoSnapshot.InfoDataPointSnapshot data) { + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); + Metrics.Gauge.Builder gaugeBuilder = Metrics.Gauge.newBuilder(); + gaugeBuilder.setValue(1); + addLabels(metricBuilder, data.getLabels()); + metricBuilder.setGauge(gaugeBuilder); + setScrapeTimestamp(metricBuilder, data); + return metricBuilder; + } + + private Metrics.Metric.Builder convert( + StateSetSnapshot.StateSetDataPointSnapshot data, String name, int i) { + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); + Metrics.Gauge.Builder gaugeBuilder = Metrics.Gauge.newBuilder(); + addLabels(metricBuilder, data.getLabels()); + metricBuilder.addLabel( + Metrics.LabelPair.newBuilder().setName(name).setValue(data.getName(i)).build()); + if (data.isTrue(i)) { + gaugeBuilder.setValue(1); + } else { + gaugeBuilder.setValue(0); + } + metricBuilder.setGauge(gaugeBuilder); + setScrapeTimestamp(metricBuilder, data); + return metricBuilder; + } + + private Metrics.Metric.Builder convert(UnknownSnapshot.UnknownDataPointSnapshot data) { + Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); + Metrics.Untyped.Builder untypedBuilder = Metrics.Untyped.newBuilder(); + untypedBuilder.setValue(data.getValue()); + addLabels(metricBuilder, data.getLabels()); + metricBuilder.setUntyped(untypedBuilder); + return metricBuilder; + } + + private Metrics.Exemplar.Builder convert(Exemplar exemplar) { + Metrics.Exemplar.Builder builder = Metrics.Exemplar.newBuilder(); + builder.setValue(exemplar.getValue()); + addLabels(builder, exemplar.getLabels()); + if (exemplar.hasTimestamp()) { + builder.setTimestamp(timestampFromMillis(exemplar.getTimestampMillis())); + } + return builder; + } + + private void setMetadataUnlessEmpty( + Metrics.MetricFamily.Builder builder, + MetricMetadata metadata, + String nameSuffix, + Metrics.MetricType type) { + if (builder.getMetricCount() == 0) { + return; + } + if (nameSuffix == null) { + builder.setName(metadata.getPrometheusName()); + } else { + builder.setName(metadata.getPrometheusName() + nameSuffix); + } + if (metadata.getHelp() != null) { + builder.setHelp(metadata.getHelp()); + } + builder.setType(type); + } + private long getNativeCount(HistogramSnapshot.HistogramDataPointSnapshot data) { if (data.hasCount()) { return data.getCount(); @@ -284,65 +354,6 @@ private void addBuckets( } } - private Metrics.Metric.Builder convert(SummarySnapshot.SummaryDataPointSnapshot data) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); - Metrics.Summary.Builder summaryBuilder = Metrics.Summary.newBuilder(); - if (data.hasCount()) { - summaryBuilder.setSampleCount(data.getCount()); - } - if (data.hasSum()) { - summaryBuilder.setSampleSum(data.getSum()); - } - Quantiles quantiles = data.getQuantiles(); - for (int i = 0; i < quantiles.size(); i++) { - summaryBuilder.addQuantile( - Metrics.Quantile.newBuilder() - .setQuantile(quantiles.get(i).getQuantile()) - .setValue(quantiles.get(i).getValue()) - .build()); - } - addLabels(metricBuilder, data.getLabels()); - metricBuilder.setSummary(summaryBuilder.build()); - setScrapeTimestamp(metricBuilder, data); - return metricBuilder; - } - - private Metrics.Metric.Builder convert(InfoSnapshot.InfoDataPointSnapshot data) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); - Metrics.Gauge.Builder gaugeBuilder = Metrics.Gauge.newBuilder(); - gaugeBuilder.setValue(1); - addLabels(metricBuilder, data.getLabels()); - metricBuilder.setGauge(gaugeBuilder); - setScrapeTimestamp(metricBuilder, data); - return metricBuilder; - } - - private Metrics.Metric.Builder convert( - StateSetSnapshot.StateSetDataPointSnapshot data, String name, int i) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); - Metrics.Gauge.Builder gaugeBuilder = Metrics.Gauge.newBuilder(); - addLabels(metricBuilder, data.getLabels()); - metricBuilder.addLabel( - Metrics.LabelPair.newBuilder().setName(name).setValue(data.getName(i)).build()); - if (data.isTrue(i)) { - gaugeBuilder.setValue(1); - } else { - gaugeBuilder.setValue(0); - } - metricBuilder.setGauge(gaugeBuilder); - setScrapeTimestamp(metricBuilder, data); - return metricBuilder; - } - - private Metrics.Metric.Builder convert(UnknownSnapshot.UnknownDataPointSnapshot data) { - Metrics.Metric.Builder metricBuilder = Metrics.Metric.newBuilder(); - Metrics.Untyped.Builder untypedBuilder = Metrics.Untyped.newBuilder(); - untypedBuilder.setValue(data.getValue()); - addLabels(metricBuilder, data.getLabels()); - metricBuilder.setUntyped(untypedBuilder); - return metricBuilder; - } - private void addLabels(Metrics.Metric.Builder metricBuilder, Labels labels) { for (int i = 0; i < labels.size(); i++) { metricBuilder.addLabel( @@ -363,16 +374,6 @@ private void addLabels(Metrics.Exemplar.Builder metricBuilder, Labels labels) { } } - private Metrics.Exemplar.Builder convert(Exemplar exemplar) { - Metrics.Exemplar.Builder builder = Metrics.Exemplar.newBuilder(); - builder.setValue(exemplar.getValue()); - addLabels(builder, exemplar.getLabels()); - if (exemplar.hasTimestamp()) { - builder.setTimestamp(timestampFromMillis(exemplar.getTimestampMillis())); - } - return builder; - } - private void setScrapeTimestamp(Metrics.Metric.Builder metricBuilder, DataPointSnapshot data) { if (data.hasScrapeTimestamp()) { metricBuilder.setTimestampMs(data.getScrapeTimestampMillis()); diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExports.java b/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExports.java index ce0318912..bd3a163ac 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExports.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/DropwizardExports.java @@ -1,19 +1,36 @@ package io.prometheus.metrics.instrumentation.dropwizard5; -import io.dropwizard.metrics5.*; +import io.dropwizard.metrics5.Counter; +import io.dropwizard.metrics5.Gauge; +import io.dropwizard.metrics5.Histogram; +import io.dropwizard.metrics5.Meter; +import io.dropwizard.metrics5.Metric; +import io.dropwizard.metrics5.MetricFilter; +import io.dropwizard.metrics5.MetricName; +import io.dropwizard.metrics5.MetricRegistry; +import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; import io.prometheus.metrics.instrumentation.dropwizard5.labels.CustomLabelMapper; import io.prometheus.metrics.model.registry.MultiCollector; import io.prometheus.metrics.model.registry.PrometheusRegistry; -import io.prometheus.metrics.model.snapshots.*; -import java.util.*; +import io.prometheus.metrics.model.snapshots.CounterSnapshot; +import io.prometheus.metrics.model.snapshots.GaugeSnapshot; +import io.prometheus.metrics.model.snapshots.MetricMetadata; +import io.prometheus.metrics.model.snapshots.MetricSnapshot; +import io.prometheus.metrics.model.snapshots.MetricSnapshots; +import io.prometheus.metrics.model.snapshots.PrometheusNaming; +import io.prometheus.metrics.model.snapshots.Quantiles; +import io.prometheus.metrics.model.snapshots.SummarySnapshot; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** Collect Dropwizard metrics from a MetricRegistry. */ public class DropwizardExports implements MultiCollector { - private static final Logger LOGGER = Logger.getLogger(DropwizardExports.class.getName()); + private static final Logger logger = Logger.getLogger(DropwizardExports.class.getName()); private final MetricRegistry registry; private final MetricFilter metricFilter; private final Optional labelMapper; @@ -92,7 +109,7 @@ MetricSnapshot fromGauge(String dropwizardName, Gauge gauge) { } else if (obj instanceof Boolean) { value = ((Boolean) obj) ? 1 : 0; } else { - LOGGER.log( + logger.log( Level.FINE, String.format( "Invalid type for Gauge %s: %s", diff --git a/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfig.java b/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfig.java index f69a27944..22f1c3339 100644 --- a/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfig.java +++ b/prometheus-metrics-instrumentation-dropwizard5/src/main/java/io/prometheus/metrics/instrumentation/dropwizard5/labels/MapperConfig.java @@ -127,13 +127,21 @@ private void validateLabels(final Map labels) { @Override public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } final MapperConfig that = (MapperConfig) o; - if (match != null ? !match.equals(that.match) : that.match != null) return false; - if (name != null ? !name.equals(that.name) : that.name != null) return false; + if (match != null ? !match.equals(that.match) : that.match != null) { + return false; + } + if (name != null ? !name.equals(that.name) : that.name != null) { + return false; + } return labels != null ? labels.equals(that.labels) : that.labels == null; } diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetrics.java index f87618f63..ebd0f296c 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmClassLoadingMetrics.java @@ -67,7 +67,8 @@ private void register(PrometheusRegistry registry) { CounterWithCallback.builder(config) .name(JVM_CLASSES_UNLOADED_TOTAL) .help( - "The total number of classes that have been unloaded since the JVM has started execution") + "The total number of classes that have been unloaded since the JVM has " + + "started execution") .callback(callback -> callback.call(classLoadingBean.getUnloadedClassCount())) .register(registry); } diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetrics.java index b0672aaf3..0b6a4d993 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryMetrics.java @@ -309,11 +309,11 @@ public void register() { } public void register(PrometheusRegistry registry) { - MemoryMXBean memoryMXBean = + MemoryMXBean bean = this.memoryBean != null ? this.memoryBean : ManagementFactory.getMemoryMXBean(); List poolBeans = this.poolBeans != null ? this.poolBeans : ManagementFactory.getMemoryPoolMXBeans(); - new JvmMemoryMetrics(poolBeans, memoryMXBean, config).register(registry); + new JvmMemoryMetrics(poolBeans, bean, config).register(registry); } } } diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetrics.java index 671c36c97..a5e7768c8 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmMemoryPoolAllocationMetrics.java @@ -56,21 +56,20 @@ private JvmMemoryPoolAllocationMetrics(List garbageColle } private void register(PrometheusRegistry registry) { - Counter allocatedCounter = Counter.builder() .name(JVM_MEMORY_POOL_ALLOCATED_BYTES_TOTAL) .help( - "Total bytes allocated in a given JVM memory pool. Only updated after GC, not continuously.") + "Total bytes allocated in a given JVM memory pool. Only updated after GC, " + + "not continuously.") .labelNames("pool") .register(registry); AllocationCountingNotificationListener listener = new AllocationCountingNotificationListener(allocatedCounter); - for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorBeans) { - if (garbageCollectorMXBean instanceof NotificationEmitter) { - ((NotificationEmitter) garbageCollectorMXBean) - .addNotificationListener(listener, null, null); + for (GarbageCollectorMXBean bean : garbageCollectorBeans) { + if (bean instanceof NotificationEmitter) { + ((NotificationEmitter) bean).addNotificationListener(listener, null, null); } } } diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetrics.java index e350568ac..53225edca 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmNativeMemoryMetrics.java @@ -110,7 +110,8 @@ private void register(PrometheusRegistry registry) { GaugeWithCallback.builder(config) .name(JVM_NATIVE_MEMORY_RESERVED_BYTES) .help( - "Reserved bytes of a given JVM. Reserved memory represents the total amount of memory the JVM can potentially use.") + "Reserved bytes of a given JVM. Reserved memory represents the total amount of " + + "memory the JVM can potentially use.") .unit(Unit.BYTES) .labelNames("pool") .callback(makeCallback(true)) @@ -119,7 +120,8 @@ private void register(PrometheusRegistry registry) { GaugeWithCallback.builder(config) .name(JVM_NATIVE_MEMORY_COMMITTED_BYTES) .help( - "Committed bytes of a given JVM. Committed memory represents the amount of memory the JVM is using right now.") + "Committed bytes of a given JVM. Committed memory represents the amount of " + + "memory the JVM is using right now.") .unit(Unit.BYTES) .labelNames("pool") .callback(makeCallback(false)) diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetrics.java index 8b6e57ac1..d3d140250 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/JvmThreadsMetrics.java @@ -109,7 +109,8 @@ private void register(PrometheusRegistry registry) { GaugeWithCallback.builder(config) .name(JVM_THREADS_DEADLOCKED) .help( - "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or ownable synchronizers") + "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or " + + "ownable synchronizers") .callback( callback -> callback.call(nullSafeArrayLength(threadBean.findDeadlockedThreads()))) .register(registry); @@ -148,7 +149,7 @@ private Map getThreadStateCountMap(ThreadMXBean threadBean) { } } - int numberOfInvalidThreadIds = threadIds.length - writePos; + final int numberOfInvalidThreadIds = threadIds.length - writePos; threadIds = Arrays.copyOf(threadIds, writePos); // Get thread information without computing any stack traces diff --git a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java index a854f5e89..e4dabd275 100644 --- a/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java +++ b/prometheus-metrics-instrumentation-jvm/src/main/java/io/prometheus/metrics/instrumentation/jvm/ProcessMetrics.java @@ -301,10 +301,10 @@ public void register() { public void register(PrometheusRegistry registry) { OperatingSystemMXBean osBean = this.osBean != null ? this.osBean : ManagementFactory.getOperatingSystemMXBean(); - RuntimeMXBean runtimeMXBean = + RuntimeMXBean bean = this.runtimeBean != null ? this.runtimeBean : ManagementFactory.getRuntimeMXBean(); Grepper grepper = this.grepper != null ? this.grepper : new FileGrepper(); - new ProcessMetrics(osBean, runtimeMXBean, grepper, config).register(registry); + new ProcessMetrics(osBean, bean, grepper, config).register(registry); } } } diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DataPointSnapshot.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DataPointSnapshot.java index 4c2d57e8e..6b455bff6 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DataPointSnapshot.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/DataPointSnapshot.java @@ -21,11 +21,13 @@ private void validate() { } if (createdTimestampMillis < 0) { throw new IllegalArgumentException( - "Created timestamp cannot be negative. Use 0 if the metric doesn't have a created timestamp."); + "Created timestamp cannot be negative. " + + "Use 0 if the metric doesn't have a created timestamp."); } if (scrapeTimestampMillis < 0) { throw new IllegalArgumentException( - "Scrape timestamp cannot be negative. Use 0 to indicate that the Prometheus server should set the scrape timestamp."); + "Scrape timestamp cannot be negative. " + + "Use 0 to indicate that the Prometheus server should set the scrape timestamp."); } if (hasCreatedTimestamp() && hasScrapeTimestamp()) { if (scrapeTimestampMillis < createdTimestampMillis) { diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/HistogramSnapshot.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/HistogramSnapshot.java index eb6213d6b..51b529616 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/HistogramSnapshot.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/HistogramSnapshot.java @@ -270,7 +270,8 @@ private static long calculateCount( nativeZeroCount, nativeBucketsForPositiveValues, nativeBucketsForNegativeValues); if (classicCount != nativeCount) { throw new IllegalArgumentException( - "Inconsistent observation count: If a histogram has both classic and native data the observation count must be the same. Classic count is " + "Inconsistent observation count: If a histogram has both classic and native " + + "data the observation count must be the same. Classic count is " + classicCount + " but native count is " + nativeCount diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Label.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Label.java index f14af41ce..45acd56ee 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Label.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Label.java @@ -34,8 +34,12 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Label label = (Label) o; return Objects.equals(name, label.name) && Objects.equals(value, label.value); } diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Labels.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Labels.java index dcb32f3bc..97cbfd43a 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Labels.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Labels.java @@ -70,19 +70,6 @@ public static Labels of(String... keyValuePairs) { } // package private for testing - static String[] makePrometheusNames(String[] names) { - String[] prometheusNames = names; - for (int i = 0; i < names.length; i++) { - if (names[i].contains(".")) { - if (prometheusNames == names) { - prometheusNames = Arrays.copyOf(names, names.length); - } - prometheusNames[i] = PrometheusNaming.prometheusName(names[i]); - } - } - return prometheusNames; - } - /** * Create a new Labels instance. You can either create Labels with one of the static {@code * Labels.of(...)} methods, or you can use the {@link Labels#builder()}. @@ -129,6 +116,19 @@ public static Labels of(String[] names, String[] values) { return new Labels(namesCopy, prometheusNames, valuesCopy); } + static String[] makePrometheusNames(String[] names) { + String[] prometheusNames = names; + for (int i = 0; i < names.length; i++) { + if (names[i].contains(".")) { + if (prometheusNames == names) { + prometheusNames = Arrays.copyOf(names, names.length); + } + prometheusNames[i] = PrometheusNaming.prometheusName(names[i]); + } + } + return prometheusNames; + } + /** * Test if these labels contain a specific label name. * @@ -286,14 +286,6 @@ public Labels merge(Labels other) { return new Labels(names, prometheusNames, values); } - /** - * Create a new Labels instance containing the labels of this and the label passed as name and - * value. The label name must not already be contained in this Labels instance. - */ - public Labels add(String name, String value) { - return merge(Labels.of(name, value)); - } - /** * Create a new Labels instance containing the labels of this and the labels passed as names and * values. The new label names must not already be contained in this Labels instance. @@ -313,6 +305,14 @@ public Labels merge(String[] names, String[] values) { return new Labels(mergedNames, prometheusNames, mergedValues); } + /** + * Create a new Labels instance containing the labels of this and the label passed as name and + * value. The label name must not already be contained in this Labels instance. + */ + public Labels add(String name, String value) { + return merge(Labels.of(name, value)); + } + public boolean hasSameNames(Labels other) { return Arrays.equals(prometheusNames, other.prometheusNames); } @@ -400,8 +400,12 @@ private void appendEscapedLabelValue(StringBuilder b, String value) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Labels labels = (Labels) o; return labels.hasSameNames(this) && labels.hasSameValues(this); } diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricMetadata.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricMetadata.java index 868cdb394..581cb9143 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricMetadata.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/MetricMetadata.java @@ -108,7 +108,8 @@ private void validate() { throw new IllegalArgumentException( "'" + name - + "': Illegal metric name. If the unit is non-null, the name must end with the unit: _" + + "': Illegal metric name. If the unit is non-null, " + + "the name must end with the unit: _" + unit + "." + " Call " diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantiles.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantiles.java index 135af6658..34a9bc048 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantiles.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Quantiles.java @@ -1,6 +1,11 @@ package io.prometheus.metrics.model.snapshots; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; /** Immutable list of quantiles. */ public class Quantiles implements Iterable { diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java index d95f93195..31a9524e7 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java @@ -61,8 +61,12 @@ public static double kiloBytesToBytes(double kilobytes) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Unit unit = (Unit) o; return Objects.equals(name, unit.name); } diff --git a/prometheus-metrics-tracer/prometheus-metrics-tracer-initializer/src/main/java/io/prometheus/metrics/tracer/initializer/SpanContextSupplier.java b/prometheus-metrics-tracer/prometheus-metrics-tracer-initializer/src/main/java/io/prometheus/metrics/tracer/initializer/SpanContextSupplier.java index 11d14ed8f..de8bf24f5 100644 --- a/prometheus-metrics-tracer/prometheus-metrics-tracer-initializer/src/main/java/io/prometheus/metrics/tracer/initializer/SpanContextSupplier.java +++ b/prometheus-metrics-tracer/prometheus-metrics-tracer-initializer/src/main/java/io/prometheus/metrics/tracer/initializer/SpanContextSupplier.java @@ -1,8 +1,8 @@ package io.prometheus.metrics.tracer.initializer; +import io.prometheus.metrics.tracer.agent.OpenTelemetryAgentSpanContext; import io.prometheus.metrics.tracer.common.SpanContext; import io.prometheus.metrics.tracer.otel.OpenTelemetrySpanContext; -import io.prometheus.metrics.tracer.otel_agent.OpenTelemetryAgentSpanContext; import java.util.concurrent.atomic.AtomicReference; public class SpanContextSupplier { diff --git a/prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/otel_agent/OpenTelemetryAgentSpanContext.java b/prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/agent/OpenTelemetryAgentSpanContext.java similarity index 97% rename from prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/otel_agent/OpenTelemetryAgentSpanContext.java rename to prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/agent/OpenTelemetryAgentSpanContext.java index 3c757ed6b..f5f93e6f3 100644 --- a/prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/otel_agent/OpenTelemetryAgentSpanContext.java +++ b/prometheus-metrics-tracer/prometheus-metrics-tracer-otel-agent/src/main/java/io/prometheus/metrics/tracer/agent/OpenTelemetryAgentSpanContext.java @@ -1,4 +1,4 @@ -package io.prometheus.metrics.tracer.otel_agent; +package io.prometheus.metrics.tracer.agent; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanId;