zebra_state/service/finalized_state/disk_db.rs
1//! Provides low-level access to RocksDB using some database-specific types.
2//!
3//! This module makes sure that:
4//! - all disk writes happen inside a RocksDB transaction
5//! ([`rocksdb::WriteBatch`]), and
6//! - format-specific invariants are maintained.
7//!
8//! # Correctness
9//!
10//! [`crate::constants::state_database_format_version_in_code()`] must be incremented
11//! each time the database format (column, serialization, etc) changes.
12
13use std::{
14 collections::{BTreeMap, HashMap},
15 fmt::{Debug, Write},
16 fs,
17 ops::RangeBounds,
18 path::Path,
19 sync::{
20 atomic::{self, AtomicBool},
21 Arc,
22 },
23};
24
25use itertools::Itertools;
26use rlimit::increase_nofile_limit;
27
28use rocksdb::{ColumnFamilyDescriptor, ErrorKind, Options, ReadOptions};
29use semver::Version;
30use tempfile::TempDir;
31use zebra_chain::{parameters::Network, primitives::byte_array::increment_big_endian};
32
33use crate::{
34 database_format_version_on_disk,
35 service::finalized_state::disk_format::{FromDisk, IntoDisk},
36 write_database_format_version_to_disk, Config, StateInitError,
37};
38
39use super::zebra_db::transparent::{
40 fetch_add_balance_and_received, BALANCE_BY_TRANSPARENT_ADDR,
41 BALANCE_BY_TRANSPARENT_ADDR_MERGE_OP,
42};
43// Doc-only imports
44#[allow(unused_imports)]
45use super::{TypedColumnFamily, WriteTypedBatch};
46
47#[cfg(any(test, feature = "proptest-impl"))]
48mod tests;
49
50/// The [`rocksdb::ThreadMode`] used by the database.
51pub type DBThreadMode = rocksdb::SingleThreaded;
52
53/// The [`rocksdb`] database type, including thread mode.
54///
55/// Also the [`rocksdb::DBAccess`] used by database iterators.
56pub type DB = rocksdb::DBWithThreadMode<DBThreadMode>;
57
58/// Wrapper struct to ensure low-level database access goes through the correct API.
59///
60/// `rocksdb` allows concurrent writes through a shared reference,
61/// so database instances are cloneable. When the final clone is dropped,
62/// the database is closed.
63///
64/// # Correctness
65///
66/// Reading transactions from the database using RocksDB iterators causes hangs.
67/// But creating iterators and reading the tip height works fine.
68///
69/// So these hangs are probably caused by holding column family locks to read:
70/// - multiple values, or
71/// - large values.
72///
73/// This bug might be fixed by moving database operations to blocking threads (#2188),
74/// so that they don't block the tokio executor.
75/// (Or it might be fixed by future RocksDB upgrades.)
76#[derive(Clone, Debug)]
77pub struct DiskDb {
78 // Configuration
79 //
80 // This configuration cannot be modified after the database is initialized,
81 // because some clones would have different values.
82 //
83 /// The configured database kind for this database.
84 db_kind: String,
85
86 /// The format version of the running Zebra code.
87 format_version_in_code: Version,
88
89 /// The configured network for this database.
90 network: Network,
91
92 /// How this database was opened: a read-write primary (persistent or ephemeral)
93 /// or a read-only secondary. See [`DbMode`].
94 mode: DbMode,
95
96 /// A boolean flag indicating whether the db format change task has finished
97 /// applying any format changes that may have been required.
98 finished_format_upgrades: Arc<AtomicBool>,
99
100 // Owned State
101 //
102 // Everything contained in this state must be shared by all clones, or read-only.
103 //
104 /// The shared inner RocksDB database.
105 ///
106 /// RocksDB allows reads and writes via a shared reference.
107 ///
108 /// In [`SingleThreaded`](rocksdb::SingleThreaded) mode,
109 /// column family changes and [`Drop`] require exclusive access.
110 ///
111 /// In [`MultiThreaded`](rocksdb::MultiThreaded) mode,
112 /// only [`Drop`] requires exclusive access.
113 db: Arc<DB>,
114
115 /// The temporary directory a read-only secondary instance keeps its own files in,
116 /// removed when the last clone is dropped. `None` for read-write primaries.
117 ///
118 /// Declared after `db` so the database closes before its directory is removed.
119 #[allow(dead_code)]
120 secondary_dir: Option<Arc<TempDir>>,
121}
122
123/// Wrapper struct to ensure low-level database writes go through the correct API.
124///
125/// [`rocksdb::WriteBatch`] is a batched set of database updates,
126/// which must be written to the database using `DiskDb::write(batch)`.
127#[must_use = "batches must be written to the database"]
128#[derive(Default)]
129pub struct DiskWriteBatch {
130 /// The inner RocksDB write batch.
131 batch: rocksdb::WriteBatch,
132}
133
134impl Debug for DiskWriteBatch {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 f.debug_struct("DiskWriteBatch")
137 .field("batch", &format!("{} bytes", self.batch.size_in_bytes()))
138 .finish()
139 }
140}
141
142impl PartialEq for DiskWriteBatch {
143 fn eq(&self, other: &Self) -> bool {
144 self.batch.data() == other.batch.data()
145 }
146}
147
148impl Eq for DiskWriteBatch {}
149
150/// Helper trait for inserting serialized typed (Key, Value) pairs into rocksdb.
151///
152/// # Deprecation
153///
154/// This trait should not be used in new code, use [`WriteTypedBatch`] instead.
155//
156// TODO: replace uses of this trait with WriteTypedBatch,
157// implement these methods directly on WriteTypedBatch, and delete the trait.
158pub trait WriteDisk {
159 /// Serialize and insert the given key and value into a rocksdb column family,
160 /// overwriting any existing `value` for `key`.
161 fn zs_insert<C, K, V>(&mut self, cf: &C, key: K, value: V)
162 where
163 C: rocksdb::AsColumnFamilyRef,
164 K: IntoDisk + Debug,
165 V: IntoDisk;
166
167 /// Serialize and merge the given key and value into a rocksdb column family,
168 /// merging with any existing `value` for `key`.
169 fn zs_merge<C, K, V>(&mut self, cf: &C, key: K, value: V)
170 where
171 C: rocksdb::AsColumnFamilyRef,
172 K: IntoDisk + Debug,
173 V: IntoDisk;
174
175 /// Remove the given key from a rocksdb column family, if it exists.
176 fn zs_delete<C, K>(&mut self, cf: &C, key: K)
177 where
178 C: rocksdb::AsColumnFamilyRef,
179 K: IntoDisk + Debug;
180
181 /// Delete the given key range from a rocksdb column family, if it exists, including `from`
182 /// and excluding `until_strictly_before`.
183 //
184 // TODO: convert zs_delete_range() to take std::ops::RangeBounds
185 // see zs_range_iter() for an example of the edge cases
186 fn zs_delete_range<C, K>(&mut self, cf: &C, from: K, until_strictly_before: K)
187 where
188 C: rocksdb::AsColumnFamilyRef,
189 K: IntoDisk + Debug;
190}
191
192/// # Deprecation
193///
194/// These impls should not be used in new code, use [`WriteTypedBatch`] instead.
195//
196// TODO: replace uses of these impls with WriteTypedBatch,
197// implement these methods directly on WriteTypedBatch, and delete the trait.
198impl WriteDisk for DiskWriteBatch {
199 fn zs_insert<C, K, V>(&mut self, cf: &C, key: K, value: V)
200 where
201 C: rocksdb::AsColumnFamilyRef,
202 K: IntoDisk + Debug,
203 V: IntoDisk,
204 {
205 let key_bytes = key.as_bytes();
206 let value_bytes = value.as_bytes();
207 self.batch.put_cf(cf, key_bytes, value_bytes);
208 }
209
210 fn zs_merge<C, K, V>(&mut self, cf: &C, key: K, value: V)
211 where
212 C: rocksdb::AsColumnFamilyRef,
213 K: IntoDisk + Debug,
214 V: IntoDisk,
215 {
216 let key_bytes = key.as_bytes();
217 let value_bytes = value.as_bytes();
218 self.batch.merge_cf(cf, key_bytes, value_bytes);
219 }
220
221 fn zs_delete<C, K>(&mut self, cf: &C, key: K)
222 where
223 C: rocksdb::AsColumnFamilyRef,
224 K: IntoDisk + Debug,
225 {
226 let key_bytes = key.as_bytes();
227 self.batch.delete_cf(cf, key_bytes);
228 }
229
230 // TODO: convert zs_delete_range() to take std::ops::RangeBounds
231 // see zs_range_iter() for an example of the edge cases
232 fn zs_delete_range<C, K>(&mut self, cf: &C, from: K, until_strictly_before: K)
233 where
234 C: rocksdb::AsColumnFamilyRef,
235 K: IntoDisk + Debug,
236 {
237 let from_bytes = from.as_bytes();
238 let until_strictly_before_bytes = until_strictly_before.as_bytes();
239 self.batch
240 .delete_range_cf(cf, from_bytes, until_strictly_before_bytes);
241 }
242}
243
244// Allow &mut DiskWriteBatch as well as owned DiskWriteBatch
245impl<T> WriteDisk for &mut T
246where
247 T: WriteDisk,
248{
249 fn zs_insert<C, K, V>(&mut self, cf: &C, key: K, value: V)
250 where
251 C: rocksdb::AsColumnFamilyRef,
252 K: IntoDisk + Debug,
253 V: IntoDisk,
254 {
255 (*self).zs_insert(cf, key, value)
256 }
257
258 fn zs_merge<C, K, V>(&mut self, cf: &C, key: K, value: V)
259 where
260 C: rocksdb::AsColumnFamilyRef,
261 K: IntoDisk + Debug,
262 V: IntoDisk,
263 {
264 (*self).zs_merge(cf, key, value)
265 }
266
267 fn zs_delete<C, K>(&mut self, cf: &C, key: K)
268 where
269 C: rocksdb::AsColumnFamilyRef,
270 K: IntoDisk + Debug,
271 {
272 (*self).zs_delete(cf, key)
273 }
274
275 fn zs_delete_range<C, K>(&mut self, cf: &C, from: K, until_strictly_before: K)
276 where
277 C: rocksdb::AsColumnFamilyRef,
278 K: IntoDisk + Debug,
279 {
280 (*self).zs_delete_range(cf, from, until_strictly_before)
281 }
282}
283
284/// Helper trait for retrieving and deserializing values from rocksdb column families.
285///
286/// # Deprecation
287///
288/// This trait should not be used in new code, use [`TypedColumnFamily`] instead.
289//
290// TODO: replace uses of this trait with TypedColumnFamily,
291// implement these methods directly on DiskDb, and delete the trait.
292pub trait ReadDisk {
293 /// Returns true if a rocksdb column family `cf` does not contain any entries.
294 fn zs_is_empty<C>(&self, cf: &C) -> bool
295 where
296 C: rocksdb::AsColumnFamilyRef;
297
298 /// Returns the value for `key` in the rocksdb column family `cf`, if present.
299 fn zs_get<C, K, V>(&self, cf: &C, key: &K) -> Option<V>
300 where
301 C: rocksdb::AsColumnFamilyRef,
302 K: IntoDisk,
303 V: FromDisk;
304
305 /// Check if a rocksdb column family `cf` contains the serialized form of `key`.
306 fn zs_contains<C, K>(&self, cf: &C, key: &K) -> bool
307 where
308 C: rocksdb::AsColumnFamilyRef,
309 K: IntoDisk;
310
311 /// Returns the lowest key in `cf`, and the corresponding value.
312 ///
313 /// Returns `None` if the column family is empty.
314 fn zs_first_key_value<C, K, V>(&self, cf: &C) -> Option<(K, V)>
315 where
316 C: rocksdb::AsColumnFamilyRef,
317 K: IntoDisk + FromDisk,
318 V: FromDisk;
319
320 /// Returns the highest key in `cf`, and the corresponding value.
321 ///
322 /// Returns `None` if the column family is empty.
323 fn zs_last_key_value<C, K, V>(&self, cf: &C) -> Option<(K, V)>
324 where
325 C: rocksdb::AsColumnFamilyRef,
326 K: IntoDisk + FromDisk,
327 V: FromDisk;
328
329 /// Returns the first key greater than or equal to `lower_bound` in `cf`,
330 /// and the corresponding value.
331 ///
332 /// Returns `None` if there are no keys greater than or equal to `lower_bound`.
333 fn zs_next_key_value_from<C, K, V>(&self, cf: &C, lower_bound: &K) -> Option<(K, V)>
334 where
335 C: rocksdb::AsColumnFamilyRef,
336 K: IntoDisk + FromDisk,
337 V: FromDisk;
338
339 /// Returns the first key strictly greater than `lower_bound` in `cf`,
340 /// and the corresponding value.
341 ///
342 /// Returns `None` if there are no keys greater than `lower_bound`.
343 fn zs_next_key_value_strictly_after<C, K, V>(&self, cf: &C, lower_bound: &K) -> Option<(K, V)>
344 where
345 C: rocksdb::AsColumnFamilyRef,
346 K: IntoDisk + FromDisk,
347 V: FromDisk;
348
349 /// Returns the first key less than or equal to `upper_bound` in `cf`,
350 /// and the corresponding value.
351 ///
352 /// Returns `None` if there are no keys less than or equal to `upper_bound`.
353 fn zs_prev_key_value_back_from<C, K, V>(&self, cf: &C, upper_bound: &K) -> Option<(K, V)>
354 where
355 C: rocksdb::AsColumnFamilyRef,
356 K: IntoDisk + FromDisk,
357 V: FromDisk;
358
359 /// Returns the first key strictly less than `upper_bound` in `cf`,
360 /// and the corresponding value.
361 ///
362 /// Returns `None` if there are no keys less than `upper_bound`.
363 fn zs_prev_key_value_strictly_before<C, K, V>(&self, cf: &C, upper_bound: &K) -> Option<(K, V)>
364 where
365 C: rocksdb::AsColumnFamilyRef,
366 K: IntoDisk + FromDisk,
367 V: FromDisk;
368
369 /// Returns the keys and values in `cf` in `range`, in an ordered `BTreeMap`.
370 ///
371 /// Holding this iterator open might delay block commit transactions.
372 fn zs_items_in_range_ordered<C, K, V, R>(&self, cf: &C, range: R) -> BTreeMap<K, V>
373 where
374 C: rocksdb::AsColumnFamilyRef,
375 K: IntoDisk + FromDisk + Ord,
376 V: FromDisk,
377 R: RangeBounds<K>;
378
379 /// Returns the keys and values in `cf` in `range`, in an unordered `HashMap`.
380 ///
381 /// Holding this iterator open might delay block commit transactions.
382 fn zs_items_in_range_unordered<C, K, V, R>(&self, cf: &C, range: R) -> HashMap<K, V>
383 where
384 C: rocksdb::AsColumnFamilyRef,
385 K: IntoDisk + FromDisk + Eq + std::hash::Hash,
386 V: FromDisk,
387 R: RangeBounds<K>;
388}
389
390/// How a [`DiskDb`] instance is opened.
391///
392/// These modes are mutually exclusive — an ephemeral database is a read-write primary
393/// this process owns and deletes on drop, a persistent database is a read-write primary
394/// whose files are kept, and a read-only secondary follows another process's primary and
395/// never writes, flushes, or deletes it.
396#[derive(Clone, Copy, Debug, PartialEq, Eq)]
397enum DbMode {
398 /// A read-write primary backed by persistent on-disk files that are kept on drop.
399 Persistent,
400
401 /// A read-write primary backed by temporary files that are deleted on drop.
402 Ephemeral,
403
404 /// A read-only secondary that follows an existing primary's on-disk state. It never
405 /// writes, flushes, or deletes the primary's files, and only owns its temporary
406 /// secondary directory.
407 ReadOnlySecondary,
408}
409
410/// The holder of a database lock that RocksDB failed to acquire.
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412enum LockHolder {
413 /// Another process has the database open.
414 OtherProcess,
415
416 /// This process already has the database open.
417 ThisProcess,
418}
419
420impl DbMode {
421 /// Returns true if dropping the database should delete its files.
422 fn deletes_files_on_drop(self) -> bool {
423 matches!(self, DbMode::Ephemeral)
424 }
425
426 /// Returns true if this is a read-only secondary instance, which RocksDB does not
427 /// allow writes or flushes on.
428 fn is_read_only(self) -> bool {
429 matches!(self, DbMode::ReadOnlySecondary)
430 }
431}
432
433impl PartialEq for DiskDb {
434 fn eq(&self, other: &Self) -> bool {
435 if self.db.path() == other.db.path() {
436 assert_eq!(
437 self.network, other.network,
438 "database with same path but different network configs",
439 );
440 assert_eq!(
441 self.mode.deletes_files_on_drop(),
442 other.mode.deletes_files_on_drop(),
443 "database with same path but different ephemeral configs",
444 );
445
446 return true;
447 }
448
449 false
450 }
451}
452
453impl Eq for DiskDb {}
454
455/// # Deprecation
456///
457/// These impls should not be used in new code, use [`TypedColumnFamily`] instead.
458//
459// TODO: replace uses of these impls with TypedColumnFamily,
460// implement these methods directly on DiskDb, and delete the trait.
461impl ReadDisk for DiskDb {
462 fn zs_is_empty<C>(&self, cf: &C) -> bool
463 where
464 C: rocksdb::AsColumnFamilyRef,
465 {
466 // Empty column families return invalid forward iterators.
467 //
468 // Checking iterator validity does not seem to cause database hangs.
469 let iterator = self.db.iterator_cf(cf, rocksdb::IteratorMode::Start);
470 let raw_iterator: rocksdb::DBRawIteratorWithThreadMode<DB> = iterator.into();
471
472 !raw_iterator.valid()
473 }
474
475 #[allow(clippy::unwrap_in_result)]
476 fn zs_get<C, K, V>(&self, cf: &C, key: &K) -> Option<V>
477 where
478 C: rocksdb::AsColumnFamilyRef,
479 K: IntoDisk,
480 V: FromDisk,
481 {
482 let key_bytes = key.as_bytes();
483
484 // We use `get_pinned_cf` to avoid taking ownership of the serialized
485 // value, because we're going to deserialize it anyways, which avoids an
486 // extra copy
487 let value_bytes = self
488 .db
489 .get_pinned_cf(cf, key_bytes)
490 .expect("unexpected database failure");
491
492 value_bytes.map(V::from_bytes)
493 }
494
495 fn zs_contains<C, K>(&self, cf: &C, key: &K) -> bool
496 where
497 C: rocksdb::AsColumnFamilyRef,
498 K: IntoDisk,
499 {
500 let key_bytes = key.as_bytes();
501
502 // We use `get_pinned_cf` to avoid taking ownership of the serialized
503 // value, because we don't use the value at all. This avoids an extra copy.
504 self.db
505 .get_pinned_cf(cf, key_bytes)
506 .expect("unexpected database failure")
507 .is_some()
508 }
509
510 fn zs_first_key_value<C, K, V>(&self, cf: &C) -> Option<(K, V)>
511 where
512 C: rocksdb::AsColumnFamilyRef,
513 K: IntoDisk + FromDisk,
514 V: FromDisk,
515 {
516 // Reading individual values from iterators does not seem to cause database hangs.
517 self.zs_forward_range_iter(cf, ..).next()
518 }
519
520 fn zs_last_key_value<C, K, V>(&self, cf: &C) -> Option<(K, V)>
521 where
522 C: rocksdb::AsColumnFamilyRef,
523 K: IntoDisk + FromDisk,
524 V: FromDisk,
525 {
526 // Reading individual values from iterators does not seem to cause database hangs.
527 self.zs_reverse_range_iter(cf, ..).next()
528 }
529
530 fn zs_next_key_value_from<C, K, V>(&self, cf: &C, lower_bound: &K) -> Option<(K, V)>
531 where
532 C: rocksdb::AsColumnFamilyRef,
533 K: IntoDisk + FromDisk,
534 V: FromDisk,
535 {
536 self.zs_forward_range_iter(cf, lower_bound..).next()
537 }
538
539 fn zs_next_key_value_strictly_after<C, K, V>(&self, cf: &C, lower_bound: &K) -> Option<(K, V)>
540 where
541 C: rocksdb::AsColumnFamilyRef,
542 K: IntoDisk + FromDisk,
543 V: FromDisk,
544 {
545 use std::ops::Bound::*;
546
547 // There is no standard syntax for an excluded start bound.
548 self.zs_forward_range_iter(cf, (Excluded(lower_bound), Unbounded))
549 .next()
550 }
551
552 fn zs_prev_key_value_back_from<C, K, V>(&self, cf: &C, upper_bound: &K) -> Option<(K, V)>
553 where
554 C: rocksdb::AsColumnFamilyRef,
555 K: IntoDisk + FromDisk,
556 V: FromDisk,
557 {
558 self.zs_reverse_range_iter(cf, ..=upper_bound).next()
559 }
560
561 fn zs_prev_key_value_strictly_before<C, K, V>(&self, cf: &C, upper_bound: &K) -> Option<(K, V)>
562 where
563 C: rocksdb::AsColumnFamilyRef,
564 K: IntoDisk + FromDisk,
565 V: FromDisk,
566 {
567 self.zs_reverse_range_iter(cf, ..upper_bound).next()
568 }
569
570 fn zs_items_in_range_ordered<C, K, V, R>(&self, cf: &C, range: R) -> BTreeMap<K, V>
571 where
572 C: rocksdb::AsColumnFamilyRef,
573 K: IntoDisk + FromDisk + Ord,
574 V: FromDisk,
575 R: RangeBounds<K>,
576 {
577 self.zs_forward_range_iter(cf, range).collect()
578 }
579
580 fn zs_items_in_range_unordered<C, K, V, R>(&self, cf: &C, range: R) -> HashMap<K, V>
581 where
582 C: rocksdb::AsColumnFamilyRef,
583 K: IntoDisk + FromDisk + Eq + std::hash::Hash,
584 V: FromDisk,
585 R: RangeBounds<K>,
586 {
587 self.zs_forward_range_iter(cf, range).collect()
588 }
589}
590
591impl DiskWriteBatch {
592 /// Creates and returns a new transactional batch write.
593 ///
594 /// # Correctness
595 ///
596 /// Each block must be written to the state inside a batch, so that:
597 /// - concurrent `ReadStateService` queries don't see half-written blocks, and
598 /// - if Zebra calls `exit`, panics, or crashes, half-written blocks are rolled back.
599 pub fn new() -> Self {
600 DiskWriteBatch {
601 batch: rocksdb::WriteBatch::default(),
602 }
603 }
604}
605
606impl DiskDb {
607 /// Prints rocksdb metrics for each column family along with total database disk size, live data disk size and database memory size.
608 pub fn print_db_metrics(&self) {
609 let mut total_size_on_disk = 0;
610 let mut total_live_size_on_disk = 0;
611 let mut total_size_in_mem = 0;
612 let db: &Arc<DB> = &self.db;
613 let db_options = DiskDb::options();
614 let column_families = DiskDb::construct_column_families(db_options, db.path(), []);
615 let mut column_families_log_string = String::from("");
616
617 write!(column_families_log_string, "Column families and sizes: ").unwrap();
618
619 for cf_descriptor in column_families {
620 let cf_name = &cf_descriptor.name();
621 let cf_handle = db
622 .cf_handle(cf_name)
623 .expect("Column family handle must exist");
624 let live_data_size = db
625 .property_int_value_cf(cf_handle, "rocksdb.estimate-live-data-size")
626 .unwrap_or(Some(0));
627 let total_sst_files_size = db
628 .property_int_value_cf(cf_handle, "rocksdb.total-sst-files-size")
629 .unwrap_or(Some(0));
630 let cf_disk_size = total_sst_files_size.unwrap_or(0);
631 total_size_on_disk += cf_disk_size;
632 total_live_size_on_disk += live_data_size.unwrap_or(0);
633 let mem_table_size = db
634 .property_int_value_cf(cf_handle, "rocksdb.size-all-mem-tables")
635 .unwrap_or(Some(0));
636 total_size_in_mem += mem_table_size.unwrap_or(0);
637
638 write!(
639 column_families_log_string,
640 "{} (Disk: {}, Memory: {})",
641 cf_name,
642 human_bytes::human_bytes(cf_disk_size as f64),
643 human_bytes::human_bytes(mem_table_size.unwrap_or(0) as f64)
644 )
645 .unwrap();
646 }
647
648 debug!("{}", column_families_log_string);
649 info!(
650 "Total Database Disk Size: {}",
651 human_bytes::human_bytes(total_size_on_disk as f64)
652 );
653 info!(
654 "Total Live Data Disk Size: {}",
655 human_bytes::human_bytes(total_live_size_on_disk as f64)
656 );
657 info!(
658 "Total Database Memory Size: {}",
659 human_bytes::human_bytes(total_size_in_mem as f64)
660 );
661 }
662
663 /// Exports RocksDB metrics to Prometheus.
664 ///
665 /// This function collects database statistics and exposes them as Prometheus metrics.
666 /// Call this periodically (e.g., every 30 seconds) from a background task.
667 pub(crate) fn export_metrics(&self) {
668 let db: &Arc<DB> = &self.db;
669 let db_options = DiskDb::options();
670 let column_families = DiskDb::construct_column_families(db_options, db.path(), []);
671
672 let mut total_disk: u64 = 0;
673 let mut total_live: u64 = 0;
674 let mut total_mem: u64 = 0;
675
676 for cf_descriptor in column_families {
677 let cf_name = cf_descriptor.name().to_string();
678 if let Some(cf_handle) = db.cf_handle(&cf_name) {
679 let disk = db
680 .property_int_value_cf(cf_handle, "rocksdb.total-sst-files-size")
681 .ok()
682 .flatten()
683 .unwrap_or(0);
684 let live = db
685 .property_int_value_cf(cf_handle, "rocksdb.estimate-live-data-size")
686 .ok()
687 .flatten()
688 .unwrap_or(0);
689 let mem = db
690 .property_int_value_cf(cf_handle, "rocksdb.size-all-mem-tables")
691 .ok()
692 .flatten()
693 .unwrap_or(0);
694
695 total_disk += disk;
696 total_live += live;
697 total_mem += mem;
698
699 metrics::gauge!("zebra.state.rocksdb.cf_disk_size_bytes", "cf" => cf_name.clone())
700 .set(disk as f64);
701 metrics::gauge!("zebra.state.rocksdb.cf_memory_size_bytes", "cf" => cf_name)
702 .set(mem as f64);
703 }
704 }
705
706 metrics::gauge!("zebra.state.rocksdb.total_disk_size_bytes").set(total_disk as f64);
707 metrics::gauge!("zebra.state.rocksdb.live_data_size_bytes").set(total_live as f64);
708 metrics::gauge!("zebra.state.rocksdb.total_memory_size_bytes").set(total_mem as f64);
709
710 // Compaction metrics - these use database-wide properties (not per-column-family)
711 if let Ok(Some(pending)) = db.property_int_value("rocksdb.compaction-pending") {
712 metrics::gauge!("zebra.state.rocksdb.compaction.pending_bytes").set(pending as f64);
713 }
714
715 if let Ok(Some(running)) = db.property_int_value("rocksdb.num-running-compactions") {
716 metrics::gauge!("zebra.state.rocksdb.compaction.running").set(running as f64);
717 }
718
719 if let Ok(Some(cache)) = db.property_int_value("rocksdb.block-cache-usage") {
720 metrics::gauge!("zebra.state.rocksdb.block_cache_usage_bytes").set(cache as f64);
721 }
722
723 // Level-by-level file counts (RocksDB typically has up to 7 levels)
724 for level in 0..7 {
725 let prop = format!("rocksdb.num-files-at-level{level}");
726 if let Ok(Some(count)) = db.property_int_value(&prop) {
727 metrics::gauge!("zebra.state.rocksdb.num_files_at_level", "level" => level.to_string())
728 .set(count as f64);
729 }
730 }
731 }
732
733 /// Returns the estimated total disk space usage of the database.
734 pub fn size(&self) -> u64 {
735 let db: &Arc<DB> = &self.db;
736 let db_options = DiskDb::options();
737 let mut total_size_on_disk = 0;
738 for cf_descriptor in DiskDb::construct_column_families(db_options, db.path(), []) {
739 let cf_name = &cf_descriptor.name();
740 let cf_handle = db
741 .cf_handle(cf_name)
742 .expect("Column family handle must exist");
743
744 total_size_on_disk += db
745 .property_int_value_cf(cf_handle, "rocksdb.total-sst-files-size")
746 .ok()
747 .flatten()
748 .unwrap_or(0);
749 }
750
751 total_size_on_disk
752 }
753
754 /// Sets `finished_format_upgrades` to true to indicate that Zebra has
755 /// finished applying any required db format upgrades.
756 pub fn mark_finished_format_upgrades(&self) {
757 self.finished_format_upgrades
758 .store(true, atomic::Ordering::SeqCst);
759 }
760
761 /// Returns true if the `finished_format_upgrades` flag has been set to true to
762 /// indicate that Zebra has finished applying any required db format upgrades.
763 pub fn finished_format_upgrades(&self) -> bool {
764 self.finished_format_upgrades.load(atomic::Ordering::SeqCst)
765 }
766
767 /// When called with a secondary DB instance, tries to catch up with the primary DB instance
768 pub fn try_catch_up_with_primary(&self) -> Result<(), rocksdb::Error> {
769 self.db.try_catch_up_with_primary()
770 }
771
772 /// Returns a forward iterator over the items in `cf` in `range`.
773 ///
774 /// Holding this iterator open might delay block commit transactions.
775 pub fn zs_forward_range_iter<C, K, V, R>(
776 &self,
777 cf: &C,
778 range: R,
779 ) -> impl Iterator<Item = (K, V)> + '_
780 where
781 C: rocksdb::AsColumnFamilyRef,
782 K: IntoDisk + FromDisk,
783 V: FromDisk,
784 R: RangeBounds<K>,
785 {
786 self.zs_range_iter_with_direction(cf, range, false)
787 }
788
789 /// Returns a reverse iterator over the items in `cf` in `range`.
790 ///
791 /// Holding this iterator open might delay block commit transactions.
792 pub fn zs_reverse_range_iter<C, K, V, R>(
793 &self,
794 cf: &C,
795 range: R,
796 ) -> impl Iterator<Item = (K, V)> + '_
797 where
798 C: rocksdb::AsColumnFamilyRef,
799 K: IntoDisk + FromDisk,
800 V: FromDisk,
801 R: RangeBounds<K>,
802 {
803 self.zs_range_iter_with_direction(cf, range, true)
804 }
805
806 /// Returns an iterator over the items in `cf` in `range`.
807 ///
808 /// RocksDB iterators are ordered by increasing key bytes by default.
809 /// Otherwise, if `reverse` is `true`, the iterator is ordered by decreasing key bytes.
810 ///
811 /// Holding this iterator open might delay block commit transactions.
812 fn zs_range_iter_with_direction<C, K, V, R>(
813 &self,
814 cf: &C,
815 range: R,
816 reverse: bool,
817 ) -> impl Iterator<Item = (K, V)> + '_
818 where
819 C: rocksdb::AsColumnFamilyRef,
820 K: IntoDisk + FromDisk,
821 V: FromDisk,
822 R: RangeBounds<K>,
823 {
824 use std::ops::Bound::{self, *};
825
826 // Replace with map() when it stabilises:
827 // https://github.com/rust-lang/rust/issues/86026
828 let map_to_vec = |bound: Bound<&K>| -> Bound<Vec<u8>> {
829 match bound {
830 Unbounded => Unbounded,
831 Included(x) => Included(x.as_bytes().as_ref().to_vec()),
832 Excluded(x) => Excluded(x.as_bytes().as_ref().to_vec()),
833 }
834 };
835
836 let start_bound = map_to_vec(range.start_bound());
837 let end_bound = map_to_vec(range.end_bound());
838 let range = (start_bound, end_bound);
839
840 let mode = Self::zs_iter_mode(&range, reverse);
841 let opts = Self::zs_iter_opts(&range);
842
843 // Reading multiple items from iterators has caused database hangs,
844 // in previous RocksDB versions
845 self.db
846 .iterator_cf_opt(cf, opts, mode)
847 .map(|result| result.expect("unexpected database failure"))
848 .map(|(key, value)| (key.to_vec(), value))
849 // Skip excluded "from" bound and empty ranges. The `mode` already skips keys
850 // strictly before the "from" bound.
851 .skip_while({
852 let range = range.clone();
853 move |(key, _value)| !range.contains(key)
854 })
855 // Take until the excluded "to" bound is reached,
856 // or we're after the included "to" bound.
857 .take_while(move |(key, _value)| range.contains(key))
858 .map(|(key, value)| (K::from_bytes(key), V::from_bytes(value)))
859 }
860
861 /// Returns the RocksDB ReadOptions with a lower and upper bound for a range.
862 fn zs_iter_opts<R>(range: &R) -> ReadOptions
863 where
864 R: RangeBounds<Vec<u8>>,
865 {
866 let mut opts = ReadOptions::default();
867 let (lower_bound, upper_bound) = Self::zs_iter_bounds(range);
868
869 if let Some(bound) = lower_bound {
870 opts.set_iterate_lower_bound(bound);
871 };
872
873 if let Some(bound) = upper_bound {
874 opts.set_iterate_upper_bound(bound);
875 };
876
877 opts
878 }
879
880 /// Returns a lower and upper iterate bounds for a range.
881 ///
882 /// Note: Since upper iterate bounds are always exclusive in RocksDB, this method
883 /// will increment the upper bound by 1 if the end bound of the provided range
884 /// is inclusive.
885 fn zs_iter_bounds<R>(range: &R) -> (Option<Vec<u8>>, Option<Vec<u8>>)
886 where
887 R: RangeBounds<Vec<u8>>,
888 {
889 use std::ops::Bound::*;
890
891 let lower_bound = match range.start_bound() {
892 Included(bound) | Excluded(bound) => Some(bound.clone()),
893 Unbounded => None,
894 };
895
896 let upper_bound = match range.end_bound().cloned() {
897 Included(mut bound) => {
898 // Increment the last byte in the upper bound that is less than u8::MAX, and
899 // clear any bytes after it to increment the next key in lexicographic order
900 // (next big-endian number). RocksDB uses lexicographic order for keys.
901 let is_wrapped_overflow = increment_big_endian(&mut bound);
902
903 if is_wrapped_overflow {
904 bound.insert(0, 0x01)
905 }
906
907 Some(bound)
908 }
909 Excluded(bound) => Some(bound),
910 Unbounded => None,
911 };
912
913 (lower_bound, upper_bound)
914 }
915
916 /// Returns the RocksDB iterator "from" mode for `range`.
917 ///
918 /// RocksDB iterators are ordered by increasing key bytes by default.
919 /// Otherwise, if `reverse` is `true`, the iterator is ordered by decreasing key bytes.
920 fn zs_iter_mode<R>(range: &R, reverse: bool) -> rocksdb::IteratorMode<'_>
921 where
922 R: RangeBounds<Vec<u8>>,
923 {
924 use std::ops::Bound::*;
925
926 let from_bound = if reverse {
927 range.end_bound()
928 } else {
929 range.start_bound()
930 };
931
932 match from_bound {
933 Unbounded => {
934 if reverse {
935 // Reversed unbounded iterators start from the last item
936 rocksdb::IteratorMode::End
937 } else {
938 // Unbounded iterators start from the first item
939 rocksdb::IteratorMode::Start
940 }
941 }
942
943 Included(bound) | Excluded(bound) => {
944 let direction = if reverse {
945 rocksdb::Direction::Reverse
946 } else {
947 rocksdb::Direction::Forward
948 };
949
950 rocksdb::IteratorMode::From(bound.as_slice(), direction)
951 }
952 }
953 }
954
955 /// The ideal open file limit for Zebra
956 const IDEAL_OPEN_FILE_LIMIT: u64 = 1024;
957
958 /// The minimum number of open files for Zebra to operate normally. Also used
959 /// as the default open file limit, when the OS doesn't tell us how many
960 /// files we can use.
961 ///
962 /// We want 100+ file descriptors for peers, and 100+ for the database.
963 ///
964 /// On Windows, the default limit is 512 high-level I/O files, and 8192
965 /// low-level I/O files:
966 /// <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-160#remarks>
967 const MIN_OPEN_FILE_LIMIT: u64 = 512;
968
969 /// The number of files used internally by Zebra.
970 ///
971 /// Zebra uses file descriptors for OS libraries (10+), polling APIs (10+),
972 /// stdio (3), and other OS facilities (2+).
973 const RESERVED_FILE_COUNT: u64 = 48;
974
975 /// The size of the database memtable RAM cache in megabytes.
976 ///
977 /// <https://github.com/facebook/rocksdb/wiki/RocksDB-FAQ#configuration-and-tuning>
978 const MEMTABLE_RAM_CACHE_MEGABYTES: usize = 128;
979
980 /// Build a vector of current column families on the disk and optionally any new column families.
981 /// Returns an iterable collection of all column families.
982 fn construct_column_families(
983 db_options: Options,
984 path: &Path,
985 column_families_in_code: impl IntoIterator<Item = String>,
986 ) -> impl Iterator<Item = ColumnFamilyDescriptor> {
987 // When opening the database in read/write mode, all column families must be opened.
988 //
989 // To make Zebra forward-compatible with databases updated by later versions,
990 // we read any existing column families off the disk, then add any new column families
991 // from the current implementation.
992 //
993 // <https://github.com/facebook/rocksdb/wiki/Column-Families#reference>
994 let column_families_on_disk = DB::list_cf(&db_options, path).unwrap_or_default();
995 let column_families_in_code = column_families_in_code.into_iter();
996
997 column_families_on_disk
998 .into_iter()
999 .chain(column_families_in_code)
1000 .unique()
1001 .map(move |cf_name: String| {
1002 let mut cf_options = db_options.clone();
1003
1004 if cf_name == BALANCE_BY_TRANSPARENT_ADDR {
1005 cf_options.set_merge_operator_associative(
1006 BALANCE_BY_TRANSPARENT_ADDR_MERGE_OP,
1007 fetch_add_balance_and_received,
1008 );
1009 }
1010
1011 rocksdb::ColumnFamilyDescriptor::new(cf_name, cf_options.clone())
1012 })
1013 }
1014
1015 /// Opens or creates the database at a path based on the kind, major version and network,
1016 /// with the supplied column families, preserving any existing column families,
1017 /// and returns a shared low-level database wrapper.
1018 ///
1019 /// # Errors
1020 ///
1021 /// - In read-only mode, if the cache directory is missing or unreadable.
1022 ///
1023 /// # Panics
1024 ///
1025 /// - In read-write mode, if the cache directory does not exist and can't be created.
1026 /// - If the database cannot be opened for whatever reason.
1027 pub fn new(
1028 config: &Config,
1029 db_kind: impl AsRef<str>,
1030 format_version_in_code: &Version,
1031 network: &Network,
1032 column_families_in_code: impl IntoIterator<Item = String>,
1033 read_only: bool,
1034 ) -> Result<DiskDb, StateInitError> {
1035 // `ephemeral` and `read_only` describe mutually-exclusive modes: an ephemeral
1036 // database is a read-write primary this process owns and deletes on drop, while
1037 // a read-only secondary follows another process's primary and must never delete
1038 // it. Combining them is a configuration error — it would delete the primary's
1039 // files on drop — so reject it here rather than silently coercing it (a check
1040 // that must hold in release builds, not just debug).
1041 let mode = match (read_only, config.ephemeral) {
1042 (true, true) => return Err(StateInitError::ReadOnlyEphemeralConflict),
1043 (true, false) => DbMode::ReadOnlySecondary,
1044 (false, true) => DbMode::Ephemeral,
1045 (false, false) => DbMode::Persistent,
1046 };
1047
1048 // If the database is ephemeral, we don't need to check the cache directory.
1049 if !config.ephemeral {
1050 if read_only {
1051 // A read-only secondary instance must never create the primary cache
1052 // directory: the primary zebrad owns it. At most, verify it already
1053 // exists and is readable, and fail with a clear error otherwise.
1054 DiskDb::check_cache_dir_readable(&config.cache_dir)?;
1055 } else {
1056 DiskDb::validate_cache_dir(&config.cache_dir);
1057 }
1058 }
1059
1060 let db_kind = db_kind.as_ref();
1061 let path = config.db_path(db_kind, format_version_in_code.major, network);
1062
1063 let db_options = DiskDb::options();
1064
1065 let column_families =
1066 DiskDb::construct_column_families(db_options.clone(), &path, column_families_in_code);
1067
1068 let secondary_dir = read_only.then(|| {
1069 let secondary_dir = tempfile::Builder::new()
1070 .prefix(&format!(
1071 "zebra-secondary_state-v{}-{}-",
1072 format_version_in_code.major,
1073 network.directory_name(),
1074 ))
1075 .tempdir()
1076 .expect("temporary directory is created successfully");
1077
1078 info!(path = ?secondary_dir.path(), "created secondary db directory");
1079
1080 Arc::new(secondary_dir)
1081 });
1082
1083 let db_result = if let Some(secondary_dir) = &secondary_dir {
1084 DB::open_cf_descriptors_as_secondary(
1085 &db_options,
1086 path.as_path(),
1087 secondary_dir.path(),
1088 column_families,
1089 )
1090 } else {
1091 DB::open_cf_descriptors(&db_options, &path, column_families)
1092 };
1093
1094 match db_result {
1095 Ok(db) => {
1096 info!("Opened Zebra state cache at {}", path.display());
1097
1098 let db = DiskDb {
1099 db_kind: db_kind.to_string(),
1100 format_version_in_code: format_version_in_code.clone(),
1101 network: network.clone(),
1102 mode,
1103 db: Arc::new(db),
1104 secondary_dir,
1105 finished_format_upgrades: Arc::new(AtomicBool::new(false)),
1106 };
1107
1108 db.assert_default_cf_is_empty();
1109
1110 Ok(db)
1111 }
1112
1113 Err(e) => match (DiskDb::lock_holder(e.as_ref()), e.kind()) {
1114 (Some(LockHolder::OtherProcess), _) => panic!(
1115 "Database {path:?} is locked by another process. \
1116 Hint: Check if another zebrad process is running. \
1117 Error: {e}"
1118 ),
1119
1120 (Some(LockHolder::ThisProcess), _) => panic!(
1121 "Database {path:?} is already open in this zebrad process. \
1122 This is a bug in Zebra. \
1123 Error: {e}"
1124 ),
1125
1126 (None, ErrorKind::IOError) => panic!(
1127 "I/O error opening database {path:?}. \
1128 Hint: Check that the state cache_dir exists, is mounted, \
1129 is writable by zebrad, and has free disk space. \
1130 Error: {e}"
1131 ),
1132
1133 (None, _) => panic!(
1134 "Opening database {path:?} failed. \
1135 Hint: Try changing the state cache_dir in the Zebra config. \
1136 Error: {e}",
1137 ),
1138 },
1139 }
1140 }
1141
1142 // Accessor methods
1143
1144 /// Returns true for a secondary instance following a primary database.
1145 pub(super) fn is_read_only(&self) -> bool {
1146 self.mode.is_read_only()
1147 }
1148
1149 /// Returns an iterator borrowing raw keys and values without serialized copies.
1150 pub(super) fn raw_iterator_cf_opt<C>(
1151 &self,
1152 cf: &C,
1153 options: ReadOptions,
1154 ) -> rocksdb::DBRawIteratorWithThreadMode<'_, DB>
1155 where
1156 C: rocksdb::AsColumnFamilyRef,
1157 {
1158 self.db.raw_iterator_cf_opt(cf, options)
1159 }
1160
1161 /// Returns the configured database kind for this database.
1162 pub fn db_kind(&self) -> String {
1163 self.db_kind.clone()
1164 }
1165
1166 /// Returns the format version of the running code that created this `DiskDb` instance in memory.
1167 pub fn format_version_in_code(&self) -> Version {
1168 self.format_version_in_code.clone()
1169 }
1170
1171 /// Returns the fixed major version for this database.
1172 pub fn major_version(&self) -> u64 {
1173 self.format_version_in_code().major
1174 }
1175
1176 /// Returns the configured network for this database.
1177 pub fn network(&self) -> Network {
1178 self.network.clone()
1179 }
1180
1181 /// Returns the `Path` where the files used by this database are located.
1182 pub fn path(&self) -> &Path {
1183 self.db.path()
1184 }
1185
1186 /// Returns the low-level rocksdb inner database.
1187 #[allow(dead_code)]
1188 fn inner(&self) -> &Arc<DB> {
1189 &self.db
1190 }
1191
1192 /// Returns the column family handle for `cf_name`.
1193 pub fn cf_handle(&self, cf_name: &str) -> Option<rocksdb::ColumnFamilyRef<'_>> {
1194 // Note: the lifetime returned by this method is subtly wrong. As of December 2023 it is
1195 // the shorter of &self and &str, but RocksDB clones column family names internally, so it
1196 // should just be &self. To avoid this restriction, clone the string before passing it to
1197 // this method. Currently Zebra uses static strings, so this doesn't matter.
1198 self.db.cf_handle(cf_name)
1199 }
1200
1201 // Read methods are located in the ReadDisk trait
1202
1203 // Write methods
1204 // Low-level write methods are located in the WriteDisk trait
1205
1206 /// Writes `batch` to the database.
1207 pub(crate) fn write(&self, batch: DiskWriteBatch) -> Result<(), rocksdb::Error> {
1208 self.db.write(batch.batch)
1209 }
1210
1211 // Private methods
1212
1213 /// Tries to reuse an existing db after a major upgrade.
1214 ///
1215 /// If the current db version belongs to `restorable_db_versions`, the function moves a previous
1216 /// db to a new path so it can be used again. It does so by merely trying to rename the path
1217 /// corresponding to the db version directly preceding the current version to the path that is
1218 /// used by the current db. If successful, it also deletes the db version file.
1219 ///
1220 /// Returns the old disk version if one existed and the db directory was renamed, or None otherwise.
1221 // TODO: Update this function to rename older major db format version to the current version (#9565).
1222 #[allow(clippy::unwrap_in_result)]
1223 pub(crate) fn try_reusing_previous_db_after_major_upgrade(
1224 restorable_db_versions: &[u64],
1225 format_version_in_code: &Version,
1226 config: &Config,
1227 db_kind: impl AsRef<str>,
1228 network: &Network,
1229 ) -> Option<Version> {
1230 if let Some(&major_db_ver) = restorable_db_versions
1231 .iter()
1232 .find(|v| **v == format_version_in_code.major)
1233 {
1234 let db_kind = db_kind.as_ref();
1235
1236 let old_major_db_ver = major_db_ver - 1;
1237 let old_path = config.db_path(db_kind, old_major_db_ver, network);
1238 // Exit early if the path doesn't exist or there's an error checking it.
1239 if !fs::exists(&old_path).unwrap_or(false) {
1240 return None;
1241 }
1242
1243 let new_path = config.db_path(db_kind, major_db_ver, network);
1244
1245 let old_path = match fs::canonicalize(&old_path) {
1246 Ok(canonicalized_old_path) => canonicalized_old_path,
1247 Err(e) => {
1248 warn!("could not canonicalize {old_path:?}: {e}");
1249 return None;
1250 }
1251 };
1252
1253 let cache_path = match fs::canonicalize(&config.cache_dir) {
1254 Ok(canonicalized_cache_path) => canonicalized_cache_path,
1255 Err(e) => {
1256 warn!("could not canonicalize {:?}: {e}", config.cache_dir);
1257 return None;
1258 }
1259 };
1260
1261 // # Correctness
1262 //
1263 // Check that the path we're about to move is inside the cache directory.
1264 //
1265 // If the user has symlinked the state directory to a non-cache directory, we don't want
1266 // to move it, because it might contain other files.
1267 //
1268 // We don't attempt to guard against malicious symlinks created by attackers
1269 // (TOCTOU attacks). Zebra should not be run with elevated privileges.
1270 if !old_path.starts_with(&cache_path) {
1271 info!("skipped reusing previous state cache: state is outside cache directory");
1272 return None;
1273 }
1274
1275 let opts = DiskDb::options();
1276 let old_db_exists = DB::list_cf(&opts, &old_path).is_ok_and(|cf| !cf.is_empty());
1277 let new_db_exists = DB::list_cf(&opts, &new_path).is_ok_and(|cf| !cf.is_empty());
1278
1279 if old_db_exists && !new_db_exists {
1280 // Create the parent directory for the new db. This is because we can't directly
1281 // rename e.g. `state/v25/mainnet/` to `state/v26/mainnet/` with `fs::rename()` if
1282 // `state/v26/` does not exist.
1283 match fs::create_dir_all(
1284 new_path
1285 .parent()
1286 .expect("new state cache must have a parent path"),
1287 ) {
1288 Ok(()) => info!("created new directory for state cache at {new_path:?}"),
1289 Err(e) => {
1290 warn!(
1291 "could not create new directory for state cache at {new_path:?}: {e}"
1292 );
1293 return None;
1294 }
1295 };
1296
1297 match fs::rename(&old_path, &new_path) {
1298 Ok(()) => {
1299 info!("moved state cache from {old_path:?} to {new_path:?}");
1300
1301 let mut disk_version =
1302 database_format_version_on_disk(config, db_kind, major_db_ver, network)
1303 .expect("unable to read database format version file")
1304 .expect("unable to parse database format version");
1305
1306 disk_version.major = old_major_db_ver;
1307
1308 write_database_format_version_to_disk(
1309 config,
1310 db_kind,
1311 major_db_ver,
1312 &disk_version,
1313 network,
1314 )
1315 .expect("unable to write database format version file to disk");
1316
1317 // Get the parent of the old path, e.g. `state/v25/` and delete it if it is
1318 // empty.
1319 let old_path = old_path
1320 .parent()
1321 .expect("old state cache must have parent path");
1322
1323 if fs::read_dir(old_path)
1324 .expect("cached state dir needs to be readable")
1325 .next()
1326 .is_none()
1327 {
1328 match fs::remove_dir_all(old_path) {
1329 Ok(()) => {
1330 info!("removed empty old state cache directory at {old_path:?}")
1331 }
1332 Err(e) => {
1333 warn!(
1334 "could not remove empty old state cache directory \
1335 at {old_path:?}: {e}"
1336 )
1337 }
1338 }
1339 }
1340
1341 return Some(disk_version);
1342 }
1343 Err(e) => {
1344 warn!("could not move state cache from {old_path:?} to {new_path:?}: {e}");
1345 }
1346 };
1347 }
1348 };
1349
1350 None
1351 }
1352
1353 /// Returns the database options for the finalized state database.
1354 fn options() -> rocksdb::Options {
1355 let mut opts = rocksdb::Options::default();
1356 let mut block_based_opts = rocksdb::BlockBasedOptions::default();
1357
1358 const ONE_MEGABYTE: usize = 1024 * 1024;
1359
1360 opts.create_if_missing(true);
1361 opts.create_missing_column_families(true);
1362
1363 // Use the recommended Ribbon filter setting for all column families.
1364 //
1365 // Ribbon filters are faster than Bloom filters in Zebra, as of April 2022.
1366 // (They aren't needed for single-valued column families, but they don't hurt either.)
1367 block_based_opts.set_ribbon_filter(9.9);
1368
1369 // Use the recommended LZ4 compression type.
1370 //
1371 // https://github.com/facebook/rocksdb/wiki/Compression#configuration
1372 opts.set_compression_type(rocksdb::DBCompressionType::Lz4);
1373
1374 // Tune level-style database file compaction.
1375 //
1376 // This improves Zebra's initial sync speed slightly, as of April 2022.
1377 opts.optimize_level_style_compaction(Self::MEMTABLE_RAM_CACHE_MEGABYTES * ONE_MEGABYTE);
1378
1379 // Increase the process open file limit if needed,
1380 // then use it to set RocksDB's limit.
1381 let open_file_limit = DiskDb::increase_open_file_limit();
1382 let db_file_limit = DiskDb::get_db_open_file_limit(open_file_limit);
1383
1384 // If the current limit is very large, set the DB limit using the ideal limit
1385 let ideal_limit = DiskDb::get_db_open_file_limit(DiskDb::IDEAL_OPEN_FILE_LIMIT)
1386 .try_into()
1387 .expect("ideal open file limit fits in a c_int");
1388 let db_file_limit = db_file_limit.try_into().unwrap_or(ideal_limit);
1389
1390 opts.set_max_open_files(db_file_limit);
1391
1392 // Set the block-based options
1393 opts.set_block_based_table_factory(&block_based_opts);
1394
1395 opts
1396 }
1397
1398 /// Calculate the database's share of `open_file_limit`
1399 fn get_db_open_file_limit(open_file_limit: u64) -> u64 {
1400 // Give the DB half the files, and reserve half the files for peers
1401 (open_file_limit - DiskDb::RESERVED_FILE_COUNT) / 2
1402 }
1403
1404 /// Increase the open file limit for this process to `IDEAL_OPEN_FILE_LIMIT`.
1405 /// If that fails, try `MIN_OPEN_FILE_LIMIT`.
1406 ///
1407 /// If the current limit is above `IDEAL_OPEN_FILE_LIMIT`, leaves it
1408 /// unchanged.
1409 ///
1410 /// Returns the current limit, after any successful increases.
1411 ///
1412 /// # Panics
1413 ///
1414 /// If the open file limit can not be increased to `MIN_OPEN_FILE_LIMIT`.
1415 fn increase_open_file_limit() -> u64 {
1416 // Zebra mainly uses TCP sockets (`zebra-network`) and low-level files
1417 // (`zebra-state` database).
1418 //
1419 // On Unix-based platforms, `increase_nofile_limit` changes the limit for
1420 // both database files and TCP connections.
1421 //
1422 // But it doesn't do anything on Windows in rlimit 0.7.0.
1423 //
1424 // On Windows, the default limits are:
1425 // - 512 high-level stream I/O files (via the C standard functions),
1426 // - 8192 low-level I/O files (via the Unix C functions), and
1427 // - 1000 TCP Control Block entries (network connections).
1428 //
1429 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-160#remarks
1430 // http://smallvoid.com/article/winnt-tcpip-max-limit.html
1431 //
1432 // `zebra-state`'s `IDEAL_OPEN_FILE_LIMIT` is much less than
1433 // the Windows low-level I/O file limit.
1434 //
1435 // The [`setmaxstdio` and `getmaxstdio`](https://docs.rs/rlimit/latest/rlimit/#windows)
1436 // functions from the `rlimit` crate only change the high-level I/O file limit.
1437 //
1438 // `zebra-network`'s default connection limit is much less than
1439 // the TCP Control Block limit on Windows.
1440
1441 // We try setting the ideal limit, then the minimum limit.
1442 let current_limit = match increase_nofile_limit(DiskDb::IDEAL_OPEN_FILE_LIMIT) {
1443 Ok(current_limit) => current_limit,
1444 Err(limit_error) => {
1445 // These errors can happen due to sandboxing or unsupported system calls,
1446 // even if the file limit is high enough.
1447 info!(
1448 ?limit_error,
1449 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1450 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1451 "unable to increase the open file limit, \
1452 assuming Zebra can open a minimum number of files"
1453 );
1454
1455 return DiskDb::MIN_OPEN_FILE_LIMIT;
1456 }
1457 };
1458
1459 if current_limit < DiskDb::MIN_OPEN_FILE_LIMIT {
1460 panic!(
1461 "open file limit too low: \
1462 unable to set the number of open files to {}, \
1463 the minimum number of files required by Zebra. \
1464 Current limit is {:?}. \
1465 Hint: Increase the open file limit to {} before launching Zebra",
1466 DiskDb::MIN_OPEN_FILE_LIMIT,
1467 current_limit,
1468 DiskDb::IDEAL_OPEN_FILE_LIMIT
1469 );
1470 } else if current_limit < DiskDb::IDEAL_OPEN_FILE_LIMIT {
1471 warn!(
1472 ?current_limit,
1473 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1474 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1475 "the maximum number of open files is below Zebra's ideal limit. \
1476 Hint: Increase the open file limit to {} before launching Zebra",
1477 DiskDb::IDEAL_OPEN_FILE_LIMIT
1478 );
1479 } else if cfg!(windows) {
1480 // This log is verbose during tests.
1481 #[cfg(not(test))]
1482 info!(
1483 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1484 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1485 "assuming the open file limit is high enough for Zebra",
1486 );
1487 #[cfg(test)]
1488 debug!(
1489 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1490 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1491 "assuming the open file limit is high enough for Zebra",
1492 );
1493 } else {
1494 #[cfg(not(test))]
1495 debug!(
1496 ?current_limit,
1497 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1498 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1499 "the open file limit is high enough for Zebra",
1500 );
1501 #[cfg(test)]
1502 debug!(
1503 ?current_limit,
1504 min_limit = ?DiskDb::MIN_OPEN_FILE_LIMIT,
1505 ideal_limit = ?DiskDb::IDEAL_OPEN_FILE_LIMIT,
1506 "the open file limit is high enough for Zebra",
1507 );
1508 }
1509
1510 current_limit
1511 }
1512
1513 // Cleanup methods
1514
1515 /// Returns the number of shared instances of this database.
1516 ///
1517 /// # Concurrency
1518 ///
1519 /// The actual number of owners can be higher or lower than the returned value,
1520 /// because databases can simultaneously be cloned or dropped in other threads.
1521 ///
1522 /// However, if the number of owners is 1, and the caller has exclusive access,
1523 /// the count can't increase unless that caller clones the database.
1524 pub(crate) fn shared_database_owners(&self) -> usize {
1525 Arc::strong_count(&self.db) + Arc::weak_count(&self.db)
1526 }
1527
1528 /// Shut down the database, cleaning up background tasks and ephemeral data.
1529 ///
1530 /// If `force` is true, clean up regardless of any shared references.
1531 /// `force` can cause errors accessing the database from other shared references.
1532 /// It should only be used in debugging or test code, immediately before a manual shutdown.
1533 ///
1534 /// TODO: make private after the stop height check has moved to the syncer (#3442)
1535 /// move shutting down the database to a blocking thread (#2188)
1536 pub(crate) fn shutdown(&mut self, force: bool) {
1537 // # Correctness
1538 //
1539 // If we're the only owner of the shared database instance,
1540 // then there are no other threads that can increase the strong or weak count.
1541 //
1542 // ## Implementation Requirements
1543 //
1544 // This function and all functions that it calls should avoid cloning the shared database
1545 // instance. If they do, they must drop it before:
1546 // - shutting down database threads, or
1547 // - deleting database files.
1548
1549 if self.shared_database_owners() > 1 {
1550 let path = self.path();
1551
1552 let mut ephemeral_note = "";
1553
1554 if force {
1555 if self.mode.deletes_files_on_drop() {
1556 ephemeral_note = " and removing ephemeral files";
1557 }
1558
1559 // This log is verbose during tests.
1560 #[cfg(not(test))]
1561 info!(
1562 ?path,
1563 "forcing shutdown{} of a state database with multiple active instances",
1564 ephemeral_note,
1565 );
1566 #[cfg(test)]
1567 debug!(
1568 ?path,
1569 "forcing shutdown{} of a state database with multiple active instances",
1570 ephemeral_note,
1571 );
1572 } else {
1573 if self.mode.deletes_files_on_drop() {
1574 ephemeral_note = " and files";
1575 }
1576
1577 debug!(
1578 ?path,
1579 "dropping DiskDb clone, \
1580 but keeping shared database instance{} until the last reference is dropped",
1581 ephemeral_note,
1582 );
1583 return;
1584 }
1585 }
1586
1587 self.assert_default_cf_is_empty();
1588
1589 // Drop isn't guaranteed to run, such as when we panic, or if the tokio shutdown times out.
1590 //
1591 // Zebra's data should be fine if we don't clean up, because:
1592 // - the database flushes regularly anyway
1593 // - Zebra commits each block in a database transaction, any incomplete blocks get rolled back
1594 // - ephemeral files are placed in the os temp dir and should be cleaned up automatically eventually
1595 let path = self.path();
1596 debug!(?path, "flushing database to disk");
1597
1598 // A read-only secondary instance has nothing to flush, and RocksDB rejects
1599 // `flush()`/`flush_wal()` on secondaries with "Not supported operation in
1600 // secondary mode". Only a read-write primary needs flushing on shutdown.
1601 if !self.mode.is_read_only() {
1602 // These flushes can fail during forced shutdown or during Drop after a shutdown,
1603 // particularly in tests. If they fail, there's nothing we can do about it anyway.
1604 if let Err(error) = self.db.flush() {
1605 if matches!(error.kind(), ErrorKind::ShutdownInProgress) {
1606 debug!(
1607 ?error,
1608 ?path,
1609 "expected shutdown error flushing database SST files to disk"
1610 );
1611 } else {
1612 info!(
1613 ?error,
1614 ?path,
1615 "unexpected error flushing database SST files to disk during shutdown"
1616 );
1617 }
1618 }
1619
1620 if let Err(error) = self.db.flush_wal(true) {
1621 if matches!(error.kind(), ErrorKind::ShutdownInProgress) {
1622 debug!(
1623 ?error,
1624 ?path,
1625 "expected shutdown error flushing database WAL buffer to disk"
1626 );
1627 } else {
1628 info!(
1629 ?error,
1630 ?path,
1631 "unexpected error flushing database WAL buffer to disk during shutdown"
1632 );
1633 }
1634 }
1635 }
1636
1637 // # Memory Safety
1638 //
1639 // We'd like to call `cancel_all_background_work()` before Zebra exits,
1640 // but when we call it, we get memory, thread, or C++ errors when the process exits.
1641 // (This seems to be a bug in RocksDB: cancel_all_background_work() should wait until
1642 // all the threads have cleaned up.)
1643 //
1644 // # Change History
1645 //
1646 // We've changed this setting multiple times since 2021, in response to new RocksDB
1647 // and Rust compiler behaviour.
1648 //
1649 // We enabled cancel_all_background_work() due to failures on:
1650 // - Rust 1.57 on Linux
1651 //
1652 // We disabled cancel_all_background_work() due to failures on:
1653 // - Rust 1.64 on Linux
1654 //
1655 // We tried enabling cancel_all_background_work() due to failures on:
1656 // - Rust 1.70 on macOS 12.6.5 on x86_64
1657 // but it didn't stop the aborts happening (PR #6820).
1658 //
1659 // There weren't any failures with cancel_all_background_work() disabled on:
1660 // - Rust 1.69 or earlier
1661 // - Linux with Rust 1.70
1662 // And with cancel_all_background_work() enabled or disabled on:
1663 // - macOS 13.2 on aarch64 (M1), native and emulated x86_64, with Rust 1.70
1664 //
1665 // # Detailed Description
1666 //
1667 // We see these kinds of errors:
1668 // ```
1669 // pthread lock: Invalid argument
1670 // pure virtual method called
1671 // terminate called without an active exception
1672 // pthread destroy mutex: Device or resource busy
1673 // Aborted (core dumped)
1674 // signal: 6, SIGABRT: process abort signal
1675 // signal: 11, SIGSEGV: invalid memory reference
1676 // ```
1677 //
1678 // # Reference
1679 //
1680 // The RocksDB wiki says:
1681 // > Q: Is it safe to close RocksDB while another thread is issuing read, write or manual compaction requests?
1682 // >
1683 // > A: No. The users of RocksDB need to make sure all functions have finished before they close RocksDB.
1684 // > You can speed up the waiting by calling CancelAllBackgroundWork().
1685 //
1686 // <https://github.com/facebook/rocksdb/wiki/RocksDB-FAQ>
1687 //
1688 // > rocksdb::DB instances need to be destroyed before your main function exits.
1689 // > RocksDB instances usually depend on some internal static variables.
1690 // > Users need to make sure rocksdb::DB instances are destroyed before those static variables.
1691 //
1692 // <https://github.com/facebook/rocksdb/wiki/Known-Issues>
1693 //
1694 // # TODO
1695 //
1696 // Try re-enabling this code and fixing the underlying concurrency bug.
1697 //
1698 //info!(?path, "stopping background database tasks");
1699 //self.db.cancel_all_background_work(true);
1700
1701 // We'd like to drop the database before deleting its files,
1702 // because that closes the column families and the database correctly.
1703 // But Rust's ownership rules make that difficult,
1704 // so we just flush and delete ephemeral data instead.
1705 //
1706 // This implementation doesn't seem to cause any issues,
1707 // and the RocksDB Drop implementation handles any cleanup.
1708 self.delete_ephemeral();
1709 }
1710
1711 /// If the database is `ephemeral`, delete its files.
1712 fn delete_ephemeral(&mut self) {
1713 // # Correctness
1714 //
1715 // This function and all functions that it calls should avoid cloning the shared database
1716 // instance. See `shutdown()` for details.
1717
1718 if !self.mode.deletes_files_on_drop() {
1719 return;
1720 }
1721
1722 let path = self.path();
1723
1724 // This log is verbose during tests.
1725 #[cfg(not(test))]
1726 info!(?path, "removing temporary database files");
1727 #[cfg(test)]
1728 debug!(?path, "removing temporary database files");
1729
1730 // We'd like to use `rocksdb::Env::mem_env` for ephemeral databases,
1731 // but the Zcash blockchain might not fit in memory. So we just
1732 // delete the database files instead.
1733 //
1734 // We'd also like to call `DB::destroy` here, but calling destroy on a
1735 // live DB is undefined behaviour:
1736 // https://github.com/facebook/rocksdb/wiki/RocksDB-FAQ#basic-readwrite
1737 //
1738 // So we assume that all the database files are under `path`, and
1739 // delete them using standard filesystem APIs. Deleting open files
1740 // might cause errors on non-Unix platforms, so we ignore the result.
1741 // (The OS will delete them eventually anyway, if they are in a temporary directory.)
1742 let result = std::fs::remove_dir_all(path);
1743
1744 if result.is_err() {
1745 // This log is verbose during tests.
1746 #[cfg(not(test))]
1747 info!(
1748 ?result,
1749 ?path,
1750 "removing temporary database files caused an error",
1751 );
1752 #[cfg(test)]
1753 debug!(
1754 ?result,
1755 ?path,
1756 "removing temporary database files caused an error",
1757 );
1758 } else {
1759 debug!(
1760 ?result,
1761 ?path,
1762 "successfully removed temporary database files",
1763 );
1764 }
1765 }
1766
1767 /// Check that the "default" column family is empty.
1768 ///
1769 /// # Panics
1770 ///
1771 /// If Zebra has a bug where it is storing data in the wrong column family.
1772 fn assert_default_cf_is_empty(&self) {
1773 // # Correctness
1774 //
1775 // This function and all functions that it calls should avoid cloning the shared database
1776 // instance. See `shutdown()` for details.
1777
1778 if let Some(default_cf) = self.cf_handle("default") {
1779 assert!(
1780 self.zs_is_empty(&default_cf),
1781 "Zebra should not store data in the 'default' column family"
1782 );
1783 }
1784 }
1785
1786 // Checks that a cache directory already exists and is readable, without creating it.
1787 //
1788 // Used when opening a read-only secondary instance, which must never create the
1789 // primary's cache directory. Returns a [`StateInitError`] if the directory is missing
1790 // or unreadable.
1791 pub(crate) fn check_cache_dir_readable(
1792 cache_dir: &std::path::Path,
1793 ) -> Result<(), StateInitError> {
1794 match fs::read_dir(cache_dir) {
1795 Ok(_) => Ok(()),
1796 Err(source) => Err(StateInitError::ReadOnlyCacheDirUnreadable {
1797 path: cache_dir.to_path_buf(),
1798 source,
1799 }),
1800 }
1801 }
1802
1803 /// Returns who holds the database lock, if the RocksDB open error `message` means
1804 /// the lock is already held.
1805 ///
1806 /// RocksDB reports a held lock as an I/O error, so the message text is the only way
1807 /// to tell it apart from other I/O errors. These are the strings RocksDB 10.4 writes
1808 /// in `env/fs_posix.cc` and `port/win/env_win.cc`. A held `fcntl` lock fails with
1809 /// `EAGAIN` or `EACCES`; other `fcntl` failures, such as `ENOLCK` on a filesystem
1810 /// without lock support, are not a held lock. The Windows check matches the English
1811 /// system message, so on other system languages a held lock is reported as an I/O
1812 /// error, which still includes the RocksDB error.
1813 fn lock_holder(message: &str) -> Option<LockHolder> {
1814 let posix_lock_held = message.contains("While lock file")
1815 && (message.contains("Resource temporarily unavailable")
1816 || message.contains("Permission denied"));
1817 let windows_lock_held = message.contains("Failed to create lock file")
1818 && message.contains("being used by another process");
1819
1820 if posix_lock_held || windows_lock_held {
1821 Some(LockHolder::OtherProcess)
1822 } else if message.contains("lock hold by current process") {
1823 Some(LockHolder::ThisProcess)
1824 } else {
1825 None
1826 }
1827 }
1828
1829 // Validates a cache directory and creates it if it doesn't exist.
1830 // If the directory cannot be created, it panics with a specific error message.
1831 fn validate_cache_dir(cache_dir: &std::path::PathBuf) {
1832 if let Err(e) = fs::create_dir_all(cache_dir) {
1833 match e.kind() {
1834 std::io::ErrorKind::PermissionDenied => panic!(
1835 "Permission denied creating {cache_dir:?}. \
1836 Hint: check if cache directory exist and has write permissions."
1837 ),
1838 std::io::ErrorKind::StorageFull => panic!(
1839 "No space left on device creating {cache_dir:?}. \
1840 Hint: check if the disk is full."
1841 ),
1842 _ => panic!("Could not create cache dir {cache_dir:?}: {e}"),
1843 }
1844 }
1845 }
1846}
1847
1848impl Drop for DiskDb {
1849 fn drop(&mut self) {
1850 let path = self.path();
1851 debug!(?path, "dropping DiskDb instance");
1852
1853 self.shutdown(false);
1854 }
1855}