1#![warn(
91 future_incompatible,
92 missing_debug_implementations,
93 missing_docs,
94 nonstandard_style,
95 rust_2018_idioms,
96 unreachable_pub,
97 unused
98)]
99#![cfg_attr(
100 docsrs,
101 feature(doc_cfg, doc_auto_cfg),
102 deny(rustdoc::broken_intra_doc_links)
103)]
104#![doc(
105 html_logo_url = "https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo.svg"
106)]
107#![cfg_attr(test, deny(warnings))]
108
109use once_cell::sync::OnceCell;
110use opentelemetry::{otel_error, otel_warn, InstrumentationScope, Key, Value};
111use opentelemetry_sdk::{
112 error::OTelSdkResult,
113 metrics::{
114 data::{self, ResourceMetrics},
115 reader::MetricReader,
116 InstrumentKind, ManualReader, Pipeline, Temporality,
117 },
118 Resource,
119};
120use prometheus::{
121 core::Desc,
122 proto::{LabelPair, MetricFamily, MetricType},
123};
124use std::{
125 borrow::Cow,
126 collections::{BTreeMap, HashMap},
127 sync::{Arc, Mutex},
128 time::Duration,
129};
130use std::{fmt, sync::Weak};
131
132const TARGET_INFO_NAME: &str = "target_info";
133const TARGET_INFO_DESCRIPTION: &str = "Target metadata";
134
135const SCOPE_INFO_METRIC_NAME: &str = "otel_scope_info";
136const SCOPE_INFO_DESCRIPTION: &str = "Instrumentation Scope metadata";
137
138const SCOPE_INFO_KEYS: [&str; 2] = ["otel_scope_name", "otel_scope_version"];
139
140const COUNTER_SUFFIX: &str = "_total";
143
144mod config;
145mod resource_selector;
146mod utils;
147
148pub use config::ExporterBuilder;
149pub use resource_selector::ResourceSelector;
150
151pub fn exporter() -> ExporterBuilder {
153 ExporterBuilder::default()
154}
155
156#[derive(Debug)]
158pub struct PrometheusExporter {
159 reader: Arc<ManualReader>,
160}
161
162impl MetricReader for PrometheusExporter {
163 fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
164 self.reader.register_pipeline(pipeline)
165 }
166
167 fn collect(&self, rm: &mut ResourceMetrics) -> OTelSdkResult {
168 self.reader.collect(rm)
169 }
170
171 fn force_flush(&self) -> OTelSdkResult {
172 self.reader.force_flush()
173 }
174
175 fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {
176 self.reader.shutdown_with_timeout(timeout)
177 }
178
179 fn temporality(&self, _kind: InstrumentKind) -> Temporality {
182 Temporality::Cumulative
183 }
184}
185
186struct Collector {
187 reader: Arc<ManualReader>,
188 disable_target_info: bool,
189 without_units: bool,
190 without_counter_suffixes: bool,
191 disable_scope_info: bool,
192 create_target_info_once: OnceCell<MetricFamily>,
193 resource_labels_once: OnceCell<Vec<LabelPair>>,
194 namespace: Option<String>,
195 inner: Mutex<CollectorInner>,
196 resource_selector: ResourceSelector,
197}
198
199#[derive(Default)]
200struct CollectorInner {
201 scope_infos: HashMap<InstrumentationScope, MetricFamily>,
202 metric_families: HashMap<String, MetricFamily>,
203}
204
205impl Collector {
206 fn metric_type_and_name(&self, m: &data::Metric) -> Option<(MetricType, Cow<'static, str>)> {
207 let mut name = self.get_name(m);
208
209 macro_rules! extract_metric_data_type_and_name {
210 ($data:expr, $counter:tt) => {
211 match $data {
212 data::MetricData::Gauge(_) => Some((MetricType::GAUGE, name)),
213 data::MetricData::Sum(sum) => {
214 let is_monotonic = sum.is_monotonic();
215 if is_monotonic {
216 if !self.without_counter_suffixes {
217 name = format!("{name}{COUNTER_SUFFIX}").into();
218 }
219 Some((MetricType::COUNTER, name))
220 } else {
221 Some((MetricType::GAUGE, name))
222 }
223 }
224 data::MetricData::Histogram(_) => Some((MetricType::HISTOGRAM, name)),
225 data::MetricData::ExponentialHistogram(_) => {
226 Some((MetricType::HISTOGRAM, name))
227 }
228 }
229 };
230 }
231
232 match m.data() {
233 data::AggregatedMetrics::F64(data) => extract_metric_data_type_and_name!(data, self),
234 data::AggregatedMetrics::U64(data) => extract_metric_data_type_and_name!(data, self),
235 data::AggregatedMetrics::I64(data) => extract_metric_data_type_and_name!(data, self),
236 }
237 }
238
239 fn get_name(&self, m: &data::Metric) -> Cow<'static, str> {
240 let name = utils::sanitize_name(&m.name().to_string().into());
241 let unit_suffixes = if self.without_units {
242 None
243 } else {
244 utils::get_unit_suffixes(m.unit())
245 };
246 match (&self.namespace, unit_suffixes) {
247 (Some(namespace), Some(suffix)) => Cow::Owned(format!("{namespace}{name}_{suffix}")),
248 (Some(namespace), None) => Cow::Owned(format!("{namespace}{name}")),
249 (None, Some(suffix)) => Cow::Owned(format!("{name}_{suffix}")),
250 (None, None) => name,
251 }
252 }
253}
254
255impl prometheus::core::Collector for Collector {
256 fn desc(&self) -> Vec<&Desc> {
257 Vec::new()
258 }
259
260 fn collect(&self) -> Vec<MetricFamily> {
261 let mut inner = match self.inner.lock() {
262 Ok(guard) => guard,
263 Err(err) => {
264 otel_error!(
265 name: "MetricScrapeFailed",
266 message = err.to_string(),
267 );
268 return Vec::new();
269 }
270 };
271
272 let mut metrics = ResourceMetrics::default();
273 if let Err(err) = self.reader.collect(&mut metrics) {
274 otel_error!(
275 name: "MetricScrapeFailed",
276 message = err.to_string(),
277 );
278 return vec![];
279 }
280 let mut res = Vec::with_capacity(metrics.scope_metrics().collect::<Vec<_>>().len() + 1);
281
282 let target_info = self.create_target_info_once.get_or_init(|| {
283 create_info_metric(
285 TARGET_INFO_NAME,
286 TARGET_INFO_DESCRIPTION,
287 metrics.resource(),
288 )
289 });
290
291 if !self.disable_target_info && !metrics.resource().is_empty() {
292 res.push(target_info.clone())
293 }
294
295 let resource_labels = self
296 .resource_labels_once
297 .get_or_init(|| self.resource_selector.select(metrics.resource()));
298
299 for scope_metrics in metrics.scope_metrics() {
300 let scope_labels = if !self.disable_scope_info {
301 if scope_metrics.scope().attributes().count() > 0 {
302 let scope_info = inner
303 .scope_infos
304 .entry(scope_metrics.scope().clone())
305 .or_insert_with_key(create_scope_info_metric);
306 res.push(scope_info.clone());
307 }
308
309 let mut labels =
310 Vec::with_capacity(1 + scope_metrics.scope().version().is_some() as usize);
311 let mut name = LabelPair::new();
312 name.set_name(SCOPE_INFO_KEYS[0].into());
313 name.set_value(scope_metrics.scope().name().to_string());
314 labels.push(name);
315 if let Some(version) = &scope_metrics.scope().version() {
316 let mut l_version = LabelPair::new();
317 l_version.set_name(SCOPE_INFO_KEYS[1].into());
318 l_version.set_value(version.to_string());
319 labels.push(l_version);
320 }
321
322 if !resource_labels.is_empty() {
323 labels.extend(resource_labels.iter().cloned());
324 }
325 labels
326 } else {
327 Vec::new()
328 };
329
330 for metrics in scope_metrics.metrics() {
331 let (metric_type, name) = match self.metric_type_and_name(metrics) {
332 Some((metric_type, name)) => (metric_type, name),
333 _ => continue,
334 };
335
336 let mfs = &mut inner.metric_families;
337 let (drop, help) = validate_metrics(&name, metrics.description(), metric_type, mfs);
338 if drop {
339 continue;
340 }
341
342 let description = help.unwrap_or_else(|| metrics.description().into());
343
344 macro_rules! add_metric {
345 ($data:expr) => {
346 match $data {
347 data::MetricData::Gauge(gauge) => {
348 add_gauge_metric(&mut res, gauge, description, &scope_labels, name);
349 }
350 data::MetricData::Sum(sum) => {
351 add_sum_metric(&mut res, sum, description, &scope_labels, name);
352 }
353 data::MetricData::Histogram(hist) => {
354 add_histogram_metric(
355 &mut res,
356 hist,
357 description,
358 &scope_labels,
359 name,
360 );
361 }
362 data::MetricData::ExponentialHistogram(_) => {
363 }
372 }
373 };
374 }
375
376 match metrics.data() {
377 data::AggregatedMetrics::F64(data) => add_metric!(data),
378 data::AggregatedMetrics::U64(data) => add_metric!(data),
379 data::AggregatedMetrics::I64(data) => add_metric!(data),
380 }
381 }
382 }
383
384 res
385 }
386}
387
388fn get_attrs(kvs: &mut dyn Iterator<Item = (&Key, &Value)>, extra: &[LabelPair]) -> Vec<LabelPair> {
393 let mut keys_map = BTreeMap::<String, Vec<String>>::new();
394 for (key, value) in kvs {
395 let key = utils::sanitize_prom_kv(key.as_str());
396 keys_map
397 .entry(key)
398 .and_modify(|v| v.push(value.to_string()))
399 .or_insert_with(|| vec![value.to_string()]);
400 }
401
402 let mut res = Vec::with_capacity(keys_map.len() + extra.len());
403
404 for (key, mut values) in keys_map.into_iter() {
405 values.sort_unstable();
406
407 let mut lp = LabelPair::new();
408 lp.set_name(key);
409 lp.set_value(values.join(";"));
410 res.push(lp);
411 }
412
413 if !extra.is_empty() {
414 res.extend(&mut extra.iter().cloned());
415 }
416
417 res
418}
419
420fn validate_metrics(
421 name: &str,
422 description: &str,
423 metric_type: MetricType,
424 mfs: &mut HashMap<String, MetricFamily>,
425) -> (bool, Option<String>) {
426 if let Some(existing) = mfs.get(name) {
427 if existing.get_field_type() != metric_type {
428 otel_warn!(
429 name: "MetricValidationFailed",
430 message = "Instrument type conflict, using existing type definition",
431 metric_type = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_field_type(), metric_type).as_str(),
432 );
433 return (true, None);
434 }
435 if existing.help() != description {
436 otel_warn!(
437 name: "MetricValidationFailed",
438 message = "Instrument description conflict, using existing",
439 metric_description = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.help().to_string(), description.to_string()).as_str(),
440 );
441 return (false, Some(existing.help().to_string()));
442 }
443 (false, None)
444 } else {
445 let mut mf = MetricFamily::default();
446 mf.set_name(name.into());
447 mf.set_help(description.to_string());
448 mf.set_field_type(metric_type);
449 mfs.insert(name.to_string(), mf);
450
451 (false, None)
452 }
453}
454
455fn add_histogram_metric<T: Numeric>(
456 res: &mut Vec<MetricFamily>,
457 histogram: &data::Histogram<T>,
458 description: String,
459 extra: &[LabelPair],
460 name: Cow<'static, str>,
461) {
462 for dp in histogram.data_points() {
466 let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
467 let bounds_len = dp.bounds().collect::<Vec<_>>().len();
468 let bucket_counts = dp.bucket_counts().collect::<Vec<_>>();
469 let (bucket, _) = dp.bounds().enumerate().fold(
470 (Vec::with_capacity(bounds_len), 0),
471 |(mut acc, mut count), (i, bound)| {
472 count += bucket_counts[i];
473
474 let mut b = prometheus::proto::Bucket::default();
475 b.set_upper_bound(bound);
476 b.set_cumulative_count(count);
477 acc.push(b);
478 (acc, count)
479 },
480 );
481
482 let mut h = prometheus::proto::Histogram::default();
483 h.set_sample_sum(dp.sum().as_f64());
484 h.set_sample_count(dp.count());
485 h.set_bucket(bucket);
486 let mut pm = prometheus::proto::Metric::default();
487 pm.set_label(kvs);
488 pm.set_histogram(h);
489
490 let mut mf = prometheus::proto::MetricFamily::default();
491 mf.set_name(name.to_string());
492 mf.set_help(description.clone());
493 mf.set_field_type(prometheus::proto::MetricType::HISTOGRAM);
494 mf.set_metric(vec![pm]);
495 res.push(mf);
496 }
497}
498
499fn add_sum_metric<T: Numeric>(
545 res: &mut Vec<MetricFamily>,
546 sum: &data::Sum<T>,
547 description: String,
548 extra: &[LabelPair],
549 name: Cow<'static, str>,
550) {
551 let metric_type = if sum.is_monotonic() {
552 MetricType::COUNTER
553 } else {
554 MetricType::GAUGE
555 };
556
557 for dp in sum.data_points() {
558 let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
559
560 let mut pm = prometheus::proto::Metric::default();
561 pm.set_label(kvs);
562
563 if sum.is_monotonic() {
564 let mut c = prometheus::proto::Counter::default();
565 c.set_value(dp.value().as_f64());
566 pm.set_counter(c);
567 } else {
568 let mut g = prometheus::proto::Gauge::default();
569 g.set_value(dp.value().as_f64());
570 pm.set_gauge(g);
571 }
572
573 let mut mf = prometheus::proto::MetricFamily::default();
574 mf.set_name(name.to_string());
575 mf.set_help(description.clone());
576 mf.set_field_type(metric_type);
577 mf.set_metric(vec![pm]);
578 res.push(mf);
579 }
580}
581
582fn add_gauge_metric<T: Numeric>(
583 res: &mut Vec<MetricFamily>,
584 gauge: &data::Gauge<T>,
585 description: String,
586 extra: &[LabelPair],
587 name: Cow<'static, str>,
588) {
589 for dp in gauge.data_points() {
590 let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
591
592 let mut g = prometheus::proto::Gauge::default();
593 g.set_value(dp.value().as_f64());
594 let mut pm = prometheus::proto::Metric::default();
595 pm.set_label(kvs);
596 pm.set_gauge(g);
597
598 let mut mf = prometheus::proto::MetricFamily::default();
599 mf.set_name(name.to_string());
600 mf.set_help(description.to_string());
601 mf.set_field_type(MetricType::GAUGE);
602 mf.set_metric(vec![pm]);
603 res.push(mf);
604 }
605}
606
607fn create_info_metric(
608 target_info_name: &str,
609 target_info_description: &str,
610 resource: &Resource,
611) -> MetricFamily {
612 let mut g = prometheus::proto::Gauge::default();
613 g.set_value(1.0);
614
615 let mut m = prometheus::proto::Metric::default();
616 m.set_label(get_attrs(&mut resource.iter(), &[]));
617 m.set_gauge(g);
618
619 let mut mf = MetricFamily::default();
620 mf.set_name(target_info_name.into());
621 mf.set_help(target_info_description.into());
622 mf.set_field_type(MetricType::GAUGE);
623 mf.set_metric(vec![m]);
624 mf
625}
626
627fn create_scope_info_metric(scope: &InstrumentationScope) -> MetricFamily {
628 let mut g = prometheus::proto::Gauge::default();
629 g.set_value(1.0);
630
631 let mut labels = Vec::with_capacity(1 + scope.version().is_some() as usize);
632 let mut name = LabelPair::new();
633 name.set_name(SCOPE_INFO_KEYS[0].into());
634 name.set_value(scope.name().to_string());
635 labels.push(name);
636 if let Some(version) = &scope.version() {
637 let mut v_label = LabelPair::new();
638 v_label.set_name(SCOPE_INFO_KEYS[1].into());
639 v_label.set_value(version.to_string());
640 labels.push(v_label);
641 }
642
643 let mut m = prometheus::proto::Metric::default();
644 m.set_label(labels);
645 m.set_gauge(g);
646
647 let mut mf = MetricFamily::default();
648 mf.set_name(SCOPE_INFO_METRIC_NAME.into());
649 mf.set_help(SCOPE_INFO_DESCRIPTION.into());
650 mf.set_field_type(MetricType::GAUGE);
651 mf.set_metric(vec![m]);
652 mf
653}
654
655trait Numeric: fmt::Debug + Copy {
656 fn as_f64(&self) -> f64;
658}
659
660impl Numeric for u64 {
661 fn as_f64(&self) -> f64 {
662 *self as f64
663 }
664}
665
666impl Numeric for i64 {
667 fn as_f64(&self) -> f64 {
668 *self as f64
669 }
670}
671
672impl Numeric for f64 {
673 fn as_f64(&self) -> f64 {
674 *self
675 }
676}