-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
accounts_index.rs
4301 lines (3927 loc) · 149 KB
/
accounts_index.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
use {
crate::{
accounts_index_storage::{AccountsIndexStorage, Startup},
ancestors::Ancestors,
bucket_map_holder::{Age, BucketMapHolder},
contains::Contains,
in_mem_accounts_index::InMemAccountsIndex,
inline_spl_token::{self, GenericTokenAccount},
inline_spl_token_2022,
pubkey_bins::PubkeyBinCalculator24,
rent_paying_accounts_by_partition::RentPayingAccountsByPartition,
rolling_bit_field::RollingBitField,
secondary_index::*,
},
log::*,
once_cell::sync::OnceCell,
ouroboros::self_referencing,
rand::{thread_rng, Rng},
rayon::{
iter::{IntoParallelIterator, ParallelIterator},
ThreadPool,
},
solana_measure::measure::Measure,
solana_sdk::{
account::ReadableAccount,
clock::{BankId, Slot},
pubkey::Pubkey,
},
std::{
collections::{btree_map::BTreeMap, HashSet},
fmt::Debug,
ops::{
Bound,
Bound::{Excluded, Included, Unbounded},
Range, RangeBounds,
},
path::PathBuf,
sync::{
atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering},
Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard,
},
},
thiserror::Error,
};
pub const ITER_BATCH_SIZE: usize = 1000;
pub const BINS_DEFAULT: usize = 8192;
pub const BINS_FOR_TESTING: usize = 2; // we want > 1, but each bin is a few disk files with a disk based index, so fewer is better
pub const BINS_FOR_BENCHMARKS: usize = 8192;
pub const FLUSH_THREADS_TESTING: usize = 1;
pub const ACCOUNTS_INDEX_CONFIG_FOR_TESTING: AccountsIndexConfig = AccountsIndexConfig {
bins: Some(BINS_FOR_TESTING),
flush_threads: Some(FLUSH_THREADS_TESTING),
drives: None,
index_limit_mb: IndexLimitMb::Unspecified,
ages_to_stay_in_cache: None,
scan_results_limit_bytes: None,
started_from_validator: false,
};
pub const ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS: AccountsIndexConfig = AccountsIndexConfig {
bins: Some(BINS_FOR_BENCHMARKS),
flush_threads: Some(FLUSH_THREADS_TESTING),
drives: None,
index_limit_mb: IndexLimitMb::Unspecified,
ages_to_stay_in_cache: None,
scan_results_limit_bytes: None,
started_from_validator: false,
};
pub type ScanResult<T> = Result<T, ScanError>;
pub type SlotList<T> = Vec<(Slot, T)>;
pub type SlotSlice<'s, T> = &'s [(Slot, T)];
pub type RefCount = u64;
pub type AccountMap<V> = Arc<InMemAccountsIndex<V>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// how accounts index 'upsert' should handle reclaims
pub enum UpsertReclaim {
/// previous entry for this slot in the index is expected to be cached, so irrelevant to reclaims
PreviousSlotEntryWasCached,
/// previous entry for this slot in the index may need to be reclaimed, so return it.
/// reclaims is the only output of upsert, requiring a synchronous execution
PopulateReclaims,
/// overwrite existing data in the same slot and do not return in 'reclaims'
IgnoreReclaims,
}
#[derive(Debug, Default)]
pub struct ScanConfig {
/// checked by the scan. When true, abort scan.
pub abort: Option<Arc<AtomicBool>>,
/// true to allow return of all matching items and allow them to be unsorted.
/// This is more efficient.
pub collect_all_unsorted: bool,
}
impl ScanConfig {
pub fn new(collect_all_unsorted: bool) -> Self {
Self {
collect_all_unsorted,
..ScanConfig::default()
}
}
/// mark the scan as aborted
pub fn abort(&self) {
if let Some(abort) = self.abort.as_ref() {
abort.store(true, Ordering::Relaxed)
}
}
/// use existing 'abort' if available, otherwise allocate one
pub fn recreate_with_abort(&self) -> Self {
ScanConfig {
abort: Some(self.abort.as_ref().map(Arc::clone).unwrap_or_default()),
collect_all_unsorted: self.collect_all_unsorted,
}
}
/// true if scan should abort
pub fn is_aborted(&self) -> bool {
if let Some(abort) = self.abort.as_ref() {
abort.load(Ordering::Relaxed)
} else {
false
}
}
}
pub(crate) type AccountMapEntry<T> = Arc<AccountMapEntryInner<T>>;
pub trait IsCached {
fn is_cached(&self) -> bool;
}
pub trait IndexValue:
'static + IsCached + Clone + Debug + PartialEq + ZeroLamport + Copy + Default + Sync + Send
{
}
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ScanError {
#[error("Node detected it replayed bad version of slot {slot:?} with id {bank_id:?}, thus the scan on said slot was aborted")]
SlotRemoved { slot: Slot, bank_id: BankId },
#[error("scan aborted: {0}")]
Aborted(String),
}
enum ScanTypes<R: RangeBounds<Pubkey>> {
Unindexed(Option<R>),
Indexed(IndexKey),
}
#[derive(Debug, Clone, Copy)]
pub enum IndexKey {
ProgramId(Pubkey),
SplTokenMint(Pubkey),
SplTokenOwner(Pubkey),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AccountIndex {
ProgramId,
SplTokenMint,
SplTokenOwner,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AccountSecondaryIndexesIncludeExclude {
pub exclude: bool,
pub keys: HashSet<Pubkey>,
}
/// specification of how much memory in-mem portion of account index can use
#[derive(Debug, Clone)]
pub enum IndexLimitMb {
/// nothing explicit specified, so default
Unspecified,
/// limit was specified, use disk index for rest
Limit(usize),
/// in-mem-only was specified, no disk index
InMemOnly,
}
impl Default for IndexLimitMb {
fn default() -> Self {
Self::Unspecified
}
}
#[derive(Debug, Default, Clone)]
pub struct AccountsIndexConfig {
pub bins: Option<usize>,
pub flush_threads: Option<usize>,
pub drives: Option<Vec<PathBuf>>,
pub index_limit_mb: IndexLimitMb,
pub ages_to_stay_in_cache: Option<Age>,
pub scan_results_limit_bytes: Option<usize>,
/// true if the accounts index is being created as a result of being started as a validator (as opposed to test, etc.)
pub started_from_validator: bool,
}
#[derive(Debug, Default, Clone)]
pub struct AccountSecondaryIndexes {
pub keys: Option<AccountSecondaryIndexesIncludeExclude>,
pub indexes: HashSet<AccountIndex>,
}
impl AccountSecondaryIndexes {
pub fn is_empty(&self) -> bool {
self.indexes.is_empty()
}
pub fn contains(&self, index: &AccountIndex) -> bool {
self.indexes.contains(index)
}
pub fn include_key(&self, key: &Pubkey) -> bool {
match &self.keys {
Some(options) => options.exclude ^ options.keys.contains(key),
None => true, // include all keys
}
}
}
#[derive(Debug, Default)]
/// data per entry in in-mem accounts index
/// used to keep track of consistency with disk index
pub struct AccountMapEntryMeta {
/// true if entry in in-mem idx has changes and needs to be written to disk
pub dirty: AtomicBool,
/// 'age' at which this entry should be purged from the cache (implements lru)
pub age: AtomicU8,
}
impl AccountMapEntryMeta {
pub fn new_dirty<T: IndexValue>(storage: &Arc<BucketMapHolder<T>>, is_cached: bool) -> Self {
AccountMapEntryMeta {
dirty: AtomicBool::new(true),
age: AtomicU8::new(storage.future_age_to_flush(is_cached)),
}
}
pub fn new_clean<T: IndexValue>(storage: &Arc<BucketMapHolder<T>>) -> Self {
AccountMapEntryMeta {
dirty: AtomicBool::new(false),
age: AtomicU8::new(storage.future_age_to_flush(false)),
}
}
}
#[derive(Debug, Default)]
/// one entry in the in-mem accounts index
/// Represents the value for an account key in the in-memory accounts index
pub struct AccountMapEntryInner<T> {
/// number of alive slots that contain >= 1 instances of account data for this pubkey
/// where alive represents a slot that has not yet been removed by clean via AccountsDB::clean_stored_dead_slots() for containing no up to date account information
ref_count: AtomicU64,
/// list of slots in which this pubkey was updated
/// Note that 'clean' removes outdated entries (ie. older roots) from this slot_list
/// purge_slot() also removes non-rooted slots from this list
pub slot_list: RwLock<SlotList<T>>,
/// synchronization metadata for in-memory state since last flush to disk accounts index
pub meta: AccountMapEntryMeta,
}
impl<T: IndexValue> AccountMapEntryInner<T> {
pub fn new(slot_list: SlotList<T>, ref_count: RefCount, meta: AccountMapEntryMeta) -> Self {
Self {
slot_list: RwLock::new(slot_list),
ref_count: AtomicU64::new(ref_count),
meta,
}
}
pub fn ref_count(&self) -> RefCount {
self.ref_count.load(Ordering::Acquire)
}
pub fn addref(&self) {
self.ref_count.fetch_add(1, Ordering::Release);
self.set_dirty(true);
}
/// decrement the ref count
/// return true if the old refcount was already 0. This indicates an under refcounting error in the system.
pub fn unref(&self) -> bool {
let previous = self.ref_count.fetch_sub(1, Ordering::Release);
self.set_dirty(true);
if previous == 0 {
inc_new_counter_info!("accounts_index-deref_from_0", 1);
}
previous == 0
}
pub fn dirty(&self) -> bool {
self.meta.dirty.load(Ordering::Acquire)
}
pub fn set_dirty(&self, value: bool) {
self.meta.dirty.store(value, Ordering::Release)
}
/// set dirty to false, return true if was dirty
pub fn clear_dirty(&self) -> bool {
self.meta
.dirty
.compare_exchange(true, false, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
}
pub fn age(&self) -> Age {
self.meta.age.load(Ordering::Acquire)
}
pub fn set_age(&self, value: Age) {
self.meta.age.store(value, Ordering::Release)
}
/// set age to 'next_age' if 'self.age' is 'expected_age'
pub fn try_exchange_age(&self, next_age: Age, expected_age: Age) {
let _ = self.meta.age.compare_exchange(
expected_age,
next_age,
Ordering::AcqRel,
Ordering::Relaxed,
);
}
}
pub enum AccountIndexGetResult<T: IndexValue> {
/// (index entry, index in slot list)
Found(ReadAccountMapEntry<T>, usize),
NotFound,
}
#[self_referencing]
pub struct ReadAccountMapEntry<T: IndexValue> {
owned_entry: AccountMapEntry<T>,
#[borrows(owned_entry)]
#[covariant]
slot_list_guard: RwLockReadGuard<'this, SlotList<T>>,
}
impl<T: IndexValue> Debug for ReadAccountMapEntry<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self.borrow_owned_entry())
}
}
impl<T: IndexValue> ReadAccountMapEntry<T> {
pub fn from_account_map_entry(account_map_entry: AccountMapEntry<T>) -> Self {
ReadAccountMapEntryBuilder {
owned_entry: account_map_entry,
slot_list_guard_builder: |lock| lock.slot_list.read().unwrap(),
}
.build()
}
pub fn slot_list(&self) -> &SlotList<T> {
self.borrow_slot_list_guard()
}
pub fn ref_count(&self) -> RefCount {
self.borrow_owned_entry().ref_count()
}
pub fn addref(&self) {
self.borrow_owned_entry().addref();
}
}
/// can be used to pre-allocate structures for insertion into accounts index outside of lock
pub enum PreAllocatedAccountMapEntry<T: IndexValue> {
Entry(AccountMapEntry<T>),
Raw((Slot, T)),
}
impl<T: IndexValue> ZeroLamport for PreAllocatedAccountMapEntry<T> {
fn is_zero_lamport(&self) -> bool {
match self {
PreAllocatedAccountMapEntry::Entry(entry) => {
entry.slot_list.read().unwrap()[0].1.is_zero_lamport()
}
PreAllocatedAccountMapEntry::Raw(raw) => raw.1.is_zero_lamport(),
}
}
}
impl<T: IndexValue> From<PreAllocatedAccountMapEntry<T>> for (Slot, T) {
fn from(source: PreAllocatedAccountMapEntry<T>) -> (Slot, T) {
match source {
PreAllocatedAccountMapEntry::Entry(entry) => entry.slot_list.read().unwrap()[0],
PreAllocatedAccountMapEntry::Raw(raw) => raw,
}
}
}
impl<T: IndexValue> PreAllocatedAccountMapEntry<T> {
/// create an entry that is equivalent to this process:
/// 1. new empty (refcount=0, slot_list={})
/// 2. update(slot, account_info)
/// This code is called when the first entry [ie. (slot,account_info)] for a pubkey is inserted into the index.
pub fn new(
slot: Slot,
account_info: T,
storage: &Arc<BucketMapHolder<T>>,
store_raw: bool,
) -> PreAllocatedAccountMapEntry<T> {
if store_raw {
Self::Raw((slot, account_info))
} else {
Self::Entry(Self::allocate(slot, account_info, storage))
}
}
fn allocate(
slot: Slot,
account_info: T,
storage: &Arc<BucketMapHolder<T>>,
) -> AccountMapEntry<T> {
let is_cached = account_info.is_cached();
let ref_count = u64::from(!is_cached);
let meta = AccountMapEntryMeta::new_dirty(storage, is_cached);
Arc::new(AccountMapEntryInner::new(
vec![(slot, account_info)],
ref_count,
meta,
))
}
pub fn into_account_map_entry(self, storage: &Arc<BucketMapHolder<T>>) -> AccountMapEntry<T> {
match self {
Self::Entry(entry) => entry,
Self::Raw((slot, account_info)) => Self::allocate(slot, account_info, storage),
}
}
}
#[derive(Debug)]
pub struct RootsTracker {
/// Current roots where appendvecs or write cache has account data.
/// Constructed during load from snapshots.
/// Updated every time we add a new root or clean/shrink an append vec into irrelevancy.
/// Range is approximately the last N slots where N is # slots per epoch.
pub(crate) alive_roots: RollingBitField,
/// Set of roots that are roots now or were roots at one point in time.
/// Range is approximately the last N slots where N is # slots per epoch.
/// A root could remain here if all entries in the append vec at that root are cleaned/shrunk and there are no
/// more entries for that slot. 'alive_roots' will no longer contain such roots.
/// This is a superset of 'alive_roots'
pub(crate) historical_roots: RollingBitField,
uncleaned_roots: HashSet<Slot>,
previous_uncleaned_roots: HashSet<Slot>,
}
impl Default for RootsTracker {
fn default() -> Self {
// we expect to keep a rolling set of 400k slots around at a time
// 4M gives us plenty of extra(?!) room to handle a width 10x what we should need.
// cost is 4M bits of memory, which is .5MB
RootsTracker::new(4194304)
}
}
impl RootsTracker {
pub fn new(max_width: u64) -> Self {
Self {
alive_roots: RollingBitField::new(max_width),
historical_roots: RollingBitField::new(max_width),
uncleaned_roots: HashSet::new(),
previous_uncleaned_roots: HashSet::new(),
}
}
pub fn min_alive_root(&self) -> Option<Slot> {
self.alive_roots.min()
}
}
#[derive(Debug, Default)]
pub struct AccountsIndexRootsStats {
pub roots_len: Option<usize>,
pub uncleaned_roots_len: Option<usize>,
pub previous_uncleaned_roots_len: Option<usize>,
pub roots_range: Option<u64>,
pub historical_roots_len: Option<usize>,
pub rooted_cleaned_count: usize,
pub unrooted_cleaned_count: usize,
pub clean_unref_from_storage_us: u64,
pub clean_dead_slot_us: u64,
}
pub struct AccountsIndexIterator<'a, T: IndexValue> {
account_maps: &'a LockMapTypeSlice<T>,
bin_calculator: &'a PubkeyBinCalculator24,
start_bound: Bound<Pubkey>,
end_bound: Bound<Pubkey>,
is_finished: bool,
collect_all_unsorted: bool,
}
impl<'a, T: IndexValue> AccountsIndexIterator<'a, T> {
fn range<R>(
map: &AccountMaps<T>,
range: R,
collect_all_unsorted: bool,
) -> Vec<(Pubkey, AccountMapEntry<T>)>
where
R: RangeBounds<Pubkey> + std::fmt::Debug,
{
let mut result = map.items(&range);
if !collect_all_unsorted {
result.sort_unstable_by(|a, b| a.0.cmp(&b.0));
}
result
}
fn clone_bound(bound: Bound<&Pubkey>) -> Bound<Pubkey> {
match bound {
Unbounded => Unbounded,
Included(k) => Included(*k),
Excluded(k) => Excluded(*k),
}
}
fn bin_from_bound(&self, bound: &Bound<Pubkey>, unbounded_bin: usize) -> usize {
match bound {
Bound::Included(bound) | Bound::Excluded(bound) => {
self.bin_calculator.bin_from_pubkey(bound)
}
Bound::Unbounded => unbounded_bin,
}
}
fn start_bin(&self) -> usize {
// start in bin where 'start_bound' would exist
self.bin_from_bound(&self.start_bound, 0)
}
fn end_bin_inclusive(&self) -> usize {
// end in bin where 'end_bound' would exist
self.bin_from_bound(&self.end_bound, usize::MAX)
}
fn bin_start_and_range(&self) -> (usize, usize) {
let start_bin = self.start_bin();
// calculate the max range of bins to look in
let end_bin_inclusive = self.end_bin_inclusive();
let bin_range = if start_bin > end_bin_inclusive {
0 // empty range
} else if end_bin_inclusive == usize::MAX {
usize::MAX
} else {
// the range is end_inclusive + 1 - start
// end_inclusive could be usize::MAX already if no bound was specified
end_bin_inclusive.saturating_add(1) - start_bin
};
(start_bin, bin_range)
}
pub fn new<R>(
index: &'a AccountsIndex<T>,
range: Option<&R>,
collect_all_unsorted: bool,
) -> Self
where
R: RangeBounds<Pubkey>,
{
Self {
start_bound: range
.as_ref()
.map(|r| Self::clone_bound(r.start_bound()))
.unwrap_or(Unbounded),
end_bound: range
.as_ref()
.map(|r| Self::clone_bound(r.end_bound()))
.unwrap_or(Unbounded),
account_maps: &index.account_maps,
is_finished: false,
bin_calculator: &index.bin_calculator,
collect_all_unsorted,
}
}
pub fn hold_range_in_memory<R>(&self, range: &R, start_holding: bool, thread_pool: &ThreadPool)
where
R: RangeBounds<Pubkey> + Debug + Sync,
{
// forward this hold request ONLY to the bins which contain keys in the specified range
let (start_bin, bin_range) = self.bin_start_and_range();
// the idea is this range shouldn't be more than a few buckets, but the process of loading from disk buckets is very slow
// so, parallelize the bucket loads
thread_pool.install(|| {
(0..bin_range).into_par_iter().for_each(|idx| {
let map = &self.account_maps[idx + start_bin];
map.hold_range_in_memory(range, start_holding);
});
});
}
}
impl<'a, T: IndexValue> Iterator for AccountsIndexIterator<'a, T> {
type Item = Vec<(Pubkey, AccountMapEntry<T>)>;
fn next(&mut self) -> Option<Self::Item> {
if self.is_finished {
return None;
}
let (start_bin, bin_range) = self.bin_start_and_range();
let mut chunk = Vec::with_capacity(ITER_BATCH_SIZE);
'outer: for i in self.account_maps.iter().skip(start_bin).take(bin_range) {
for (pubkey, account_map_entry) in Self::range(
&i,
(self.start_bound, self.end_bound),
self.collect_all_unsorted,
) {
if chunk.len() >= ITER_BATCH_SIZE && !self.collect_all_unsorted {
break 'outer;
}
let item = (pubkey, account_map_entry);
chunk.push(item);
}
}
if chunk.is_empty() {
self.is_finished = true;
return None;
} else if self.collect_all_unsorted {
self.is_finished = true;
}
self.start_bound = Excluded(chunk.last().unwrap().0);
Some(chunk)
}
}
pub trait ZeroLamport {
fn is_zero_lamport(&self) -> bool;
}
type MapType<T> = AccountMap<T>;
type LockMapType<T> = Vec<MapType<T>>;
type LockMapTypeSlice<T> = [MapType<T>];
type AccountMaps<'a, T> = &'a MapType<T>;
#[derive(Debug, Default)]
pub struct ScanSlotTracker {
is_removed: bool,
}
impl ScanSlotTracker {
pub fn is_removed(&self) -> bool {
self.is_removed
}
pub fn mark_removed(&mut self) {
self.is_removed = true;
}
}
#[derive(Copy, Clone)]
pub enum AccountsIndexScanResult {
/// if the entry is not in the in-memory index, do not add it, make no modifications to it
None,
/// keep the entry in the in-memory index
KeepInMemory,
/// reduce refcount by 1
Unref,
}
#[derive(Debug)]
pub struct AccountsIndex<T: IndexValue> {
pub account_maps: LockMapType<T>,
pub bin_calculator: PubkeyBinCalculator24,
program_id_index: SecondaryIndex<DashMapSecondaryIndexEntry>,
spl_token_mint_index: SecondaryIndex<DashMapSecondaryIndexEntry>,
spl_token_owner_index: SecondaryIndex<RwLockSecondaryIndexEntry>,
pub(crate) roots_tracker: RwLock<RootsTracker>,
ongoing_scan_roots: RwLock<BTreeMap<Slot, u64>>,
// Each scan has some latest slot `S` that is the tip of the fork the scan
// is iterating over. The unique id of that slot `S` is recorded here (note we don't use
// `S` as the id because there can be more than one version of a slot `S`). If a fork
// is abandoned, all of the slots on that fork up to `S` will be removed via
// `AccountsDb::remove_unrooted_slots()`. When the scan finishes, it'll realize that the
// results of the scan may have been corrupted by `remove_unrooted_slots` and abort its results.
//
// `removed_bank_ids` tracks all the slot ids that were removed via `remove_unrooted_slots()` so any attempted scans
// on any of these slots fails. This is safe to purge once the associated Bank is dropped and
// scanning the fork with that Bank at the tip is no longer possible.
pub removed_bank_ids: Mutex<HashSet<BankId>>,
storage: AccountsIndexStorage<T>,
/// when a scan's accumulated data exceeds this limit, abort the scan
pub scan_results_limit_bytes: Option<usize>,
/// # roots added since last check
pub roots_added: AtomicUsize,
/// # roots removed since last check
pub roots_removed: AtomicUsize,
/// # scans active currently
pub active_scans: AtomicUsize,
/// # of slots between latest max and latest scan
pub max_distance_to_min_scan_slot: AtomicU64,
/// populated at generate_index time - accounts that could possibly be rent paying
pub rent_paying_accounts_by_partition: OnceCell<RentPayingAccountsByPartition>,
}
impl<T: IndexValue> AccountsIndex<T> {
pub fn default_for_tests() -> Self {
Self::new(Some(ACCOUNTS_INDEX_CONFIG_FOR_TESTING), &Arc::default())
}
pub fn new(config: Option<AccountsIndexConfig>, exit: &Arc<AtomicBool>) -> Self {
let scan_results_limit_bytes = config
.as_ref()
.and_then(|config| config.scan_results_limit_bytes);
let (account_maps, bin_calculator, storage) = Self::allocate_accounts_index(config, exit);
Self {
account_maps,
bin_calculator,
program_id_index: SecondaryIndex::<DashMapSecondaryIndexEntry>::new(
"program_id_index_stats",
),
spl_token_mint_index: SecondaryIndex::<DashMapSecondaryIndexEntry>::new(
"spl_token_mint_index_stats",
),
spl_token_owner_index: SecondaryIndex::<RwLockSecondaryIndexEntry>::new(
"spl_token_owner_index_stats",
),
roots_tracker: RwLock::<RootsTracker>::default(),
ongoing_scan_roots: RwLock::<BTreeMap<Slot, u64>>::default(),
removed_bank_ids: Mutex::<HashSet<BankId>>::default(),
storage,
scan_results_limit_bytes,
roots_added: AtomicUsize::default(),
roots_removed: AtomicUsize::default(),
active_scans: AtomicUsize::default(),
max_distance_to_min_scan_slot: AtomicU64::default(),
rent_paying_accounts_by_partition: OnceCell::default(),
}
}
fn allocate_accounts_index(
config: Option<AccountsIndexConfig>,
exit: &Arc<AtomicBool>,
) -> (
LockMapType<T>,
PubkeyBinCalculator24,
AccountsIndexStorage<T>,
) {
let bins = config
.as_ref()
.and_then(|config| config.bins)
.unwrap_or(BINS_DEFAULT);
// create bin_calculator early to verify # bins is reasonable
let bin_calculator = PubkeyBinCalculator24::new(bins);
let storage = AccountsIndexStorage::new(bins, &config, exit);
let account_maps = (0..bins)
.into_iter()
.map(|bin| Arc::clone(&storage.in_mem[bin]))
.collect::<Vec<_>>();
(account_maps, bin_calculator, storage)
}
fn iter<R>(&self, range: Option<&R>, collect_all_unsorted: bool) -> AccountsIndexIterator<T>
where
R: RangeBounds<Pubkey>,
{
AccountsIndexIterator::new(self, range, collect_all_unsorted)
}
/// is the accounts index using disk as a backing store
pub fn is_disk_index_enabled(&self) -> bool {
self.storage.storage.is_disk_index_enabled()
}
fn min_ongoing_scan_root_from_btree(ongoing_scan_roots: &BTreeMap<Slot, u64>) -> Option<Slot> {
ongoing_scan_roots.keys().next().cloned()
}
fn do_checked_scan_accounts<F, R>(
&self,
metric_name: &'static str,
ancestors: &Ancestors,
scan_bank_id: BankId,
func: F,
scan_type: ScanTypes<R>,
config: &ScanConfig,
) -> Result<(), ScanError>
where
F: FnMut(&Pubkey, (&T, Slot)),
R: RangeBounds<Pubkey> + std::fmt::Debug,
{
{
let locked_removed_bank_ids = self.removed_bank_ids.lock().unwrap();
if locked_removed_bank_ids.contains(&scan_bank_id) {
return Err(ScanError::SlotRemoved {
slot: ancestors.max_slot(),
bank_id: scan_bank_id,
});
}
}
self.active_scans.fetch_add(1, Ordering::Relaxed);
let max_root = {
let mut w_ongoing_scan_roots = self
// This lock is also grabbed by clean_accounts(), so clean
// has at most cleaned up to the current `max_root` (since
// clean only happens *after* BankForks::set_root() which sets
// the `max_root`)
.ongoing_scan_roots
.write()
.unwrap();
// `max_root()` grabs a lock while
// the `ongoing_scan_roots` lock is held,
// make sure inverse doesn't happen to avoid
// deadlock
let max_root_inclusive = self.max_root_inclusive();
if let Some(min_ongoing_scan_root) =
Self::min_ongoing_scan_root_from_btree(&w_ongoing_scan_roots)
{
if min_ongoing_scan_root < max_root_inclusive {
let current = max_root_inclusive - min_ongoing_scan_root;
self.max_distance_to_min_scan_slot
.fetch_max(current, Ordering::Relaxed);
}
}
*w_ongoing_scan_roots.entry(max_root_inclusive).or_default() += 1;
max_root_inclusive
};
// First we show that for any bank `B` that is a descendant of
// the current `max_root`, it must be true that and `B.ancestors.contains(max_root)`,
// regardless of the pattern of `squash()` behavior, where `ancestors` is the set
// of ancestors that is tracked in each bank.
//
// Proof: At startup, if starting from a snapshot, generate_index() adds all banks
// in the snapshot to the index via `add_root()` and so `max_root` will be the
// greatest of these. Thus, so the claim holds at startup since there are no
// descendants of `max_root`.
//
// Now we proceed by induction on each `BankForks::set_root()`.
// Assume the claim holds when the `max_root` is `R`. Call the set of
// descendants of `R` present in BankForks `R_descendants`.
//
// Then for any banks `B` in `R_descendants`, it must be that `B.ancestors.contains(S)`,
// where `S` is any ancestor of `B` such that `S >= R`.
//
// For example:
// `R` -> `A` -> `C` -> `B`
// Then `B.ancestors == {R, A, C}`
//
// Next we call `BankForks::set_root()` at some descendant of `R`, `R_new`,
// where `R_new > R`.
//
// When we squash `R_new`, `max_root` in the AccountsIndex here is now set to `R_new`,
// and all nondescendants of `R_new` are pruned.
//
// Now consider any outstanding references to banks in the system that are descended from
// `max_root == R_new`. Take any one of these references and call it `B`. Because `B` is
// a descendant of `R_new`, this means `B` was also a descendant of `R`. Thus `B`
// must be a member of `R_descendants` because `B` was constructed and added to
// BankForks before the `set_root`.
//
// This means by the guarantees of `R_descendants` described above, because
// `R_new` is an ancestor of `B`, and `R < R_new < B`, then `B.ancestors.contains(R_new)`.
//
// Now until the next `set_root`, any new banks constructed from `new_from_parent` will
// also have `max_root == R_new` in their ancestor set, so the claim holds for those descendants
// as well. Once the next `set_root` happens, we once again update `max_root` and the same
// inductive argument can be applied again to show the claim holds.
// Check that the `max_root` is present in `ancestors`. From the proof above, if
// `max_root` is not present in `ancestors`, this means the bank `B` with the
// given `ancestors` is not descended from `max_root, which means
// either:
// 1) `B` is on a different fork or
// 2) `B` is an ancestor of `max_root`.
// In both cases we can ignore the given ancestors and instead just rely on the roots
// present as `max_root` indicates the roots present in the index are more up to date
// than the ancestors given.
let empty = Ancestors::default();
let ancestors = if ancestors.contains_key(&max_root) {
ancestors
} else {
/*
This takes of edge cases like:
Diagram 1:
slot 0
|
slot 1
/ \
slot 2 |
| slot 3 (max root)
slot 4 (scan)
By the time the scan on slot 4 is called, slot 2 may already have been
cleaned by a clean on slot 3, but slot 4 may not have been cleaned.
The state in slot 2 would have been purged and is not saved in any roots.
In this case, a scan on slot 4 wouldn't accurately reflect the state when bank 4
was frozen. In cases like this, we default to a scan on the latest roots by
removing all `ancestors`.
*/
&empty
};
/*
Now there are two cases, either `ancestors` is empty or nonempty:
1) If ancestors is empty, then this is the same as a scan on a rooted bank,
and `ongoing_scan_roots` provides protection against cleanup of roots necessary
for the scan, and passing `Some(max_root)` to `do_scan_accounts()` ensures newer
roots don't appear in the scan.
2) If ancestors is non-empty, then from the `ancestors_contains(&max_root)` above, we know
that the fork structure must look something like:
Diagram 2:
Build fork structure:
slot 0
|
slot 1 (max_root)
/ \
slot 2 |
| slot 3 (potential newer max root)
slot 4
|
slot 5 (scan)
Consider both types of ancestors, ancestor <= `max_root` and
ancestor > `max_root`, where `max_root == 1` as illustrated above.
a) The set of `ancestors <= max_root` are all rooted, which means their state
is protected by the same guarantees as 1).
b) As for the `ancestors > max_root`, those banks have at least one reference discoverable
through the chain of `Bank::BankRc::parent` starting from the calling bank. For instance
bank 5's parent reference keeps bank 4 alive, which will prevent the `Bank::drop()` from
running and cleaning up bank 4. Furthermore, no cleans can happen past the saved max_root == 1,
so a potential newer max root at 3 will not clean up any of the ancestors > 1, so slot 4
will not be cleaned in the middle of the scan either. (NOTE similar reasoning is employed for
assert!() justification in AccountsDb::retry_to_get_account_accessor)
*/
match scan_type {
ScanTypes::Unindexed(range) => {
// Pass "" not to log metrics, so RPC doesn't get spammy
self.do_scan_accounts(metric_name, ancestors, func, range, Some(max_root), config);
}
ScanTypes::Indexed(IndexKey::ProgramId(program_id)) => {
self.do_scan_secondary_index(
ancestors,
func,
&self.program_id_index,
&program_id,
Some(max_root),
config,
);
}
ScanTypes::Indexed(IndexKey::SplTokenMint(mint_key)) => {
self.do_scan_secondary_index(
ancestors,
func,
&self.spl_token_mint_index,
&mint_key,
Some(max_root),
config,
);
}
ScanTypes::Indexed(IndexKey::SplTokenOwner(owner_key)) => {
self.do_scan_secondary_index(
ancestors,
func,
&self.spl_token_owner_index,
&owner_key,
Some(max_root),
config,
);
}
}
{
self.active_scans.fetch_sub(1, Ordering::Relaxed);
let mut ongoing_scan_roots = self.ongoing_scan_roots.write().unwrap();
let count = ongoing_scan_roots.get_mut(&max_root).unwrap();
*count -= 1;
if *count == 0 {
ongoing_scan_roots.remove(&max_root);
}
}
// If the fork with tip at bank `scan_bank_id` was removed during our scan, then the scan
// may have been corrupted, so abort the results.
let was_scan_corrupted = self
.removed_bank_ids
.lock()
.unwrap()
.contains(&scan_bank_id);