Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update otel versions for prometheus to 0.27 #2309

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
9 changes: 5 additions & 4 deletions opentelemetry-prometheus/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

## vNext

- Bump MSRV to 1.70 [#2179](https://github.com/open-telemetry/opentelemetry-rust/pull/2179)
- Update `opentelemetry` dependency version to 0.26
- Update `opentelemetry_sdk` dependency version to 0.26
- Update `opentelemetry-semantic-conventions` dependency version to 0.26
## v0.27.0

- Update `opentelemetry` dependency version to 0.27
- Update `opentelemetry_sdk` dependency version to 0.27
- Update `opentelemetry-semantic-conventions` dependency version to 0.27


## v0.17.0
Expand Down
11 changes: 7 additions & 4 deletions opentelemetry-prometheus/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "opentelemetry-prometheus"
version = "0.17.0"
version = "0.27.0"
description = "Prometheus exporter for OpenTelemetry"
homepage = "https://github.com/open-telemetry/opentelemetry-rust"
repository = "https://github.com/open-telemetry/opentelemetry-rust"
Expand All @@ -21,17 +21,20 @@ rustdoc-args = ["--cfg", "docsrs"]

[dependencies]
once_cell = { workspace = true }
opentelemetry = { version = "0.26", default-features = false, features = ["metrics"] }
opentelemetry_sdk = { version = "0.26", default-features = false, features = ["metrics"] }
opentelemetry = { version = "0.27", default-features = false, features = ["metrics"] }
opentelemetry_sdk = { version = "0.27", default-features = false, features = ["metrics", "spec_unstable_metrics_views"] }
prometheus = "0.13"
protobuf = "2.14"
tracing = {workspace = true, optional = true} # optional for opentelemetry internal logging

[dev-dependencies]
opentelemetry-semantic-conventions = { version = "0.26" }
opentelemetry-semantic-conventions = { version = "0.27" }
http-body-util = { workspace = true }
hyper = { workspace = true, features = ["full"] }
hyper-util = { workspace = true, features = ["full"] }
tokio = { workspace = true, features = ["full"] }

[features]
default = ["internal-logs"]
prometheus-encoding = []
internal-logs = ["tracing"]
2 changes: 1 addition & 1 deletion opentelemetry-prometheus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
[`Prometheus`] integration for applications instrumented with [`OpenTelemetry`].

**The development of prometheus exporter has halt until the Opentelemetry metrics API and SDK reaches 1.0. Current
implementation is based on Opentelemetry API and SDK 0.24**.
implementation is based on Opentelemetry API and SDK 0.27**.

[![Crates.io: opentelemetry-prometheus](https://img.shields.io/crates/v/opentelemetry-prometheus.svg)](https://crates.io/crates/opentelemetry-prometheus)
[![Documentation](https://docs.rs/opentelemetry-prometheus/badge.svg)](https://docs.rs/opentelemetry-prometheus)
Expand Down
6 changes: 3 additions & 3 deletions opentelemetry-prometheus/examples/hyper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,17 +85,17 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
http_counter: meter
.u64_counter("http_requests_total")
.with_description("Total number of HTTP requests made.")
.init(),
.build(),
http_body_gauge: meter
.u64_histogram("example.http_response_size")
.with_unit("By")
.with_description("The metrics HTTP response sizes in bytes.")
.init(),
.build(),
http_req_histogram: meter
.f64_histogram("example.http_request_duration")
.with_unit("ms")
.with_description("The HTTP request latencies in milliseconds.")
.init(),
.build(),
});

let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
Expand Down
7 changes: 3 additions & 4 deletions opentelemetry-prometheus/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use core::fmt;
use once_cell::sync::OnceCell;
use opentelemetry::metrics::{MetricsError, Result};
use opentelemetry_sdk::metrics::ManualReaderBuilder;
use opentelemetry_sdk::metrics::{ManualReaderBuilder, MetricError, MetricResult};
use std::sync::{Arc, Mutex};

use crate::{Collector, PrometheusExporter, ResourceSelector};
Expand Down Expand Up @@ -116,7 +115,7 @@ impl ExporterBuilder {
}

/// Creates a new [PrometheusExporter] from this configuration.
pub fn build(self) -> Result<PrometheusExporter> {
pub fn build(self) -> MetricResult<PrometheusExporter> {
let reader = Arc::new(self.reader.build());

let collector = Collector {
Expand All @@ -135,7 +134,7 @@ impl ExporterBuilder {
let registry = self.registry.unwrap_or_default();
registry
.register(Box::new(collector))
.map_err(|e| MetricsError::Other(e.to_string()))?;
.map_err(|e| MetricError::Other(e.to_string()))?;

Ok(PrometheusExporter { reader })
}
Expand Down
78 changes: 43 additions & 35 deletions opentelemetry-prometheus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
//! let counter = meter
//! .u64_counter("a.counter")
//! .with_description("Counts things")
//! .init();
//! .build();
//! let histogram = meter
//! .u64_histogram("a.histogram")
//! .with_description("Records values")
//! .init();
//! .build();
//!
//! counter.add(100, &[KeyValue::new("key", "value")]);
//! histogram.record(100, &[KeyValue::new("key", "value")]);
Expand Down Expand Up @@ -97,18 +97,14 @@
#![cfg_attr(test, deny(warnings))]

use once_cell::sync::{Lazy, OnceCell};
use opentelemetry::{
global,
metrics::{MetricsError, Result},
Key, Value,
};
use opentelemetry::{otel_error, otel_warn, InstrumentationScope, Key, Value};
use opentelemetry_sdk::{
metrics::{
data::{self, ResourceMetrics, Temporality},
reader::{MetricReader, TemporalitySelector},
InstrumentKind, ManualReader, Pipeline,
data::{self, ResourceMetrics},
reader::MetricReader,
InstrumentKind, ManualReader, MetricResult, Pipeline, Temporality,
},
Resource, Scope,
Resource,
};
use prometheus::{
core::Desc,
Expand Down Expand Up @@ -152,30 +148,28 @@
reader: Arc<ManualReader>,
}

impl TemporalitySelector for PrometheusExporter {
/// Note: Prometheus only supports cumulative temporality so this will always be
/// [Temporality::Cumulative].
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
fn temporality(&self, kind: InstrumentKind) -> Temporality {
self.reader.temporality(kind)
}
}

impl MetricReader for PrometheusExporter {
fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
self.reader.register_pipeline(pipeline)
}

fn collect(&self, rm: &mut ResourceMetrics) -> Result<()> {
fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> {

Check warning on line 156 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L156

Added line #L156 was not covered by tests
self.reader.collect(rm)
}

fn force_flush(&self) -> Result<()> {
fn force_flush(&self) -> MetricResult<()> {

Check warning on line 160 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L160

Added line #L160 was not covered by tests
self.reader.force_flush()
}

fn shutdown(&self) -> Result<()> {
fn shutdown(&self) -> MetricResult<()> {
self.reader.shutdown()
}

/// Note: Prometheus only supports cumulative temporality, so this will always be
/// [Temporality::Cumulative].
fn temporality(&self, _kind: InstrumentKind) -> Temporality {
Temporality::Cumulative
}
}

struct Collector {
Expand All @@ -193,7 +187,7 @@

#[derive(Default)]
struct CollectorInner {
scope_infos: HashMap<Scope, MetricFamily>,
scope_infos: HashMap<InstrumentationScope, MetricFamily>,
metric_families: HashMap<String, MetricFamily>,
}

Expand Down Expand Up @@ -281,7 +275,10 @@
let mut inner = match self.inner.lock() {
Ok(guard) => guard,
Err(err) => {
global::handle_error(err);
otel_error!(

Check warning on line 278 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L278

Added line #L278 was not covered by tests
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
name: "MetricScrapeFailed",
message = err.to_string(),

Check warning on line 280 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L280

Added line #L280 was not covered by tests
);
return Vec::new();
}
};
Expand All @@ -291,7 +288,10 @@
scope_metrics: vec![],
};
if let Err(err) = self.reader.collect(&mut metrics) {
global::handle_error(err);
otel_error!(

Check warning on line 291 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L291

Added line #L291 was not covered by tests
cijothomas marked this conversation as resolved.
Show resolved Hide resolved
name: "MetricScrapeFailed",
message = err.to_string(),

Check warning on line 293 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L293

Added line #L293 was not covered by tests
);
return vec![];
}
let mut res = Vec::with_capacity(metrics.scope_metrics.len() + 1);
Expand All @@ -311,7 +311,7 @@

for scope_metrics in metrics.scope_metrics {
let scope_labels = if !self.disable_scope_info {
if !scope_metrics.scope.attributes.is_empty() {
if scope_metrics.scope.attributes().count() > 0 {
let scope_info = inner
.scope_infos
.entry(scope_metrics.scope.clone())
Expand All @@ -320,12 +320,12 @@
}

let mut labels =
Vec::with_capacity(1 + scope_metrics.scope.version.is_some() as usize);
Vec::with_capacity(1 + scope_metrics.scope.version().is_some() as usize);
let mut name = LabelPair::new();
name.set_name(SCOPE_INFO_KEYS[0].into());
name.set_value(scope_metrics.scope.name.to_string());
name.set_value(scope_metrics.scope.name().to_string());
labels.push(name);
if let Some(version) = &scope_metrics.scope.version {
if let Some(version) = &scope_metrics.scope.version() {
let mut l_version = LabelPair::new();
l_version.set_name(SCOPE_INFO_KEYS[1].into());
l_version.set_value(version.to_string());
Expand Down Expand Up @@ -421,11 +421,19 @@
) -> (bool, Option<String>) {
if let Some(existing) = mfs.get(name) {
if existing.get_field_type() != metric_type {
global::handle_error(MetricsError::Other(format!("Instrument type conflict, using existing type definition. Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_field_type(), metric_type)));
otel_warn!(
name: "MetricValidationFailed",
message = "Instrument type conflict, using existing type definition",
metric_type = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_field_type(), metric_type).as_str(),

Check warning on line 427 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L427

Added line #L427 was not covered by tests
);
return (true, None);
}
if existing.get_help() != description {
global::handle_error(MetricsError::Other(format!("Instrument description conflict, using existing. Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_help(), description)));
otel_warn!(
name: "MetricValidationFailed",
message = "Instrument description conflict, using existing",
metric_description = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_help().to_string(), description.to_string()).as_str(),

Check warning on line 435 in opentelemetry-prometheus/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-prometheus/src/lib.rs#L435

Added line #L435 was not covered by tests
);
return (false, Some(existing.get_help().to_string()));
}
(false, None)
Expand Down Expand Up @@ -578,16 +586,16 @@
mf
}

fn create_scope_info_metric(scope: &Scope) -> MetricFamily {
fn create_scope_info_metric(scope: &InstrumentationScope) -> MetricFamily {
let mut g = prometheus::proto::Gauge::default();
g.set_value(1.0);

let mut labels = Vec::with_capacity(1 + scope.version.is_some() as usize);
let mut labels = Vec::with_capacity(1 + scope.version().is_some() as usize);
let mut name = LabelPair::new();
name.set_name(SCOPE_INFO_KEYS[0].into());
name.set_value(scope.name.to_string());
name.set_value(scope.name().to_string());
labels.push(name);
if let Some(version) = &scope.version {
if let Some(version) = &scope.version() {
let mut v_label = LabelPair::new();
v_label.set_name(SCOPE_INFO_KEYS[1].into());
v_label.set_value(version.to_string());
Expand Down
Loading
Loading