|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//! OTLP metric export support. |
| 5 | +
|
| 6 | +use opentelemetry_otlp::MetricExporter; |
| 7 | +use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider}; |
| 8 | + |
| 9 | +use crate::{OtlpTarget, Protocol, SetupError}; |
| 10 | + |
| 11 | +impl OtlpTarget { |
| 12 | + /// Build a meter provider that periodically exports to this collector. |
| 13 | + pub fn meter_provider(&self) -> Result<SdkMeterProvider, SetupError> { |
| 14 | + self.check_tls()?; |
| 15 | + let exporter = match self.protocol { |
| 16 | + Protocol::Grpc => self |
| 17 | + .configure(MetricExporter::builder().with_tonic()) |
| 18 | + .build()?, |
| 19 | + Protocol::HttpProtobuf => self |
| 20 | + .configure_http( |
| 21 | + MetricExporter::builder().with_http(), |
| 22 | + "v1/metrics", |
| 23 | + "OTEL_EXPORTER_OTLP_METRICS_TIMEOUT", |
| 24 | + )? |
| 25 | + .build()?, |
| 26 | + }; |
| 27 | + Ok(SdkMeterProvider::builder() |
| 28 | + .with_reader(PeriodicReader::builder(exporter).build()) |
| 29 | + .with_resource(self.resource().clone()) |
| 30 | + .build()) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +#[cfg(test)] |
| 35 | +mod tests { |
| 36 | + use openshell_otel_test_support::{OtlpHttpTestServer, OtlpTestServer, ServerTls, TestPki}; |
| 37 | + use opentelemetry::{KeyValue, metrics::MeterProvider as _}; |
| 38 | + use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; |
| 39 | + use opentelemetry_proto::tonic::metrics::v1::{metric, number_data_point}; |
| 40 | + use prost::Message as _; |
| 41 | + |
| 42 | + use super::*; |
| 43 | + use crate::{OtlpExportConfig, OtlpTls, ServiceName}; |
| 44 | + |
| 45 | + fn target(endpoint: &str, protocol: Protocol) -> OtlpTarget { |
| 46 | + OtlpTarget::new(&OtlpExportConfig { |
| 47 | + endpoint, |
| 48 | + service_name: ServiceName::Fixed("metrics-test"), |
| 49 | + service_version: Some("1.2.3"), |
| 50 | + resource_attributes: vec![KeyValue::new("openshell.gateway.name", "test-gateway")], |
| 51 | + }) |
| 52 | + .unwrap() |
| 53 | + .with_protocol(protocol) |
| 54 | + } |
| 55 | + |
| 56 | + fn assert_counter(request: &ExportMetricsServiceRequest) { |
| 57 | + let resource = &request.resource_metrics[0]; |
| 58 | + assert!( |
| 59 | + resource |
| 60 | + .resource |
| 61 | + .as_ref() |
| 62 | + .unwrap() |
| 63 | + .attributes |
| 64 | + .iter() |
| 65 | + .any(|attribute| attribute.key == "service.name" |
| 66 | + && format!("{:?}", attribute.value).contains("metrics-test")) |
| 67 | + ); |
| 68 | + let metric = &resource.scope_metrics[0].metrics[0]; |
| 69 | + assert_eq!(metric.name, "requests_total"); |
| 70 | + let Some(metric::Data::Sum(sum)) = &metric.data else { |
| 71 | + panic!("expected counter sum") |
| 72 | + }; |
| 73 | + assert!(sum.is_monotonic); |
| 74 | + assert_eq!( |
| 75 | + sum.data_points[0].value, |
| 76 | + Some(number_data_point::Value::AsInt(7)) |
| 77 | + ); |
| 78 | + assert_eq!(sum.data_points[0].attributes[0].key, "method"); |
| 79 | + } |
| 80 | + |
| 81 | + #[tokio::test] |
| 82 | + async fn metrics_reuse_headers_and_mutual_tls_over_both_protocols() { |
| 83 | + crate::test_environment::Environment::new() |
| 84 | + .remove("OTEL_EXPORTER_OTLP_HEADERS") |
| 85 | + .remove("OTEL_EXPORTER_OTLP_METRICS_HEADERS") |
| 86 | + .run_async(async { |
| 87 | + let pki = TestPki::generate(); |
| 88 | + let server_tls = ServerTls::mutual(&pki); |
| 89 | + let tls = OtlpTls::from_pem( |
| 90 | + Some(pki.ca_pem.as_bytes()), |
| 91 | + Some(( |
| 92 | + pki.client.cert_pem.as_bytes(), |
| 93 | + pki.client.key_pem.as_bytes(), |
| 94 | + )), |
| 95 | + ) |
| 96 | + .unwrap(); |
| 97 | + for protocol in [Protocol::Grpc, Protocol::HttpProtobuf] { |
| 98 | + let grpc = OtlpTestServer::start_with_tls(&server_tls).await; |
| 99 | + let mut http = OtlpHttpTestServer::start_with_tls(&server_tls).await; |
| 100 | + let endpoint = if protocol == Protocol::Grpc { |
| 101 | + grpc.endpoint() |
| 102 | + } else { |
| 103 | + http.endpoint() |
| 104 | + }; |
| 105 | + let provider = target(endpoint, protocol) |
| 106 | + .with_tls(tls.clone()) |
| 107 | + .with_headers(crate::parse_otlp_headers("authorization=Bearer%20metrics")) |
| 108 | + .meter_provider() |
| 109 | + .unwrap(); |
| 110 | + provider |
| 111 | + .meter("test") |
| 112 | + .u64_counter("requests_total") |
| 113 | + .build() |
| 114 | + .add(7, &[KeyValue::new("method", "GET")]); |
| 115 | + let flush = { |
| 116 | + let provider = provider.clone(); |
| 117 | + tokio::task::spawn_blocking(move || provider.force_flush()) |
| 118 | + }; |
| 119 | + flush.await.unwrap().unwrap(); |
| 120 | + tokio::task::spawn_blocking(move || provider.shutdown()) |
| 121 | + .await |
| 122 | + .unwrap() |
| 123 | + .unwrap(); |
| 124 | + if protocol == Protocol::Grpc { |
| 125 | + let received = grpc.shutdown().await; |
| 126 | + assert_eq!(received.metric_authorizations[0], "Bearer metrics"); |
| 127 | + assert_counter(&received.metric_exports[0]); |
| 128 | + } else { |
| 129 | + let export = http.next_export().await; |
| 130 | + assert_eq!(export.path, "/v1/metrics"); |
| 131 | + assert_eq!(export.headers["authorization"], "Bearer metrics"); |
| 132 | + assert_counter(&ExportMetricsServiceRequest::decode(export.body).unwrap()); |
| 133 | + grpc.shutdown().await; |
| 134 | + } |
| 135 | + } |
| 136 | + }) |
| 137 | + .await; |
| 138 | + } |
| 139 | + |
| 140 | + #[tokio::test] |
| 141 | + async fn metrics_export_periodically_without_scraping_and_flush_on_shutdown() { |
| 142 | + crate::test_environment::Environment::new() |
| 143 | + .set("OTEL_METRIC_EXPORT_INTERVAL", "25") |
| 144 | + .set("OTEL_EXPORTER_OTLP_METRICS_HEADERS", "x-metrics=from-env") |
| 145 | + .set( |
| 146 | + "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", |
| 147 | + "http://ignored.invalid:4318", |
| 148 | + ) |
| 149 | + .run_async(async { |
| 150 | + let mut collector = OtlpHttpTestServer::start().await; |
| 151 | + let provider = target( |
| 152 | + &format!("{}/prefix", collector.endpoint()), |
| 153 | + Protocol::HttpProtobuf, |
| 154 | + ) |
| 155 | + .meter_provider() |
| 156 | + .unwrap(); |
| 157 | + let counter = provider.meter("test").u64_counter("requests_total").build(); |
| 158 | + counter.add(7, &[KeyValue::new("method", "GET")]); |
| 159 | + for _ in 0..2 { |
| 160 | + let export = collector.next_export().await; |
| 161 | + assert_eq!(export.path, "/prefix/v1/metrics"); |
| 162 | + assert_eq!(export.headers["x-metrics"], "from-env"); |
| 163 | + assert_counter(&ExportMetricsServiceRequest::decode(export.body).unwrap()); |
| 164 | + } |
| 165 | + tokio::task::spawn_blocking(move || provider.shutdown()) |
| 166 | + .await |
| 167 | + .unwrap() |
| 168 | + .unwrap(); |
| 169 | + collector.next_export().await; |
| 170 | + }) |
| 171 | + .await; |
| 172 | + } |
| 173 | +} |
0 commit comments