1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
mod entry_point;
use self::entry_point::EntryPoint;
use std::{fmt::Write as _, io::Write as _, process};
use abscissa_core::{
application::{self, AppCell},
config::{self, Configurable},
status_err,
terminal::{component::Terminal, stderr, stdout, ColorChoice},
Application, Component, FrameworkError, Shutdown, StandardPaths, Version,
};
use zebra_network::constants::PORT_IN_USE_ERROR;
use zebra_state::constants::{DATABASE_FORMAT_VERSION, LOCK_FILE_ERROR};
use crate::{commands::ZebradCmd, components::tracing::Tracing, config::ZebradConfig};
fn fatal_error(app_name: String, err: &dyn std::error::Error) -> ! {
status_err!("{} fatal error: {}", app_name, err);
process::exit(1)
}
pub static APPLICATION: AppCell<ZebradApp> = AppCell::new();
pub fn app_reader() -> application::lock::Reader<ZebradApp> {
APPLICATION.read()
}
pub fn app_writer() -> application::lock::Writer<ZebradApp> {
APPLICATION.write()
}
pub fn app_config() -> config::Reader<ZebradApp> {
config::Reader::new(&APPLICATION)
}
pub fn app_version() -> Version {
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
let vergen_git_semver: Option<&str> = option_env!("VERGEN_GIT_SEMVER_LIGHTWEIGHT");
match vergen_git_semver {
Some(mut vergen_git_semver) if !vergen_git_semver.is_empty() => {
if &vergen_git_semver[0..1] == "v" {
vergen_git_semver = &vergen_git_semver[1..];
}
let rparts: Vec<_> = vergen_git_semver.rsplitn(3, '-').collect();
match rparts.as_slice() {
[_] | [_, _] => vergen_git_semver.parse().unwrap_or_else(|_| {
panic!(
"VERGEN_GIT_SEMVER without a hash {vergen_git_semver:?} must be valid semver 2.0"
)
}),
[hash, commit_count, tag] => {
let semver_fix = format!("{tag}+{commit_count}.{hash}");
semver_fix.parse().unwrap_or_else(|_|
panic!("Modified VERGEN_GIT_SEMVER {vergen_git_semver:?} -> {rparts:?} -> {semver_fix:?} must be valid. Note: CARGO_PKG_VERSION was {CARGO_PKG_VERSION:?}."))
}
_ => unreachable!("split is limited to 3 parts"),
}
}
_ => CARGO_PKG_VERSION.parse().unwrap_or_else(|_| {
panic!("CARGO_PKG_VERSION {CARGO_PKG_VERSION:?} must be valid semver 2.0")
}),
}
}
#[derive(Debug)]
pub struct ZebradApp {
config: Option<ZebradConfig>,
state: application::State<Self>,
}
impl ZebradApp {
fn outputs_are_ttys() -> bool {
atty::is(atty::Stream::Stdout) && atty::is(atty::Stream::Stderr)
}
pub fn git_commit() -> Option<&'static str> {
const GIT_COMMIT_GCLOUD: Option<&str> = option_env!("SHORT_SHA");
const GIT_COMMIT_VERGEN: Option<&str> = option_env!("VERGEN_GIT_SHA_SHORT");
GIT_COMMIT_GCLOUD.or(GIT_COMMIT_VERGEN)
}
}
#[allow(unknown_lints)]
#[allow(clippy::derivable_impls)]
impl Default for ZebradApp {
fn default() -> Self {
Self {
config: None,
state: application::State::default(),
}
}
}
impl Application for ZebradApp {
type Cmd = EntryPoint;
type Cfg = ZebradConfig;
type Paths = StandardPaths;
fn config(&self) -> &ZebradConfig {
self.config.as_ref().expect("config not loaded")
}
fn state(&self) -> &application::State<Self> {
&self.state
}
fn state_mut(&mut self) -> &mut application::State<Self> {
&mut self.state
}
fn framework_components(
&mut self,
command: &Self::Cmd,
) -> Result<Vec<Box<dyn Component<Self>>>, FrameworkError> {
let mut term_colors = self.term_colors(command);
if term_colors == ColorChoice::Auto {
if !Self::outputs_are_ttys() {
term_colors = ColorChoice::Never;
}
}
let terminal = Terminal::new(term_colors);
Ok(vec![Box::new(terminal)])
}
#[allow(clippy::print_stderr)]
#[allow(clippy::unwrap_in_result)]
fn register_components(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
use crate::components::{
metrics::MetricsEndpoint, tokio::TokioComponent, tracing::TracingEndpoint,
};
let mut components = self.framework_components(command)?;
let config = match command.config_path() {
Some(path) => match self.load_config(&path) {
Ok(config) => config,
Err(e) => {
status_err!("Zebra could not parse the provided config file. This might mean you are using a deprecated format of the file. You can generate a valid config by running \"zebrad generate\", and diff it against yours to examine any format inconsistencies.");
return Err(e);
}
},
None => ZebradConfig::default(),
};
let config = command.process_config(config)?;
let theme = if Self::outputs_are_ttys() && config.tracing.use_color {
color_eyre::config::Theme::dark()
} else {
color_eyre::config::Theme::new()
};
let app_metadata = vec![
("version", app_version().to_string()),
("Zcash network", config.network.network.to_string()),
("state version", DATABASE_FORMAT_VERSION.to_string()),
];
let git_metadata: &[(_, Option<_>)] = &[
("branch", option_env!("VERGEN_GIT_BRANCH")),
("git commit", Self::git_commit()),
(
"commit timestamp",
option_env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
),
];
let git_metadata: Vec<(_, String)> = git_metadata
.iter()
.filter_map(|(k, v)| Some((k, (*v)?)))
.map(|(k, v)| (*k, v.to_string()))
.collect();
let build_metadata: Vec<_> = [
("target triple", env!("VERGEN_CARGO_TARGET_TRIPLE")),
("build profile", env!("VERGEN_CARGO_PROFILE")),
]
.iter()
.map(|(k, v)| (*k, v.to_string()))
.collect();
let panic_metadata: Vec<_> = app_metadata
.iter()
.chain(git_metadata.iter())
.chain(build_metadata.iter())
.collect();
let mut builder = color_eyre::config::HookBuilder::default();
let mut metadata_section = "Metadata:".to_string();
for (k, v) in panic_metadata {
builder = builder.add_issue_metadata(k, v.clone());
write!(&mut metadata_section, "\n{k}: {}", &v)
.expect("unexpected failure writing to string");
}
builder = builder
.theme(theme)
.panic_section(metadata_section.clone())
.issue_url(concat!(env!("CARGO_PKG_REPOSITORY"), "/issues/new"))
.issue_filter(|kind| match kind {
color_eyre::ErrorKind::NonRecoverable(error) => {
let error_str = match error.downcast_ref::<String>() {
Some(as_string) => as_string,
None => return true,
};
if PORT_IN_USE_ERROR.is_match(error_str) {
return false;
}
if LOCK_FILE_ERROR.is_match(error_str) {
return false;
}
true
}
color_eyre::ErrorKind::Recoverable(error) => {
if error.is::<tower::timeout::error::Elapsed>()
|| error.is::<tokio::time::error::Elapsed>()
|| error.is::<zebra_network::PeerError>()
|| error.is::<zebra_network::SharedPeerError>()
|| error.is::<zebra_network::HandshakeError>()
{
return false;
}
let error_str = error.to_string();
!error_str.contains("timed out")
&& !error_str.contains("duplicate hash")
&& !error_str.contains("No space left on device")
}
});
let (panic_hook, eyre_hook) = builder.into_hooks();
eyre_hook.install().expect("eyre_hook.install() error");
#[cfg(feature = "sentry")]
let guard = sentry::init(sentry::ClientOptions {
debug: true,
release: Some(app_version().to_string().into()),
..Default::default()
});
std::panic::set_hook(Box::new(move |panic_info| {
let panic_report = panic_hook.panic_report(panic_info);
eprintln!("{panic_report}");
#[cfg(feature = "sentry")]
{
let event = crate::sentry::panic_event_from(panic_report);
sentry::capture_event(event);
if !guard.close(None) {
warn!("unable to flush sentry events during panic");
}
}
}));
rayon::ThreadPoolBuilder::new()
.num_threads(config.sync.parallel_cpu_threads)
.thread_name(|thread_index| format!("rayon {thread_index}"))
.build_global()
.expect("unable to initialize rayon thread pool");
self.config = Some(config);
let cfg_ref = self
.config
.as_ref()
.expect("config is loaded before register_components");
let default_filter = command
.command
.as_ref()
.map(|zcmd| zcmd.default_tracing_filter(command.verbose, command.help))
.unwrap_or("warn");
let is_server = command
.command
.as_ref()
.map(ZebradCmd::is_server)
.unwrap_or(false);
let mut tracing_config = cfg_ref.tracing.clone();
let metrics_config = cfg_ref.metrics.clone();
if is_server {
tracing_config.filter = tracing_config
.filter
.or_else(|| Some(default_filter.to_owned()));
} else {
tracing_config.filter = Some(default_filter.to_owned());
tracing_config.flamegraph = None;
}
components.push(Box::new(Tracing::new(tracing_config)?));
if is_server {
tracing::info!("Diagnostic {}", metadata_section);
info!(config_path = ?command.config_path(), config = ?cfg_ref, "loaded zebrad config");
}
let net = &self.config.clone().unwrap().network.network.to_string()[..4];
let global_span = if let Some(git_commit) = ZebradApp::git_commit() {
error_span!("", zebrad = git_commit, net)
} else {
error_span!("", net)
};
let global_guard = global_span.enter();
std::mem::forget(global_guard);
tracing::info!(
num_threads = rayon::current_num_threads(),
"initialized rayon thread pool for CPU-bound tasks",
);
if is_server {
components.push(Box::new(TokioComponent::new()?));
components.push(Box::new(TracingEndpoint::new(cfg_ref)?));
components.push(Box::new(MetricsEndpoint::new(&metrics_config)?));
}
self.state.components.register(components)
}
#[allow(clippy::unwrap_in_result)]
fn init(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
self.register_components(command)?;
let config = self
.config
.take()
.expect("register_components always populates the config");
self.after_config(config)?;
Ok(())
}
fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
self.state.components.after_config(&config)?;
self.config = Some(config);
Ok(())
}
fn shutdown(&mut self, shutdown: Shutdown) -> ! {
let _ = stdout().lock().flush();
let _ = stderr().lock().flush();
if let Err(e) = self.state().components.shutdown(self, shutdown) {
let app_name = self.name().to_string();
let _ = std::mem::take(self);
fatal_error(app_name, &e);
}
let _ = std::mem::take(self);
match shutdown {
Shutdown::Graceful => process::exit(0),
Shutdown::Forced => process::exit(1),
Shutdown::Crash => process::exit(2),
}
}
fn version(&self) -> Version {
app_version()
}
}