Skip to main content

zebrad/components/tracing/
component.rs

1//! The Abscissa component for Zebra's `tracing` implementation.
2
3use std::{
4    fs::{self, File},
5    io::Write,
6    path::Path,
7};
8
9use abscissa_core::{Component, FrameworkError, Shutdown};
10
11use tokio::sync::watch;
12use tracing::{field::Visit, Level};
13use tracing_appender::non_blocking::{NonBlockingBuilder, WorkerGuard};
14use tracing_error::ErrorLayer;
15use tracing_subscriber::{
16    fmt, layer::SubscriberExt, reload::Handle, util::SubscriberInitExt, EnvFilter, Layer, Registry,
17};
18use zebra_chain::parameters::Network;
19
20use crate::{
21    application::build_version,
22    components::tracing::{Config, LogFormat},
23};
24
25#[cfg(feature = "flamegraph")]
26use super::flame;
27
28// Art generated with these two images.
29// Zebra logo: book/theme/favicon.png
30// License: MIT or Apache 2.0
31//
32// Heart image: https://commons.wikimedia.org/wiki/File:Love_Heart_SVG.svg
33// Author: Bubinator
34// License: Public Domain or Unconditional Use
35//
36// How to render
37//
38// Convert heart image to PNG (2000px):
39// curl -o heart.svg https://upload.wikimedia.org/wikipedia/commons/4/42/Love_Heart_SVG.svg
40// cargo install resvg
41// resvg --width 2000 --height 2000 heart.svg heart.png
42//
43// Then to text (40x20):
44// img2txt -W 40 -H 20 -f utf8 -d none heart.png > heart.utf8
45// img2txt -W 40 -H 20 -f utf8 -d none favicon.png > logo.utf8
46// paste -d "\0" logo.utf8 heart.utf8 > zebra.utf8
47static ZEBRA_ART: [u8; include_bytes!("zebra.utf8").len()] = *include_bytes!("zebra.utf8");
48
49/// A type-erased boxed writer that can be sent between threads safely.
50pub type BoxWrite = Box<dyn Write + Send + Sync + 'static>;
51
52/// Abscissa component for initializing the `tracing` subsystem
53pub struct Tracing {
54    /// The installed filter reloading handle, if the `filter-reload` feature is enabled.
55    filter_handle: Option<Handle<EnvFilter, Registry>>,
56
57    /// The originally configured filter.
58    initial_filter: String,
59
60    /// The installed flame graph collector, if enabled.
61    #[cfg(feature = "flamegraph")]
62    flamegrapher: Option<flame::Grapher>,
63
64    /// The OpenTelemetry tracer provider, if enabled.
65    #[cfg(feature = "opentelemetry")]
66    otel_provider: Option<opentelemetry_sdk::trace::SdkTracerProvider>,
67
68    /// Drop guard for worker thread of non-blocking logger,
69    /// responsible for flushing any remaining logs when the program terminates.
70    //
71    // Correctness: must be listed last in the struct, so it drops after other drops have logged.
72    _guard: Option<WorkerGuard>,
73}
74
75impl Tracing {
76    /// Try to create a new [`Tracing`] component with the given `config`.
77    ///
78    /// If `uses_intro` is true, show a welcome message, the `network`,
79    /// and the Zebra logo on startup. (If the terminal supports it.)
80    //
81    // This method should only print to stderr, because stdout is for tracing logs.
82    #[allow(clippy::print_stdout, clippy::print_stderr, clippy::unwrap_in_result)]
83    pub fn new(
84        network: &Network,
85        config: Config,
86        uses_intro: bool,
87    ) -> Result<Self, FrameworkError> {
88        // Only use color if tracing output is being sent to a terminal or if it was explicitly
89        // forced to.
90        let use_color = config.use_color_stdout();
91        let use_color_stderr = config.use_color_stderr();
92
93        let filter = config.filter.clone().unwrap_or_default();
94        let flame_root = &config.flamegraph;
95
96        // Only show the intro for user-focused node server commands like `start`
97        // Also skip the intro for regtest, since it pollutes the QA test logs,
98        // and for JSON logs, since log collectors usually read standard error as well.
99        if uses_intro && !network.is_regtest() && config.log_format == LogFormat::Text {
100            // If it's a terminal and color escaping is enabled: clear screen and
101            // print Zebra logo (here `use_color` is being interpreted as
102            // "use escape codes")
103            if use_color_stderr {
104                // Clear screen
105                eprint!("\x1B[2J");
106                eprintln!(
107                    "{}",
108                    std::str::from_utf8(&ZEBRA_ART)
109                        .expect("should always work on a UTF-8 encoded constant")
110                );
111            }
112
113            eprintln!(
114                "Thank you for running a {} zebrad {} node!",
115                network.lowercase_name(),
116                build_version()
117            );
118            eprintln!(
119                "You're helping to strengthen the network and contributing to a social good :)"
120            );
121        }
122
123        let writer = if let Some(log_file) = config.log_file.as_ref() {
124            let text_logs = config.log_format == LogFormat::Text;
125            Box::new(open_log_file(log_file, text_logs, uses_intro)?) as BoxWrite
126        } else {
127            let stdout = std::io::stdout();
128            Box::new(stdout) as BoxWrite
129        };
130
131        // Builds a lossy NonBlocking logger with a default line limit of 128_000 or an explicit buffer_limit.
132        // The write method queues lines down a bounded channel with this capacity to a worker thread that writes to stdout.
133        // Increments error_counter and drops lines when the buffer is full.
134        let (non_blocking, worker_guard) = NonBlockingBuilder::default()
135            .buffered_lines_limit(config.buffer_limit.max(100))
136            .finish(writer);
137
138        let (event_format, field_format) = super::format::EventFormat::new(config.log_format);
139        let logger = fmt::layer()
140            .fmt_fields(field_format)
141            .event_format(event_format)
142            .with_ansi(use_color)
143            .with_writer(non_blocking);
144        let warn_error_layer = LastWarnErrorLayer {
145            last_warn_error_sender: crate::application::LAST_WARN_ERROR_LOG_SENDER.clone(),
146        };
147
148        // The subscriber is built on `Registry`, so individual layers can add their own filters.
149        //
150        // The configured filter applies to every layer, except in tokio-console builds, where
151        // the console layer needs every tokio span and event.
152        #[cfg(not(all(feature = "tokio-console", tokio_unstable)))]
153        let (subscriber, filter_handle) = {
154            let env_filter = EnvFilter::from(&filter);
155
156            // A reloadable filter takes a lock on every filter check, so it is only installed
157            // when that feature is selected.
158            #[cfg(feature = "filter-reload")]
159            let (env_filter, filter_handle) = {
160                let (env_filter, handle) = tracing_subscriber::reload::Layer::new(env_filter);
161                (env_filter, Some(handle))
162            };
163
164            #[cfg(not(feature = "filter-reload"))]
165            let filter_handle = None;
166
167            let subscriber = tracing_subscriber::registry()
168                .with(env_filter)
169                .with(logger)
170                .with(warn_error_layer)
171                .with(ErrorLayer::new(field_format));
172
173            (subscriber, filter_handle)
174        };
175
176        #[cfg(all(feature = "tokio-console", tokio_unstable))]
177        let (subscriber, filter_handle) = {
178            // TODO: find out why crawl_and_dial and try_to_sync evade this filter,
179            //       and why they also don't get the global net/commit span.
180            // Note: this might have been fixed by tracing 0.3.15, or by recent Zebra refactors.
181            let subscriber = tracing_subscriber::registry()
182                .with(logger.with_filter(EnvFilter::from(&filter)))
183                .with(warn_error_layer.with_filter(EnvFilter::from(&filter)))
184                .with(ErrorLayer::new(field_format).with_filter(EnvFilter::from(&filter)));
185
186            (subscriber, None)
187        };
188
189        // Add optional layers based on dynamic and compile-time configs
190
191        // Add a flamegraph
192        #[cfg(feature = "flamegraph")]
193        let (flamelayer, flamegrapher) = if let Some(path) = flame_root {
194            let (flamelayer, flamegrapher) = flame::layer(path);
195
196            (Some(flamelayer), Some(flamegrapher))
197        } else {
198            (None, None)
199        };
200        #[cfg(feature = "flamegraph")]
201        let subscriber = subscriber.with(flamelayer);
202
203        #[cfg(feature = "journald")]
204        let journaldlayer = if config.use_journald {
205            use abscissa_core::FrameworkErrorKind;
206
207            let layer = tracing_journald::layer()
208                .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?;
209
210            #[cfg(all(feature = "tokio-console", tokio_unstable))]
211            let layer = layer.with_filter(EnvFilter::from(&filter));
212
213            Some(layer)
214        } else {
215            None
216        };
217        #[cfg(feature = "journald")]
218        let subscriber = subscriber.with(journaldlayer);
219
220        #[cfg(feature = "sentry")]
221        let sentry_layer = crate::sentry::tracing_layer();
222        #[cfg(feature = "sentry")]
223        let sentry_installed = sentry_layer.is_some();
224        #[cfg(feature = "sentry")]
225        let subscriber = subscriber.with(sentry_layer);
226
227        // OpenTelemetry layer - zero overhead when config.opentelemetry_endpoint is None
228        #[cfg(feature = "opentelemetry")]
229        let (otel_layer, otel_provider, otel_resolved_config) = {
230            // Check standard OTEL_* env vars as fallback (lower precedence than config/ZEBRA_*)
231            let endpoint = config
232                .opentelemetry_endpoint
233                .clone()
234                .or_else(|| std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok());
235            let service_name = config
236                .opentelemetry_service_name
237                .clone()
238                .or_else(|| std::env::var("OTEL_SERVICE_NAME").ok());
239            let sample_percent = config.opentelemetry_sample_percent;
240
241            // Capture resolved values for logging once the subscriber is installed
242            let sampler_problem = if sample_percent.is_none() {
243                super::otel::sampler_env_problem(
244                    std::env::var("OTEL_TRACES_SAMPLER").ok().as_deref(),
245                    std::env::var("OTEL_TRACES_SAMPLER_ARG").ok().as_deref(),
246                )
247            } else {
248                None
249            };
250            let resolved_config = (
251                endpoint.clone(),
252                service_name.clone().unwrap_or_else(|| "zebra".to_string()),
253                super::otel::sampler_description(sample_percent),
254                sampler_problem,
255            );
256
257            match super::otel::layer(endpoint.as_deref(), service_name.as_deref(), sample_percent) {
258                Ok((layer, provider)) => (layer, provider, resolved_config),
259                Err(e) => {
260                    tracing::warn!(
261                        ?e,
262                        "failed to initialize OpenTelemetry, traces will not be exported"
263                    );
264                    (None, None, resolved_config)
265                }
266            }
267        };
268        #[cfg(feature = "opentelemetry")]
269        let subscriber = subscriber.with(otel_layer);
270
271        // spawn the console server in the background, and apply the console layer
272        // TODO: set Builder::poll_duration_histogram_max() if needed
273        #[cfg(all(feature = "tokio-console", tokio_unstable))]
274        let subscriber = subscriber.with(console_subscriber::spawn());
275
276        // Initialise the global tracing subscriber
277        subscriber.init();
278
279        // Log the tracing stack we just created
280        tracing::info!(
281            ?filter,
282            TRACING_STATIC_MAX_LEVEL = ?tracing::level_filters::STATIC_MAX_LEVEL,
283            LOG_STATIC_MAX_LEVEL = ?log::STATIC_MAX_LEVEL,
284            "started tracing component",
285        );
286
287        if flame_root.is_some() {
288            if cfg!(feature = "flamegraph") {
289                info!(flamegraph = ?flame_root, "installed flamegraph tracing layer");
290            } else {
291                warn!(
292                    flamegraph = ?flame_root,
293                    "unable to activate configured flamegraph: \
294                     enable the 'flamegraph' feature when compiling zebrad",
295                );
296            }
297        }
298
299        if config.use_journald {
300            if cfg!(feature = "journald") {
301                info!("installed journald tracing layer");
302            } else {
303                warn!(
304                    "unable to activate configured journald tracing: \
305                     enable the 'journald' feature when compiling zebrad",
306                );
307            }
308        }
309
310        #[cfg(feature = "sentry")]
311        if sentry_installed {
312            info!("installed sentry tracing layer");
313        }
314
315        #[cfg(all(feature = "tokio-console", tokio_unstable))]
316        info!(
317            TRACING_STATIC_MAX_LEVEL = ?tracing::level_filters::STATIC_MAX_LEVEL,
318            LOG_STATIC_MAX_LEVEL = ?log::STATIC_MAX_LEVEL,
319            "installed tokio-console tracing layer",
320        );
321
322        // Log OpenTelemetry status
323        #[cfg(feature = "opentelemetry")]
324        if otel_provider.is_some() {
325            let (ref endpoint, ref service_name, ref sampler, sampler_problem) =
326                otel_resolved_config;
327            info!(
328                ?endpoint,
329                %service_name,
330                %sampler,
331                "installed OpenTelemetry tracing layer",
332            );
333            if let Some(problem) = sampler_problem {
334                warn!(%sampler, "{problem}");
335            }
336        }
337
338        // Warning if OpenTelemetry is configured but feature not compiled
339        #[cfg(not(feature = "opentelemetry"))]
340        if config.opentelemetry_endpoint.is_some() {
341            warn!(
342                endpoint = ?config.opentelemetry_endpoint,
343                "unable to activate OpenTelemetry tracing: \
344                 enable the 'opentelemetry' feature when compiling zebrad",
345            );
346        }
347
348        // Write any progress reports sent by other tasks to the terminal
349        //
350        // TODO: move this to its own module?
351        #[cfg(feature = "progress-bar")]
352        if let Some(progress_bar_config) = config.progress_bar.as_ref() {
353            use howudoin::consumers::TermLine;
354            use std::time::Duration;
355
356            // Stops flickering during the initial sync.
357            const PROGRESS_BAR_DEBOUNCE: Duration = Duration::from_secs(2);
358
359            let terminal_consumer = TermLine::with_debounce(PROGRESS_BAR_DEBOUNCE);
360            howudoin::init(terminal_consumer);
361
362            info!(?progress_bar_config, "activated progress bars");
363        } else {
364            info!(
365                "set 'tracing.progress_bar =\"summary\"' in zebrad.toml to activate progress bars"
366            );
367        }
368
369        Ok(Self {
370            filter_handle,
371            initial_filter: filter,
372            #[cfg(feature = "flamegraph")]
373            flamegrapher,
374            #[cfg(feature = "opentelemetry")]
375            otel_provider,
376            _guard: Some(worker_guard),
377        })
378    }
379
380    /// Drops guard for worker thread of non-blocking logger,
381    /// to flush any remaining logs when the program terminates.
382    pub fn shutdown(&mut self) {
383        self.filter_handle.take();
384
385        #[cfg(feature = "flamegraph")]
386        self.flamegrapher.take();
387
388        #[cfg(feature = "opentelemetry")]
389        if let Some(provider) = self.otel_provider.take() {
390            if let Err(e) = provider.shutdown() {
391                tracing::warn!(?e, "OpenTelemetry shutdown error");
392            }
393        }
394
395        self._guard.take();
396    }
397
398    /// Return the currently-active tracing filter.
399    pub fn filter(&self) -> String {
400        if let Some(filter_handle) = self.filter_handle.as_ref() {
401            filter_handle
402                .with_current(|filter| filter.to_string())
403                .expect("the subscriber is not dropped before the component is")
404        } else {
405            self.initial_filter.clone()
406        }
407    }
408
409    /// Reload the currently-active filter with the supplied value.
410    ///
411    /// This can be used to provide a dynamic tracing filter endpoint.
412    pub fn reload_filter(&self, filter: impl Into<EnvFilter>) {
413        let filter = filter.into();
414
415        if let Some(filter_handle) = self.filter_handle.as_ref() {
416            tracing::info!(
417                ?filter,
418                TRACING_STATIC_MAX_LEVEL = ?tracing::level_filters::STATIC_MAX_LEVEL,
419                LOG_STATIC_MAX_LEVEL = ?log::STATIC_MAX_LEVEL,
420                "reloading tracing filter",
421            );
422
423            filter_handle
424                .reload(filter)
425                .expect("the subscriber is not dropped before the component is");
426        } else {
427            tracing::warn!(
428                ?filter,
429                TRACING_STATIC_MAX_LEVEL = ?tracing::level_filters::STATIC_MAX_LEVEL,
430                LOG_STATIC_MAX_LEVEL = ?log::STATIC_MAX_LEVEL,
431                "attempted to reload tracing filter, but filter reloading is disabled",
432            );
433        }
434    }
435}
436
437/// Opens `log_file` for appending, and creates its directory if it doesn't exist.
438///
439/// Plain text notices are printed only with text logs, because log collectors usually read
440/// standard output and standard error as well. Opening the file reports any error.
441///
442/// # Security
443///
444/// If the user is running Zebra with elevated permissions ("root"), they should create the log
445/// file directory before running Zebra, and make sure the Zebra user account has exclusive
446/// access to that directory, and other users can't modify its parent directories.
447///
448/// This avoids a TOCTOU security issue in the Rust filesystem API.
449#[allow(clippy::print_stdout, clippy::print_stderr)]
450fn open_log_file(log_file: &Path, text_logs: bool, uses_intro: bool) -> std::io::Result<File> {
451    // If the log is configured in the current directory, it won't have a parent directory.
452    let missing_dir = log_file.parent().filter(|dir| !dir.exists());
453
454    if let Some(log_file_dir) = missing_dir {
455        if text_logs {
456            eprintln!("Directory for log file {log_file:?} does not exist, trying to create it...");
457        }
458
459        let created = fs::create_dir_all(log_file_dir);
460        if let (Err(create_dir_error), true) = (created, text_logs) {
461            eprintln!("Failed to create directory for log file: {create_dir_error}");
462            eprintln!("Trying log file anyway...");
463        }
464    }
465
466    if uses_intro && text_logs {
467        // We want this to appear on stdout instead of the usual log messages.
468        println!("Sending logs to {log_file:?}...");
469    }
470
471    File::options().append(true).create(true).open(log_file)
472}
473
474impl std::fmt::Debug for Tracing {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        f.debug_struct("Tracing").finish()
477    }
478}
479
480impl<A: abscissa_core::Application> Component<A> for Tracing {
481    fn id(&self) -> abscissa_core::component::Id {
482        abscissa_core::component::Id::new("zebrad::components::tracing::component::Tracing")
483    }
484
485    fn version(&self) -> abscissa_core::Version {
486        build_version()
487    }
488
489    fn before_shutdown(&self, _kind: Shutdown) -> Result<(), FrameworkError> {
490        #[cfg(feature = "flamegraph")]
491        if let Some(ref grapher) = self.flamegrapher {
492            use abscissa_core::FrameworkErrorKind;
493
494            info!("writing flamegraph");
495
496            grapher
497                .write_flamegraph()
498                .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?
499        }
500
501        #[cfg(feature = "progress-bar")]
502        howudoin::disable();
503
504        Ok(())
505    }
506}
507
508impl Drop for Tracing {
509    fn drop(&mut self) {
510        #[cfg(feature = "progress-bar")]
511        howudoin::disable();
512    }
513}
514
515// Visitor to extract only the "message" field from a log event.
516struct MessageVisitor {
517    message: Option<String>,
518}
519
520impl Visit for MessageVisitor {
521    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
522        if field.name() == "message" {
523            self.message = Some(format!("{value:?}"));
524        }
525    }
526}
527
528// Layer to store the last WARN or ERROR log event.
529#[derive(Debug, Clone)]
530struct LastWarnErrorLayer {
531    last_warn_error_sender: watch::Sender<Option<(String, Level, chrono::DateTime<chrono::Utc>)>>,
532}
533
534impl<S> Layer<S> for LastWarnErrorLayer
535where
536    S: tracing::Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
537{
538    fn on_event(
539        &self,
540        event: &tracing::Event<'_>,
541        _ctx: tracing_subscriber::layer::Context<'_, S>,
542    ) {
543        let level = *event.metadata().level();
544        let timestamp = chrono::Utc::now();
545
546        if level == Level::WARN || level == Level::ERROR {
547            let mut visitor = MessageVisitor { message: None };
548            event.record(&mut visitor);
549
550            if let Some(message) = visitor.message {
551                let _ = self
552                    .last_warn_error_sender
553                    .send(Some((message, level, timestamp)));
554            }
555        }
556    }
557}