-
Notifications
You must be signed in to change notification settings - Fork 296
/
state_layout.rs
2272 lines (2078 loc) · 80 KB
/
state_layout.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::error::LayoutError;
use crate::utils::do_copy;
use ic_base_types::{NumBytes, NumSeconds};
use ic_config::flag_status::FlagStatus;
use ic_logger::{error, info, warn, ReplicaLogger};
use ic_metrics::{buckets::decimal_buckets, MetricsRegistry};
use ic_protobuf::{
proxy::{try_from_option_field, ProxyDecodeError},
state::{
canister_state_bits::v1 as pb_canister_state_bits, ingress::v1 as pb_ingress,
queues::v1 as pb_queues, stats::v1 as pb_stats, system_metadata::v1 as pb_metadata,
},
};
use ic_replicated_state::{
canister_state::{
execution_state::{NextScheduledMethod, WasmMetadata},
system_state::{wasm_chunk_store::WasmChunkStoreMetadata, CanisterHistory, CyclesUseCase},
},
CallContextManager, CanisterStatus, ExecutionTask, ExportedFunctions, Global, NumWasmPages,
};
use ic_sys::mmap::ScopedMmap;
use ic_types::{
batch::TotalQueryStats, nominal_cycles::NominalCycles, AccumulatedPriority, CanisterId,
ComputeAllocation, Cycles, ExecutionRound, Height, MemoryAllocation, NumInstructions,
PrincipalId,
};
use ic_utils::fs::sync_path;
use ic_utils::thread::parallel_map;
use ic_wasm_types::{CanisterModule, WasmHash};
use prometheus::{Histogram, IntCounterVec};
use std::collections::{BTreeMap, BTreeSet};
use std::convert::{identity, From, TryFrom, TryInto};
use std::ffi::OsStr;
use std::fs::OpenOptions;
use std::io::{Error, Write};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
#[cfg(test)]
mod tests;
// State layout directory and file names.
pub const CHECKPOINTS_DIR: &str = "checkpoints";
pub const CANISTER_STATES_DIR: &str = "canister_states";
pub const QUEUES_FILE: &str = "queues.pbuf";
pub const CANISTER_FILE: &str = "canister.pbuf";
pub const INGRESS_HISTORY_FILE: &str = "ingress_history.pbuf";
pub const SPLIT_MARKER_FILE: &str = "split_from.pbuf";
pub const SUBNET_QUEUES_FILE: &str = "subnet_queues.pbuf";
pub const SYSTEM_METADATA_FILE: &str = "system_metadata.pbuf";
pub const STATS_FILE: &str = "stats.pbuf";
/// `ReadOnly` is the access policy used for reading checkpoints. We
/// don't want to ever modify persisted states.
pub enum ReadOnly {}
/// `WriteOnly` is the access policy used while we are creating a new
/// checkpoint.
pub enum WriteOnly {}
/// `RwPolicy` is the access policy used for tip on disk state.
pub struct RwPolicy<'a, Owner> {
lifetime_tag: PhantomData<&'a Owner>,
}
pub trait AccessPolicy {
/// `check_dir` specifies what to do the first time we enter a
/// directory while reading/writing a checkpoint.
///
/// The default behavior is to do nothing. This is suitable for
/// the `ReadOnly` mode because if the directory doesn't exist,
/// we'll fail anyway when we try to read files from it.
fn check_dir(_p: &Path) -> Result<(), LayoutError> {
Ok(())
}
}
pub trait ReadPolicy: AccessPolicy {}
pub trait WritePolicy: AccessPolicy {}
pub trait ReadWritePolicy: ReadPolicy + WritePolicy {}
impl<T> ReadWritePolicy for T where T: ReadPolicy + WritePolicy {}
impl AccessPolicy for ReadOnly {}
impl ReadPolicy for ReadOnly {}
impl AccessPolicy for WriteOnly {
/// For `WriteOnly` mode we want to ensure the directory exists
/// when we visit it for the first time as we'll certainly want to
/// create new files inside.
fn check_dir(path: &Path) -> Result<(), LayoutError> {
std::fs::create_dir_all(path).map_err(|err| LayoutError::IoError {
path: path.to_path_buf(),
message: "Failed to create directory".to_string(),
io_err: err,
})
}
}
impl WritePolicy for WriteOnly {}
impl<'a, T> AccessPolicy for RwPolicy<'a, T> {
fn check_dir(p: &Path) -> Result<(), LayoutError> {
WriteOnly::check_dir(p)
}
}
impl<'a, T> ReadPolicy for RwPolicy<'a, T> {}
impl<'a, T> WritePolicy for RwPolicy<'a, T> {}
pub type CompleteCheckpointLayout = CheckpointLayout<ReadOnly>;
/// This struct contains bits of the `ExecutionState` that are not already
/// covered somewhere else and are too small to be serialized separately.
#[derive(Debug)]
pub struct ExecutionStateBits {
pub exported_globals: Vec<Global>,
pub heap_size: NumWasmPages,
pub exports: ExportedFunctions,
pub last_executed_round: ExecutionRound,
pub metadata: WasmMetadata,
pub binary_hash: Option<WasmHash>,
pub next_scheduled_method: NextScheduledMethod,
}
/// This struct contains bits of the `CanisterState` that are not already
/// covered somewhere else and are too small to be serialized separately.
#[derive(Debug)]
pub struct CanisterStateBits {
pub controllers: BTreeSet<PrincipalId>,
pub last_full_execution_round: ExecutionRound,
pub call_context_manager: Option<CallContextManager>,
pub compute_allocation: ComputeAllocation,
pub accumulated_priority: AccumulatedPriority,
pub execution_state_bits: Option<ExecutionStateBits>,
pub memory_allocation: MemoryAllocation,
pub freeze_threshold: NumSeconds,
pub cycles_balance: Cycles,
pub cycles_debit: Cycles,
pub reserved_balance: Cycles,
pub reserved_balance_limit: Option<Cycles>,
pub status: CanisterStatus,
pub scheduled_as_first: u64,
pub skipped_round_due_to_no_messages: u64,
pub executed: u64,
pub interrupted_during_execution: u64,
pub certified_data: Vec<u8>,
pub consumed_cycles_since_replica_started: NominalCycles,
pub stable_memory_size: NumWasmPages,
pub heap_delta_debit: NumBytes,
pub install_code_debit: NumInstructions,
pub task_queue: Vec<ExecutionTask>,
pub time_of_last_allocation_charge_nanos: u64,
pub global_timer_nanos: Option<u64>,
pub canister_version: u64,
pub consumed_cycles_since_replica_started_by_use_cases: BTreeMap<CyclesUseCase, NominalCycles>,
pub canister_history: CanisterHistory,
pub wasm_chunk_store_metadata: WasmChunkStoreMetadata,
pub total_query_stats: TotalQueryStats,
}
#[derive(Clone)]
struct StateLayoutMetrics {
state_layout_error_count: IntCounterVec,
state_layout_remove_checkpoint_duration: Histogram,
#[cfg(target_os = "linux")]
state_layout_syncfs_duration: Histogram,
}
impl StateLayoutMetrics {
fn new(metric_registry: &MetricsRegistry) -> StateLayoutMetrics {
StateLayoutMetrics {
state_layout_error_count: metric_registry.int_counter_vec(
"state_layout_error_count",
"Total number of errors encountered in the state layout.",
&["source"],
),
state_layout_remove_checkpoint_duration: metric_registry.histogram(
"state_layout_remove_checkpoint_duration",
"Time elapsed in removing checkpoint.",
decimal_buckets(-3, 1),
),
#[cfg(target_os = "linux")]
state_layout_syncfs_duration: metric_registry.histogram(
"state_layout_syncfs_duration_seconds",
"Time elapsed in syncfs.",
decimal_buckets(-2, 2),
),
}
}
}
struct CheckpointRefData {
// CheckpointLayouts using this ref that are still alive.
checkpoint_layout_counter: i32,
// The ref is scheduled for removal once checkpoint_layout_counter drops to zero.
mark_deleted: bool,
}
/// `StateLayout` provides convenience functions to construct correct
/// paths to individual components of the replicated execution
/// state and checkpoints.
///
/// ```text
/// <root>
/// ├── states_metadata.pbuf
/// │
/// │── tip
/// │ ├── canister_states
/// │ │ └── <hex(canister_id)>
/// │ │ ├── canister.pbuf
/// │ │ ├── queues.pbuf
/// │ │ ├── software.wasm
/// │ │ ├── stable_memory.bin
/// │ │ └── vmemory_0.bin
/// │ ├── ingress_history.pbuf
/// │ ├── split_from.pbuf
/// │ ├── subnet_queues.pbuf
/// │ └── system_metadata.pbuf
/// │
/// ├── [checkpoints, backups, diverged_checkpoints]
/// │ └──<hex(round)>
/// │ ├── canister_states
/// │ │ └── <hex(canister_id)>
/// │ │ ├── canister.pbuf
/// │ │ ├── queues.pbuf
/// │ │ ├── software.wasm
/// │ │ ├── stable_memory.bin
/// │ │ ├── vmemory_0.bin
/// │ │ └── wasm_chunk_store.bin
/// │ ├── ingress_history.pbuf
/// │ ├── split_from.pbuf
/// │ ├── subnet_queues.pbuf
/// │ └── system_metadata.pbuf
/// │
/// ├── diverged_state_markers
/// │ └──<hex(round)>
/// │
/// ├── tmp
/// └── fs_tmp
/// ```
///
/// Needs to be pub for criterion performance regression tests.
///
/// Checkpoints management
///
/// Checkpoints are created under "checkpoints" directory. fs_tmp directory
/// is used as intermediate scratchpad area. Additional directory structure
/// could be overlaid by state_layout on top of following directory structure.
///
/// For correctness reasons we need to make sure that checkpoints we create are
/// internally consistent and only "publish" them in the `checkpoints` directory
/// once they are fully synced to disk.
///
/// There are 2 ways to construct a checkpoint:
/// 1. Compute it locally by applying blocks to an older state.
/// 2. Fetch it from a peer using the state sync protocol.
///
/// Let's look at how each case is handled.
///
/// ## Promoting a TIP to a checkpoint
///
/// 1. Dump the state to files and directories under "<state_root>/tip", mark
/// readonly and sync all files
///
/// 2. Rename tip to checkpoint.
///
/// 3. Reflink the checkpoint back to writeable tip
///
/// ## Promoting a State Sync artifact to a checkpoint
///
/// 1. Create state files directly in
/// "<state_root>/fs_tmp/state_sync_scratchpad_<height>".
///
/// 2. When all the writes are complete, call sync_and_mark_files_readonly()
/// on "<state_root>/fs_tmp/state_sync_scratchpad_<height>". This function
/// syncs all the files and directories under the scratchpad directory,
/// including the scratchpad directory itself.
///
/// 3. Rename "<state_root>/fs_tmp/state_sync_scratchpad_<height>" to
/// "<state_root>/checkpoints/<height>", sync "<state_root>/checkpoints".
#[derive(Clone)]
pub struct StateLayout {
root: PathBuf,
log: ReplicaLogger,
metrics: StateLayoutMetrics,
tip_handler_captured: Arc<AtomicBool>,
checkpoint_ref_registry: Arc<Mutex<BTreeMap<Height, CheckpointRefData>>>,
}
pub struct TipHandler {
tip_path: PathBuf,
}
impl TipHandler {
pub fn tip_path(&mut self) -> PathBuf {
self.tip_path.clone()
}
/// Returns a layout object representing tip state in "tip"
/// directory. During round execution this directory may contain
/// inconsistent state. During full checkpointing this directory contains
/// full state and is converted to a checkpoint.
/// This directory is cleaned during restart of a node and reset to
/// last full checkpoint.
pub fn tip(&mut self, height: Height) -> Result<CheckpointLayout<RwPolicy<Self>>, LayoutError> {
CheckpointLayout::new_untracked(self.tip_path(), height)
}
/// Resets "tip" to a checkpoint identified by height.
pub fn reset_tip_to(
&mut self,
state_layout: &StateLayout,
cp: &CheckpointLayout<ReadOnly>,
lsmt_storage: FlagStatus,
thread_pool: Option<&mut scoped_threadpool::Pool>,
) -> Result<(), LayoutError> {
let tip = self.tip_path();
if tip.exists() {
std::fs::remove_dir_all(&tip).map_err(|err| LayoutError::IoError {
path: tip.to_path_buf(),
message: format!("Cannot remove tip for checkpoint {}", cp.height),
io_err: err,
})?;
}
debug_assert!(cp.root.exists());
let file_copy_instruction = |path: &Path| {
if path.extension() == Some(OsStr::new("pbuf")) {
// Do not copy protobufs.
CopyInstruction::Skip
} else if path.extension() == Some(OsStr::new("bin"))
&& lsmt_storage == FlagStatus::Disabled
{
// PageMap files need to be modified in the tip,
// but only with non-LSMT storage layer that modifies these files.
// With LSMT we always write additional overlay files instead.
CopyInstruction::ReadWrite
} else {
// Everything else should be readonly.
CopyInstruction::ReadOnly
}
};
match copy_recursively(
&state_layout.log,
&state_layout.metrics,
cp.root.as_path(),
&tip,
FSync::No,
file_copy_instruction,
thread_pool,
) {
Ok(()) => Ok(()),
Err(e) => {
if let Err(err) = std::fs::remove_dir_all(&tip) {
error!(
state_layout.log,
"Failed to tip directory. Path: {}, Error: {}.",
tip.display(),
err
)
}
Err(LayoutError::IoError {
path: tip,
message: format!(
"Failed to convert reset tip to checkpoint to {} (err kind: {:?})",
cp.root.display(),
e.kind()
),
io_err: e,
})
}
}
}
/// Deletes canisters from tip if they are not in ids.
pub fn filter_tip_canisters(
&mut self,
height: Height,
ids: &BTreeSet<CanisterId>,
) -> Result<(), LayoutError> {
let tip = self.tip(height)?;
let canisters_on_disk = tip.canister_ids()?;
for id in canisters_on_disk {
if !ids.contains(&id) {
let canister_path = tip.canister(&id)?.raw_path();
std::fs::remove_dir_all(&canister_path).map_err(|err| LayoutError::IoError {
path: canister_path,
message: "Cannot remove canister.".to_string(),
io_err: err,
})?;
}
}
Ok(())
}
}
impl StateLayout {
/// Needs to be pub for criterion performance regression tests.
pub fn try_new(
log: ReplicaLogger,
root: PathBuf,
metrics_registry: &MetricsRegistry,
) -> Result<Self, LayoutError> {
let state_layout = Self {
root,
log,
metrics: StateLayoutMetrics::new(metrics_registry),
tip_handler_captured: Arc::new(false.into()),
checkpoint_ref_registry: Arc::new(Mutex::new(BTreeMap::new())),
};
state_layout.init()?;
Ok(state_layout)
}
fn init(&self) -> Result<(), LayoutError> {
self.cleanup_tip()?;
self.cleanup_tmp()?;
// This is for testing only. In production the Guest OS setup
// would have already created the page_deltas directory, however
// in testing the directory does not already exist and we need to
// create it.
if !Path::new(&self.page_deltas()).exists() {
WriteOnly::check_dir(&self.page_deltas())?;
}
WriteOnly::check_dir(&self.backups())?;
WriteOnly::check_dir(&self.checkpoints())?;
WriteOnly::check_dir(&self.diverged_checkpoints())?;
WriteOnly::check_dir(&self.diverged_state_markers())?;
WriteOnly::check_dir(&self.fs_tmp())?;
WriteOnly::check_dir(&self.tip_path())?;
WriteOnly::check_dir(&self.tmp())?;
for path in [
&self.backups(),
&self.checkpoints(),
&self.diverged_checkpoints(),
&self.diverged_state_markers(),
] {
sync_path(path).map_err(|err| LayoutError::IoError {
path: path.clone(),
message: "Could not sync StateLayout during init".to_string(),
io_err: err,
})?
}
Ok(())
}
/// Create tip handler. Could only be called once as TipHandler is an exclusive owner of the
/// tip folder.
pub fn capture_tip_handler(&self) -> TipHandler {
assert_eq!(
self.tip_handler_captured.compare_exchange(
false,
true,
Ordering::SeqCst,
Ordering::SeqCst
),
Ok(false)
);
TipHandler {
tip_path: self.tip_path(),
}
}
/// Returns the the raw root path for state
pub fn raw_path(&self) -> &Path {
&self.root
}
/// Returns the path to the temporary directory.
/// This directory is cleaned during restart of a node.
pub fn tmp(&self) -> PathBuf {
self.root.join("tmp")
}
/// Returns the path to the temporary directory for checkpoint operations,
/// aka fs_tmp. This directory is cleaned during restart of a node.
pub fn fs_tmp(&self) -> PathBuf {
self.root.join("fs_tmp")
}
pub fn page_deltas(&self) -> PathBuf {
self.root.join("page_deltas")
}
/// Removes the tmp directory and all its contents.
fn cleanup_tmp(&self) -> Result<(), LayoutError> {
let tmp = self.tmp();
if tmp.exists() {
std::fs::remove_dir_all(&tmp).map_err(|err| LayoutError::IoError {
path: tmp,
message: "Unable to remove temporary directory".to_string(),
io_err: err,
})?
}
let fs_tmp = self.fs_tmp();
if fs_tmp.exists() {
std::fs::remove_dir_all(&fs_tmp).map_err(|err| LayoutError::IoError {
path: fs_tmp,
message: "Unable to remove fs_tmp directory".to_string(),
io_err: err,
})?
}
// The page deltas directory will always exist because
// the guest os deployment scripts should have created it.
// Also, if we delete the directory here and re-create it as
// it happens for the other sibling dirs then the SELinux
// settings will be overwritten, which will not grant the sandbox
// the proper access to the files in the dir.
let page_deltas = self.page_deltas();
if page_deltas.exists() {
for entry in std::fs::read_dir(page_deltas.as_path()).unwrap() {
let entry = entry.map_err(|err| LayoutError::IoError {
path: page_deltas.clone(),
message: "Unable to remove content of the page_deltas directory".to_string(),
io_err: err,
});
std::fs::remove_file(entry.unwrap().path()).unwrap();
}
}
Ok(())
}
/// Returns the path to the serialized states metadata.
pub fn states_metadata(&self) -> PathBuf {
self.root.join("states_metadata.pbuf")
}
/// Returns scratchpad used during statesync
pub fn state_sync_scratchpad(&self, height: Height) -> Result<PathBuf, LayoutError> {
Ok(self
.tmp()
.join(format!("state_sync_scratchpad_{:016x}", height.get())))
}
/// Returns the path to cache an unfinished statesync at `height`
pub fn state_sync_cache(&self, height: Height) -> Result<PathBuf, LayoutError> {
let tmp = self.tmp();
Ok(tmp.join(format!("state_sync_cache_{:016x}", height.get())))
}
fn cleanup_tip(&self) -> Result<(), LayoutError> {
if self.tip_path().exists() {
std::fs::remove_dir_all(self.tip_path()).map_err(|err| LayoutError::IoError {
path: self.tip_path(),
message: "Unable to remove old tip. Tip could be inconsistent".to_string(),
io_err: err,
})
} else {
Ok(())
}
}
pub fn scratchpad_to_checkpoint<T>(
&self,
layout: CheckpointLayout<RwPolicy<'_, T>>,
height: Height,
thread_pool: Option<&mut scoped_threadpool::Pool>,
) -> Result<CheckpointLayout<ReadOnly>, LayoutError> {
debug_assert_eq!(height, layout.height);
let scratchpad = layout.raw_path();
let checkpoints_path = self.checkpoints();
let cp_path = checkpoints_path.join(Self::checkpoint_name(height));
sync_and_mark_files_readonly(&self.log, scratchpad, &self.metrics, thread_pool).map_err(
|err| LayoutError::IoError {
path: scratchpad.to_path_buf(),
message: format!(
"Could not sync and mark readonly scratchpad for checkpoint {}",
height
),
io_err: err,
},
)?;
std::fs::rename(scratchpad, cp_path).map_err(|err| {
if is_already_exists_err(&err) {
LayoutError::AlreadyExists(height)
} else {
LayoutError::IoError {
path: scratchpad.to_path_buf(),
message: format!("Failed to rename scratchpad to checkpoint {}", height),
io_err: err,
}
}
})?;
sync_path(&checkpoints_path).map_err(|err| LayoutError::IoError {
path: checkpoints_path,
message: "Could not sync checkpoints".to_string(),
io_err: err,
})?;
self.checkpoint(height)
}
pub fn clone_checkpoint(&self, from: Height, to: Height) -> Result<(), LayoutError> {
let src = self.checkpoints().join(Self::checkpoint_name(from));
let dst = self.checkpoints().join(Self::checkpoint_name(to));
self.copy_and_sync_checkpoint(&Self::checkpoint_name(to), &src, &dst, None)
.map_err(|io_err| {
if is_already_exists_err(&io_err) {
LayoutError::AlreadyExists(to)
} else {
LayoutError::IoError {
path: dst,
message: format!("Failed to clone checkpoint {} to {}", from, to),
io_err,
}
}
})?;
Ok(())
}
/// Returns the layout of the checkpoint with the given height (if
/// there is one).
pub fn checkpoint(&self, height: Height) -> Result<CheckpointLayout<ReadOnly>, LayoutError> {
let cp_name = Self::checkpoint_name(height);
let path = self.checkpoints().join(cp_name);
if !path.exists() {
return Err(LayoutError::NotFound(height));
}
{
let mut checkpoint_ref_registry = self.checkpoint_ref_registry.lock().unwrap();
match checkpoint_ref_registry.get_mut(&height) {
Some(ref mut ref_data) => {
ref_data.checkpoint_layout_counter += 1;
#[cfg(debug_assert)]
{
let mark_deleted = ref_data.mark_deleted;
drop(checkpoint_ref_registry);
debug_assert!(!mark_deleted);
}
}
None => {
checkpoint_ref_registry.insert(
height,
CheckpointRefData {
checkpoint_layout_counter: 1,
mark_deleted: false,
},
);
}
}
}
CheckpointLayout::new(path, height, self.clone())
}
fn increment_checkpoint_ref_counter(&self, height: Height) {
let mut checkpoint_ref_registry = self.checkpoint_ref_registry.lock().unwrap();
checkpoint_ref_registry
.entry(height)
.or_insert(CheckpointRefData {
checkpoint_layout_counter: 0,
mark_deleted: false,
})
.checkpoint_layout_counter += 1;
}
fn remove_checkpoint_ref(&self, height: Height) {
let mut checkpoint_ref_registry = self.checkpoint_ref_registry.lock().unwrap();
match checkpoint_ref_registry.get_mut(&height) {
None => {
debug_assert!(false, "Double removal at height {}", height);
return;
}
Some(ref mut data) => {
debug_assert!(data.checkpoint_layout_counter >= 1);
data.checkpoint_layout_counter -= 1;
if data.checkpoint_layout_counter != 0 {
return;
}
let mark_deleted = data.mark_deleted;
let _removed = checkpoint_ref_registry.remove(&height);
debug_assert!(_removed.is_some());
if !mark_deleted {
return;
}
}
}
self.remove_checkpoint_if_not_the_latest(height, checkpoint_ref_registry);
}
/// Schedule checkpoint for removal when no CheckpointLayout points to it.
/// If none then remove immediately.
pub fn remove_checkpoint_when_unused(&self, height: Height) {
let mut checkpoint_ref_registry = self.checkpoint_ref_registry.lock().unwrap();
match checkpoint_ref_registry.get_mut(&height) {
Some(ref mut data) => data.mark_deleted = true,
None => self.remove_checkpoint_if_not_the_latest(height, checkpoint_ref_registry),
}
}
/// Returns a sorted list of `Height`s for which a checkpoint is available.
pub fn checkpoint_heights(&self) -> Result<Vec<Height>, LayoutError> {
let names = dir_file_names(&self.checkpoints()).map_err(|err| LayoutError::IoError {
path: self.checkpoints(),
message: format!("Failed to get all checkpoints (err kind: {:?})", err.kind()),
io_err: err,
})?;
parse_and_sort_checkpoint_heights(&names[..])
}
/// Returns a sorted in ascended order list of `Height`s of checkpoints that were marked as
/// diverged.
pub fn diverged_checkpoint_heights(&self) -> Result<Vec<Height>, LayoutError> {
let names = dir_file_names(&self.diverged_checkpoints()).map_err(|io_err| {
LayoutError::IoError {
path: self.diverged_checkpoints(),
message: "failed to enumerate diverged checkpoints".to_string(),
io_err,
}
})?;
parse_and_sort_checkpoint_heights(&names[..])
}
/// Returns a sorted in ascending order list of `Height`s of states that were marked as
/// diverged.
pub fn diverged_state_heights(&self) -> Result<Vec<Height>, LayoutError> {
let names = dir_file_names(&self.diverged_state_markers()).map_err(|io_err| {
LayoutError::IoError {
path: self.diverged_state_markers(),
message: "failed to enumerate diverged states".to_string(),
io_err,
}
})?;
parse_and_sort_checkpoint_heights(&names[..])
}
/// Returns a sorted in ascended order list of heights of checkpoints that were "backed up"
/// for future inspection because they corresponded to diverged states.
pub fn backup_heights(&self) -> Result<Vec<Height>, LayoutError> {
let names = dir_file_names(&self.backups()).map_err(|io_err| LayoutError::IoError {
path: self.backups(),
message: "failed to enumerate backups".to_string(),
io_err,
})?;
parse_and_sort_checkpoint_heights(&names[..])
}
/// Returns a path to a diverged checkpoint given its height.
///
/// If there is no diverged checkpoint with the specified height, the
/// returned path doesn't exist on the filesystem.
///
/// Precondition:
/// h ∈ self.diverged_checkpoint_heights()
pub fn diverged_checkpoint_path(&self, h: Height) -> PathBuf {
self.diverged_checkpoints().join(Self::checkpoint_name(h))
}
/// Returns a path to a backed up state given its height.
///
/// Precondition:
/// h ∈ self.backup_heights()
pub fn backup_checkpoint_path(&self, h: Height) -> PathBuf {
self.backups().join(Self::checkpoint_name(h))
}
/// Removes a checkpoint for a given height if it exists.
/// Drops drop_after_rename once the checkpoint is moved to tmp.
///
/// Postcondition:
/// height ∉ self.checkpoint_heights()
fn remove_checkpoint<T>(
&self,
height: Height,
drop_after_rename: T,
) -> Result<(), LayoutError> {
let start = Instant::now();
let cp_name = Self::checkpoint_name(height);
let cp_path = self.checkpoints().join(&cp_name);
let tmp_path = self.fs_tmp().join(&cp_name);
self.atomically_remove_via_path(&cp_path, &tmp_path, drop_after_rename)
.map_err(|err| LayoutError::IoError {
path: cp_path,
message: format!(
"failed to remove checkpoint {} (err kind: {:?})",
cp_name,
err.kind()
),
io_err: err,
})?;
let elapsed = start.elapsed();
info!(self.log, "Removed checkpoint @{} in {:?}", height, elapsed);
self.metrics
.state_layout_remove_checkpoint_duration
.observe(elapsed.as_secs_f64());
Ok(())
}
pub fn force_remove_checkpoint(&self, height: Height) -> Result<(), LayoutError> {
self.remove_checkpoint(height, ())
}
/// Removes a checkpoint for a given height if it exists and it is not the latest checkpoint.
/// Crashes in debug if removal of the last checkpoint is ever attempted or the checkpoint is
/// not found.
///
/// Postcondition:
/// height ∉ self.checkpoint_heights()[0:-1]
fn remove_checkpoint_if_not_the_latest<T>(&self, height: Height, drop_after_rename: T) {
match self.checkpoint_heights() {
Err(err) => {
error!(self.log, "Failed to get checkpoint heights: {}", err);
self.metrics
.state_layout_error_count
.with_label_values(&["remove_checkpoint_no_heights"])
.inc();
}
Ok(mut heights) => {
if heights.is_empty() {
error!(
self.log,
"Trying to remove non-existing checkpoint {}. The CheckpoinLayout was invalid",
height,
);
self.metrics
.state_layout_error_count
.with_label_values(&["remove_checkpoint_non_existent"])
.inc();
return;
}
if heights.pop() == Some(height) {
error!(self.log, "Trying to remove the last checkpoint {}", height);
self.metrics
.state_layout_error_count
.with_label_values(&["remove_last_checkpoint"])
.inc();
debug_assert!(false);
return;
}
if let Err(err) = self.remove_checkpoint(height, drop_after_rename) {
error!(self.log, "Failed to remove checkpoint: {}", err);
debug_assert!(false);
self.metrics
.state_layout_error_count
.with_label_values(&["remove_checkpoint_other"])
.inc();
}
}
}
}
/// Marks the checkpoint with the specified height as diverged.
///
/// Precondition:
/// height ∈ self.checkpoint_heights()
///
/// Postcondition:
/// height ∈ self.diverged_checkpoint_heights() ∧
/// height ∉ self.checkpoint_heights()
pub fn mark_checkpoint_diverged(&self, height: Height) -> Result<(), LayoutError> {
let cp_name = Self::checkpoint_name(height);
let cp_path = self.checkpoints().join(&cp_name);
let dst_path = self.diverged_checkpoints().join(&cp_name);
match std::fs::rename(&cp_path, dst_path) {
Ok(()) => {
for path in [&self.checkpoints(), &self.diverged_checkpoints()] {
sync_path(path).map_err(|err| LayoutError::IoError {
path: path.clone(),
message: "Failed to sync checkpoints".to_string(),
io_err: err,
})?
}
Ok(())
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
other => other.map_err(|err| LayoutError::IoError {
path: cp_path,
message: format!("Failed to mark checkpoint {} diverged", height),
io_err: err,
}),
}
}
/// Path of diverged state marker for the given height.
pub fn diverged_state_marker_path(&self, height: Height) -> PathBuf {
self.diverged_state_markers()
.join(Self::checkpoint_name(height))
}
/// Creates a diverged state marker for the given height.
///
/// Postcondition:
/// h ∈ self.diverged_state_heights()
pub fn create_diverged_state_marker(&self, height: Height) -> Result<(), LayoutError> {
open_for_write(&self.diverged_state_marker_path(height))?;
sync_path(self.diverged_state_markers()).map_err(|err| LayoutError::IoError {
path: self.diverged_state_markers(),
message: "Failed to sync diverged state markers".to_string(),
io_err: err,
})
}
/// Removes a diverged checkpoint given its height.
///
/// Precondition:
/// h ∈ self.diverged_state_heights()
pub fn remove_diverged_state_marker(&self, height: Height) -> Result<(), LayoutError> {
let path = self.diverged_state_marker_path(height);
remove_existing_file(&path)
}
/// Removes a diverged checkpoint given its height.
///
/// Precondition:
/// h ∈ self.diverged_checkpoint_heights()
pub fn remove_diverged_checkpoint(&self, height: Height) -> Result<(), LayoutError> {
let checkpoint_name = Self::checkpoint_name(height);
let cp_path = self.diverged_checkpoints().join(&checkpoint_name);
let tmp_path = self
.fs_tmp()
.join(format!("diverged_checkpoint_{}", &checkpoint_name));
self.atomically_remove_via_path(&cp_path, &tmp_path, ())
.map_err(|err| LayoutError::IoError {
path: cp_path,
message: format!("failed to remove diverged checkpoint {}", height),
io_err: err,
})
}
/// Creates a copy of the checkpoint with the specified height and places it
/// into a location that is not affected by normal state removal requests.
///
/// This is mostly useful for pinning good fetched states with the same
/// height as the locally computed diverged ones. This makes it possible to
/// check the difference between these two states and debug the
/// non-determinism even if the whole subnet moved forward.
pub fn backup_checkpoint(&self, height: Height) -> Result<(), LayoutError> {
let cp_name = Self::checkpoint_name(height);
let cp_path = self.checkpoints().join(&cp_name);
if !cp_path.exists() {
return Err(LayoutError::NotFound(height));
}
let backups_dir = self.backups();
let dst = backups_dir.join(&cp_name);
self.copy_and_sync_checkpoint(&cp_name, cp_path.as_path(), dst.as_path(), None)
.map_err(|err| LayoutError::IoError {
path: cp_path,
message: format!("Failed to backup checkpoint {}", height),
io_err: err,
})?;
sync_path(&backups_dir).map_err(|err| LayoutError::IoError {
path: backups_dir,
message: "Failed to sync backups".to_string(),
io_err: err,
})
}
/// Removes a backed up state given its height.
///
/// Precondition:
/// h ∈ self.backup_heights()
pub fn remove_backup(&self, height: Height) -> Result<(), LayoutError> {
let backup_name = Self::checkpoint_name(height);
let backup_path = self.backups().join(&backup_name);
let tmp_path = self.fs_tmp().join(format!("backup_{}", &backup_name));
self.atomically_remove_via_path(backup_path.as_path(), tmp_path.as_path(), ())
.map_err(|err| LayoutError::IoError {
path: backup_path,
message: format!("failed to remove backup {}", height),
io_err: err,
})
}
/// Moves the checkpoint with the specified height to backup location so
/// that state manager ignores it on restart.
///
/// If checkpoint at `height` was already backed-up/archived before, it's
/// removed.
pub fn archive_checkpoint(&self, height: Height) -> Result<(), LayoutError> {
let cp_name = Self::checkpoint_name(height);
let cp_path = self.checkpoints().join(&cp_name);
if !cp_path.exists() {
return Err(LayoutError::NotFound(height));
}
let backups_dir = self.backups();
let dst = backups_dir.join(&cp_name);
if dst.exists() {
// This might happen if we archived a checkpoint, then
// recomputed it again, and then restarted again. We don't need
// another copy.
return self.force_remove_checkpoint(height);
}
std::fs::rename(&cp_path, &dst).map_err(|err| LayoutError::IoError {
path: cp_path,
message: format!("failed to archive checkpoint {}", height),
io_err: err,