Skip to main content

zebrad/
application.rs

1//! Zebrad Abscissa Application
2//!
3//! This is the code that starts `zebrad`, and launches its tasks and services.
4//! See [the crate docs](crate) and [the start docs](crate::commands::start) for more details.
5
6use std::{env, fmt::Write as _, io::Write as _, process, sync::Arc};
7
8use abscissa_core::{
9    application::{self, AppCell},
10    config::CfgCell,
11    status_err,
12    terminal::{component::Terminal, stderr, stdout, ColorChoice},
13    Application, Component, Configurable, FrameworkError, Shutdown, StandardPaths,
14};
15use semver::{BuildMetadata, Version};
16
17use tokio::sync::watch;
18use zebra_network::constants::PORT_IN_USE_ERROR;
19use zebra_state::{
20    constants::LOCK_FILE_ERROR, state_database_format_version_in_code,
21    state_database_format_version_on_disk,
22};
23
24use crate::{
25    commands::EntryPoint,
26    components::{
27        sync::end_of_support::EOS_PANIC_MESSAGE_HEADER,
28        tracing::{json_panic_line, LogFormat, Tracing},
29    },
30    config::ZebradConfig,
31};
32
33/// See <https://docs.rs/abscissa_core/latest/src/abscissa_core/application/exit.rs.html#7-10>
34/// Print a fatal error message and exit
35fn fatal_error(app_name: String, err: &dyn std::error::Error) -> ! {
36    status_err!("{} fatal error: {}", app_name, err);
37    process::exit(1)
38}
39
40/// Application state
41pub static APPLICATION: AppCell<ZebradApp> = AppCell::new();
42
43lazy_static::lazy_static! {
44    /// The last log event that occurred in the application.
45    pub static ref LAST_WARN_ERROR_LOG_SENDER: watch::Sender<Option<(String, tracing::Level, chrono::DateTime<chrono::Utc>)>> = watch::Sender::new(None);
46}
47
48/// Returns the `zebrad` version for this build, in SemVer 2.0 format.
49///
50/// Includes `git describe` build metatata if available:
51/// - the number of commits since the last version tag, and
52/// - the git commit.
53///
54/// Otherwise, includes the git commit alone if it is known, such as in Docker images, which are
55/// built without `.git`.
56///
57/// For details, see <https://semver.org/>
58pub fn build_version() -> Version {
59    // CARGO_PKG_VERSION is always a valid SemVer 2.0 version.
60    const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
61
62    // We're using the same library as cargo uses internally, so this is guaranteed.
63    let fallback_version = CARGO_PKG_VERSION.parse().unwrap_or_else(|error| {
64        panic!(
65            "unexpected invalid CARGO_PKG_VERSION: {error:?} in {CARGO_PKG_VERSION:?}, \
66             should have been checked by cargo"
67        )
68    });
69
70    with_git_commit(
71        vergen_build_version().unwrap_or(fallback_version),
72        ZebradApp::git_commit(),
73    )
74}
75
76/// Adds `git.<git_commit>` build metadata to `version`, if it has no build metadata.
77fn with_git_commit(mut version: Version, git_commit: Option<&str>) -> Version {
78    if version.build.is_empty() {
79        if let Some(build) =
80            git_commit.and_then(|commit| BuildMetadata::new(&format!("git.{commit}")).ok())
81        {
82            version.build = build;
83        }
84    }
85
86    version
87}
88
89/// Returns the `zebrad` version from this build, if available from `vergen`.
90fn vergen_build_version() -> Option<Version> {
91    // VERGEN_GIT_DESCRIBE should be in the format:
92    // - v1.0.0-rc.9-6-g319b01bb84
93    // - v1.0.0-6-g319b01bb84
94    // but sometimes it is just a short commit hash. See #6879 for details.
95    //
96    // Currently it is the output of `git describe --tags --dirty --match='v*.*.*'`,
97    // or whatever is specified in zebrad/build.rs.
98    const VERGEN_GIT_DESCRIBE: Option<&str> = option_env!("VERGEN_GIT_DESCRIBE");
99
100    // The SemVer 2.0 format is:
101    // - 1.0.0-rc.9+6.g319b01bb84
102    // - 1.0.0+6.g319b01bb84
103    //
104    // Or as a pattern:
105    // - version: major`.`minor`.`patch
106    // - optional pre-release: `-`tag[`.`tag ...]
107    // - optional build: `+`tag[`.`tag ...]
108    // change the git describe format to the semver 2.0 format
109    let vergen_git_describe = VERGEN_GIT_DESCRIBE?;
110
111    // `git describe` uses "dirty" for uncommitted changes,
112    // but users won't understand what that means.
113    let vergen_git_describe = vergen_git_describe.replace("dirty", "modified");
114
115    // Split using "git describe" separators.
116    let mut vergen_git_describe = vergen_git_describe.split('-').peekable();
117
118    // Check the "version core" part.
119    let mut version = vergen_git_describe.next()?;
120
121    // strip the leading "v", if present.
122    version = version.strip_prefix('v').unwrap_or(version);
123
124    // If the initial version is empty, just a commit hash, or otherwise invalid.
125    if Version::parse(version).is_err() {
126        return None;
127    }
128
129    let mut semver = version.to_string();
130
131    // Check if the next part is a pre-release or build part,
132    // but only consume it if it is a pre-release tag.
133    let Some(part) = vergen_git_describe.peek() else {
134        // No pre-release or build.
135        return semver.parse().ok();
136    };
137
138    if part.starts_with(char::is_alphabetic) {
139        // It's a pre-release tag.
140        semver.push('-');
141        semver.push_str(part);
142
143        // Consume the pre-release tag to move on to the build tags, if any.
144        let _ = vergen_git_describe.next();
145    }
146
147    // Check if the next part is a build part.
148    let Some(build) = vergen_git_describe.peek() else {
149        // No build tags.
150        return semver.parse().ok();
151    };
152
153    if !build.starts_with(char::is_numeric) {
154        // It's not a valid "commit count" build tag from "git describe".
155        return None;
156    }
157
158    // Append the rest of the build parts with the correct `+` and `.` separators.
159    let build_parts: Vec<_> = vergen_git_describe.collect();
160    let build_parts = build_parts.join(".");
161
162    semver.push('+');
163    semver.push_str(&build_parts);
164
165    semver.parse().ok()
166}
167
168/// The Zebra current release version, without any build metadata.
169pub fn release_version() -> Version {
170    let mut release_version = build_version();
171
172    release_version.build = BuildMetadata::EMPTY;
173
174    release_version
175}
176
177/// The User-Agent string provided by the node.
178///
179/// This must be a valid [BIP 14] user agent.
180///
181/// [BIP 14]: https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki
182pub fn user_agent() -> String {
183    let release_version = release_version();
184    format!("/Zebra:{release_version}/")
185}
186
187/// Zebrad Application
188#[derive(Debug, Default)]
189pub struct ZebradApp {
190    /// Application configuration.
191    config: CfgCell<ZebradConfig>,
192
193    /// Application state.
194    state: application::State<Self>,
195}
196
197impl ZebradApp {
198    /// Returns the git commit for this build, if available.
199    ///
200    ///
201    /// # Accuracy
202    ///
203    /// If the user makes changes, but does not commit them, the git commit will
204    /// not match the compiled source code.
205    pub fn git_commit() -> Option<&'static str> {
206        const GIT_COMMIT_GCLOUD: Option<&str> = option_env!("SHORT_SHA");
207        const GIT_COMMIT_VERGEN: Option<&str> = option_env!("VERGEN_GIT_SHA");
208
209        GIT_COMMIT_GCLOUD.or(GIT_COMMIT_VERGEN)
210    }
211}
212
213impl Application for ZebradApp {
214    /// Entrypoint command for this application.
215    type Cmd = EntryPoint;
216
217    /// Application configuration.
218    type Cfg = ZebradConfig;
219
220    /// Paths to resources within the application.
221    type Paths = StandardPaths;
222
223    /// Accessor for application configuration.
224    fn config(&self) -> Arc<ZebradConfig> {
225        self.config.read()
226    }
227
228    /// Borrow the application state immutably.
229    fn state(&self) -> &application::State<Self> {
230        &self.state
231    }
232
233    /// Returns the framework components used by this application.
234    fn framework_components(
235        &mut self,
236        _command: &Self::Cmd,
237    ) -> Result<Vec<Box<dyn Component<Self>>>, FrameworkError> {
238        // TODO: Open a PR in abscissa to add a TerminalBuilder for opting out
239        //       of the `color_eyre::install` part of `Terminal::new` without
240        //       ColorChoice::Never?
241
242        // The Tracing component uses stdout directly and will apply colors automatically.
243        //
244        // Note: It's important to use `ColorChoice::Never` here to avoid panicking in
245        //       `register_components()` below if `color_eyre::install()` is called
246        //       after `color_spantrace` has been initialized.
247        let terminal = Terminal::new(ColorChoice::Never);
248
249        Ok(vec![Box::new(terminal)])
250    }
251
252    /// Register all components used by this application.
253    ///
254    /// If you would like to add additional components to your application
255    /// beyond the default ones provided by the framework, this is the place
256    /// to do so.
257    #[allow(clippy::print_stderr)]
258    #[allow(clippy::unwrap_in_result)]
259    fn register_components(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
260        use crate::components::{
261            metrics::MetricsEndpoint, tokio::TokioComponent, tracing::TracingEndpoint,
262        };
263
264        let mut components = self.framework_components(command)?;
265
266        // Load config *after* framework components so that we can
267        // report an error to the terminal if it occurs (unless used with a command that doesn't need the config).
268        let config = match ZebradConfig::load(command.config_path()) {
269            Ok(config) => config,
270            // Ignore errors loading the config for some commands.
271            Err(_e) if command.cmd().should_ignore_load_config_error() => Default::default(),
272            Err(e) => {
273                status_err!(
274                    "Zebra could not load the provided configuration file and/or environment variables.\
275                     This might mean you are using a deprecated format of the file, or are attempting to
276                     configure deprecated or unknown fields via environment variables.\
277                     You can generate a valid config by running \"zebrad generate\", \
278                     and diff it against yours to examine any format inconsistencies."
279                );
280                // Convert config::ConfigError to FrameworkError using a generic IO error
281                let io_error = std::io::Error::new(
282                    std::io::ErrorKind::InvalidData,
283                    format!("Configuration error: {}", e),
284                );
285                return Err(FrameworkError::from(io_error));
286            }
287        };
288
289        let config = command.process_config(config)?;
290
291        let theme = if config.tracing.use_color_stdout_and_stderr() {
292            color_eyre::config::Theme::dark()
293        } else {
294            color_eyre::config::Theme::new()
295        };
296
297        // collect the common metadata for the issue URL and panic report,
298        // skipping any env vars that aren't present
299
300        // reads state disk version file, doesn't open RocksDB database
301        let disk_db_version =
302            match state_database_format_version_on_disk(&config.state, &config.network.network) {
303                Ok(Some(version)) => version.to_string(),
304                // This "version" is specially formatted to match a relaxed version regex in CI
305                Ok(None) => "creating.new.database".to_string(),
306                Err(error) => {
307                    let mut error = format!("error: {error:?}");
308                    error.truncate(100);
309                    error
310                }
311            };
312
313        let app_metadata = [
314            // build-time constant: cargo or git tag + short commit
315            ("version", build_version().to_string()),
316            // config
317            ("Zcash network", config.network.network.to_string()),
318            // code constant
319            (
320                "running state version",
321                state_database_format_version_in_code().to_string(),
322            ),
323            // state disk file, doesn't open database
324            ("initial disk state version", disk_db_version),
325            // build-time constant
326            ("features", env!("VERGEN_CARGO_FEATURES").to_string()),
327        ];
328
329        // git env vars can be skipped if there is no `.git` during the
330        // build, so they must all be optional
331        let git_metadata: &[(_, Option<_>)] = &[
332            ("branch", option_env!("VERGEN_GIT_BRANCH")),
333            ("git commit", Self::git_commit()),
334            (
335                "commit timestamp",
336                option_env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
337            ),
338        ];
339        // skip missing metadata
340        let git_metadata: Vec<(_, String)> = git_metadata
341            .iter()
342            .filter_map(|(k, v)| Some((k, (*v)?)))
343            .map(|(k, v)| (*k, v.to_string()))
344            .collect();
345
346        let build_metadata: Vec<_> = [
347            ("target triple", env!("VERGEN_CARGO_TARGET_TRIPLE")),
348            ("rust compiler", env!("VERGEN_RUSTC_SEMVER")),
349            ("rust release date", env!("VERGEN_RUSTC_COMMIT_DATE")),
350            ("optimization level", env!("VERGEN_CARGO_OPT_LEVEL")),
351            ("debug checks", env!("VERGEN_CARGO_DEBUG")),
352        ]
353        .iter()
354        .map(|(k, v)| (*k, v.to_string()))
355        .collect();
356
357        let panic_metadata: Vec<_> = app_metadata
358            .iter()
359            .chain(git_metadata.iter())
360            .chain(build_metadata.iter())
361            .collect();
362
363        let mut builder = color_eyre::config::HookBuilder::default();
364        let mut metadata_section = "Diagnostic metadata:".to_string();
365        for (k, v) in panic_metadata {
366            builder = builder.add_issue_metadata(k, v.clone());
367            write!(&mut metadata_section, "\n{k}: {v}")
368                .expect("unexpected failure writing to string");
369        }
370
371        builder = builder
372            .theme(theme)
373            .panic_section(metadata_section.clone())
374            .issue_url(concat!(env!("CARGO_PKG_REPOSITORY"), "/issues/new"))
375            .issue_filter(|kind| match kind {
376                color_eyre::ErrorKind::NonRecoverable(error) => {
377                    let error_str = match error.downcast_ref::<String>() {
378                        Some(as_string) => as_string,
379                        None => return true,
380                    };
381                    // listener port conflicts
382                    if PORT_IN_USE_ERROR.is_match(error_str) {
383                        return false;
384                    }
385                    // RocksDB lock file conflicts
386                    if LOCK_FILE_ERROR.is_match(error_str) {
387                        return false;
388                    }
389                    // Don't ask users to report old version panics.
390                    if error_str.to_string().contains(EOS_PANIC_MESSAGE_HEADER) {
391                        return false;
392                    }
393                    true
394                }
395                color_eyre::ErrorKind::Recoverable(error) => {
396                    // Type checks should be faster than string conversions.
397                    //
398                    // Don't ask users to create bug reports for timeouts, peer errors, or
399                    // RPC credential configuration errors.
400                    if error.is::<tower::timeout::error::Elapsed>()
401                        || error.is::<tokio::time::error::Elapsed>()
402                        || error.is::<zebra_network::PeerError>()
403                        || error.is::<zebra_network::SharedPeerError>()
404                        || error.is::<zebra_network::HandshakeError>()
405                        || error.is::<zebra_rpc::config::rpc::StaticCredentialsError>()
406                    {
407                        return false;
408                    }
409
410                    // Don't ask users to create bug reports for known timeouts, duplicate blocks,
411                    // full disks, or updated binaries.
412                    let error_str = error.to_string();
413                    !error_str.contains("timed out")
414                        && !error_str.contains("duplicate hash")
415                        && !error_str.contains("No space left on device")
416                        // abscissa panics like this when the running zebrad binary has been updated
417                        && !error_str.contains("error canonicalizing application path")
418                }
419            });
420
421        // This MUST happen after `Terminal::new` to ensure our preferred panic
422        // handler is the last one installed
423        let (panic_hook, eyre_hook) = builder.into_hooks();
424        eyre_hook.install().expect("eyre_hook.install() error");
425
426        // The Sentry default config pulls in the DSN from the `SENTRY_DSN`
427        // environment variable.
428        let uses_sentry = env::var_os("SENTRY_DSN").is_some();
429        let json_logs = config.tracing.log_format == LogFormat::Json;
430
431        #[cfg(feature = "sentry")]
432        if uses_sentry {
433            crate::sentry::init(&config.network.network);
434        }
435
436        // Otherwise, the default panic hook prints the panic.
437        if uses_sentry || json_logs {
438            install_panic_hook(panic_hook, uses_sentry, json_logs);
439        }
440
441        // Apply the configured number of threads to the thread pool.
442        //
443        // TODO:
444        // - set rayon panic handler to a function that takes `Box<dyn Any + Send + 'static>`,
445        //   which forwards to sentry. If possible, use eyre's panic report for formatting.
446        // - do we also need to call this code in `zebra_consensus::init()`,
447        //   when that crate is being used by itself?
448        rayon::ThreadPoolBuilder::new()
449            .num_threads(config.sync.parallel_cpu_threads)
450            .thread_name(|thread_index| format!("rayon {thread_index}"))
451            .build_global()
452            .expect("unable to initialize rayon thread pool");
453
454        let default_filter = command.cmd().default_tracing_filter(command.verbose);
455        let is_server = command.cmd().is_server();
456
457        // Ignore the configured tracing filter for short-lived utility commands
458        let mut tracing_config = config.tracing.clone();
459        let metrics_config = config.metrics.clone();
460        if is_server {
461            // Override the default tracing filter based on the command-line verbosity.
462            tracing_config.filter = tracing_config
463                .filter
464                .clone()
465                .or_else(|| Some(default_filter.to_owned()));
466        } else {
467            // Don't apply the configured filter for short-lived commands.
468            tracing_config.filter = Some(default_filter.to_owned());
469            tracing_config.flamegraph = None;
470        }
471        components.push(Box::new(Tracing::new(
472            &config.network.network,
473            tracing_config,
474            command.cmd().uses_intro(),
475        )?));
476
477        // Log git metadata and platform info when zebrad starts up
478        if is_server {
479            info!("{metadata_section}");
480
481            if command.config_path().is_some() {
482                info!("Using config file at: {:?}", command.config_path().unwrap());
483            } else {
484                info!("No config file provided, using default configuration");
485            }
486
487            info!("{config:?}");
488
489            // Explicitly log the configured miner address so CI can assert env override
490            if let Some(miner_address) = &config.mining.miner_address {
491                info!(%miner_address, "configured miner address");
492            }
493        }
494
495        // Activate the global span, so it's visible when we load the other
496        // components. Space is at a premium here, so we use an empty message,
497        // short commit hash, and the unique part of the network name.
498        let net = config.network.network.to_string();
499        let net = match net.as_str() {
500            default_net_name @ ("Testnet" | "Mainnet") => &default_net_name[..4],
501            other_net_name => other_net_name,
502        };
503        let global_span = if let Some(git_commit) = ZebradApp::git_commit() {
504            error_span!("", zebrad = git_commit, net)
505        } else {
506            error_span!("", net)
507        };
508
509        let global_guard = global_span.enter();
510        // leak the global span, to make sure it stays active
511        std::mem::forget(global_guard);
512
513        tracing::info!(
514            num_threads = rayon::current_num_threads(),
515            "initialized rayon thread pool for CPU-bound tasks",
516        );
517
518        // Launch network and async endpoints only for long-running commands.
519        if is_server {
520            components.push(Box::new(TokioComponent::new()?));
521            components.push(Box::new(TracingEndpoint::new(&config)?));
522            components.push(Box::new(MetricsEndpoint::new(&metrics_config)?));
523        }
524
525        self.state.components_mut().register(components)?;
526
527        // Fire callback to signal state in the application lifecycle
528        self.after_config(config)
529    }
530
531    /// Load this application's configuration and initialize its components.
532    #[allow(clippy::unwrap_in_result)]
533    fn init(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
534        // Create and register components with the application.
535        // We do this first to calculate a proper dependency ordering before
536        // application configuration is processed
537        self.register_components(command)
538    }
539
540    /// Post-configuration lifecycle callback.
541    ///
542    /// Called regardless of whether config is loaded to indicate this is the
543    /// time in app lifecycle when configuration would be loaded if
544    /// possible.
545    fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
546        // Configure components
547        self.state.components_mut().after_config(&config)?;
548        self.config.set_once(config);
549
550        Ok(())
551    }
552
553    fn shutdown(&self, shutdown: Shutdown) -> ! {
554        // Some OSes require a flush to send all output to the terminal.
555        // zebrad's logging uses Abscissa, so we flush its streams.
556        //
557        // TODO:
558        // - if this doesn't work, send an empty line as well
559        // - move this code to the tracing component's `before_shutdown()`
560        let _ = stdout().lock().flush();
561        let _ = stderr().lock().flush();
562
563        let shutdown_result = self.state().components().shutdown(self, shutdown);
564
565        #[cfg(feature = "sentry")]
566        {
567            let status = match shutdown {
568                Shutdown::Graceful => sentry::protocol::SessionStatus::Exited,
569                Shutdown::Forced | Shutdown::Crash => sentry::protocol::SessionStatus::Crashed,
570            };
571
572            if !crate::sentry::end(status) {
573                warn!("unable to flush sentry events during shutdown");
574            }
575        }
576
577        self.state()
578            .components_mut()
579            .get_downcast_mut::<Tracing>()
580            .map(Tracing::shutdown);
581
582        if let Err(e) = shutdown_result {
583            let app_name = self.name().to_string();
584            fatal_error(app_name, &e);
585        }
586
587        match shutdown {
588            Shutdown::Graceful => process::exit(0),
589            Shutdown::Forced => process::exit(1),
590            Shutdown::Crash => process::exit(2),
591        }
592    }
593}
594
595/// Boot the given application, parsing subcommand and options from
596/// command-line arguments, and terminating when complete.
597// <https://docs.rs/abscissa_core/0.7.0/src/abscissa_core/application.rs.html#174-178>
598pub fn boot(app_cell: &'static AppCell<ZebradApp>) -> ! {
599    let args =
600        EntryPoint::process_cli_args(env::args_os().collect()).unwrap_or_else(|err| err.exit());
601
602    ZebradApp::run(app_cell, args);
603    process::exit(0);
604}
605
606/// Installs a panic hook that writes the panic to standard error, as one JSON line with JSON
607/// logs, and sends it to Sentry when Sentry is enabled.
608///
609/// Logs are written by another thread, which doesn't run again after a panic, so the panic is
610/// written to standard error directly.
611#[allow(clippy::print_stderr)]
612fn install_panic_hook(
613    panic_hook: color_eyre::config::PanicHook,
614    #[cfg_attr(not(feature = "sentry"), allow(unused_variables))] uses_sentry: bool,
615    json_logs: bool,
616) {
617    std::panic::set_hook(Box::new(move |panic_info| {
618        let panic_report = panic_hook.panic_report(panic_info);
619
620        if json_logs {
621            eprintln!("{}", json_panic_line(panic_info));
622        } else {
623            eprintln!("{panic_report}");
624        }
625
626        #[cfg(feature = "sentry")]
627        if uses_sentry {
628            let event = crate::sentry::panic_event_from(panic_info, panic_report);
629            sentry::capture_event(event);
630
631            if !crate::sentry::end(sentry::protocol::SessionStatus::Crashed) {
632                warn!("unable to flush sentry events during panic");
633            }
634        }
635    }));
636}
637
638#[cfg(test)]
639mod tests {
640    use semver::Version;
641
642    use super::with_git_commit;
643
644    #[test]
645    fn with_git_commit_adds_commit_without_build_metadata() {
646        let version = with_git_commit(Version::new(7, 0, 0), Some("6d1e414"));
647
648        assert_eq!(version.to_string(), "7.0.0+git.6d1e414");
649    }
650
651    #[test]
652    fn with_git_commit_keeps_git_describe_metadata() {
653        let version =
654            Version::parse("7.0.0-rc.0+12.g6d1e414").expect("hard-coded version is valid");
655
656        assert_eq!(with_git_commit(version.clone(), Some("6d1e414")), version);
657    }
658
659    #[test]
660    fn with_git_commit_skips_missing_or_invalid_commits() {
661        let version = Version::new(7, 0, 0);
662
663        assert_eq!(with_git_commit(version.clone(), None), version);
664        assert_eq!(
665            with_git_commit(version.clone(), Some("not a commit")),
666            version
667        );
668    }
669}