1use 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
33fn fatal_error(app_name: String, err: &dyn std::error::Error) -> ! {
36 status_err!("{} fatal error: {}", app_name, err);
37 process::exit(1)
38}
39
40pub static APPLICATION: AppCell<ZebradApp> = AppCell::new();
42
43lazy_static::lazy_static! {
44 pub static ref LAST_WARN_ERROR_LOG_SENDER: watch::Sender<Option<(String, tracing::Level, chrono::DateTime<chrono::Utc>)>> = watch::Sender::new(None);
46}
47
48pub fn build_version() -> Version {
59 const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
61
62 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
76fn 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
89fn vergen_build_version() -> Option<Version> {
91 const VERGEN_GIT_DESCRIBE: Option<&str> = option_env!("VERGEN_GIT_DESCRIBE");
99
100 let vergen_git_describe = VERGEN_GIT_DESCRIBE?;
110
111 let vergen_git_describe = vergen_git_describe.replace("dirty", "modified");
114
115 let mut vergen_git_describe = vergen_git_describe.split('-').peekable();
117
118 let mut version = vergen_git_describe.next()?;
120
121 version = version.strip_prefix('v').unwrap_or(version);
123
124 if Version::parse(version).is_err() {
126 return None;
127 }
128
129 let mut semver = version.to_string();
130
131 let Some(part) = vergen_git_describe.peek() else {
134 return semver.parse().ok();
136 };
137
138 if part.starts_with(char::is_alphabetic) {
139 semver.push('-');
141 semver.push_str(part);
142
143 let _ = vergen_git_describe.next();
145 }
146
147 let Some(build) = vergen_git_describe.peek() else {
149 return semver.parse().ok();
151 };
152
153 if !build.starts_with(char::is_numeric) {
154 return None;
156 }
157
158 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
168pub fn release_version() -> Version {
170 let mut release_version = build_version();
171
172 release_version.build = BuildMetadata::EMPTY;
173
174 release_version
175}
176
177pub fn user_agent() -> String {
183 let release_version = release_version();
184 format!("/Zebra:{release_version}/")
185}
186
187#[derive(Debug, Default)]
189pub struct ZebradApp {
190 config: CfgCell<ZebradConfig>,
192
193 state: application::State<Self>,
195}
196
197impl ZebradApp {
198 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 type Cmd = EntryPoint;
216
217 type Cfg = ZebradConfig;
219
220 type Paths = StandardPaths;
222
223 fn config(&self) -> Arc<ZebradConfig> {
225 self.config.read()
226 }
227
228 fn state(&self) -> &application::State<Self> {
230 &self.state
231 }
232
233 fn framework_components(
235 &mut self,
236 _command: &Self::Cmd,
237 ) -> Result<Vec<Box<dyn Component<Self>>>, FrameworkError> {
238 let terminal = Terminal::new(ColorChoice::Never);
248
249 Ok(vec![Box::new(terminal)])
250 }
251
252 #[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 let config = match ZebradConfig::load(command.config_path()) {
269 Ok(config) => config,
270 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 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 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 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 ("version", build_version().to_string()),
316 ("Zcash network", config.network.network.to_string()),
318 (
320 "running state version",
321 state_database_format_version_in_code().to_string(),
322 ),
323 ("initial disk state version", disk_db_version),
325 ("features", env!("VERGEN_CARGO_FEATURES").to_string()),
327 ];
328
329 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 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 if PORT_IN_USE_ERROR.is_match(error_str) {
383 return false;
384 }
385 if LOCK_FILE_ERROR.is_match(error_str) {
387 return false;
388 }
389 if error_str.to_string().contains(EOS_PANIC_MESSAGE_HEADER) {
391 return false;
392 }
393 true
394 }
395 color_eyre::ErrorKind::Recoverable(error) => {
396 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 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 && !error_str.contains("error canonicalizing application path")
418 }
419 });
420
421 let (panic_hook, eyre_hook) = builder.into_hooks();
424 eyre_hook.install().expect("eyre_hook.install() error");
425
426 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 if uses_sentry || json_logs {
438 install_panic_hook(panic_hook, uses_sentry, json_logs);
439 }
440
441 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 let mut tracing_config = config.tracing.clone();
459 let metrics_config = config.metrics.clone();
460 if is_server {
461 tracing_config.filter = tracing_config
463 .filter
464 .clone()
465 .or_else(|| Some(default_filter.to_owned()));
466 } else {
467 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 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 if let Some(miner_address) = &config.mining.miner_address {
491 info!(%miner_address, "configured miner address");
492 }
493 }
494
495 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 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 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 self.after_config(config)
529 }
530
531 #[allow(clippy::unwrap_in_result)]
533 fn init(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
534 self.register_components(command)
538 }
539
540 fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
546 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 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
595pub 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#[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}