-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
blockstore_db.rs
2217 lines (1960 loc) · 74.2 KB
/
blockstore_db.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub use rocksdb::Direction as IteratorDirection;
use {
crate::{
blockstore_meta,
blockstore_meta::MerkleRootMeta,
blockstore_metrics::{
maybe_enable_rocksdb_perf, report_rocksdb_read_perf, report_rocksdb_write_perf,
BlockstoreRocksDbColumnFamilyMetrics, PerfSamplingStatus, PERF_METRIC_OP_NAME_GET,
PERF_METRIC_OP_NAME_MULTI_GET, PERF_METRIC_OP_NAME_PUT,
PERF_METRIC_OP_NAME_WRITE_BATCH,
},
blockstore_options::{
AccessType, BlockstoreOptions, LedgerColumnOptions, ShredStorageType,
},
},
bincode::{deserialize, serialize},
byteorder::{BigEndian, ByteOrder},
log::*,
prost::Message,
rocksdb::{
self,
compaction_filter::CompactionFilter,
compaction_filter_factory::{CompactionFilterContext, CompactionFilterFactory},
properties as RocksProperties, ColumnFamily, ColumnFamilyDescriptor, CompactionDecision,
DBCompactionStyle, DBCompressionType, DBIterator, DBPinnableSlice, DBRawIterator,
FifoCompactOptions, IteratorMode as RocksIteratorMode, LiveFile, Options,
WriteBatch as RWriteBatch, DB,
},
serde::{de::DeserializeOwned, Serialize},
solana_accounts_db::hardened_unpack::UnpackError,
solana_sdk::{
clock::{Slot, UnixTimestamp},
pubkey::Pubkey,
signature::Signature,
},
solana_storage_proto::convert::generated,
std::{
collections::{HashMap, HashSet},
ffi::{CStr, CString},
fs,
marker::PhantomData,
path::Path,
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
},
thiserror::Error,
};
const BLOCKSTORE_METRICS_ERROR: i64 = -1;
const MAX_WRITE_BUFFER_SIZE: u64 = 256 * 1024 * 1024; // 256MB
const FIFO_WRITE_BUFFER_SIZE: u64 = 2 * MAX_WRITE_BUFFER_SIZE;
// SST files older than this value will be picked up for compaction. This value
// was chosen to be one day to strike a balance between storage getting
// reclaimed in a timely manner and the additional I/O that compaction incurs.
// For more details on this property, see
// https://github.com/facebook/rocksdb/blob/749b179c041347d150fa6721992ae8398b7d2b39/
// include/rocksdb/advanced_options.h#L908C30-L908C30
const PERIODIC_COMPACTION_SECONDS: u64 = 60 * 60 * 24;
// Column family for metadata about a leader slot
const META_CF: &str = "meta";
// Column family for slots that have been marked as dead
const DEAD_SLOTS_CF: &str = "dead_slots";
// Column family for storing proof that there were multiple
// versions of a slot
const DUPLICATE_SLOTS_CF: &str = "duplicate_slots";
// Column family storing erasure metadata for a slot
const ERASURE_META_CF: &str = "erasure_meta";
// Column family for orphans data
const ORPHANS_CF: &str = "orphans";
/// Column family for bank hashes
const BANK_HASH_CF: &str = "bank_hashes";
// Column family for root data
const ROOT_CF: &str = "root";
/// Column family for indexes
const INDEX_CF: &str = "index";
/// Column family for Data Shreds
pub const DATA_SHRED_CF: &str = "data_shred";
/// Column family for Code Shreds
const CODE_SHRED_CF: &str = "code_shred";
/// Column family for Transaction Status
const TRANSACTION_STATUS_CF: &str = "transaction_status";
/// Column family for Address Signatures
const ADDRESS_SIGNATURES_CF: &str = "address_signatures";
/// Column family for TransactionMemos
const TRANSACTION_MEMOS_CF: &str = "transaction_memos";
/// Column family for the Transaction Status Index.
/// This column family is used for tracking the active primary index for columns that for
/// query performance reasons should not be indexed by Slot.
const TRANSACTION_STATUS_INDEX_CF: &str = "transaction_status_index";
/// Column family for Rewards
const REWARDS_CF: &str = "rewards";
/// Column family for Blocktime
const BLOCKTIME_CF: &str = "blocktime";
/// Column family for Performance Samples
const PERF_SAMPLES_CF: &str = "perf_samples";
/// Column family for BlockHeight
const BLOCK_HEIGHT_CF: &str = "block_height";
/// Column family for ProgramCosts
const PROGRAM_COSTS_CF: &str = "program_costs";
/// Column family for optimistic slots
const OPTIMISTIC_SLOTS_CF: &str = "optimistic_slots";
/// Column family for merkle roots
const MERKLE_ROOT_META_CF: &str = "merkle_root_meta";
#[derive(Error, Debug)]
pub enum BlockstoreError {
ShredForIndexExists,
InvalidShredData(Box<bincode::ErrorKind>),
RocksDb(#[from] rocksdb::Error),
SlotNotRooted,
DeadSlot,
Io(#[from] std::io::Error),
Serialize(#[from] Box<bincode::ErrorKind>),
FsExtraError(#[from] fs_extra::error::Error),
SlotCleanedUp,
UnpackError(#[from] UnpackError),
UnableToSetOpenFileDescriptorLimit,
TransactionStatusSlotMismatch,
EmptyEpochStakes,
NoVoteTimestampsInRange,
ProtobufEncodeError(#[from] prost::EncodeError),
ProtobufDecodeError(#[from] prost::DecodeError),
ParentEntriesUnavailable,
SlotUnavailable,
UnsupportedTransactionVersion,
MissingTransactionMetadata,
}
pub type Result<T> = std::result::Result<T, BlockstoreError>;
impl std::fmt::Display for BlockstoreError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "blockstore error")
}
}
pub enum IteratorMode<Index> {
Start,
End,
From(Index, IteratorDirection),
}
pub mod columns {
// This avoids relatively obvious `super::` qualifications required for all non-trivial type
// references in the column doc-comments.
#[cfg(doc)]
use super::{blockstore_meta, generated, Pubkey, Signature, Slot, SlotColumn, UnixTimestamp};
#[derive(Debug)]
/// The slot metadata column.
///
/// This column family tracks the status of the received shred data for a
/// given slot. Tracking the progress as the slot fills up allows us to
/// know if the slot (or pieces of the slot) are ready to be replayed.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::SlotMeta`]
pub struct SlotMeta;
#[derive(Debug)]
/// The orphans column.
///
/// This column family tracks whether a slot has a parent. Slots without a
/// parent are by definition orphan slots. Orphans will have an entry in
/// this column family with true value. Once an orphan slot has a parent,
/// its entry in this column will be deleted.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: `bool`
pub struct Orphans;
#[derive(Debug)]
/// The dead slots column.
/// This column family tracks whether a slot is dead.
///
/// A slot is marked as dead if the validator thinks it will never be able
/// to successfully replay this slot. Example scenarios include errors
/// during the replay of a slot, or the validator believes it will never
/// receive all the shreds of a slot.
///
/// If a slot has been mistakenly marked as dead, the ledger-tool's
/// --remove-dead-slot can unmark a dead slot.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: `bool`
pub struct DeadSlots;
#[derive(Debug)]
/// The duplicate slots column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::DuplicateSlotProof`]
pub struct DuplicateSlots;
#[derive(Debug)]
/// The erasure meta column.
///
/// This column family stores ErasureMeta which includes metadata about
/// dropped network packets (or erasures) that can be used to recover
/// missing data shreds.
///
/// Its index type is `crate::shred::ErasureSetId`, which consists of a Slot ID
/// and a FEC (Forward Error Correction) set index.
///
/// * index type: `crate::shred::ErasureSetId` `(Slot, fec_set_index: u64)`
/// * value type: [`blockstore_meta::ErasureMeta`]
pub struct ErasureMeta;
#[derive(Debug)]
/// The bank hash column.
///
/// This column family persists the bank hash of a given slot. Note that
/// not every slot has a bank hash (e.g., a dead slot.)
///
/// The bank hash of a slot is derived from hashing the delta state of all
/// the accounts in a slot combined with the bank hash of its parent slot.
/// A bank hash of a slot essentially represents all the account states at
/// that slot.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::FrozenHashVersioned`]
pub struct BankHash;
#[derive(Debug)]
/// The root column.
///
/// This column family persists whether a slot is a root. Slots on the
/// main fork will be inserted into this column when they are finalized.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: `bool`
pub struct Root;
#[derive(Debug)]
/// The index column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::Index`]
pub struct Index;
#[derive(Debug)]
/// The shred data column
///
/// * index type: `(u64, u64)`
/// * value type: [`Vec<u8>`]
pub struct ShredData;
#[derive(Debug)]
/// The shred erasure code column
///
/// * index type: `(u64, u64)`
/// * value type: [`Vec<u8>`]
pub struct ShredCode;
#[derive(Debug)]
/// The transaction status column
///
/// * index type: `(u64, `[`Signature`]`, `[`Slot`])`
/// * value type: [`generated::TransactionStatusMeta`]
pub struct TransactionStatus;
#[derive(Debug)]
/// The address signatures column
///
/// * index type: `(u64, `[`Pubkey`]`, `[`Slot`]`, `[`Signature`]`)`
/// * value type: [`blockstore_meta::AddressSignatureMeta`]
pub struct AddressSignatures;
#[derive(Debug)]
/// The transaction memos column
///
/// * index type: [`Signature`]
/// * value type: [`String`]
pub struct TransactionMemos;
#[derive(Debug)]
/// The transaction status index column.
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::TransactionStatusIndexMeta`]
pub struct TransactionStatusIndex;
#[derive(Debug)]
/// The rewards column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`generated::Rewards`]
pub struct Rewards;
#[derive(Debug)]
/// The blocktime column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`UnixTimestamp`]
pub struct Blocktime;
#[derive(Debug)]
/// The performance samples column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::PerfSample`]
pub struct PerfSamples;
#[derive(Debug)]
/// The block height column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: `u64`
pub struct BlockHeight;
#[derive(Debug)]
/// The program costs column
///
/// * index type: [`Pubkey`]
/// * value type: [`blockstore_meta::ProgramCost`]
pub struct ProgramCosts;
#[derive(Debug)]
/// The optimistic slot column
///
/// * index type: `u64` (see [`SlotColumn`])
/// * value type: [`blockstore_meta::OptimisticSlotMetaVersioned`]
pub struct OptimisticSlots;
#[derive(Debug)]
/// The merkle root meta column
///
/// Each merkle shred is part of a merkle tree for
/// its FEC set. This column stores that merkle root and associated
/// meta information about the first shred received.
///
/// Its index type is (Slot, fec_set_index).
///
/// * index type: `crate::shred::ErasureSetId` `(Slot, fec_set_index: u32)`
/// * value type: [`blockstore_meta::MerkleRootMeta`]`
pub struct MerkleRootMeta;
// When adding a new column ...
// - Add struct below and implement `Column` and `ColumnName` traits
// - Add descriptor in Rocks::cf_descriptors() and name in Rocks::columns()
// - Account for column in both `run_purge_with_stats()` and
// `compact_storage()` in ledger/src/blockstore/blockstore_purge.rs !!
// - Account for column in `analyze_storage()` in ledger-tool/src/main.rs
}
#[derive(Default, Clone, Debug)]
struct OldestSlot(Arc<AtomicU64>);
impl OldestSlot {
pub fn set(&self, oldest_slot: Slot) {
// this is independently used for compaction_filter without any data dependency.
// also, compaction_filters are created via its factories, creating short-lived copies of
// this atomic value for the single job of compaction. So, Relaxed store can be justified
// in total
self.0.store(oldest_slot, Ordering::Relaxed);
}
pub fn get(&self) -> Slot {
// copy from the AtomicU64 as a general precaution so that the oldest_slot can not mutate
// across single run of compaction for simpler reasoning although this isn't strict
// requirement at the moment
// also eventual propagation (very Relaxed) load is Ok, because compaction by nature doesn't
// require strictly synchronized semantics in this regard
self.0.load(Ordering::Relaxed)
}
}
#[derive(Debug)]
struct Rocks {
db: rocksdb::DB,
access_type: AccessType,
oldest_slot: OldestSlot,
column_options: LedgerColumnOptions,
write_batch_perf_status: PerfSamplingStatus,
}
impl Rocks {
fn open(path: &Path, options: BlockstoreOptions) -> Result<Rocks> {
let access_type = options.access_type.clone();
let recovery_mode = options.recovery_mode.clone();
fs::create_dir_all(path)?;
// Use default database options
let mut db_options = get_db_options(&access_type);
if let Some(recovery_mode) = recovery_mode {
db_options.set_wal_recovery_mode(recovery_mode.into());
}
let oldest_slot = OldestSlot::default();
let column_options = options.column_options.clone();
let cf_descriptors = Self::cf_descriptors(path, &options, &oldest_slot);
// Open the database
let db = match access_type {
AccessType::Primary | AccessType::PrimaryForMaintenance => Rocks {
db: DB::open_cf_descriptors(&db_options, path, cf_descriptors)?,
access_type,
oldest_slot,
column_options,
write_batch_perf_status: PerfSamplingStatus::default(),
},
AccessType::Secondary => {
let secondary_path = path.join("solana-secondary");
info!(
"Opening Rocks with secondary (read only) access at: {:?}",
secondary_path
);
info!("This secondary access could temporarily degrade other accesses, such as by solana-validator");
Rocks {
db: DB::open_cf_descriptors_as_secondary(
&db_options,
path,
&secondary_path,
cf_descriptors,
)?,
access_type,
oldest_slot,
column_options,
write_batch_perf_status: PerfSamplingStatus::default(),
}
}
};
db.configure_compaction();
Ok(db)
}
/// Create the column family (CF) descriptors necessary to open the database.
///
/// In order to open a RocksDB database with Primary access, all columns must be opened. So,
/// in addition to creating descriptors for all of the expected columns, also create
/// descriptors for columns that were discovered but are otherwise unknown to the software.
///
/// One case where columns could be unknown is if a RocksDB database is modified with a newer
/// software version that adds a new column, and then also opened with an older version that
/// did not have knowledge of that new column.
fn cf_descriptors(
path: &Path,
options: &BlockstoreOptions,
oldest_slot: &OldestSlot,
) -> Vec<ColumnFamilyDescriptor> {
use columns::*;
let (cf_descriptor_shred_data, cf_descriptor_shred_code) =
new_cf_descriptor_pair_shreds::<ShredData, ShredCode>(options, oldest_slot);
let mut cf_descriptors = vec![
new_cf_descriptor::<SlotMeta>(options, oldest_slot),
new_cf_descriptor::<DeadSlots>(options, oldest_slot),
new_cf_descriptor::<DuplicateSlots>(options, oldest_slot),
new_cf_descriptor::<ErasureMeta>(options, oldest_slot),
new_cf_descriptor::<Orphans>(options, oldest_slot),
new_cf_descriptor::<BankHash>(options, oldest_slot),
new_cf_descriptor::<Root>(options, oldest_slot),
new_cf_descriptor::<Index>(options, oldest_slot),
cf_descriptor_shred_data,
cf_descriptor_shred_code,
new_cf_descriptor::<TransactionStatus>(options, oldest_slot),
new_cf_descriptor::<AddressSignatures>(options, oldest_slot),
new_cf_descriptor::<TransactionMemos>(options, oldest_slot),
new_cf_descriptor::<TransactionStatusIndex>(options, oldest_slot),
new_cf_descriptor::<Rewards>(options, oldest_slot),
new_cf_descriptor::<Blocktime>(options, oldest_slot),
new_cf_descriptor::<PerfSamples>(options, oldest_slot),
new_cf_descriptor::<BlockHeight>(options, oldest_slot),
new_cf_descriptor::<ProgramCosts>(options, oldest_slot),
new_cf_descriptor::<OptimisticSlots>(options, oldest_slot),
new_cf_descriptor::<MerkleRootMeta>(options, oldest_slot),
];
// If the access type is Secondary, we don't need to open all of the
// columns so we can just return immediately.
match options.access_type {
AccessType::Secondary => {
return cf_descriptors;
}
AccessType::Primary | AccessType::PrimaryForMaintenance => {}
}
// Attempt to detect the column families that are present. It is not a
// fatal error if we cannot, for example, if the Blockstore is brand
// new and will be created by the call to Rocks::open().
let detected_cfs = match DB::list_cf(&Options::default(), path) {
Ok(detected_cfs) => detected_cfs,
Err(err) => {
warn!("Unable to detect Rocks columns: {err:?}");
vec![]
}
};
// The default column is handled automatically, we don't need to create
// a descriptor for it
const DEFAULT_COLUMN_NAME: &str = "default";
let known_cfs: HashSet<_> = cf_descriptors
.iter()
.map(|cf_descriptor| cf_descriptor.name().to_string())
.chain(std::iter::once(DEFAULT_COLUMN_NAME.to_string()))
.collect();
detected_cfs.iter().for_each(|cf_name| {
if known_cfs.get(cf_name.as_str()).is_none() {
info!("Detected unknown column {cf_name}, opening column with basic options");
// This version of the software was unaware of the column, so
// it is fair to assume that we will not attempt to read or
// write the column. So, set some bare bones settings to avoid
// using extra resources on this unknown column.
let mut options = Options::default();
// Lower the default to avoid unnecessary allocations
options.set_write_buffer_size(1024 * 1024);
// Disable compactions to avoid any modifications to the column
options.set_disable_auto_compactions(true);
cf_descriptors.push(ColumnFamilyDescriptor::new(cf_name, options));
}
});
cf_descriptors
}
fn columns() -> Vec<&'static str> {
use columns::*;
vec![
ErasureMeta::NAME,
DeadSlots::NAME,
DuplicateSlots::NAME,
Index::NAME,
Orphans::NAME,
BankHash::NAME,
Root::NAME,
SlotMeta::NAME,
ShredData::NAME,
ShredCode::NAME,
TransactionStatus::NAME,
AddressSignatures::NAME,
TransactionMemos::NAME,
TransactionStatusIndex::NAME,
Rewards::NAME,
Blocktime::NAME,
PerfSamples::NAME,
BlockHeight::NAME,
ProgramCosts::NAME,
OptimisticSlots::NAME,
MerkleRootMeta::NAME,
]
}
// Configure compaction on a per-column basis
fn configure_compaction(&self) {
// If compactions are disabled altogether, no need to tune values
if should_disable_auto_compactions(&self.access_type) {
info!(
"Rocks's automatic compactions are disabled due to {:?} access",
self.access_type
);
return;
}
// Some columns make use of rocksdb's compaction to help in cleaning
// the database. See comments in should_enable_cf_compaction() for more
// details on why some columns need compaction and why others do not.
//
// More specifically, periodic (automatic) compaction is used as
// opposed to manual compaction requests on a range.
// - Periodic compaction operates on individual files once the file
// has reached a certain (configurable) age. See comments at
// PERIODIC_COMPACTION_SECONDS for some more deatil.
// - Manual compaction operates on a range and could end up propagating
// through several files and/or levels of the db.
//
// Given that data is inserted into the db at a somewhat steady rate,
// the age of the individual files will be fairly evently distributed
// over time as well. Thus, the I/O to perform cleanup with periodic
// compaction is also evenly distributed over time. On the other hand,
// a manual compaction spanning a large numbers of files could cause
// a sudden burst in I/O. Such a burst could potentially cause a write
// stall in addition to negatively impacting other parts of the system.
// Thus, the choice to use periodic compactions is fairly easy.
for cf_name in Self::columns() {
if should_enable_cf_compaction(cf_name) {
let cf_handle = self.cf_handle(cf_name);
self.db
.set_options_cf(
&cf_handle,
&[(
"periodic_compaction_seconds",
&PERIODIC_COMPACTION_SECONDS.to_string(),
)],
)
.unwrap();
}
}
}
fn destroy(path: &Path) -> Result<()> {
DB::destroy(&Options::default(), path)?;
Ok(())
}
fn cf_handle(&self, cf: &str) -> &ColumnFamily {
self.db
.cf_handle(cf)
.expect("should never get an unknown column")
}
fn get_cf(&self, cf: &ColumnFamily, key: &[u8]) -> Result<Option<Vec<u8>>> {
let opt = self.db.get_cf(cf, key)?;
Ok(opt)
}
fn get_pinned_cf(&self, cf: &ColumnFamily, key: &[u8]) -> Result<Option<DBPinnableSlice>> {
let opt = self.db.get_pinned_cf(cf, key)?;
Ok(opt)
}
fn put_cf(&self, cf: &ColumnFamily, key: &[u8], value: &[u8]) -> Result<()> {
self.db.put_cf(cf, key, value)?;
Ok(())
}
fn multi_get_cf(
&self,
cf: &ColumnFamily,
keys: Vec<&[u8]>,
) -> Vec<Result<Option<DBPinnableSlice>>> {
let values = self
.db
.batched_multi_get_cf(cf, keys, false)
.into_iter()
.map(|result| match result {
Ok(opt) => Ok(opt),
Err(e) => Err(BlockstoreError::RocksDb(e)),
})
.collect::<Vec<_>>();
values
}
fn delete_cf(&self, cf: &ColumnFamily, key: &[u8]) -> Result<()> {
self.db.delete_cf(cf, key)?;
Ok(())
}
/// Delete files whose slot range is within \[`from`, `to`\].
fn delete_file_in_range_cf(
&self,
cf: &ColumnFamily,
from_key: &[u8],
to_key: &[u8],
) -> Result<()> {
self.db.delete_file_in_range_cf(cf, from_key, to_key)?;
Ok(())
}
fn iterator_cf<C>(&self, cf: &ColumnFamily, iterator_mode: IteratorMode<C::Index>) -> DBIterator
where
C: Column,
{
let start_key;
let iterator_mode = match iterator_mode {
IteratorMode::From(start_from, direction) => {
start_key = C::key(start_from);
RocksIteratorMode::From(&start_key, direction)
}
IteratorMode::Start => RocksIteratorMode::Start,
IteratorMode::End => RocksIteratorMode::End,
};
self.db.iterator_cf(cf, iterator_mode)
}
fn raw_iterator_cf(&self, cf: &ColumnFamily) -> DBRawIterator {
self.db.raw_iterator_cf(cf)
}
fn batch(&self) -> RWriteBatch {
RWriteBatch::default()
}
fn write(&self, batch: RWriteBatch) -> Result<()> {
let op_start_instant = maybe_enable_rocksdb_perf(
self.column_options.rocks_perf_sample_interval,
&self.write_batch_perf_status,
);
let result = self.db.write(batch);
if let Some(op_start_instant) = op_start_instant {
report_rocksdb_write_perf(
PERF_METRIC_OP_NAME_WRITE_BATCH, // We use write_batch as cf_name for write batch.
PERF_METRIC_OP_NAME_WRITE_BATCH, // op_name
&op_start_instant.elapsed(),
&self.column_options,
);
}
match result {
Ok(_) => Ok(()),
Err(e) => Err(BlockstoreError::RocksDb(e)),
}
}
fn is_primary_access(&self) -> bool {
self.access_type == AccessType::Primary
|| self.access_type == AccessType::PrimaryForMaintenance
}
/// Retrieves the specified RocksDB integer property of the current
/// column family.
///
/// Full list of properties that return int values could be found
/// [here](https://github.com/facebook/rocksdb/blob/08809f5e6cd9cc4bc3958dd4d59457ae78c76660/include/rocksdb/db.h#L654-L689).
fn get_int_property_cf(&self, cf: &ColumnFamily, name: &'static std::ffi::CStr) -> Result<i64> {
match self.db.property_int_value_cf(cf, name) {
Ok(Some(value)) => Ok(value.try_into().unwrap()),
Ok(None) => Ok(0),
Err(e) => Err(BlockstoreError::RocksDb(e)),
}
}
fn live_files_metadata(&self) -> Result<Vec<LiveFile>> {
match self.db.live_files() {
Ok(live_files) => Ok(live_files),
Err(e) => Err(BlockstoreError::RocksDb(e)),
}
}
}
pub trait Column {
type Index;
fn key_size() -> usize {
std::mem::size_of::<Self::Index>()
}
fn key(index: Self::Index) -> Vec<u8>;
fn index(key: &[u8]) -> Self::Index;
// this return Slot or some u64
fn primary_index(index: Self::Index) -> u64;
fn as_index(slot: Slot) -> Self::Index;
fn slot(index: Self::Index) -> Slot {
Self::primary_index(index)
}
}
pub trait ColumnName {
const NAME: &'static str;
}
pub trait TypedColumn: Column {
type Type: Serialize + DeserializeOwned;
}
impl TypedColumn for columns::AddressSignatures {
type Type = blockstore_meta::AddressSignatureMeta;
}
impl TypedColumn for columns::TransactionMemos {
type Type = String;
}
impl TypedColumn for columns::TransactionStatusIndex {
type Type = blockstore_meta::TransactionStatusIndexMeta;
}
pub trait ProtobufColumn: Column {
type Type: prost::Message + Default;
}
/// SlotColumn is a trait for slot-based column families. Its index is
/// essentially Slot (or more generally speaking, has a 1:1 mapping to Slot).
///
/// The clean-up of any LedgerColumn that implements SlotColumn is managed by
/// `LedgerCleanupService`, which will periodically deprecate and purge
/// oldest entries that are older than the latest root in order to maintain the
/// configured --limit-ledger-size under the validator argument.
pub trait SlotColumn<Index = Slot> {}
impl<T: SlotColumn> Column for T {
type Index = Slot;
/// Converts a u64 Index to its RocksDB key.
fn key(slot: u64) -> Vec<u8> {
let mut key = vec![0; 8];
BigEndian::write_u64(&mut key[..], slot);
key
}
/// Converts a RocksDB key to its u64 Index.
fn index(key: &[u8]) -> u64 {
BigEndian::read_u64(&key[..8])
}
/// Obtains the primary index from the specified index.
fn primary_index(index: u64) -> Slot {
index
}
/// Converts a Slot to its u64 Index.
fn as_index(slot: Slot) -> u64 {
slot
}
}
#[derive(Debug)]
pub enum IndexError {
UnpackError,
}
/// Helper trait to transition primary indexes out from the columns that are using them. This
/// abbreviated trait assists in iterating past data with new keys. It will be modified and
/// expanded in a future version to support writing with the new key and reading both key types.
pub trait ColumnIndexDeprecation: Column {
const CURRENT_INDEX_LEN: usize;
fn try_current_index(key: &[u8]) -> std::result::Result<Self::Index, IndexError>;
}
impl Column for columns::TransactionStatus {
type Index = (u64, Signature, Slot);
fn key((index, signature, slot): (u64, Signature, Slot)) -> Vec<u8> {
let mut key = vec![0; 8 + 64 + 8]; // size_of u64 + size_of Signature + size_of Slot
BigEndian::write_u64(&mut key[0..8], index);
key[8..72].clone_from_slice(&signature.as_ref()[0..64]);
BigEndian::write_u64(&mut key[72..80], slot);
key
}
fn index(key: &[u8]) -> (u64, Signature, Slot) {
<columns::TransactionStatus as ColumnIndexDeprecation>::try_current_index(key)
.unwrap_or_else(|_| Self::as_index(0))
}
fn primary_index(index: Self::Index) -> u64 {
index.0
}
fn slot(index: Self::Index) -> Slot {
index.2
}
fn as_index(index: u64) -> Self::Index {
(index, Signature::default(), 0)
}
}
impl ColumnName for columns::TransactionStatus {
const NAME: &'static str = TRANSACTION_STATUS_CF;
}
impl ProtobufColumn for columns::TransactionStatus {
type Type = generated::TransactionStatusMeta;
}
impl ColumnIndexDeprecation for columns::TransactionStatus {
const CURRENT_INDEX_LEN: usize = 80;
fn try_current_index(key: &[u8]) -> std::result::Result<Self::Index, IndexError> {
if key.len() != Self::CURRENT_INDEX_LEN {
return Err(IndexError::UnpackError);
}
let primary_index = BigEndian::read_u64(&key[0..8]);
let signature = Signature::try_from(&key[8..72]).unwrap();
let slot = BigEndian::read_u64(&key[72..80]);
Ok((primary_index, signature, slot))
}
}
impl Column for columns::AddressSignatures {
type Index = (u64, Pubkey, Slot, Signature);
fn key((index, pubkey, slot, signature): (u64, Pubkey, Slot, Signature)) -> Vec<u8> {
let mut key = vec![0; 8 + 32 + 8 + 64]; // size_of u64 + size_of Pubkey + size_of Slot + size_of Signature
BigEndian::write_u64(&mut key[0..8], index);
key[8..40].clone_from_slice(&pubkey.as_ref()[0..32]);
BigEndian::write_u64(&mut key[40..48], slot);
key[48..112].clone_from_slice(&signature.as_ref()[0..64]);
key
}
fn index(key: &[u8]) -> (u64, Pubkey, Slot, Signature) {
<columns::AddressSignatures as ColumnIndexDeprecation>::try_current_index(key).unwrap()
}
fn primary_index(index: Self::Index) -> u64 {
index.0
}
fn slot(index: Self::Index) -> Slot {
index.2
}
fn as_index(index: u64) -> Self::Index {
(index, Pubkey::default(), 0, Signature::default())
}
}
impl ColumnName for columns::AddressSignatures {
const NAME: &'static str = ADDRESS_SIGNATURES_CF;
}
impl ColumnIndexDeprecation for columns::AddressSignatures {
const CURRENT_INDEX_LEN: usize = 112;
fn try_current_index(key: &[u8]) -> std::result::Result<Self::Index, IndexError> {
if key.len() != Self::CURRENT_INDEX_LEN {
return Err(IndexError::UnpackError);
}
let primary_index = BigEndian::read_u64(&key[0..8]);
let pubkey = Pubkey::try_from(&key[8..40]).unwrap();
let slot = BigEndian::read_u64(&key[40..48]);
let signature = Signature::try_from(&key[48..112]).unwrap();
Ok((primary_index, pubkey, slot, signature))
}
}
impl Column for columns::TransactionMemos {
type Index = Signature;
fn key(signature: Signature) -> Vec<u8> {
let mut key = vec![0; 64]; // size_of Signature
key[0..64].clone_from_slice(&signature.as_ref()[0..64]);
key
}
fn index(key: &[u8]) -> Signature {
Signature::try_from(&key[..64]).unwrap()
}
fn primary_index(_index: Self::Index) -> u64 {
unimplemented!()
}
fn slot(_index: Self::Index) -> Slot {
unimplemented!()
}
fn as_index(_index: u64) -> Self::Index {
Signature::default()
}
}
impl ColumnName for columns::TransactionMemos {
const NAME: &'static str = TRANSACTION_MEMOS_CF;
}
impl Column for columns::TransactionStatusIndex {
type Index = u64;
fn key(index: u64) -> Vec<u8> {
let mut key = vec![0; 8];
BigEndian::write_u64(&mut key[..], index);
key
}
fn index(key: &[u8]) -> u64 {
BigEndian::read_u64(&key[..8])
}
fn primary_index(index: u64) -> u64 {
index
}
fn slot(_index: Self::Index) -> Slot {
unimplemented!()
}
fn as_index(slot: u64) -> u64 {
slot
}
}
impl ColumnName for columns::TransactionStatusIndex {
const NAME: &'static str = TRANSACTION_STATUS_INDEX_CF;
}
impl SlotColumn for columns::Rewards {}
impl ColumnName for columns::Rewards {
const NAME: &'static str = REWARDS_CF;
}
impl ProtobufColumn for columns::Rewards {
type Type = generated::Rewards;
}
impl SlotColumn for columns::Blocktime {}
impl ColumnName for columns::Blocktime {
const NAME: &'static str = BLOCKTIME_CF;
}
impl TypedColumn for columns::Blocktime {
type Type = UnixTimestamp;
}
impl SlotColumn for columns::PerfSamples {}
impl ColumnName for columns::PerfSamples {
const NAME: &'static str = PERF_SAMPLES_CF;
}
impl SlotColumn for columns::BlockHeight {}
impl ColumnName for columns::BlockHeight {
const NAME: &'static str = BLOCK_HEIGHT_CF;
}
impl TypedColumn for columns::BlockHeight {
type Type = u64;
}
impl ColumnName for columns::ProgramCosts {
const NAME: &'static str = PROGRAM_COSTS_CF;