|
| 1 | +# Copyright 2020, OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Prometheus Metrics Exporter for OpenTelemetry.""" |
| 16 | + |
| 17 | +import collections |
| 18 | +import logging |
| 19 | +import re |
| 20 | +from typing import Sequence |
| 21 | + |
| 22 | +from prometheus_client import start_http_server |
| 23 | +from prometheus_client.core import ( |
| 24 | + REGISTRY, |
| 25 | + CollectorRegistry, |
| 26 | + CounterMetricFamily, |
| 27 | + GaugeMetricFamily, |
| 28 | + UnknownMetricFamily, |
| 29 | +) |
| 30 | + |
| 31 | +from opentelemetry.metrics import Counter, Gauge, Measure, Metric |
| 32 | +from opentelemetry.sdk.metrics.export import ( |
| 33 | + MetricRecord, |
| 34 | + MetricsExporter, |
| 35 | + MetricsExportResult, |
| 36 | +) |
| 37 | + |
| 38 | +logger = logging.getLogger(__name__) |
| 39 | + |
| 40 | + |
| 41 | +class PrometheusMetricsExporter(MetricsExporter): |
| 42 | + """Prometheus metric exporter for OpenTelemetry. |
| 43 | +
|
| 44 | + Args: |
| 45 | + prefix: single-word application prefix relevant to the domain |
| 46 | + the metric belongs to. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, prefix: str = ""): |
| 50 | + self._collector = CustomCollector(prefix) |
| 51 | + REGISTRY.register(self._collector) |
| 52 | + |
| 53 | + def export( |
| 54 | + self, metric_records: Sequence[MetricRecord] |
| 55 | + ) -> MetricsExportResult: |
| 56 | + self._collector.add_metrics_data(metric_records) |
| 57 | + return MetricsExportResult.SUCCESS |
| 58 | + |
| 59 | + def shutdown(self) -> None: |
| 60 | + REGISTRY.unregister(self._collector) |
| 61 | + |
| 62 | + |
| 63 | +class CustomCollector: |
| 64 | + """ CustomCollector represents the Prometheus Collector object |
| 65 | + https://github.com/prometheus/client_python#custom-collectors |
| 66 | + """ |
| 67 | + |
| 68 | + def __init__(self, prefix: str = ""): |
| 69 | + self._prefix = prefix |
| 70 | + self._metrics_to_export = collections.deque() |
| 71 | + self._non_letters_nor_digits_re = re.compile( |
| 72 | + r"[^\w]", re.UNICODE | re.IGNORECASE |
| 73 | + ) |
| 74 | + |
| 75 | + def add_metrics_data(self, metric_records: Sequence[MetricRecord]): |
| 76 | + self._metrics_to_export.append(metric_records) |
| 77 | + |
| 78 | + def collect(self): |
| 79 | + """Collect fetches the metrics from OpenTelemetry |
| 80 | + and delivers them as Prometheus Metrics. |
| 81 | + Collect is invoked every time a prometheus.Gatherer is run |
| 82 | + for example when the HTTP endpoint is invoked by Prometheus. |
| 83 | + """ |
| 84 | + |
| 85 | + while self._metrics_to_export: |
| 86 | + for metric_record in self._metrics_to_export.popleft(): |
| 87 | + prometheus_metric = self._translate_to_prometheus( |
| 88 | + metric_record |
| 89 | + ) |
| 90 | + if prometheus_metric is not None: |
| 91 | + yield prometheus_metric |
| 92 | + |
| 93 | + def _translate_to_prometheus(self, metric_record: MetricRecord): |
| 94 | + prometheus_metric = None |
| 95 | + label_values = [] |
| 96 | + label_keys = [] |
| 97 | + for label_tuple in metric_record.label_set.labels: |
| 98 | + label_keys.append(self._sanitize(label_tuple[0])) |
| 99 | + label_values.append(label_tuple[1]) |
| 100 | + |
| 101 | + metric_name = "" |
| 102 | + if self._prefix != "": |
| 103 | + metric_name = self._prefix + "_" |
| 104 | + metric_name += self._sanitize(metric_record.metric.name) |
| 105 | + |
| 106 | + if isinstance(metric_record.metric, Counter): |
| 107 | + prometheus_metric = CounterMetricFamily( |
| 108 | + name=metric_name, |
| 109 | + documentation=metric_record.metric.description, |
| 110 | + labels=label_keys, |
| 111 | + ) |
| 112 | + prometheus_metric.add_metric( |
| 113 | + labels=label_values, value=metric_record.aggregator.checkpoint |
| 114 | + ) |
| 115 | + |
| 116 | + elif isinstance(metric_record.metric, Gauge): |
| 117 | + prometheus_metric = GaugeMetricFamily( |
| 118 | + name=metric_name, |
| 119 | + documentation=metric_record.metric.description, |
| 120 | + labels=label_keys, |
| 121 | + ) |
| 122 | + prometheus_metric.add_metric( |
| 123 | + labels=label_values, value=metric_record.aggregator.checkpoint |
| 124 | + ) |
| 125 | + |
| 126 | + # TODO: Add support for histograms when supported in OT |
| 127 | + elif isinstance(metric_record.metric, Measure): |
| 128 | + prometheus_metric = UnknownMetricFamily( |
| 129 | + name=metric_name, |
| 130 | + documentation=metric_record.metric.description, |
| 131 | + labels=label_keys, |
| 132 | + ) |
| 133 | + prometheus_metric.add_metric( |
| 134 | + labels=label_values, value=metric_record.aggregator.checkpoint |
| 135 | + ) |
| 136 | + |
| 137 | + else: |
| 138 | + logger.warning( |
| 139 | + "Unsupported metric type. %s", type(metric_record.metric) |
| 140 | + ) |
| 141 | + return prometheus_metric |
| 142 | + |
| 143 | + def _sanitize(self, key): |
| 144 | + """ sanitize the given metric name or label according to Prometheus rule. |
| 145 | + Replace all characters other than [A-Za-z0-9_] with '_'. |
| 146 | + """ |
| 147 | + return self._non_letters_nor_digits_re.sub("_", key) |
0 commit comments