Skip to main content

zebrad/components/tracing/
otel.rs

1//! OpenTelemetry tracing layer with zero overhead when disabled.
2//!
3//! This module provides OpenTelemetry distributed tracing support that can be
4//! compiled into production builds but only activated at runtime when an
5//! endpoint is configured.
6//!
7//! # Transport
8//!
9//! Uses HTTP transport with a blocking reqwest client. This works without an
10//! async runtime context because:
11//! - The BatchSpanProcessor spawns its own dedicated background thread
12//! - The reqwest-blocking-client handles HTTP exports synchronously
13//!
14//! This is important because Zebra's tracing component initializes before the
15//! Tokio runtime starts.
16
17use opentelemetry::trace::TracerProvider as _;
18use opentelemetry_otlp::{Protocol, WithExportConfig};
19use opentelemetry_sdk::{
20    trace::{RandomIdGenerator, Sampler, SdkTracer, SdkTracerProvider},
21    Resource,
22};
23use tracing::{Level, Metadata, Subscriber};
24use tracing_opentelemetry::OpenTelemetryLayer;
25use tracing_subscriber::{filter::filter_fn, registry::LookupSpan, Layer};
26
27/// The spans exported as traces, as `(crate, span name)` pairs.
28///
29/// Each one covers a single bounded operation, such as a peer connection attempt or request.
30/// Zebra's other INFO spans, such as `sync`, `crawl`, and the per-connection and global spans,
31/// last as long as the process or a connection, so a trace under them would never end, and
32/// every span below them would share their one sampling decision.
33const EXPORTED_SPANS: &[(&str, &str)] = &[
34    ("zebra_network", "dial"),
35    ("zebra_network", "connector"),
36    ("zebra_network", "accept_inbound_handshake"),
37    ("zebra_network", "msg_as_req"),
38    ("zebrad", "inbound"),
39    ("zebrad", "mempool"),
40    ("zebra_consensus", "checkpoint"),
41    ("zebra_rpc", "rpc_request"),
42    ("zebra_rpc", "lightwalletd_grpc_request"),
43];
44
45/// Returns `true` if the OpenTelemetry layer should see this span or event.
46///
47/// Spans not in [`EXPORTED_SPANS`] are hidden from the layer, so a span exported under one of
48/// them starts its own trace. Events are exported only at WARN and above, attached to the
49/// exported span they happen in.
50fn is_exported(metadata: &Metadata<'_>) -> bool {
51    if metadata.is_event() {
52        return *metadata.level() <= Level::WARN;
53    }
54
55    let krate = metadata.target().split("::").next().unwrap_or_default();
56
57    EXPORTED_SPANS.contains(&(krate, metadata.name()))
58}
59
60/// Error type for OpenTelemetry layer initialization.
61pub type OtelError = Box<dyn std::error::Error + Send + Sync + 'static>;
62
63/// Creates an OpenTelemetry layer if an endpoint is configured.
64///
65/// Returns `(None, None)` with ZERO overhead when endpoint is `None` -
66/// no SDK objects are created, no background tasks are spawned.
67///
68/// # Arguments
69///
70/// * `endpoint` - OTLP HTTP endpoint URL (e.g., "http://localhost:4318")
71/// * `service_name` - Service name for traces (defaults to "zebra")
72/// * `sample_percent` - Sampling percentage between 0 and 100. If `None`, the sampler is read
73///   from the standard `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` environment
74///   variables, and every trace is sampled if they are unset.
75///
76/// # Errors
77///
78/// Returns an error if the OTLP exporter fails to initialize.
79pub fn layer<S>(
80    endpoint: Option<&str>,
81    service_name: Option<&str>,
82    sample_percent: Option<u8>,
83) -> Result<(Option<impl Layer<S>>, Option<SdkTracerProvider>), OtelError>
84where
85    S: Subscriber + for<'span> LookupSpan<'span>,
86{
87    // CRITICAL: Check config FIRST - zero-cost path when None
88    let endpoint = match endpoint {
89        Some(ep) => ep,
90        None => return Ok((None, None)), // No SDK objects created
91    };
92
93    // HTTP transport requires the /v1/traces path suffix.
94    // Append it if not already present.
95    let endpoint = if endpoint.ends_with("/v1/traces") {
96        endpoint.to_string()
97    } else {
98        format!("{}/v1/traces", endpoint.trim_end_matches('/'))
99    };
100
101    let service_name = service_name.unwrap_or("zebra");
102
103    // Build the HTTP exporter with blocking client.
104    // This works without an async runtime because:
105    // 1. reqwest-blocking-client doesn't need tokio
106    // 2. BatchSpanProcessor spawns its own background thread for exports
107    let exporter = opentelemetry_otlp::SpanExporter::builder()
108        .with_http()
109        .with_protocol(Protocol::HttpBinary)
110        .with_endpoint(&endpoint)
111        .build()?;
112
113    let resource = Resource::builder()
114        .with_service_name(service_name.to_owned())
115        .build();
116
117    // Use batch exporter - it spawns its own dedicated background thread
118    // for collecting and exporting spans, so it doesn't need an external runtime
119    let mut provider = SdkTracerProvider::builder()
120        .with_batch_exporter(exporter)
121        .with_id_generator(RandomIdGenerator::default())
122        .with_resource(resource);
123
124    // The builder starts from the sampler in the standard environment variables, so only a
125    // configured percentage replaces it.
126    if let Some(sample_percent) = sample_percent {
127        provider = provider.with_sampler(sampler_for_percent(sample_percent));
128    }
129
130    let provider = provider.build();
131
132    let layer = exporting_layer(provider.tracer(service_name.to_owned()));
133
134    Ok((Some(layer), Some(provider)))
135}
136
137/// Returns the sampler for a percentage of traces, treating values above 100 as 100.
138fn sampler_for_percent(sample_percent: u8) -> Sampler {
139    match sample_percent {
140        0 => Sampler::AlwaysOff,
141        100.. => Sampler::AlwaysOn,
142        percent => Sampler::TraceIdRatioBased(f64::from(percent) / 100.0),
143    }
144}
145
146/// Returns the sampler Zebra uses, as the OpenTelemetry SDK describes it.
147///
148/// A configured percentage replaces the sampler in the standard environment variables.
149pub(super) fn sampler_description(sample_percent: Option<u8>) -> String {
150    match sample_percent {
151        Some(percent) => format!("{:?}", sampler_for_percent(percent)),
152        // The SDK reads the environment variables when it builds its default configuration.
153        None => format!("{:?}", opentelemetry_sdk::trace::Config::default().sampler),
154    }
155}
156
157/// Returns why the standard sampler environment variables won't sample as an operator
158/// probably intended, if they won't.
159///
160/// The SDK warns about some of these itself, but before Zebra installs its logs, so those
161/// warnings are lost.
162pub(super) fn sampler_env_problem(
163    sampler: Option<&str>,
164    arg: Option<&str>,
165) -> Option<&'static str> {
166    const RATIO_SAMPLERS: [&str; 2] = ["traceidratio", "parentbased_traceidratio"];
167    const OTHER_SAMPLERS: [&str; 4] = [
168        "always_on",
169        "always_off",
170        "parentbased_always_on",
171        "parentbased_always_off",
172    ];
173
174    match sampler {
175        None if arg.is_some() => Some(
176            "OTEL_TRACES_SAMPLER_ARG applies only when OTEL_TRACES_SAMPLER is set, \
177             so every trace is sampled",
178        ),
179        None => None,
180        Some(sampler) if RATIO_SAMPLERS.contains(&sampler) => {
181            match arg.and_then(|arg| arg.parse::<f64>().ok()) {
182                None => Some(
183                    "OTEL_TRACES_SAMPLER_ARG is missing or not a number, \
184                     so every trace is sampled",
185                ),
186                Some(ratio) if !(0.0..=1.0).contains(&ratio) => {
187                    Some("OTEL_TRACES_SAMPLER_ARG is a ratio from 0.0 to 1.0, not a percentage")
188                }
189                Some(_) => None,
190            }
191        }
192        Some(sampler) if OTHER_SAMPLERS.contains(&sampler) => None,
193        Some(_) => Some(
194            "OTEL_TRACES_SAMPLER is not a sampler this OpenTelemetry SDK supports, \
195             so every trace is sampled unless its remote parent was not",
196        ),
197    }
198}
199
200/// Returns a layer that exports the spans and events [`is_exported`] selects to `tracer`.
201pub(super) fn exporting_layer<S>(tracer: SdkTracer) -> impl Layer<S>
202where
203    S: Subscriber + for<'span> LookupSpan<'span>,
204{
205    // Zebra doesn't record thread and idle time attributes, which would only add cost. Entering
206    // an exported span activates its context, which gives JSON logs its trace and span IDs.
207    OpenTelemetryLayer::new(tracer)
208        .with_threads(false)
209        .with_tracked_inactivity(false)
210        .with_filter(filter_fn(is_exported).with_max_level_hint(Level::INFO))
211}
212
213#[cfg(test)]
214mod tests {
215    use opentelemetry::trace::SpanId;
216    use opentelemetry_sdk::trace::{InMemorySpanExporter, SpanData};
217    use tracing::{info, info_span, warn};
218    use tracing_subscriber::{layer::SubscriberExt, Registry};
219
220    use super::*;
221
222    /// Runs `work` under a subscriber with only the exporting layer, and returns the exported
223    /// spans.
224    fn export(sampler: Sampler, work: impl FnOnce()) -> Vec<SpanData> {
225        let exporter = InMemorySpanExporter::default();
226        let provider = SdkTracerProvider::builder()
227            .with_simple_exporter(exporter.clone())
228            .with_sampler(sampler)
229            .build();
230        let subscriber = Registry::default().with(exporting_layer(provider.tracer("test")));
231
232        tracing::subscriber::with_default(subscriber, work);
233
234        provider.force_flush().expect("in-memory export can't fail");
235        exporter
236            .get_finished_spans()
237            .expect("in-memory export can't fail")
238    }
239
240    /// Runs `requests` inside process-long spans, like the global span and `sync`.
241    fn under_long_lived_spans(requests: impl FnOnce()) {
242        let _global = tracing::error_span!("", net = "Main").entered();
243        let _sync = tracing::info_span!(target: "zebrad::components::sync", "sync").entered();
244
245        requests();
246    }
247
248    fn request() {
249        let _req = info_span!(target: "zebra_network::peer::connection", "msg_as_req").entered();
250        info!("not exported");
251        warn!("exported");
252    }
253
254    #[test]
255    fn sampler_env_problems() {
256        let cases = [
257            (None, None, false),
258            (None, Some("10"), true),
259            (Some("always_off"), None, false),
260            (Some("parentbased_always_on"), Some("0.5"), false),
261            (Some("traceidratio"), Some("0.1"), false),
262            (Some("traceidratio"), Some("1"), false),
263            (Some("parentbased_traceidratio"), Some("0"), false),
264            (Some("traceidratio"), None, true),
265            (Some("traceidratio"), Some("10%"), true),
266            (Some("traceidratio"), Some("10"), true),
267            (Some("ratio"), Some("0.1"), true),
268        ];
269
270        for (sampler, arg, has_problem) in cases {
271            assert_eq!(
272                sampler_env_problem(sampler, arg).is_some(),
273                has_problem,
274                "OTEL_TRACES_SAMPLER={sampler:?} OTEL_TRACES_SAMPLER_ARG={arg:?}",
275            );
276        }
277    }
278
279    /// Changes the process environment, which only this test reads. Nextest runs each test in
280    /// its own process.
281    #[test]
282    fn sampler_comes_from_env_unless_percent_is_configured() {
283        let with_env = |sampler: &str, arg: &str, sample_percent| {
284            std::env::set_var("OTEL_TRACES_SAMPLER", sampler);
285            std::env::set_var("OTEL_TRACES_SAMPLER_ARG", arg);
286            sampler_description(sample_percent)
287        };
288
289        assert_eq!(with_env("always_off", "", None), "AlwaysOff");
290        assert_eq!(
291            with_env("traceidratio", "0.25", None),
292            "TraceIdRatioBased(0.25)"
293        );
294        assert_eq!(
295            with_env("parentbased_traceidratio", "0", None),
296            "ParentBased(TraceIdRatioBased(0.0))"
297        );
298        assert_eq!(
299            with_env("traceidratio", "0.25", Some(10)),
300            "TraceIdRatioBased(0.1)"
301        );
302        assert_eq!(with_env("always_on", "", Some(0)), "AlwaysOff");
303
304        std::env::remove_var("OTEL_TRACES_SAMPLER");
305        std::env::remove_var("OTEL_TRACES_SAMPLER_ARG");
306        assert_eq!(sampler_description(None), "ParentBased(AlwaysOn)");
307    }
308
309    #[test]
310    fn exports_only_operation_spans_as_roots() {
311        let spans = export(Sampler::AlwaysOn, || under_long_lived_spans(request));
312
313        let [span] = spans.as_slice() else {
314            panic!("expected only the request span, got {spans:?}");
315        };
316        assert_eq!(span.name, "msg_as_req");
317        assert_eq!(span.parent_span_id, SpanId::INVALID);
318
319        let events: Vec<_> = span.events.iter().map(|event| &event.name).collect();
320        assert_eq!(events, ["exported"]);
321    }
322
323    #[test]
324    fn samples_each_operation_separately() {
325        const REQUESTS: usize = 1000;
326
327        let spans = export(Sampler::TraceIdRatioBased(0.5), || {
328            under_long_lived_spans(|| (0..REQUESTS).for_each(|_| request()))
329        });
330
331        // With one decision per process, this would be 0 or 1000. The bounds are about 10
332        // standard deviations from the mean, so the test doesn't flake.
333        assert!(
334            (340..=660).contains(&spans.len()),
335            "{} of {REQUESTS} requests were sampled",
336            spans.len(),
337        );
338    }
339}