diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2fb971743d..e4fab212f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,8 @@ jobs: sudo ./ci/setup_ci_environment.sh - name: run tests run: ./ci/do_ci.sh cmake.test + - name: run prometheus exporter tests + run: ./ci/do_ci.sh cmake.exporter.prometheus.test cmake_test_cxx20: name: CMake C++20 test diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..94dac0ba74 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third_party/prometheus-cpp"] + path = third_party/prometheus-cpp + url = https://github.com/jupp0r/prometheus-cpp.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 94b6c44354..78ff1b5c89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,6 +13,9 @@ endif() option(WITH_OTPROTOCOL "Whether to include the OpenTelemetry Protocol in the SDK" OFF) +option(WITH_PROMETHEUS "Whether to include the Prometheus Client in the SDK" + OFF) + set(WITH_PROTOBUF OFF) if(WITH_OTPROTOCOL) set(WITH_PROTOBUF ON) diff --git a/WORKSPACE b/WORKSPACE index 615d1d27ef..ef2c9611be 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -88,3 +88,17 @@ http_archive( "https://github.com/nlohmann/json/releases/download/v3.6.1/include.zip", ], ) + +# C++ Prometheus Client library. +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") + +http_archive( + name = "com_github_jupp0r_prometheus_cpp", + sha256 = "85ad6fea0f0dcb413104366b7d6109acdb015aff8767945511c5cad8202a28a6", + strip_prefix = "prometheus-cpp-0.9.0", + urls = ["https://github.com/jupp0r/prometheus-cpp/archive/v0.9.0.tar.gz"], +) + +load("@com_github_jupp0r_prometheus_cpp//bazel:repositories.bzl", "prometheus_cpp_repositories") + +prometheus_cpp_repositories() diff --git a/ci/do_ci.sh b/ci/do_ci.sh index fb641aa701..54e84b9e92 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -40,6 +40,33 @@ elif [[ "$1" == "cmake.exporter.otprotocol.test" ]]; then make make test exit 0 +elif [[ "$1" == "cmake.exporter.prometheus.test" ]]; then +# export DEBIAN_FRONTEND=noninteractive +# apt-get update +# apt-get install sudo +# apt-get install zlib1g-dev +# apt-get -y install libcurl4-openssl-dev + cd third_party + git clone https://github.com/jupp0r/prometheus-cpp + cd prometheus-cpp + git checkout v0.9.0 + git submodule init + git submodule update + mkdir _build && cd _build + cmake .. -DBUILD_SHARED_LIBS=ON + make -j 4 + sudo make install + + cd "${BUILD_DIR}" + rm -rf * + + cmake -DCMAKE_BUILD_TYPE=Debug \ + -DWITH_PROMETHEUS=ON \ + -DCMAKE_CXX_FLAGS="-Werror" \ + "${SRC_DIR}" + make + make test + exit 0 elif [[ "$1" == "cmake.test_example_plugin" ]]; then # Build the plugin cd "${BUILD_DIR}" @@ -83,8 +110,10 @@ elif [[ "$1" == "bazel.legacy.test" ]]; then bazel test $BAZEL_TEST_OPTIONS -- //... -//exporters/otlp/... exit 0 elif [[ "$1" == "bazel.noexcept" ]]; then - bazel build --copt=-fno-exceptions $BAZEL_OPTIONS //... - bazel test --copt=-fno-exceptions $BAZEL_TEST_OPTIONS //... + # there are some exceptions and error handling code from the Prometheus Client + # that make this test always fail. ignore Prometheus exporter in the noexcept here. + bazel build --copt=-fno-exceptions $BAZEL_OPTIONS -- //... -//exporters/prometheus/... + bazel test --copt=-fno-exceptions $BAZEL_TEST_OPTIONS -- //... -//exporters/prometheus/... exit 0 elif [[ "$1" == "bazel.asan" ]]; then bazel test --config=asan $BAZEL_TEST_OPTIONS //... diff --git a/ci/setup_cmake.sh b/ci/setup_cmake.sh index 0ab9be37fd..34097dbaa3 100755 --- a/ci/setup_cmake.sh +++ b/ci/setup_cmake.sh @@ -2,10 +2,15 @@ set -e +export DEBIAN_FRONTEND=noninteractive +apt-get update apt-get install --no-install-recommends --no-install-suggests -y \ cmake \ libbenchmark-dev \ - libgtest-dev + libgtest-dev \ + zlib1g-dev \ + sudo \ + libcurl4-openssl-dev # Follows these instructions for setting up gtest # https://www.eriksmistad.no/getting-started-with-google-test-on-ubuntu/ diff --git a/exporters/CMakeLists.txt b/exporters/CMakeLists.txt index a5144a9a24..227c0f7f1f 100644 --- a/exporters/CMakeLists.txt +++ b/exporters/CMakeLists.txt @@ -1,4 +1,9 @@ if(WITH_OTPROTOCOL) add_subdirectory(otlp) endif() + add_subdirectory(ostream) + +if(WITH_PROMETHEUS) + add_subdirectory(prometheus) +endif() diff --git a/exporters/prometheus/BUILD b/exporters/prometheus/BUILD new file mode 100644 index 0000000000..0852586ec4 --- /dev/null +++ b/exporters/prometheus/BUILD @@ -0,0 +1,42 @@ +# Copyright 2020, OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +package(default_visibility = ["//visibility:public"]) + +cc_library( + name = "prometheus_utils", + srcs = [ + "src/prometheus_exporter_utils.cc", + ], + hdrs = [ + "include/opentelemetry/exporters/prometheus/prometheus_exporter_utils.h", + ], + strip_include_prefix = "include", + deps = [ + "//api", + "//sdk:headers", + "@com_github_jupp0r_prometheus_cpp//core", + ], +) + +cc_test( + name = "prometheus_exporter_utils_test", + srcs = [ + "test/prometheus_exporter_utils_test.cc", + ], + deps = [ + ":prometheus_utils", + "@com_google_googletest//:gtest_main", + ], +) diff --git a/exporters/prometheus/CMakeLists.txt b/exporters/prometheus/CMakeLists.txt new file mode 100644 index 0000000000..8a2658e97b --- /dev/null +++ b/exporters/prometheus/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright 2020, OpenTelemetry Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +include_directories(include) + +find_package(prometheus-cpp CONFIG REQUIRED) +add_library(prometheus_exporter src/prometheus_exporter_utils.cc) + +if(BUILD_TESTING) + add_subdirectory(test) +endif() diff --git a/exporters/prometheus/include/opentelemetry/exporters/prometheus/prometheus_exporter_utils.h b/exporters/prometheus/include/opentelemetry/exporters/prometheus/prometheus_exporter_utils.h new file mode 100644 index 0000000000..de63b4d88e --- /dev/null +++ b/exporters/prometheus/include/opentelemetry/exporters/prometheus/prometheus_exporter_utils.h @@ -0,0 +1,182 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "opentelemetry/sdk/metrics/record.h" +#include "prometheus/metric_family.h" + +namespace metric_sdk = opentelemetry::sdk::metrics; + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace exporter +{ +namespace prometheus +{ +/** + * The Prometheus Utils contains utility functions for Prometheus Exporter + */ +class PrometheusExporterUtils +{ +public: + /** + * Helper function to convert OpenTelemetry metrics data collection + * to Prometheus metrics data collection + * + * @param records a collection of metrics in OpenTelemetry + * @return a collection of translated metrics that is acceptable by Prometheus + */ + static std::vector<::prometheus::MetricFamily> TranslateToPrometheus( + const std::vector &records); + +private: + /** + * Set value to metric family according to record + */ + static void SetMetricFamily(metric_sdk::Record &record, + ::prometheus::MetricFamily *metric_family); + + /** + * Sanitize the given metric name or label according to Prometheus rule. + * + * This function is needed because names in OpenTelemetry can contain + * alphanumeric characters, '_', '.', and '-', whereas in Prometheus the + * name should only contain alphanumeric characters and '_'. + */ + static std::string SanitizeNames(std::string name); + + /** + * Set value to metric family for different aggregator + */ + template + static void SetMetricFamilyByAggregator(std::shared_ptr> aggregator, + std::string labels_str, + ::prometheus::MetricFamily *metric_family); + + /** + * Translate the OTel metric type to Prometheus metric type + */ + static ::prometheus::MetricType TranslateType(metric_sdk::AggregatorKind kind); + + /** + * Set metric data for: + * Counter => Prometheus Counter + * Gauge => Prometheus Gauge + */ + template + static void SetData(std::vector values, + const std::string &labels, + ::prometheus::MetricType type, + std::chrono::nanoseconds time, + ::prometheus::MetricFamily *metric_family); + + /** + * Set metric data for: + * Histogram => Prometheus Histogram + */ + template + static void SetData(std::vector values, + const std::vector &boundaries, + const std::vector &counts, + const std::string &labels, + std::chrono::nanoseconds time, + ::prometheus::MetricFamily *metric_family); + + /** + * Set metric data for: + * MinMaxSumCount => Prometheus Gauge + * Use Average (sum / count) as the gauge metric + */ + static void SetData(double value, + const std::string &labels, + std::chrono::nanoseconds time, + ::prometheus::MetricFamily *metric_family); + + /** + * Set metric data for: + * Exact => Prometheus Summary + * Sketch => Prometheus Summary + */ + template + static void SetData(std::vector values, + metric_sdk::AggregatorKind kind, + const std::vector &quantiles, + const std::string &labels, + std::chrono::nanoseconds time, + ::prometheus::MetricFamily *metric_family, + bool do_quantile, + std::vector quantile_points); + + /** + * Set time and labels to metric data + */ + static void SetMetricBasic(::prometheus::ClientMetric &metric, + std::chrono::nanoseconds time, + const std::string &labels); + + /** + * Parse a string of labels (key:value) into a vector of pairs + * {,} + * {l1:v1,l2:v2,...,} + */ + static std::vector> ParseLabel(std::string labels); + + /** + * Build a quantiles vector from aggregator + */ + template + static std::vector GetQuantilesVector(std::shared_ptr> aggregator, + const std::vector &quantile_points); + + /** + * Handle Counter and Gauge. + */ + template + static void SetValue(std::vector values, + ::prometheus::MetricType type, + ::prometheus::ClientMetric *metric); + + /** + * Handle Gauge from MinMaxSumCount + */ + static void SetValue(double value, ::prometheus::ClientMetric *metric); + + /** + * Handle Histogram + */ + template + static void SetValue(std::vector values, + std::vector boundaries, + std::vector counts, + ::prometheus::ClientMetric *metric); + + /** + * Handle Exact and Sketch + */ + template + static void SetValue(std::vector values, + metric_sdk::AggregatorKind kind, + std::vector quantiles, + ::prometheus::ClientMetric *metric, + bool do_quantile, + const std::vector &quantile_points); +}; +} // namespace prometheus +} // namespace exporter +OPENTELEMETRY_END_NAMESPACE diff --git a/exporters/prometheus/src/prometheus_exporter_utils.cc b/exporters/prometheus/src/prometheus_exporter_utils.cc new file mode 100644 index 0000000000..de2a233fa8 --- /dev/null +++ b/exporters/prometheus/src/prometheus_exporter_utils.cc @@ -0,0 +1,459 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "opentelemetry/exporters/prometheus/prometheus_exporter_utils.h" +#include "opentelemetry/sdk/metrics/aggregator/aggregator.h" +#include "prometheus/metric_type.h" + +namespace prometheus_client = ::prometheus; + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace exporter +{ +namespace prometheus +{ +/** + * Helper function to convert OpenTelemetry metrics data collection + * to Prometheus metrics data collection + * + * @param records a collection of metrics in OpenTelemetry + * @return a collection of translated metrics that is acceptable by Prometheus + */ +std::vector PrometheusExporterUtils::TranslateToPrometheus( + const std::vector &records) +{ + if (records.empty()) + { + return {}; + } + + // initialize output vector + std::vector output(records.size()); + + // iterate through the vector and set result data into it + int i = 0; + for (auto r : records) + { + SetMetricFamily(r, &output[i]); + i++; + } + + return output; +} + +// ======================= private helper functions ========================= +/** + * Set value to metric family according to record + */ +void PrometheusExporterUtils::SetMetricFamily(metric_sdk::Record &record, + prometheus_client::MetricFamily *metric_family) +{ + + auto origin_name = record.GetName(); + auto sanitized = SanitizeNames(origin_name); + metric_family->name = sanitized; + metric_family->help = record.GetDescription(); + + // unpack the variant and set the metric data to metric family struct + auto agg_var = record.GetAggregator(); + auto labels_str = record.GetLabels(); + if (nostd::holds_alternative>>(agg_var)) + { + auto aggregator = nostd::get>>(agg_var); + SetMetricFamilyByAggregator(aggregator, labels_str, metric_family); + } + else if (nostd::holds_alternative>>(agg_var)) + { + auto aggregator = nostd::get>>(agg_var); + SetMetricFamilyByAggregator(aggregator, labels_str, metric_family); + } + else if (nostd::holds_alternative>>( + record.GetAggregator())) + { + auto aggregator = nostd::get>>(agg_var); + SetMetricFamilyByAggregator(aggregator, labels_str, metric_family); + } + else if (nostd::holds_alternative>>( + record.GetAggregator())) + { + auto aggregator = nostd::get>>(agg_var); + SetMetricFamilyByAggregator(aggregator, labels_str, metric_family); + } +} + +/** + * Sanitize the given metric name or label according to Prometheus rule. + * + * This function is needed because names in OpenTelemetry can contain + * alphanumeric characters, '_', '.', and '-', whereas in Prometheus the + * name should only contain alphanumeric characters and '_'. + */ +std::string PrometheusExporterUtils::SanitizeNames(std::string name) +{ + // replace all '.' and '-' with '_' + std::replace(name.begin(), name.end(), '.', '_'); + std::replace(name.begin(), name.end(), '-', '_'); + + return name; +} + +/** + * Set value to metric family for different aggregator + */ +template +void PrometheusExporterUtils::SetMetricFamilyByAggregator( + std::shared_ptr> aggregator, + std::string labels_str, + prometheus_client::MetricFamily *metric_family) +{ + // get aggregator kind and translate to Prometheus metric type + auto kind = aggregator->get_aggregator_kind(); + const prometheus_client::MetricType type = TranslateType(kind); + metric_family->type = type; + // get check-pointed values, label string and check-pointed time + auto checkpointed_values = aggregator->get_checkpoint(); + auto time = aggregator->get_checkpoint_timestamp().time_since_epoch(); + + if (type == prometheus_client::MetricType::Histogram) // Histogram + { + auto boundaries = aggregator->get_boundaries(); + auto counts = aggregator->get_counts(); + SetData(checkpointed_values, boundaries, counts, labels_str, time, metric_family); + } + else if (type == prometheus_client::MetricType::Summary) // Sketch, Exact + { + std::vector quantile_points = {0, 0.5, 0.9, 0.95, 0.99, 1}; + if (kind == metric_sdk::AggregatorKind::Exact) + { + std::vector quantiles; + bool do_quantile = aggregator->get_quant_estimation(); + if (do_quantile) + { + quantiles = GetQuantilesVector(aggregator, quantile_points); + } + SetData(checkpointed_values, kind, quantiles, labels_str, time, metric_family, do_quantile, + quantile_points); + } + else if (kind == metric_sdk::AggregatorKind::Sketch) + { + auto quantiles = GetQuantilesVector(aggregator, quantile_points); + SetData(checkpointed_values, kind, quantiles, labels_str, time, metric_family, true, + quantile_points); + } + } + else // Counter, Gauge, MinMaxSumCount, Untyped + { + // Handle MinMaxSumCount: https://github.com/open-telemetry/opentelemetry-cpp/issues/228 + // Use sum/count is ok. + if (kind == metric_sdk::AggregatorKind::MinMaxSumCount) + { + double avg = (double)checkpointed_values[2] / checkpointed_values[3]; + SetData(avg, labels_str, time, metric_family); + } + else + { + SetData(checkpointed_values, labels_str, type, time, metric_family); + } + } +} + +/** + * Translate the OTel metric type to Prometheus metric type + */ +prometheus_client::MetricType PrometheusExporterUtils::TranslateType( + metric_sdk::AggregatorKind kind) +{ + switch (kind) + { + case metric_sdk::AggregatorKind::Counter: + return prometheus_client::MetricType::Counter; + case metric_sdk::AggregatorKind::Gauge: + case metric_sdk::AggregatorKind::MinMaxSumCount: + return prometheus_client::MetricType::Gauge; + case metric_sdk::AggregatorKind::Histogram: + return prometheus_client::MetricType::Histogram; + case metric_sdk::AggregatorKind::Sketch: + case metric_sdk::AggregatorKind::Exact: + return prometheus_client::MetricType::Summary; + default: + return prometheus_client::MetricType::Untyped; + } +} + +/** + * Set metric data for: + * Counter => Prometheus Counter + * Gauge => Prometheus Gauge + */ +template +void PrometheusExporterUtils::SetData(std::vector values, + const std::string &labels, + prometheus_client::MetricType type, + std::chrono::nanoseconds time, + prometheus_client::MetricFamily *metric_family) +{ + metric_family->metric.emplace_back(); + prometheus_client::ClientMetric &metric = metric_family->metric.back(); + SetMetricBasic(metric, time, labels); + SetValue(values, type, &metric); +} + +/** + * Set metric data for: + * Histogram => Prometheus Histogram + */ +template +void PrometheusExporterUtils::SetData(std::vector values, + const std::vector &boundaries, + const std::vector &counts, + const std::string &labels, + std::chrono::nanoseconds time, + prometheus_client::MetricFamily *metric_family) +{ + metric_family->metric.emplace_back(); + prometheus_client::ClientMetric &metric = metric_family->metric.back(); + SetMetricBasic(metric, time, labels); + SetValue(values, boundaries, counts, &metric); +} + +/** + * Set metric data for: + * MinMaxSumCount => Prometheus Gauge + * Use Average (sum / count) as the gauge metric + */ +void PrometheusExporterUtils::SetData(double value, + const std::string &labels, + std::chrono::nanoseconds time, + prometheus_client::MetricFamily *metric_family) +{ + metric_family->metric.emplace_back(); + prometheus_client::ClientMetric &metric = metric_family->metric.back(); + SetMetricBasic(metric, time, labels); + SetValue(value, &metric); +} + +/** + * Set metric data for: + * Exact => Prometheus Summary + * Sketch => Prometheus Summary + */ +template +void PrometheusExporterUtils::SetData(std::vector values, + metric_sdk::AggregatorKind kind, + const std::vector &quantiles, + const std::string &labels, + std::chrono::nanoseconds time, + prometheus_client::MetricFamily *metric_family, + bool do_quantile, + std::vector quantile_points) +{ + metric_family->metric.emplace_back(); + prometheus_client::ClientMetric &metric = metric_family->metric.back(); + SetMetricBasic(metric, time, labels); + SetValue(values, kind, quantiles, &metric, do_quantile, quantile_points); +} + +/** + * Set time and labels to metric data + */ +void PrometheusExporterUtils::SetMetricBasic(prometheus_client::ClientMetric &metric, + std::chrono::nanoseconds time, + const std::string &labels) +{ + metric.timestamp_ms = time.count() / 1000000; + + auto label_pairs = ParseLabel(labels); + if (!label_pairs.empty()) + { + metric.label.resize(label_pairs.size()); + for (int i = 0; i < label_pairs.size(); ++i) + { + auto origin_name = label_pairs[i].first; + auto sanitized = SanitizeNames(origin_name); + metric.label[i].name = sanitized; + metric.label[i].value = label_pairs[i].second; + } + } +}; + +/** + * Parse a string of labels (key:value) into a vector of pairs + * {,} + * {l1:v1,l2:v2,...,} + */ +std::vector> PrometheusExporterUtils::ParseLabel( + std::string labels) +{ + labels = labels.substr(1, labels.size() - 2); + + std::vector paired_labels; + std::stringstream s_stream(labels); + while (s_stream.good()) + { + std::string substr; + getline(s_stream, substr, ','); // get first string delimited by comma + if (!substr.empty()) + { + paired_labels.push_back(substr); + } + } + + std::vector> result; + for (auto &paired : paired_labels) + { + std::size_t split_index = paired.find(':'); + std::string label = paired.substr(0, split_index); + std::string value = paired.substr(split_index + 1); + result.emplace_back(std::pair(label, value)); + } + + return result; +} + +/** + * Build a quantiles vector from aggregator + */ +template +std::vector PrometheusExporterUtils::GetQuantilesVector( + std::shared_ptr> aggregator, + const std::vector &quantile_points) +{ + std::vector quantiles; + for (double q : quantile_points) + { + T quantile = aggregator->get_quantiles(q); + quantiles.emplace_back(quantile); + } + return quantiles; +} + +/** + * Handle Counter and Gauge. + */ +template +void PrometheusExporterUtils::SetValue(std::vector values, + prometheus_client::MetricType type, + prometheus_client::ClientMetric *metric) +{ + switch (type) + { + case prometheus_client::MetricType::Counter: + { + metric->counter.value = values[0]; + break; + } + case prometheus_client::MetricType::Gauge: + { + metric->gauge.value = values[0]; + break; + } + case prometheus_client::MetricType::Untyped: + { + metric->untyped.value = values[0]; + break; + } + default: + return; + } +} + +/** + * Handle Gauge from MinMaxSumCount + */ +void PrometheusExporterUtils::SetValue(double value, prometheus_client::ClientMetric *metric) +{ + metric->gauge.value = value; +} + +/** + * Handle Histogram + */ +template +void PrometheusExporterUtils::SetValue(std::vector values, + std::vector boundaries, + std::vector counts, + prometheus_client::ClientMetric *metric) +{ + metric->histogram.sample_sum = values[0]; + metric->histogram.sample_count = values[1]; + int cumulative = 0; + std::vector buckets; + for (int i = 0; i < boundaries.size() + 1; i++) + { + prometheus_client::ClientMetric::Bucket bucket; + cumulative += counts[i]; + bucket.cumulative_count = cumulative; + if (i != boundaries.size()) + { + bucket.upper_bound = boundaries[i]; + } + else + { + bucket.upper_bound = std::numeric_limits::infinity(); + } + buckets.emplace_back(bucket); + } + metric->histogram.bucket = buckets; +} + +/** + * Handle Exact and Sketch + */ +template +void PrometheusExporterUtils::SetValue(std::vector values, + metric_sdk::AggregatorKind kind, + std::vector quantiles, + prometheus_client::ClientMetric *metric, + bool do_quantile, + const std::vector &quantile_points) +{ + if (kind == metric_sdk::AggregatorKind::Exact) + { + metric->summary.sample_count = values.size(); + auto sum = 0; + for (auto val : values) + { + sum += val; + } + metric->summary.sample_sum = sum; + } + else if (kind == metric_sdk::AggregatorKind::Sketch) + { + metric->summary.sample_sum = values[0]; + metric->summary.sample_count = values[1]; + } + + if (do_quantile) + { + std::vector prometheus_quantiles; + for (int i = 0; i < quantiles.size(); i++) + { + prometheus_client::ClientMetric::Quantile quantile; + quantile.quantile = quantile_points[i]; + quantile.value = quantiles[i]; + prometheus_quantiles.emplace_back(quantile); + } + metric->summary.quantile = prometheus_quantiles; + } +} +} // namespace prometheus +} // namespace exporter +OPENTELEMETRY_END_NAMESPACE diff --git a/exporters/prometheus/test/CMakeLists.txt b/exporters/prometheus/test/CMakeLists.txt new file mode 100644 index 0000000000..a42feed797 --- /dev/null +++ b/exporters/prometheus/test/CMakeLists.txt @@ -0,0 +1,8 @@ +foreach(testname prometheus_exporter_utils_test) + add_executable(${testname} "${testname}.cc") + target_link_libraries( + ${testname} ${GTEST_BOTH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} + prometheus_exporter prometheus-cpp::pull) + gtest_add_tests(TARGET ${testname} TEST_PREFIX exporter. TEST_LIST + ${testname}) +endforeach() diff --git a/exporters/prometheus/test/prometheus_exporter_utils_test.cc b/exporters/prometheus/test/prometheus_exporter_utils_test.cc new file mode 100644 index 0000000000..ed8f921265 --- /dev/null +++ b/exporters/prometheus/test/prometheus_exporter_utils_test.cc @@ -0,0 +1,475 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include +#include +#include "opentelemetry/exporters/prometheus/prometheus_exporter_utils.h" +#include "opentelemetry/sdk/metrics/aggregator/counter_aggregator.h" +#include "opentelemetry/sdk/metrics/aggregator/exact_aggregator.h" +#include "opentelemetry/sdk/metrics/aggregator/gauge_aggregator.h" +#include "opentelemetry/sdk/metrics/aggregator/histogram_aggregator.h" +#include "opentelemetry/sdk/metrics/aggregator/min_max_sum_count_aggregator.h" +#include "opentelemetry/sdk/metrics/aggregator/sketch_aggregator.h" + +using opentelemetry::exporter::prometheus::PrometheusExporterUtils; +namespace metric_sdk = opentelemetry::sdk::metrics; +namespace metric_api = opentelemetry::metrics; +namespace prometheus_client = ::prometheus; + +OPENTELEMETRY_BEGIN_NAMESPACE +template +void assert_basic(prometheus_client::MetricFamily &metric, + const std::string &sanitized_name, + const std::string &description, + prometheus_client::MetricType type, + int label_num, + std::vector vals) +{ + ASSERT_EQ(metric.name, sanitized_name); // name sanitized + ASSERT_EQ(metric.help, description); // description not changed + ASSERT_EQ(metric.type, type); // type translated + + auto metric_data = metric.metric[0]; + ASSERT_EQ(metric_data.label.size(), label_num); + + switch (type) + { + case prometheus_client::MetricType::Counter: + { + ASSERT_DOUBLE_EQ(metric_data.counter.value, vals[0]); + break; + } + case prometheus_client::MetricType::Gauge: + { + ASSERT_EQ(metric_data.gauge.value, vals[0]); + break; + } + case prometheus_client::MetricType::Histogram: + { + ASSERT_DOUBLE_EQ(metric_data.histogram.sample_count, vals[0]); + ASSERT_DOUBLE_EQ(metric_data.histogram.sample_sum, vals[1]); + auto buckets = metric_data.histogram.bucket; + ASSERT_EQ(buckets.size(), vals[2]); + break; + } + case prometheus_client::MetricType::Summary: + { + ASSERT_DOUBLE_EQ(metric_data.summary.sample_count, vals[0]); + ASSERT_DOUBLE_EQ(metric_data.summary.sample_sum, vals[1]); + break; + } + case prometheus::MetricType::Untyped: + break; + } +} + +void assert_histogram(prometheus_client::MetricFamily &metric, + std::vector boundaries, + std::vector correct) +{ + int cumulative_count = 0; + auto buckets = metric.metric[0].histogram.bucket; + for (int i = 0; i < buckets.size(); i++) + { + auto bucket = buckets[i]; + if (i != buckets.size() - 1) + { + ASSERT_DOUBLE_EQ(boundaries[i], bucket.upper_bound); + } + else + { + ASSERT_DOUBLE_EQ(std::numeric_limits::infinity(), bucket.upper_bound); + } + cumulative_count += correct[i]; + ASSERT_EQ(cumulative_count, bucket.cumulative_count); + } +} + +template +metric_sdk::Record get_record(const std::string &type, + int version, + const std::string &label, + std::shared_ptr> aggregator) +{ + std::string name = "test-" + type + "-metric-record-v_" + std::to_string(version) + ".0"; + std::string desc = "this is a test " + type + " metric record"; + metric_sdk::Record record(name, desc, label, aggregator); + return record; +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusEmptyInputReturnsEmptyCollection) +{ + std::vector collection; + auto translated2 = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated2.size(), 0); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusIntegerCounter) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::CounterAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + + auto record1 = get_record("int-counter", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + aggregator->update(10); + aggregator->checkpoint(); + collection.emplace_back(record1); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {10}; + assert_basic(metric1, "test_int_counter_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Counter, 3, vals); + + auto record2 = get_record("int-counter", 2, "{,}", aggregator); + aggregator->update(20); + aggregator->update(30); + aggregator->checkpoint(); + collection.emplace_back(record2); + + translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric2 = translated[1]; + vals = {50}; + assert_basic(metric2, "test_int_counter_metric_record_v_2_0", record2.GetDescription(), + prometheus_client::MetricType::Counter, 0, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusDoubleCounter) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::CounterAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + aggregator->update(10.5); + aggregator->checkpoint(); + auto record1 = get_record("double-counter", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + aggregator->update(22.4); + aggregator->update(31.2); + aggregator->checkpoint(); + auto record2 = get_record("double-counter", 2, "{,}", aggregator); + collection.emplace_back(record1); + collection.emplace_back(record2); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {53.6}; + assert_basic(metric1, "test_double_counter_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Counter, 3, vals); + auto metric2 = translated[1]; + assert_basic(metric2, "test_double_counter_metric_record_v_2_0", record2.GetDescription(), + prometheus_client::MetricType::Counter, 0, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusShortCounter) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::CounterAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + aggregator->update(10); + aggregator->checkpoint(); + auto record1 = get_record("short-counter", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + aggregator->update(20); + aggregator->update(30); + aggregator->checkpoint(); + auto record2 = get_record("short-counter", 2, "{,}", aggregator); + collection.emplace_back(record1); + collection.emplace_back(record2); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {50}; + assert_basic(metric1, "test_short_counter_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Counter, 3, vals); + auto metric2 = translated[1]; + assert_basic(metric2, "test_short_counter_metric_record_v_2_0", record2.GetDescription(), + prometheus_client::MetricType::Counter, 0, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusFloatCounter) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::CounterAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + aggregator->update(10.5f); + aggregator->checkpoint(); + auto record1 = get_record("float-counter", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + aggregator->update(22.4f); + aggregator->update(31.2f); + aggregator->checkpoint(); + auto record2 = get_record("float-counter", 2, "{,}", aggregator); + collection.emplace_back(record1); + collection.emplace_back(record2); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {53.6f}; + assert_basic(metric1, "test_float_counter_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Counter, 3, vals); + auto metric2 = translated[1]; + assert_basic(metric2, "test_float_counter_metric_record_v_2_0", record2.GetDescription(), + prometheus_client::MetricType::Counter, 0, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusGauge) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::GaugeAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + aggregator->update(10); + aggregator->checkpoint(); + auto record1 = get_record("gauge", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + aggregator->update(20); + aggregator->update(30); + aggregator->checkpoint(); + auto record2 = get_record("gauge", 2, "{,}", aggregator); + collection.emplace_back(record1); + collection.emplace_back(record2); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {30}; + assert_basic(metric1, "test_gauge_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Gauge, 3, vals); + auto metric2 = translated[1]; + assert_basic(metric2, "test_gauge_metric_record_v_2_0", record2.GetDescription(), + prometheus_client::MetricType::Gauge, 0, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusHistogramUniform) +{ + std::vector boundaries{10, 20, 30, 40, 50}; + auto aggregator = std::shared_ptr>( + new metric_sdk::HistogramAggregator(metric_api::InstrumentKind::Counter, boundaries)); + + std::vector collection; + auto record = get_record("histogram-uniform", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + int count_num = 60; + for (int i = 0; i < count_num; i++) + { + aggregator->update(i); + } + aggregator->checkpoint(); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + std::vector vals = {aggregator->get_checkpoint()[1], aggregator->get_checkpoint()[0], + (int)boundaries.size() + 1}; + assert_basic(metric, "test_histogram_uniform_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Histogram, 3, vals); + std::vector correct = aggregator->get_counts(); + assert_histogram(metric, boundaries, correct); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusHistogramNormal) +{ + std::vector boundaries{2, 4, 6, 8, 10, 12}; + auto aggregator = std::shared_ptr>( + new metric_sdk::HistogramAggregator(metric_api::InstrumentKind::Counter, boundaries)); + + std::vector collection; + auto record = get_record("histogram-normal", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + std::vector values{1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 11, 11, 13}; + for (int i : values) + { + aggregator->update(i); + } + aggregator->checkpoint(); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + std::vector vals = {aggregator->get_checkpoint()[1], aggregator->get_checkpoint()[0], + (int)boundaries.size() + 1}; + assert_basic(metric, "test_histogram_normal_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Histogram, 3, vals); + std::vector correct = aggregator->get_counts(); + assert_histogram(metric, boundaries, correct); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusExact) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::ExactAggregator(metric_api::InstrumentKind::Counter, true)); + + std::vector collection; + int count_num = 100; + for (int i = 0; i <= count_num; i++) + { + aggregator->update(i); + } + aggregator->checkpoint(); + auto record = get_record("exact", 1, "{label-1:v1,label_2:v2,label3:v3,}", aggregator); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + std::vector vals = {101, 5050}; + assert_basic(metric, "test_exact_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Summary, 3, vals); + auto quantile = metric.metric[0].summary.quantile; + ASSERT_EQ(quantile.size(), 6); + ASSERT_DOUBLE_EQ(quantile[0].value, 0); + ASSERT_DOUBLE_EQ(quantile[1].value, 50); + ASSERT_DOUBLE_EQ(quantile[2].value, 90); + ASSERT_DOUBLE_EQ(quantile[3].value, 95); + ASSERT_DOUBLE_EQ(quantile[4].value, 99); + ASSERT_DOUBLE_EQ(quantile[5].value, 100); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusExactNoQuantile) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::ExactAggregator(metric_api::InstrumentKind::Counter, false)); + + std::vector collection; + int count_num = 10; + for (int i = 0; i < count_num; i++) + { + aggregator->update(i); + } + aggregator->checkpoint(); + auto record = get_record("exact-no-quantile", 1, "{label1:v1,label2:v2,}", aggregator); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + std::vector vals = {count_num, 45}; + assert_basic(metric, "test_exact_no_quantile_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Summary, 2, vals); + auto quantile = metric.metric[0].summary.quantile; + ASSERT_EQ(quantile.size(), 0); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusMinMaxSumCount) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::MinMaxSumCountAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + // min: 1, max: 10, sum: 55, count: 10 + for (int i = 1; i <= 10; i++) + { + aggregator->update(i); + } + aggregator->checkpoint(); + auto record = get_record("mmsc", 1, "{label1:v1,label2:v2,label3:v3,}", aggregator); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + // in this version of implementation, we use the sum/count as a gauge + std::vector vals = {5.5}; + assert_basic(metric, "test_mmsc_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Gauge, 3, vals); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusSketch) +{ + auto aggregator = std::shared_ptr>( + new metric_sdk::SketchAggregator(metric_api::InstrumentKind::Counter, 0.0005)); + + std::vector collection; + for (int i = 0; i <= 100; i++) + { + aggregator->update(i); + } + aggregator->checkpoint(); + auto record = get_record("sketch", 1, "{label1:v1,label2:v2,}", aggregator); + collection.emplace_back(record); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric = translated[0]; + std::vector vals = {aggregator->get_checkpoint()[1], aggregator->get_checkpoint()[0]}; + assert_basic(metric, "test_sketch_metric_record_v_1_0", record.GetDescription(), + prometheus_client::MetricType::Summary, 2, vals); + + auto quantile = metric.metric[0].summary.quantile; + ASSERT_EQ(quantile.size(), 6); + ASSERT_DOUBLE_EQ(quantile[0].value, 0); + ASSERT_DOUBLE_EQ(quantile[1].value, 49); + ASSERT_DOUBLE_EQ(quantile[2].value, 89); + ASSERT_DOUBLE_EQ(quantile[3].value, 94); + ASSERT_DOUBLE_EQ(quantile[4].value, 98); + ASSERT_DOUBLE_EQ(quantile[5].value, 99); +} + +TEST(PrometheusExporterUtils, TranslateToPrometheusMultipleAggregators) +{ + auto counter_aggregator = std::shared_ptr>( + new metric_sdk::CounterAggregator(metric_api::InstrumentKind::Counter)); + auto gauge_aggregator = std::shared_ptr>( + new metric_sdk::GaugeAggregator(metric_api::InstrumentKind::Counter)); + + std::vector collection; + counter_aggregator->update(10); + counter_aggregator->update(20); + counter_aggregator->checkpoint(); + auto record1 = get_record("counter", 1, "{label1:v1,label2:v2,label3:v3,}", counter_aggregator); + gauge_aggregator->update(10); + gauge_aggregator->update(30); + gauge_aggregator->update(20); + gauge_aggregator->checkpoint(); + auto record2 = get_record("gauge", 1, "{label1:v1,}", gauge_aggregator); + collection.emplace_back(record1); + collection.emplace_back(record2); + + auto translated = PrometheusExporterUtils::TranslateToPrometheus(collection); + ASSERT_EQ(translated.size(), collection.size()); + + auto metric1 = translated[0]; + std::vector vals = {30}; + assert_basic(metric1, "test_counter_metric_record_v_1_0", record1.GetDescription(), + prometheus_client::MetricType::Counter, 3, vals); + auto metric2 = translated[1]; + vals = {20}; + assert_basic(metric2, "test_gauge_metric_record_v_1_0", record2.GetDescription(), + prometheus_client::MetricType::Gauge, 1, vals); +} +OPENTELEMETRY_END_NAMESPACE