zebra_state/service/finalized_state/disk_format/upgrade.rs
1//! In-place format upgrades and format validity checks for the Zebra state database.
2
3use std::{
4 cmp::Ordering,
5 sync::Arc,
6 thread::{self, JoinHandle},
7 time::Duration,
8};
9
10use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, Sender};
11use semver::Version;
12use tracing::Span;
13
14use zebra_chain::{
15 block::Height,
16 diagnostic::{
17 task::{CheckForPanics, WaitForPanics},
18 CodeTimer,
19 },
20};
21
22use DbFormatChange::*;
23
24use crate::service::finalized_state::ZebraDb;
25
26pub(crate) mod add_ironwood_tree;
27pub(crate) mod add_subtrees;
28pub(crate) mod block_info_and_address_received;
29pub(crate) mod cache_genesis_roots;
30pub(crate) mod fix_tree_key_type;
31pub(crate) mod no_migration;
32pub(crate) mod prune_trees;
33pub(crate) mod tree_keys_and_caches_upgrade;
34
35#[cfg(not(feature = "indexer"))]
36pub(crate) mod drop_tx_locs_by_spends;
37
38#[cfg(feature = "indexer")]
39pub(crate) mod track_tx_locs_by_spends;
40
41/// Defines method signature for running disk format upgrades.
42pub trait DiskFormatUpgrade {
43 /// Returns the version at which this upgrade is applied.
44 fn version(&self) -> Version;
45
46 /// Returns the description of this upgrade.
47 fn description(&self) -> &'static str;
48
49 /// Runs disk format upgrade.
50 fn run(
51 &self,
52 initial_tip_height: Height,
53 db: &ZebraDb,
54 cancel_receiver: &Receiver<CancelFormatChange>,
55 ) -> Result<(), CancelFormatChange>;
56
57 /// Check that state has been upgraded to this format correctly.
58 ///
59 /// The outer `Result` indicates whether the validation was cancelled (due to e.g. node shutdown).
60 /// The inner `Result` indicates whether the validation itself failed or not.
61 fn validate(
62 &self,
63 _db: &ZebraDb,
64 _cancel_receiver: &Receiver<CancelFormatChange>,
65 ) -> Result<Result<(), String>, CancelFormatChange> {
66 Ok(Ok(()))
67 }
68
69 /// Prepare for disk format upgrade.
70 fn prepare(
71 &self,
72 _initial_tip_height: Height,
73 _upgrade_db: &ZebraDb,
74 _cancel_receiver: &Receiver<CancelFormatChange>,
75 _older_disk_version: &Version,
76 ) -> Result<(), CancelFormatChange> {
77 Ok(())
78 }
79
80 /// Returns true if the [`DiskFormatUpgrade`] needs to run a migration on existing data in the db.
81 fn needs_migration(&self) -> bool {
82 true
83 }
84
85 /// Returns true if the upgrade is a major upgrade that can reuse the cache in the previous major db format version.
86 fn is_reusable_major_upgrade(&self) -> bool {
87 let version = self.version();
88 version.minor == 0 && version.patch == 0
89 }
90}
91
92fn format_upgrades(
93 min_version: Option<Version>,
94) -> impl DoubleEndedIterator<Item = Box<dyn DiskFormatUpgrade>> {
95 let min_version = move || min_version.clone().unwrap_or(Version::new(0, 0, 0));
96
97 // Note: Disk format upgrades must be run in order of database version.
98 ([
99 Box::new(prune_trees::PruneTrees),
100 Box::new(add_subtrees::AddSubtrees),
101 Box::new(tree_keys_and_caches_upgrade::FixTreeKeyTypeAndCacheGenesisRoots),
102 Box::new(no_migration::NoMigration::new(
103 "add value balance upgrade",
104 Version::new(26, 0, 0),
105 )),
106 Box::new(block_info_and_address_received::Upgrade),
107 // The NU6.3 Ironwood shielded pool adds new column families and widens the chain value pool
108 // serialization. New column families and the wider records are created/read in place when
109 // the database is opened, but the genesis Ironwood tree and anchor must be backfilled so an
110 // upgraded database matches a genesis-synced one (otherwise ironwood_tree_for_tip() panics
111 // and the genesis Ironwood anchor is missing for NU6.3 anchor validation). This is a
112 // major-version upgrade that is restorable from the previous major database format version.
113 Box::new(add_ironwood_tree::Upgrade),
114 // Legacy value pools and block info default the absent NSM balance to zero, so existing
115 // records need no rewrite even though new writes use the wider v29 layout.
116 Box::new(no_migration::NoMigration::new(
117 "add NSM value balance",
118 Version::new(29, 0, 0),
119 )),
120 ] as [Box<dyn DiskFormatUpgrade>; 7])
121 .into_iter()
122 .filter(move |upgrade| upgrade.version() > min_version())
123}
124
125/// Returns a list of all the major db format versions that can restored from the
126/// previous major database format.
127pub fn restorable_db_versions() -> Vec<u64> {
128 format_upgrades(None)
129 .filter_map(|upgrade| {
130 upgrade
131 .is_reusable_major_upgrade()
132 .then_some(upgrade.version().major)
133 })
134 .collect()
135}
136
137/// The kind of database format change or validity check we're performing.
138#[derive(Clone, Debug, Eq, PartialEq)]
139pub enum DbFormatChange {
140 // Data Format Changes
141 //
142 /// Upgrade the format from `older_disk_version` to `newer_running_version`.
143 ///
144 /// Until this upgrade is complete, the format is a mixture of both versions.
145 Upgrade {
146 older_disk_version: Version,
147 newer_running_version: Version,
148 },
149
150 // Format Version File Changes
151 //
152 /// Mark the format as newly created by `running_version`.
153 ///
154 /// Newly created databases are opened with no disk version.
155 /// It is set to the running version by the format change code.
156 NewlyCreated { running_version: Version },
157
158 /// Mark the format as downgraded from `newer_disk_version` to `older_running_version`.
159 ///
160 /// Until the state is upgraded to `newer_disk_version` by a Zebra version with that state
161 /// version (or greater), the format will be a mixture of both versions.
162 Downgrade {
163 newer_disk_version: Version,
164 older_running_version: Version,
165 },
166
167 // Data Format Checks
168 //
169 /// Check that the database from a previous instance has the current `running_version` format.
170 ///
171 /// Current version databases have a disk version that matches the running version.
172 /// No upgrades are needed, so we just run a format check on the database.
173 /// The data in that database was created or updated by a previous Zebra instance.
174 CheckOpenCurrent { running_version: Version },
175
176 /// Check that the database from this instance has the current `running_version` format.
177 ///
178 /// The data in that database was created or updated by the currently running Zebra instance.
179 /// So we periodically check for data bugs, which can happen if the upgrade and new block
180 /// code produce different data. (They can also be caused by disk corruption.)
181 CheckNewBlocksCurrent { running_version: Version },
182}
183
184/// A handle to a spawned format change thread.
185///
186/// Cloning this struct creates an additional handle to the same thread.
187///
188/// # Concurrency
189///
190/// Cancelling the thread on drop has a race condition, because two handles can be dropped at
191/// the same time.
192///
193/// If cancelling the thread is required for correct operation or usability, the owner of the
194/// handle must call force_cancel().
195#[derive(Clone, Debug)]
196pub struct DbFormatChangeThreadHandle {
197 /// A handle to the format change/check thread.
198 /// If configured, this thread continues running so it can perform periodic format checks.
199 ///
200 /// Panics from this thread are propagated into Zebra's state service.
201 /// The task returns an error if the upgrade was cancelled by a shutdown.
202 update_task: Option<Arc<JoinHandle<Result<(), CancelFormatChange>>>>,
203
204 /// A channel that tells the running format thread to finish early.
205 cancel_handle: Sender<CancelFormatChange>,
206}
207
208/// Marker type that is sent to cancel a format upgrade, and returned as an error on cancellation.
209#[derive(Copy, Clone, Debug, Eq, PartialEq)]
210pub struct CancelFormatChange;
211
212impl DbFormatChange {
213 /// Returns the format change for `running_version` code loading a `disk_version` database.
214 ///
215 /// Also logs that change at info level.
216 ///
217 /// If `disk_version` is `None`, Zebra is creating a new database.
218 pub fn open_database(running_version: &Version, disk_version: Option<Version>) -> Self {
219 let running_version = running_version.clone();
220
221 let Some(disk_version) = disk_version else {
222 info!(
223 %running_version,
224 "creating new database with the current format"
225 );
226
227 return NewlyCreated { running_version };
228 };
229
230 match disk_version.cmp_precedence(&running_version) {
231 Ordering::Less => {
232 info!(
233 %running_version,
234 %disk_version,
235 "trying to open older database format: launching upgrade task"
236 );
237
238 Upgrade {
239 older_disk_version: disk_version,
240 newer_running_version: running_version,
241 }
242 }
243 Ordering::Greater => {
244 info!(
245 %running_version,
246 %disk_version,
247 "trying to open newer database format: data should be compatible"
248 );
249
250 Downgrade {
251 newer_disk_version: disk_version,
252 older_running_version: running_version,
253 }
254 }
255 Ordering::Equal => {
256 info!(%running_version, "trying to open current database format");
257
258 CheckOpenCurrent { running_version }
259 }
260 }
261 }
262
263 /// Returns a format check for newly added blocks in the currently running Zebra version.
264 /// This check makes sure the upgrade and new block code produce the same data.
265 ///
266 /// Also logs the check at info level.
267 pub fn check_new_blocks(db: &ZebraDb) -> Self {
268 let running_version = db.format_version_in_code();
269
270 info!(%running_version, "checking new blocks were written in current database format");
271 CheckNewBlocksCurrent { running_version }
272 }
273
274 /// Returns true if this format change/check is an upgrade.
275 #[allow(dead_code)]
276 pub fn is_upgrade(&self) -> bool {
277 matches!(self, Upgrade { .. })
278 }
279
280 /// Returns true if this format change indicates a newly created database
281 /// (no database was found on disk).
282 pub fn is_newly_created(&self) -> bool {
283 matches!(self, NewlyCreated { .. })
284 }
285
286 /// Returns true if this format change/check happens at startup.
287 #[allow(dead_code)]
288 pub fn is_run_at_startup(&self) -> bool {
289 !matches!(self, CheckNewBlocksCurrent { .. })
290 }
291
292 /// Returns the running version in this format change.
293 pub fn running_version(&self) -> Version {
294 match self {
295 Upgrade {
296 newer_running_version,
297 ..
298 } => newer_running_version,
299 Downgrade {
300 older_running_version,
301 ..
302 } => older_running_version,
303 NewlyCreated { running_version }
304 | CheckOpenCurrent { running_version }
305 | CheckNewBlocksCurrent { running_version } => running_version,
306 }
307 .clone()
308 }
309
310 /// Returns the initial database version before this format change.
311 ///
312 /// Returns `None` if the database was newly created.
313 pub fn initial_disk_version(&self) -> Option<Version> {
314 match self {
315 Upgrade {
316 older_disk_version, ..
317 } => Some(older_disk_version),
318 Downgrade {
319 newer_disk_version, ..
320 } => Some(newer_disk_version),
321 CheckOpenCurrent { running_version } | CheckNewBlocksCurrent { running_version } => {
322 Some(running_version)
323 }
324 NewlyCreated { .. } => None,
325 }
326 .cloned()
327 }
328
329 /// Launch a `std::thread` that applies this format change to the database,
330 /// then continues running to perform periodic format checks.
331 ///
332 /// `initial_tip_height` is the database height when it was opened, and `db` is the
333 /// database instance to upgrade or check.
334 pub fn spawn_format_change(
335 self,
336 db: ZebraDb,
337 initial_tip_height: Option<Height>,
338 ) -> DbFormatChangeThreadHandle {
339 // # Correctness
340 //
341 // Cancel handles must use try_send() to avoid blocking waiting for the format change
342 // thread to shut down.
343 let (cancel_handle, cancel_receiver) = bounded(1);
344
345 let span = Span::current();
346 let update_task = thread::spawn(move || {
347 span.in_scope(move || {
348 self.format_change_run_loop(db, initial_tip_height, cancel_receiver)
349 })
350 });
351
352 let mut handle = DbFormatChangeThreadHandle {
353 update_task: Some(Arc::new(update_task)),
354 cancel_handle,
355 };
356
357 handle.check_for_panics();
358
359 handle
360 }
361
362 /// Run the initial format change or check to the database. Under the default runtime config,
363 /// this method returns after the format change or check.
364 ///
365 /// But if runtime validity checks are enabled, this method periodically checks the format of
366 /// newly added blocks matches the current format. It will run until it is cancelled or panics.
367 fn format_change_run_loop(
368 self,
369 db: ZebraDb,
370 initial_tip_height: Option<Height>,
371 cancel_receiver: Receiver<CancelFormatChange>,
372 ) -> Result<(), CancelFormatChange> {
373 self.run_format_change_or_check(&db, initial_tip_height, &cancel_receiver)?;
374
375 let Some(debug_validity_check_interval) = db.config().debug_validity_check_interval else {
376 return Ok(());
377 };
378
379 loop {
380 // We've just run a format check, so sleep first, then run another one.
381 // But return early if there is a cancel signal.
382 if !matches!(
383 cancel_receiver.recv_timeout(debug_validity_check_interval),
384 Err(RecvTimeoutError::Timeout)
385 ) {
386 return Err(CancelFormatChange);
387 }
388
389 Self::check_new_blocks(&db).run_format_change_or_check(
390 &db,
391 initial_tip_height,
392 &cancel_receiver,
393 )?;
394 }
395 }
396
397 /// Run a format change in the database, or check the format of the database once.
398 #[allow(clippy::unwrap_in_result)]
399 pub(crate) fn run_format_change_or_check(
400 &self,
401 db: &ZebraDb,
402 initial_tip_height: Option<Height>,
403 cancel_receiver: &Receiver<CancelFormatChange>,
404 ) -> Result<(), CancelFormatChange> {
405 // Mark the database as having finished applying any format upgrades if there are no
406 // format upgrades that need to be applied.
407 if !self.is_upgrade() {
408 db.mark_finished_format_upgrades();
409 }
410
411 match self {
412 // Perform any required upgrades, then mark the state as upgraded.
413 Upgrade { .. } => {
414 self.apply_format_upgrade(db, initial_tip_height, cancel_receiver)?;
415 db.mark_finished_format_upgrades();
416 }
417
418 NewlyCreated { .. } => {
419 Self::mark_as_newly_created(db);
420 }
421
422 Downgrade { .. } => {
423 // # Correctness
424 //
425 // At the start of a format downgrade, the database must be marked as partially or
426 // fully downgraded. This lets newer Zebra versions know that some blocks with older
427 // formats have been added to the database.
428 Self::mark_as_downgraded(db);
429
430 // Older supported versions just assume they can read newer formats,
431 // because they can't predict all changes a newer Zebra version could make.
432 //
433 // The responsibility of staying backwards-compatible is on the newer version.
434 // We do this on a best-effort basis for versions that are still supported.
435 }
436
437 CheckOpenCurrent { running_version } => {
438 // If we're re-opening a previously upgraded or newly created database,
439 // the database format should be valid. This check is done below.
440 info!(
441 %running_version,
442 "checking database format produced by a previous zebra instance \
443 is current and valid"
444 );
445 }
446
447 CheckNewBlocksCurrent { running_version } => {
448 // If we've added new blocks using the non-upgrade code,
449 // the database format should be valid. This check is done below.
450 //
451 // TODO: should this check panic or just log an error?
452 // Currently, we panic to avoid consensus bugs, but this could cause a denial
453 // of service. We can make errors fail in CI using ZEBRA_FAILURE_MESSAGES.
454 info!(
455 %running_version,
456 "checking database format produced by new blocks in this instance is valid"
457 );
458 }
459 }
460
461 #[cfg(feature = "indexer")]
462 if let (
463 Upgrade { .. } | CheckOpenCurrent { .. } | Downgrade { .. },
464 Some(initial_tip_height),
465 ) = (self, initial_tip_height)
466 {
467 // Indexing transaction locations by their spent outpoints and revealed nullifiers.
468 let timer = CodeTimer::start();
469
470 // Add build metadata to on-disk version file just before starting to add indexes
471 let mut version = db
472 .format_version_on_disk()
473 .expect("unable to read database format version file")
474 .expect("should write database format version file above");
475 version.build = db.format_version_in_code().build;
476
477 db.update_format_version_on_disk(&version)
478 .expect("unable to write database format version file to disk");
479
480 info!("started checking/adding indexes for spending tx ids");
481 track_tx_locs_by_spends::run(initial_tip_height, db, cancel_receiver)?;
482 info!("finished checking/adding indexes for spending tx ids");
483
484 timer.finish_desc("indexing spending transaction ids");
485 };
486
487 #[cfg(not(feature = "indexer"))]
488 if let (
489 Upgrade { .. } | CheckOpenCurrent { .. } | Downgrade { .. },
490 Some(initial_tip_height),
491 ) = (self, initial_tip_height)
492 {
493 let mut version = db
494 .format_version_on_disk()
495 .expect("unable to read database format version file")
496 .expect("should write database format version file above");
497
498 if version.build.contains("indexer") {
499 // Indexing transaction locations by their spent outpoints and revealed nullifiers.
500 let timer = CodeTimer::start();
501
502 info!("started removing indexes for spending tx ids");
503 drop_tx_locs_by_spends::run(initial_tip_height, db, cancel_receiver)?;
504 info!("finished removing indexes for spending tx ids");
505
506 // Remove build metadata to on-disk version file after indexes have been dropped.
507 version.build = db.format_version_in_code().build;
508 db.update_format_version_on_disk(&version)
509 .expect("unable to write database format version file to disk");
510
511 timer.finish_desc("removing spending transaction ids");
512 }
513 };
514
515 // These checks should pass for all format changes:
516 // - upgrades should produce a valid format (and they already do that check)
517 // - an empty state should pass all the format checks
518 // - since the running Zebra code knows how to upgrade the database to this format,
519 // downgrades using this running code still know how to create a valid database
520 // (unless a future upgrade breaks these format checks)
521 // - re-opening the current version should be valid, regardless of whether the upgrade
522 // or new block code created the format (or any combination).
523 Self::format_validity_checks_detailed(db, cancel_receiver)?.unwrap_or_else(|_| {
524 panic!(
525 "unexpected invalid database format: delete and re-sync the database at '{:?}'",
526 db.path()
527 )
528 });
529
530 let initial_disk_version = self
531 .initial_disk_version()
532 .map_or_else(|| "None".to_string(), |version| version.to_string());
533 info!(
534 running_version = %self.running_version(),
535 %initial_disk_version,
536 "database format is valid"
537 );
538
539 Ok(())
540 }
541
542 // TODO: Move state-specific upgrade code to a finalized_state/* module.
543
544 /// Apply any required format updates to the database.
545 /// Format changes should be launched in an independent `std::thread`.
546 ///
547 /// If `cancel_receiver` gets a message, or its sender is dropped,
548 /// the format change stops running early, and returns an error.
549 ///
550 /// See the format upgrade design docs for more details:
551 /// <https://github.com/ZcashFoundation/zebra/blob/main/book/src/dev/state-db-upgrades.md#design>
552 //
553 // New format upgrades must be added to the *end* of this method.
554 #[allow(clippy::unwrap_in_result)]
555 fn apply_format_upgrade(
556 &self,
557 db: &ZebraDb,
558 initial_tip_height: Option<Height>,
559 cancel_receiver: &Receiver<CancelFormatChange>,
560 ) -> Result<(), CancelFormatChange> {
561 let Upgrade {
562 newer_running_version,
563 older_disk_version,
564 } = self
565 else {
566 unreachable!("already checked for Upgrade")
567 };
568
569 // # New Upgrades Sometimes Go Here
570 //
571 // If the format change is outside RocksDb, put new code above this comment!
572 let Some(initial_tip_height) = initial_tip_height else {
573 // If the database is empty, then the RocksDb format doesn't need any changes.
574 info!(
575 %newer_running_version,
576 %older_disk_version,
577 "marking empty database as upgraded"
578 );
579
580 Self::mark_as_upgraded_to(db, newer_running_version);
581
582 info!(
583 %newer_running_version,
584 %older_disk_version,
585 "empty database is fully upgraded"
586 );
587
588 return Ok(());
589 };
590
591 // Apply or validate format upgrades
592 for upgrade in format_upgrades(Some(older_disk_version.clone())) {
593 if upgrade.needs_migration() {
594 let timer = CodeTimer::start();
595
596 upgrade.prepare(initial_tip_height, db, cancel_receiver, older_disk_version)?;
597 upgrade.run(initial_tip_height, db, cancel_receiver)?;
598
599 // Before marking the state as upgraded, check that the upgrade completed successfully.
600 upgrade
601 .validate(db, cancel_receiver)?
602 .expect("db should be valid after upgrade");
603
604 timer.finish_desc(upgrade.description());
605 }
606
607 // Mark the database as upgraded. Zebra won't repeat the upgrade anymore once the
608 // database is marked, so the upgrade MUST be complete at this point.
609 info!(
610 newer_running_version = ?upgrade.version(),
611 "Zebra automatically upgraded the database format"
612 );
613 Self::mark_as_upgraded_to(db, &upgrade.version());
614 }
615
616 Ok(())
617 }
618
619 /// Run quick checks that the current database format is valid.
620 #[allow(clippy::vec_init_then_push)]
621 pub fn format_validity_checks_quick(db: &ZebraDb) -> Result<(), String> {
622 let timer = CodeTimer::start();
623 let mut results = Vec::new();
624
625 // Check the entire format before returning any errors.
626 results.push(db.check_max_on_disk_tip_height());
627
628 // This check can be run before the upgrade, but the upgrade code is finished, so we don't
629 // run it early any more. (If future code changes accidentally make it depend on the
630 // upgrade, they would accidentally break compatibility with older Zebra cached states.)
631 results.push(add_subtrees::subtree_format_calculation_pre_checks(db));
632
633 results.push(cache_genesis_roots::quick_check(db));
634 results.push(fix_tree_key_type::quick_check(db));
635
636 // The work is done in the functions we just called.
637 timer.finish_desc("format_validity_checks_quick()");
638
639 if results.iter().any(Result::is_err) {
640 let err = Err(format!("invalid quick check: {results:?}"));
641 error!(?err);
642 return err;
643 }
644
645 Ok(())
646 }
647
648 /// Run detailed checks that the current database format is valid.
649 #[allow(clippy::vec_init_then_push)]
650 pub fn format_validity_checks_detailed(
651 db: &ZebraDb,
652 cancel_receiver: &Receiver<CancelFormatChange>,
653 ) -> Result<Result<(), String>, CancelFormatChange> {
654 let timer = CodeTimer::start();
655 let mut results = Vec::new();
656
657 // Check the entire format before returning any errors.
658 //
659 // Do the quick checks first, so we don't have to do this in every detailed check.
660 results.push(Self::format_validity_checks_quick(db));
661
662 for upgrade in format_upgrades(None) {
663 results.push(upgrade.validate(db, cancel_receiver)?);
664 }
665
666 // The work is done in the functions we just called.
667 timer.finish_desc("format_validity_checks_detailed()");
668
669 if results.iter().any(Result::is_err) {
670 let err = Err(format!("invalid detailed check: {results:?}"));
671 error!(?err);
672 return Ok(err);
673 }
674
675 Ok(Ok(()))
676 }
677
678 /// Mark a newly created database with the current format version.
679 ///
680 /// This should be called when a newly created database is opened.
681 ///
682 /// # Concurrency
683 ///
684 /// The version must only be updated while RocksDB is holding the database
685 /// directory lock. This prevents multiple Zebra instances corrupting the version
686 /// file.
687 ///
688 /// # Panics
689 ///
690 /// If the format should not have been upgraded, because the database is not newly created.
691 fn mark_as_newly_created(db: &ZebraDb) {
692 let running_version = db.format_version_in_code();
693 let disk_version = db
694 .format_version_on_disk()
695 .expect("unable to read database format version file path");
696
697 let default_new_version = Some(Version::new(running_version.major, 0, 0));
698
699 // The database version isn't empty any more, because we've created the RocksDB database
700 // and acquired its lock. (If it is empty, we have a database locking bug.)
701 assert_eq!(
702 disk_version, default_new_version,
703 "can't overwrite the format version in an existing database:\n\
704 disk: {disk_version:?}\n\
705 running: {running_version}"
706 );
707
708 db.update_format_version_on_disk(&running_version)
709 .expect("unable to write database format version file to disk");
710
711 info!(
712 %running_version,
713 disk_version = %disk_version.map_or("None".to_string(), |version| version.to_string()),
714 "marked database format as newly created"
715 );
716 }
717
718 /// Mark the database as upgraded to `format_upgrade_version`.
719 ///
720 /// This should be called when an older database is opened by an older Zebra version,
721 /// after each version upgrade is complete.
722 ///
723 /// # Concurrency
724 ///
725 /// The version must only be updated while RocksDB is holding the database
726 /// directory lock. This prevents multiple Zebra instances corrupting the version
727 /// file.
728 ///
729 /// # Panics
730 ///
731 /// If the format should not have been upgraded, because the running version is:
732 /// - older than the disk version (that's a downgrade)
733 /// - the same as to the disk version (no upgrade needed)
734 ///
735 /// If the format should not have been upgraded, because the format upgrade version is:
736 /// - older or the same as the disk version
737 /// (multiple upgrades to the same version are not allowed)
738 /// - greater than the running version (that's a logic bug)
739 fn mark_as_upgraded_to(db: &ZebraDb, format_upgrade_version: &Version) {
740 let running_version = db.format_version_in_code();
741 let disk_version = db
742 .format_version_on_disk()
743 .expect("unable to read database format version file")
744 .expect("tried to upgrade a newly created database");
745
746 assert!(
747 running_version > disk_version,
748 "can't upgrade a database that is being opened by an older or the same Zebra version:\n\
749 disk: {disk_version}\n\
750 upgrade: {format_upgrade_version}\n\
751 running: {running_version}"
752 );
753
754 assert!(
755 format_upgrade_version > &disk_version,
756 "can't upgrade a database that has already been upgraded, or is newer:\n\
757 disk: {disk_version}\n\
758 upgrade: {format_upgrade_version}\n\
759 running: {running_version}"
760 );
761
762 assert!(
763 format_upgrade_version <= &running_version,
764 "can't upgrade to a newer version than the running Zebra version:\n\
765 disk: {disk_version}\n\
766 upgrade: {format_upgrade_version}\n\
767 running: {running_version}"
768 );
769
770 db.update_format_version_on_disk(format_upgrade_version)
771 .expect("unable to write database format version file to disk");
772
773 info!(
774 %running_version,
775 %disk_version,
776 // wait_for_state_version_upgrade() needs this to be the last field,
777 // so the regex matches correctly
778 %format_upgrade_version,
779 "marked database format as upgraded"
780 );
781 }
782
783 /// Mark the database as downgraded to the running database version.
784 /// This should be called after a newer database is opened by an older Zebra version.
785 ///
786 /// # Concurrency
787 ///
788 /// The version must only be updated while RocksDB is holding the database
789 /// directory lock. This prevents multiple Zebra instances corrupting the version
790 /// file.
791 ///
792 /// # Panics
793 ///
794 /// If the format should have been upgraded, because the running version is newer.
795 /// If the state is newly created, because the running version should be the same.
796 ///
797 /// Multiple downgrades are allowed, because they all downgrade to the same running version.
798 fn mark_as_downgraded(db: &ZebraDb) {
799 let running_version = db.format_version_in_code();
800 let disk_version = db
801 .format_version_on_disk()
802 .expect("unable to read database format version file")
803 .expect("can't downgrade a newly created database");
804
805 assert!(
806 disk_version >= running_version,
807 "can't downgrade a database that is being opened by a newer Zebra version:\n\
808 disk: {disk_version}\n\
809 running: {running_version}"
810 );
811
812 db.update_format_version_on_disk(&running_version)
813 .expect("unable to write database format version file to disk");
814
815 info!(
816 %running_version,
817 %disk_version,
818 "marked database format as downgraded"
819 );
820 }
821}
822
823impl DbFormatChangeThreadHandle {
824 /// Cancel the running format change thread, if this is the last handle.
825 /// Returns true if it was actually cancelled.
826 pub fn cancel_if_needed(&self) -> bool {
827 // # Correctness
828 //
829 // Checking the strong count has a race condition, because two handles can be dropped at
830 // the same time.
831 //
832 // If cancelling the thread is important, the owner of the handle must call force_cancel().
833 if let Some(update_task) = self.update_task.as_ref() {
834 if Arc::strong_count(update_task) <= 1 {
835 self.force_cancel();
836 return true;
837 }
838 }
839
840 false
841 }
842
843 /// Force the running format change thread to cancel, even if there are other handles.
844 pub fn force_cancel(&self) {
845 // There's nothing we can do about errors here.
846 // If the channel is disconnected, the task has exited.
847 // If it's full, it's already been cancelled.
848 let _ = self.cancel_handle.try_send(CancelFormatChange);
849 }
850
851 /// Check for panics in the code running in the spawned thread.
852 /// If the thread exited with a panic, resume that panic.
853 ///
854 /// This method should be called regularly, so that panics are detected as soon as possible.
855 pub fn check_for_panics(&mut self) {
856 self.update_task.panic_if_task_has_panicked();
857 }
858
859 /// Wait for the spawned thread to finish. If it exited with a panic, resume that panic.
860 ///
861 /// Exits early if the thread has other outstanding handles.
862 ///
863 /// This method should be called during shutdown.
864 pub fn wait_for_panics(&mut self) {
865 self.update_task.wait_for_panics();
866 }
867
868 /// Wait for the spawned thread to exit, without joining it, so that other handles can still
869 /// check it for panics.
870 pub fn wait_for_exit(&self) {
871 if let Some(update_task) = self.update_task.as_ref() {
872 // Every handle shares the thread's `JoinHandle`, so none of them can join it.
873 while !update_task.is_finished() {
874 thread::sleep(Duration::from_millis(1));
875 }
876 }
877 }
878}
879
880impl Drop for DbFormatChangeThreadHandle {
881 fn drop(&mut self) {
882 // Only cancel the format change if the state service is shutting down.
883 if self.cancel_if_needed() {
884 self.wait_for_panics();
885 } else {
886 self.check_for_panics();
887 }
888 }
889}
890
891#[test]
892fn format_upgrades_are_in_version_order() {
893 let mut last_version = Version::new(0, 0, 0);
894 for upgrade in format_upgrades(None) {
895 assert!(upgrade.version() > last_version);
896 last_version = upgrade.version();
897 }
898}