-
Notifications
You must be signed in to change notification settings - Fork 294
/
chunkable.rs
1531 lines (1408 loc) · 63.8 KB
/
chunkable.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::{
manifest::{build_file_group_chunks, filter_out_zero_chunks, DiffScript},
StateManagerMetrics, StateSyncMetrics, StateSyncRefs,
CRITICAL_ERROR_STATE_SYNC_CORRUPTED_CHUNKS, LABEL_COPY_CHUNKS, LABEL_COPY_FILES, LABEL_FETCH,
LABEL_PREALLOCATE, LABEL_STATE_SYNC_MAKE_CHECKPOINT,
};
use ic_logger::{debug, error, fatal, info, trace, warn, ReplicaLogger};
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::page_map::PageAllocatorFileDescriptor;
use ic_state_layout::utils::do_copy_overwrite;
use ic_state_layout::{error::LayoutError, CheckpointLayout, ReadOnly, RwPolicy, StateLayout};
use ic_sys::mmap::ScopedMmap;
use ic_types::{
artifact::StateSyncMessage,
chunkable::{
ArtifactChunk,
ArtifactErrorCode::{self, ChunkVerificationFailed, ChunksMoreNeeded},
ChunkId, Chunkable,
},
malicious_flags::MaliciousFlags,
state_sync::{
decode_manifest, decode_meta_manifest, state_sync_chunk_type, FileGroupChunks, Manifest,
MetaManifest, StateSyncChunk, FILE_CHUNK_ID_OFFSET, FILE_GROUP_CHUNK_ID_OFFSET,
MANIFEST_CHUNK_ID_OFFSET, META_MANIFEST_CHUNK,
},
CryptoHashOfState, Height,
};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::time::Instant;
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
sync::{Arc, Mutex},
};
pub mod cache;
// If set to true, we validate chunks even in situations where it might not be
// necessary.
const ALWAYS_VALIDATE: bool = false;
type SubManifest = Vec<u8>;
/// The state of the communication with up-to-date nodes.
#[derive(Clone)]
enum DownloadState {
/// Haven't received any chunks yet, waiting for the meta-manifest chunk.
Blank,
/// In the process of assembling the manifest.
Prep {
/// The received meta-manifest
meta_manifest: MetaManifest,
/// This field stores the sub-manifests received and can be used to reconstruct the whole manifest.
manifest_in_construction: BTreeMap<u32, SubManifest>,
/// Set of chunks that still needed to be fetched for the manifest.
manifest_chunks: BTreeSet<u32>,
},
/// In the process of loading chunks, have some more to load.
Loading {
/// The received meta-manifest
meta_manifest: MetaManifest,
/// The received manifest
manifest: Manifest,
state_sync_file_group: FileGroupChunks,
/// Set of chunks that still need to be fetched. For the purpose of this
/// set, chunk 0 is the meta-manifest.
///
/// To get indices into the manifest's chunk table, subtract 1. Note that
/// it does not apply to file group chunks because they are assigned with
/// a dedicated chunk id range.
/// The manifest chunks are not part of `fetch_chunks` because they are fetched in the `Prep` phase.
fetch_chunks: HashSet<usize>,
},
/// Successfully completed and returned the artifact to P2P, nothing else to
/// do.
Complete(Box<StateSyncMessage>),
}
/// An implementation of Chunkable trait that represents a (on-disk) state under
/// construction.
///
/// P2P decides when to start or abort a fetch based on the output of the state
/// sync priority function. When priority function returns "Fetch", P2P calls
/// StateManager to construct an IncompleteState corresponding to the state
/// artifact advert.
pub struct IncompleteState {
log: ReplicaLogger,
root: PathBuf,
state_layout: StateLayout,
height: Height,
root_hash: CryptoHashOfState,
state: DownloadState,
manifest_with_checkpoint_layout: Option<(Manifest, CheckpointLayout<ReadOnly>)>,
metrics: StateManagerMetrics,
started_at: Instant,
fetch_started_at: Option<Instant>,
own_subnet_type: SubnetType,
thread_pool: Arc<Mutex<scoped_threadpool::Pool>>,
state_sync_refs: StateSyncRefs,
fd_factory: Arc<dyn PageAllocatorFileDescriptor>,
#[allow(dead_code)]
malicious_flags: MaliciousFlags,
}
impl Drop for IncompleteState {
fn drop(&mut self) {
// If state sync is aborted before completion we need to
// measure the total duration here
let elapsed = self.started_at.elapsed();
match &self.state {
DownloadState::Blank => {
self.metrics
.state_sync_metrics
.duration
.with_label_values(&["aborted_blank"])
.observe(elapsed.as_secs_f64());
}
DownloadState::Prep { .. } => {
self.metrics
.state_sync_metrics
.duration
.with_label_values(&["aborted_prep"])
.observe(elapsed.as_secs_f64());
}
DownloadState::Loading {
meta_manifest: _,
manifest: _,
state_sync_file_group,
fetch_chunks,
} => {
self.metrics
.state_sync_metrics
.duration
.with_label_values(&["aborted"])
.observe(elapsed.as_secs_f64());
let dropped_chunks: usize = fetch_chunks
.iter()
.map(|ix| {
if (*ix as u32) < FILE_GROUP_CHUNK_ID_OFFSET {
1
} else {
state_sync_file_group
.get(&(*ix as u32))
.map(|vec| vec.len())
.unwrap_or(0)
}
})
.sum();
self.metrics
.state_sync_metrics
.remaining
.sub(dropped_chunks as i64);
}
DownloadState::Complete(_) => {
// state sync duration already recorded earlier in make_checkpoint
}
}
// We need to record the download state before passing self to the cache, as
// passing it to the cache might alter the download state
let description = match self.state {
DownloadState::Blank => "aborted before receiving any chunks",
DownloadState::Prep { .. } => "aborted before receiving the entire manifest",
DownloadState::Loading { .. } => "aborted before receiving all the chunks",
DownloadState::Complete(_) => "completed successfully",
};
info!(self.log, "State sync @{} {}", self.height, description);
// Pass self to the cache, taking ownership of chunks on disk
let cache = Arc::clone(&self.state_sync_refs.cache);
cache.write().push(self);
if self.state_sync_refs.remove(&self.height).is_none() {
warn!(
self.log,
"State sync refs does not contain incomplete state @{}.", self.height,
);
}
}
}
impl IncompleteState {
#[allow(clippy::too_many_arguments)]
pub fn new(
log: ReplicaLogger,
height: Height,
root_hash: CryptoHashOfState,
state_layout: StateLayout,
manifest_with_checkpoint_layout: Option<(Manifest, CheckpointLayout<ReadOnly>)>,
metrics: StateManagerMetrics,
own_subnet_type: SubnetType,
thread_pool: Arc<Mutex<scoped_threadpool::Pool>>,
state_sync_refs: StateSyncRefs,
fd_factory: Arc<dyn PageAllocatorFileDescriptor>,
malicious_flags: MaliciousFlags,
) -> Self {
if state_sync_refs.insert(height, root_hash.clone()).is_some() {
// Currently, we don't handle two concurrent fetches of the same state
// correctly. This case indicates a non-deterministic bug either in StateManager
// or P2P. We'd rather detect this early and crash, the replica
// should be able to recover after a restart.
fatal!(log, "There is already a live state sync @{}.", height);
}
Self {
log,
root: state_layout
.state_sync_scratchpad(height)
.expect("failed to create directory for state sync scratchpad"),
state_layout,
height,
root_hash,
state: DownloadState::Blank,
manifest_with_checkpoint_layout,
metrics,
started_at: Instant::now(),
fetch_started_at: None,
own_subnet_type,
thread_pool,
state_sync_refs,
fd_factory,
malicious_flags,
}
}
/// Creates all the files listed in the manifest and resizes them to their
/// expected sizes. This way we won't have to worry about creating parent
/// directories when we receive chunks.
pub(crate) fn preallocate_layout(log: &ReplicaLogger, root: &Path, manifest: &Manifest) {
for file_info in manifest.file_table.iter() {
let path = root.join(&file_info.relative_path);
std::fs::create_dir_all(
path.parent()
.expect("every file in the manifest must have a parent"),
)
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to create parent directory for path {}: {}",
path.display(),
err
)
});
let f = std::fs::File::create(&path).unwrap_or_else(|err| {
fatal!(log, "Failed to create file {}: {}", path.display(), err)
});
f.set_len(file_info.size_bytes).unwrap_or_else(|err| {
fatal!(
log,
"Failed to truncate file {} to size {}: {}",
path.display(),
file_info.size_bytes,
err
)
});
}
}
/// Copy reusable files from previous checkpoint according to diff script.
#[allow(clippy::too_many_arguments)]
pub(crate) fn copy_files(
log: &ReplicaLogger,
metrics: &StateSyncMetrics,
thread_pool: &mut scoped_threadpool::Pool,
root_old: &Path,
root_new: &Path,
manifest_old: &Manifest,
manifest_new: &Manifest,
diff_script: &DiffScript,
validate_data: bool,
fetch_chunks: &mut HashSet<usize>,
) {
let _timer = metrics
.step_duration
.with_label_values(&[LABEL_COPY_FILES])
.start_timer();
info!(
log,
"state sync: copy_files for {} files {} validation",
diff_script.copy_files.len(),
if validate_data || ALWAYS_VALIDATE {
"with"
} else {
"without"
}
);
let corrupted_chunks = Arc::new(Mutex::new(Vec::new()));
thread_pool.scoped(|scope| {
for (new_index, old_index) in diff_script.copy_files.iter() {
let src_path = root_old.join(&manifest_old.file_table[*old_index].relative_path);
let dst_path = root_new.join(&manifest_new.file_table[*new_index].relative_path);
let corrupted_chunks = Arc::clone(&corrupted_chunks);
scope.execute(move || {
let new_chunk_range = crate::manifest::file_chunk_range(
&manifest_new.chunk_table,
*new_index,
);
let original_perms = std::fs::metadata(&dst_path).unwrap_or_else(|err| {
fatal!(
log,
"Failed to get metadata of file {}: {}",
dst_path.display(),
err
)
})
.permissions();
if validate_data || ALWAYS_VALIDATE {
let src = std::fs::File::open(&src_path).unwrap_or_else(|err| {
fatal!(
log,
"Failed to open file {} for read: {}",
src_path.display(),
err
)
});
let src_len = src
.metadata()
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to get metadata of file {}: {}",
src_path.display(),
err
)
})
.len() as usize;
let src_map = ScopedMmap::from_readonly_file(&src, src_len).unwrap_or_else(|err| {
fatal!(log, "Failed to mmap file {}: {}", src_path.display(), err)
});
let src_data = src_map.as_slice();
let old_chunk_range = crate::manifest::file_chunk_range(
&manifest_old.chunk_table,
*old_index,
);
// bad_chunks contains ids of chunks from the old checkpoint that
// didn't pass validation or refer to non-existing portions of
// the corresponding file. The contents of these chunks will be
// requested later from peers.
let mut bad_chunks = vec![];
// Go through all the chunks of the local file and validate
// each one. If the validation fails, add the corresponding new
// chunk ids to the set of chunks to fetch.
for idx in old_chunk_range.clone() {
let chunk = &manifest_old.chunk_table[idx];
let chunk_offset = idx - old_chunk_range.start;
let new_chunk_idx = new_chunk_range.start + chunk_offset;
let byte_range = chunk.byte_range();
if src_data.len() < byte_range.end {
warn!(
log,
"Local chunk {} ({}@{}—{}) is out of range (file len = {}), \
will request chunk {} instead",
idx,
src_path.display(),
byte_range.start,
byte_range.end,
src_data.len(),
new_chunk_idx + FILE_CHUNK_ID_OFFSET
);
bad_chunks.push(idx);
corrupted_chunks.lock().unwrap().push(new_chunk_idx + FILE_CHUNK_ID_OFFSET);
if !validate_data && ALWAYS_VALIDATE {
error!(
log,
"{}: Unexpected chunk validation error for local chunk {}",
CRITICAL_ERROR_STATE_SYNC_CORRUPTED_CHUNKS,
idx,
);
metrics.corrupted_chunks_critical.inc();
}
metrics.corrupted_chunks.with_label_values(&[LABEL_COPY_FILES]).inc();
continue;
}
if let Err(err) = crate::manifest::validate_chunk(
idx,
&src_data[byte_range.clone()],
manifest_old,
) {
warn!(
log,
"Local chunk {} ({}@{}–{}) doesn't pass validation: {}, \
will request chunk {} instead",
idx,
src_path.display(),
byte_range.start,
byte_range.end,
err,
new_chunk_idx + FILE_CHUNK_ID_OFFSET
);
bad_chunks.push(idx);
corrupted_chunks.lock().unwrap().push(new_chunk_idx + FILE_CHUNK_ID_OFFSET);
if !validate_data && ALWAYS_VALIDATE {
error!(
log,
"{}: Unexpected chunk validation error for local chunk {}",
CRITICAL_ERROR_STATE_SYNC_CORRUPTED_CHUNKS,
idx,
);
metrics.corrupted_chunks_critical.inc();
}
metrics.corrupted_chunks.with_label_values(&[LABEL_COPY_FILES]).inc();
}
}
if bad_chunks.is_empty()
&& src_data.len()
== manifest_old.file_table[*old_index].size_bytes as usize
{
// All the hash sums and the file size match, so we can
// simply copy the whole file. That's much faster than
// copying one chunk at a time.
do_copy_overwrite(log, &src_path, &dst_path).unwrap_or_else(
|err| {
fatal!(
log,
"Failed to copy file from {} to {}: {}",
src_path.display(),
dst_path.display(),
err
)
},
);
metrics
.remaining
.sub(new_chunk_range.len() as i64);
} else {
// Copy the chunks that passed validation to the
// destination, the rest will be fetched and applied later.
let dst = std::fs::OpenOptions::new()
.write(true)
.create(false)
.open(&dst_path)
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to open file {}: {}",
dst_path.display(),
err
)
});
for idx in old_chunk_range {
if bad_chunks.contains(&idx) {
continue;
}
let chunk = &manifest_old.chunk_table[idx];
#[cfg(target_os = "linux")]
{
// The source and the destination offsets are the same because we are copying
// over uncorrupted chunks of the file into the new checkpoint.
let src_offset = chunk.offset as i64;
let dst_offset = chunk.offset as i64;
ic_utils::fs::copy_file_range_all(
&src,
src_offset,
&dst,
dst_offset,
chunk.size_bytes as usize
).unwrap_or_else(|err| {
fatal!(
log,
"Failed to copy file range from {} => {} (offset = {}, size = {}): {}",
src_path.display(),
dst_path.display(),
chunk.offset,
chunk.size_bytes,
err
)
});
}
#[cfg(not(target_os = "linux"))]
{
let data = &src_data[chunk.byte_range()];
dst.write_all_at(data, chunk.offset).unwrap_or_else(|err| {
fatal!(
log,
"Failed to write chunk (offset = {}, size = {}) to file {}: {}",
chunk.offset,
chunk.size_bytes,
dst_path.display(),
err
)
});
}
metrics.remaining.sub(1);
}
}
} else {
// Since we do not validate in this else branch, we can simply copy the
// file without any extra work
do_copy_overwrite(log, &src_path, &dst_path).unwrap_or_else(|err| {
fatal!(
log,
"Failed to copy file from {} to {}: {}",
src_path.display(),
dst_path.display(),
err
)
});
metrics
.remaining
.sub(new_chunk_range.len() as i64);
}
std::fs::set_permissions(&dst_path, original_perms).unwrap_or_else(|err| {
fatal!(
log,
"failed to set permissions for file {}: {}",
dst_path.display(),
err
)
});
});
}
});
for chunk_idx in corrupted_chunks.lock().unwrap().iter() {
fetch_chunks.insert(*chunk_idx);
}
}
/// Copy reusable chunks from previous checkpoint according to diff script.
#[allow(clippy::too_many_arguments)]
pub(crate) fn copy_chunks(
log: &ReplicaLogger,
metrics: &StateSyncMetrics,
thread_pool: &mut scoped_threadpool::Pool,
root_old: &Path,
root_new: &Path,
manifest_old: &Manifest,
manifest_new: &Manifest,
diff_script: &DiffScript,
validate_data: bool,
fetch_chunks: &mut HashSet<usize>,
) {
let _timer = metrics
.step_duration
.with_label_values(&[LABEL_COPY_CHUNKS])
.start_timer();
info!(
log,
"state sync: copy_chunks for {} chunks {} validation",
diff_script.copy_chunks.len(),
if validate_data || ALWAYS_VALIDATE {
"with"
} else {
"without"
}
);
type DstIndex = usize;
type SrcIndex = usize;
type ChunkGroup = Vec<(DstIndex, SrcIndex)>;
// Group chunks by the file index to lower cost of opening files.
// Key is the pair of dst file index and src file index,
// value is vector of pairs of the dst chunk index and src chunk index.
let mut chunk_groups: HashMap<(DstIndex, SrcIndex), ChunkGroup> = HashMap::default();
for (dst_chunk_index, src_chunk_index) in &diff_script.copy_chunks {
let dst_file_index = manifest_new.chunk_table[*dst_chunk_index].file_index;
let src_file_index = manifest_old.chunk_table[*src_chunk_index].file_index;
let entry = chunk_groups
.entry((dst_file_index as usize, src_file_index as usize))
.or_default();
entry.push((*dst_chunk_index, *src_chunk_index));
}
let corrupted_chunks = Arc::new(Mutex::new(Vec::new()));
thread_pool.scoped(|scope| {
for ((dst_file_index, src_file_index), chunk_group) in chunk_groups.iter() {
let dst_path =
root_new.join(&manifest_new.file_table[*dst_file_index].relative_path);
let src_path =
root_old.join(&manifest_old.file_table[*src_file_index].relative_path);
let corrupted_chunks = Arc::clone(&corrupted_chunks);
scope.execute(move || {
let src = std::fs::File::open(&src_path).unwrap_or_else(|err| {
fatal!(
log,
"Failed to open file {} for read: {}",
src_path.display(),
err
)
});
let src_len = src
.metadata()
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to get metadata of file {}: {}",
src_path.display(),
err
)
})
.len() as usize;
let dst = std::fs::OpenOptions::new()
.write(true)
.create(false)
.open(&dst_path)
.unwrap_or_else(|err| {
fatal!(log, "Failed to open file {}: {}", dst_path.display(), err)
});
let src_map = ScopedMmap::from_readonly_file(&src, src_len).unwrap_or_else(|err| {
fatal!(log, "Failed to mmap file {}: {}", src_path.display(), err)
});
// Validate each chunk that we happen to have locally. If the
// validation passes, copy it to the corresponding location, otherwise
// add the destination chunk id to the set of chunks to fetch.
for (dst_chunk_index, src_chunk_index) in chunk_group {
let dst_chunk = &manifest_new.chunk_table[*dst_chunk_index];
let src_chunk = &manifest_old.chunk_table[*src_chunk_index];
let byte_range = src_chunk.byte_range();
if src_map.len() < byte_range.end {
warn!(
log,
"Local chunk {} ({}@{}—{}) is out of range (file len = {}), \
will request chunk {} instead",
*src_chunk_index,
src_path.display(),
byte_range.start,
byte_range.end,
src_map.len(),
*dst_chunk_index + FILE_CHUNK_ID_OFFSET
);
corrupted_chunks.lock().unwrap().push(*dst_chunk_index + FILE_CHUNK_ID_OFFSET);
continue;
}
#[cfg(not(target_os = "linux"))]
let src_data = &src_map.as_slice()[byte_range];
if validate_data || ALWAYS_VALIDATE {
#[cfg(target_os = "linux")]
let src_data = &src_map.as_slice()[byte_range];
if let Err(err) = crate::manifest::validate_chunk(
*dst_chunk_index,
src_data,
manifest_new,
) {
let byte_range = src_chunk.byte_range();
warn!(
log,
"Local chunk {} ({}@{}–{}) doesn't pass validation: {}, \
will request chunk {} instead",
*src_chunk_index,
src_path.display(),
byte_range.start,
byte_range.end,
err,
*dst_chunk_index + FILE_CHUNK_ID_OFFSET
);
corrupted_chunks.lock().unwrap().push(*dst_chunk_index + FILE_CHUNK_ID_OFFSET);
if !validate_data && ALWAYS_VALIDATE {
error!(
log,
"{}: Unexpected chunk validation error for local chunk {}.",
CRITICAL_ERROR_STATE_SYNC_CORRUPTED_CHUNKS,
*src_chunk_index,
);
metrics.corrupted_chunks_critical.inc();
}
metrics
.corrupted_chunks
.with_label_values(&[LABEL_COPY_CHUNKS])
.inc();
continue;
}
}
#[cfg(target_os = "linux")]
{
let src_offset = src_chunk.offset as i64;
let dst_offset = dst_chunk.offset as i64;
ic_utils::fs::copy_file_range_all(
&src,
src_offset,
&dst,
dst_offset,
dst_chunk.size_bytes as usize,
)
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to copy file range from {} => {} (offset = {}, size = {}): {}",
src_path.display(),
dst_path.display(),
dst_chunk.offset,
dst_chunk.size_bytes,
err
)
});
}
#[cfg(not(target_os = "linux"))]
{
dst.write_all_at(src_data, dst_chunk.offset)
.unwrap_or_else(|err| {
fatal!(
log,
"Failed to write chunk (offset = {}, size = {}) to file {}: {}",
dst_chunk.offset,
dst_chunk.size_bytes,
dst_path.display(),
err
)
});
}
metrics.remaining.sub(1);
}
});
}
});
for chunk_idx in corrupted_chunks.lock().unwrap().iter() {
fetch_chunks.insert(*chunk_idx);
}
}
pub(crate) fn apply_chunk(
log: &ReplicaLogger,
metrics: &StateSyncMetrics,
root: &Path,
ix: usize,
bytes: &[u8],
manifest: &Manifest,
) {
let chunk = &manifest.chunk_table[ix];
let file_index = chunk.file_index as usize;
let path = root.join(&manifest.file_table[file_index].relative_path);
let f = std::fs::OpenOptions::new()
.write(true)
.create(false)
.open(&path)
.unwrap_or_else(|err| fatal!(log, "Failed to open file {}: {}", path.display(), err));
f.write_all_at(bytes, chunk.offset).unwrap_or_else(|err| {
fatal!(
log,
"Failed to write chunk (offset = {}, size = {}) to file {}: {}",
chunk.offset,
chunk.size_bytes,
path.display(),
err
)
});
metrics.remaining.sub(1);
}
fn build_artifact(
state_layout: &StateLayout,
height: Height,
root_hash: CryptoHashOfState,
manifest: &Manifest,
meta_manifest: &MetaManifest,
) -> StateSyncMessage {
StateSyncMessage {
height,
root_hash,
checkpoint_root: state_layout
.checkpoint(height)
.unwrap()
.raw_path()
.to_path_buf(),
meta_manifest: Arc::new(meta_manifest.clone()),
manifest: manifest.clone(),
// `state_sync_file_group` and `checkpoint_root` are not included in the integrity hash of this artifact.
// Therefore it is OK to pass a default value here as it is only used when fetching chunks.
state_sync_file_group: Default::default(),
}
}
fn make_checkpoint(
log: &ReplicaLogger,
metrics: &StateManagerMetrics,
started_at: Instant,
root: &Path,
height: Height,
state_layout: &StateLayout,
own_subnet_type: SubnetType,
thread_pool: &mut scoped_threadpool::Pool,
fd_factory: Arc<dyn PageAllocatorFileDescriptor>,
) {
let _timer = metrics
.state_sync_metrics
.step_duration
.with_label_values(&[LABEL_STATE_SYNC_MAKE_CHECKPOINT])
.start_timer();
info!(
log,
"state sync: start to make a checkpoint from the scratchpad"
);
let ro_layout = CheckpointLayout::<ReadOnly>::new_untracked(root.to_path_buf(), height)
.expect("failed to create checkpoint layout");
// Recover the state to make sure it's usable
if let Err(err) = crate::checkpoint::load_checkpoint(
&ro_layout,
own_subnet_type,
&metrics.checkpoint_metrics,
Some(thread_pool),
Arc::clone(&fd_factory),
) {
let elapsed = started_at.elapsed();
metrics
.state_sync_metrics
.duration
.with_label_values(&["unrecoverable"])
.observe(elapsed.as_secs_f64());
fatal!(
log,
"Failed to recover synced state {} after {:?}: {}",
height,
elapsed,
err
)
}
let scratchpad_layout =
CheckpointLayout::<RwPolicy<()>>::new_untracked(root.to_path_buf(), height)
.expect("failed to create checkpoint layout");
match state_layout.scratchpad_to_checkpoint(scratchpad_layout, height, Some(thread_pool)) {
Ok(_) => {
let elapsed = started_at.elapsed();
metrics
.state_sync_metrics
.duration
.with_label_values(&["ok"])
.observe(elapsed.as_secs_f64());
info!(
log,
"Successfully completed sync of state {} in {:?}", height, elapsed
);
}
Err(LayoutError::AlreadyExists(_)) => {
let elapsed = started_at.elapsed();
metrics
.state_sync_metrics
.duration
.with_label_values(&["already_exists"])
.observe(elapsed.as_secs_f64());
warn!(
log,
"Couldn't complete sync of state {} because it already exists locally ({:?} elapsed)",
height,
elapsed,
);
}
Err(LayoutError::IoError {
path,
message,
io_err,
}) => {
let elapsed = started_at.elapsed();
metrics
.state_sync_metrics
.duration
.with_label_values(&["io_err"])
.observe(elapsed.as_secs_f64());
fatal!(
log,
"Failed to promote synced state to a checkpoint {} after {:?}: {}: {} (at {})",
height,
elapsed,
message,
io_err,
path.display(),
)
}
Err(err) => fatal!(log, "Unexpected layout error: {}", err),
}
}
/// Preallocates the files listed in the manifest and copies the chunks
/// that we have locally.
/// Returns a set of chunks that still need to be fetched
fn initialize_state_on_disk(&mut self, manifest_new: &Manifest) -> HashSet<usize> {
Self::preallocate_layout(&self.log, &self.root, manifest_new);
let state_sync_size_fetch = self
.metrics
.state_sync_metrics
.size
.with_label_values(&[LABEL_FETCH]);
let state_sync_size_copy_files = self
.metrics
.state_sync_metrics
.size
.with_label_values(&[LABEL_COPY_FILES]);
let state_sync_size_copy_chunks = self
.metrics
.state_sync_metrics
.size
.with_label_values(&[LABEL_COPY_CHUNKS]);
let state_sync_size_preallocate = self
.metrics
.state_sync_metrics
.size
.with_label_values(&[LABEL_PREALLOCATE]);
let total_bytes: u64 = manifest_new.file_table.iter().map(|f| f.size_bytes).sum();
self.metrics
.state_sync_metrics
.remaining
.add(manifest_new.chunk_table.len() as i64);
// Get the cache line. We now own an Arc on that cache line, so we are extending
// the lifetime of the data on disk as long as we keep this cache line in scope
let cache = self.state_sync_refs.cache.read().get();
// A little helper struct of all we need to know to copy out of
struct DiffData<'a> {
manifest_old: &'a Manifest,
missing_chunks: HashSet<usize>,
root_old: PathBuf,
height_old: Height,
validate_data: bool,
}
// Get a DiffData from the cache or checkpoint_layout, or neither
let diff_data: Option<DiffData> = match (
cache.as_ref(),
self.manifest_with_checkpoint_layout.as_ref(),
) {
(Some(cache_entry), Some((checkpoint_manifest, checkpoint_layout))) => {
let cache_height = cache_entry.height;
let checkpoint_height = checkpoint_layout.height();
if cache_height > checkpoint_height {
// The cache will have missing chunks. However, it likely started from a
// DiffScript with the same checkpoint we have now, so there should be more
// relevant chunks in the cache than in the checkpoint.
// This is just a heuristic however, as the cached chunks might have been
// initialized with a DiffScript from an older checkpoint.
Some(DiffData {
manifest_old: &cache_entry.manifest,
missing_chunks: cache_entry.missing_chunks.clone(),
// The data at root_old will live at least as long as the
// StateSyncCacheEntry, so cloning the path is safe
root_old: cache_entry.path().to_path_buf(),
height_old: cache_entry.height,
validate_data: false,
})
} else {
// This should be a special case that can only happen if the source of the
// checkpoint is outside of state sync, as otherwise we would have cleared
// the cache upon successfully syncing a state.
Some(DiffData {
manifest_old: checkpoint_manifest,
missing_chunks: Default::default(),
root_old: checkpoint_layout.raw_path().to_path_buf(),
height_old: checkpoint_height,
validate_data: true,
})
}
}
(Some(cache_entry), None) => Some(DiffData {
manifest_old: &cache_entry.manifest,
missing_chunks: cache_entry.missing_chunks.clone(),
root_old: cache_entry.path().to_path_buf(),
height_old: cache_entry.height,
validate_data: false,
}),
(None, Some((checkpoint_manifest, checkpoint_old))) => {
let checkpoint_height = checkpoint_old.height();
Some(DiffData {
manifest_old: checkpoint_manifest,
missing_chunks: Default::default(),
root_old: checkpoint_old.raw_path().to_path_buf(),
height_old: checkpoint_height,
validate_data: !self