Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions crates/telemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use env::otel_logs_enabled;
use env::otel_metrics_enabled;
use env::otel_tracing_enabled;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::resource::ResourceDetector;
use tracing_subscriber::{EnvFilter, Layer, fmt, prelude::*, registry};

mod alert_in_dev;
Expand Down Expand Up @@ -100,8 +101,14 @@ pub fn init(spin_version: String, histogram_buckets: Vec<HistogramBuckets>) -> a
opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());

if otel_metrics_enabled() {
let meter_provider = metrics::metrics_provider(spin_version.clone(), histogram_buckets)
.context("failed to initialize otel metrics")?;
// Initialize and register the global OTel meter provider.
let resource_detectors: Vec<Box<dyn ResourceDetector>> =
vec![Box::new(detector::SpinResourceDetector::new(
spin_version.clone(),
))];
let meter_provider =
metrics::metrics_provider(None, resource_detectors, histogram_buckets)
.context("failed to initialize otel metrics")?;
opentelemetry::global::set_meter_provider(meter_provider);
}

Expand Down
70 changes: 48 additions & 22 deletions crates/telemetry/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::{Result, bail};
use opentelemetry_otlp::WithHttpConfig;
use opentelemetry_otlp::{WithExportConfig, WithHttpConfig};
use opentelemetry_sdk::{
Resource,
metrics::{
Expand All @@ -10,7 +10,7 @@ use opentelemetry_sdk::{
runtime::Tokio,
};

use crate::{detector::SpinResourceDetector, env::OtlpProtocol};
use crate::env::OtlpProtocol;

/// Re-exported so the metric macros can refer to `$crate::opentelemetry::...`.
#[doc(hidden)]
Expand All @@ -32,42 +32,68 @@ pub struct HistogramBuckets {

/// Builds an [`SdkMeterProvider`] configured to export to an OTLP collector.
///
/// It pulls OTEL configuration from the environment based on the variables defined
/// [here](https://opentelemetry.io/docs/specs/otel/protocol/exporter/) and
/// Aside from `endpoint`, it pulls OTEL configuration from the environment based on the
/// variables defined [here](https://opentelemetry.io/docs/specs/otel/protocol/exporter/) and
/// [here](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/#general-sdk-configuration).
///
/// `endpoint` overrides the collector endpoint the environment would otherwise select (via
/// `OTEL_EXPORTER_OTLP_ENDPOINT`/`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`), for callers that take
/// their own explicit configuration (e.g. a CLI flag) rather than expecting operators to set
/// OTel's environment variables directly. Pass `None` to use the environment as normal.
///
/// `resource_detectors` lets the caller contribute additional resource attributes.
/// They run before this crate's own detectors, which set fields from `OTEL_RESOURCE_ATTRIBUTES`
/// and `telemetry.sdk{name, language, version}`.
///
/// The caller is responsible for registering the returned provider as the global one (e.g. via
/// [`opentelemetry::global::set_meter_provider`]). Instruments created by the macros in this
/// module (e.g. [`counter`](crate::counter)) bind to whatever meter
/// provider is global *at the time they're first used*, and never rebind afterwards.
pub(crate) fn metrics_provider(
spin_version: String,
///
/// Exposed publicly so embedders that manage their own [tracing::Subscriber] (and so can't call
/// [`crate::init`], which also installs one) can still set up Spin's metrics: build a provider

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This made me wonder if crate::init should be offering more flexibility to consumers (with the CLI defaults hived off to an init_default kind of function). But I'm not familiar with the telemetry subsystem so I'm fine with this less invasive change! But I'd like @calebschoepp to look it over too.

/// with this function and register it themselves, alongside their own, via
/// [`opentelemetry::global::set_meter_provider`].
pub fn metrics_provider(
endpoint: Option<String>,
resource_detectors: Vec<Box<dyn ResourceDetector>>,
histogram_buckets: Vec<HistogramBuckets>,
) -> Result<SdkMeterProvider> {
let resource = Resource::builder()
.with_detectors(&[
// Set service.name from env OTEL_SERVICE_NAME > env OTEL_RESOURCE_ATTRIBUTES > spin
// Set service.version from Spin metadata
Box::new(SpinResourceDetector::new(spin_version)) as Box<dyn ResourceDetector>,
// Sets fields from env OTEL_RESOURCE_ATTRIBUTES
Box::new(EnvResourceDetector::new()),
// Sets telemetry.sdk{name, language, version}
Box::new(TelemetryResourceDetector),
])
.with_detectors(
&resource_detectors
.into_iter()
.chain([
// Sets fields from env OTEL_RESOURCE_ATTRIBUTES
Box::new(EnvResourceDetector::new()) as Box<dyn ResourceDetector>,
// Sets telemetry.sdk{name, language, version}
Box::new(TelemetryResourceDetector),
])
.collect::<Vec<_>>(),
)
.build();

// This will configure the exporter based on the OTEL_EXPORTER_* environment variables. We
// currently default to using the HTTP exporter but in the future we could select off of the
// combination of OTEL_EXPORTER_OTLP_PROTOCOL and OTEL_EXPORTER_OTLP_TRACES_PROTOCOL to
// determine whether we should use http/protobuf or grpc.
let exporter = match OtlpProtocol::metrics_protocol_from_env() {
OtlpProtocol::Grpc => opentelemetry_otlp::MetricExporter::builder()
.with_tonic()
.build()?,
OtlpProtocol::HttpProtobuf => opentelemetry_otlp::MetricExporter::builder()
.with_http()
.with_http_client(crate::rustls_reqwest_client()?)
.build()?,
OtlpProtocol::Grpc => {
let mut builder = opentelemetry_otlp::MetricExporter::builder().with_tonic();
if let Some(endpoint) = endpoint {
builder = builder.with_endpoint(endpoint);
}
builder.build()?
}
OtlpProtocol::HttpProtobuf => {
let mut builder = opentelemetry_otlp::MetricExporter::builder()
.with_http()
.with_http_client(crate::rustls_reqwest_client()?);
if let Some(endpoint) = endpoint {
builder = builder.with_endpoint(endpoint);
}
builder.build()?
}
OtlpProtocol::HttpJson => bail!("http/json OTLP protocol is not supported"),
};

Expand Down
Loading