-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathregion.rs
4493 lines (3788 loc) · 147 KB
/
region.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
// Copyright 2023 Oxide Computer Company
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::convert::TryInto;
use std::fmt::Debug;
use std::fs::{rename, File, OpenOptions};
use std::io::{IoSlice, Write};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use anyhow::{bail, Result};
use futures::TryStreamExt;
use tracing::instrument;
use crucible_common::*;
use crucible_protocol::SnapshotDetails;
use repair_client::Client;
use super::*;
use crate::extent::{
copy_dir, extent_dir, extent_file_name, move_replacement_extent,
replace_dir, sync_path, Extent, ExtentMeta, ExtentState, ExtentType,
};
/**
* Validate the repair file.
*
* There is only one repair file: the raw file itself (which also contains
* structured context and metadata at the end).
*/
pub fn validate_repair_files(eid: usize, files: &[String]) -> bool {
files == [extent_file_name(eid as u32, ExtentType::Data)]
}
/// Validate the possible files during a clone.
///
/// During a clone of a downstairs region, we have one, two or four
/// possible files we expect to see.
pub fn validate_clone_files(eid: usize, files: &[String]) -> bool {
let one = vec![extent_file_name(eid as u32, ExtentType::Data)];
let mut some = one.clone();
some.extend(vec![extent_file_name(eid as u32, ExtentType::Db)]);
let mut all = some.clone();
all.extend(vec![
extent_file_name(eid as u32, ExtentType::DbShm),
extent_file_name(eid as u32, ExtentType::DbWal),
]);
// For replacement, we require one, some, or all
files == one || files == some || files == all
}
/// Wrapper type for either a job or reconciliation ID
///
/// This is useful for debug logging / DTrace probes, and not much else
#[derive(Copy, Clone, Debug)]
pub(crate) enum JobOrReconciliationId {
JobId(JobId),
ReconciliationId(ReconciliationId),
}
impl JobOrReconciliationId {
pub fn get(self) -> u64 {
match self {
Self::JobId(i) => i.0,
Self::ReconciliationId(i) => i.0,
}
}
}
impl From<JobId> for JobOrReconciliationId {
fn from(i: JobId) -> Self {
Self::JobId(i)
}
}
impl From<ReconciliationId> for JobOrReconciliationId {
fn from(i: ReconciliationId) -> Self {
Self::ReconciliationId(i)
}
}
/**
* The main structure describing a region.
*/
#[derive(Debug)]
pub struct Region {
pub dir: PathBuf,
def: RegionDefinition,
pub extents: Vec<ExtentState>,
/// Extents which are dirty and need to be flushed. Should be true if the
/// dirty flag in the extent's metadata is set. When an extent is opened, if
/// it's dirty, it's added to here. When a write is issued to an extent,
/// it's added to here. If the write doesn't actually make the extent dirty
/// that's fine, because the extent will NOP during the flush anyway, but
/// this mainly serves to cut down on the extents we're considering for a
/// flush in the first place.
dirty_extents: HashSet<usize>,
read_only: bool,
log: Logger,
/// Select the backend to use when creating and opening extents
///
/// The SQLite backend is only allowed in tests; all new extents must be raw
/// files
backend: Backend,
}
impl Region {
/// Set the number of open files resource limit to the max. Use the provided
/// RegionDefinition to check that this Downstairs can open all the files it
/// needs.
pub fn set_max_open_files_rlimit(
log: &Logger,
def: &RegionDefinition,
) -> Result<()> {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) } != 0 {
bail!(
"libc::getrlimit failed with {}",
std::io::Error::last_os_error()
);
}
let number_of_files_limit = match rlim.rlim_cur.cmp(&rlim.rlim_max) {
std::cmp::Ordering::Less => {
debug!(
log,
"raising number of open files limit to from {} to {}",
rlim.rlim_cur,
rlim.rlim_max,
);
rlim.rlim_cur = rlim.rlim_max;
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) } != 0 {
bail!(
"libc::setrlimit failed with {}",
std::io::Error::last_os_error()
);
}
rlim.rlim_max
}
Ordering::Equal => {
debug!(
log,
"current number of open files limit {} is already the maximum",
rlim.rlim_cur,
);
rlim.rlim_cur
}
Ordering::Greater => {
// wat
warn!(
log,
"current number of open files limit {} is already ABOVE THE MAXIMUM {}?",
rlim.rlim_cur,
rlim.rlim_max,
);
rlim.rlim_cur
}
};
// The downstairs needs to open (at minimum) the extent file, the sqlite
// database, the write-ahead lock, and the sqlite shared memory file for
// each extent in the region, plus:
//
// - the seed database (db + shm + wal)
// - region.json
// - stdin, stdout, and stderr
// - the listen and repair sockets (arbitrarily saying two sockets per
// server)
// - optionally, the stat connection to oximeter
// - optionally, a control interface
//
// If the downstairs cannot open this many files, error here.
let required_number_of_files = def.extent_count() as u64 * 4 + 13;
if number_of_files_limit < required_number_of_files {
bail!("this downstairs cannot open all required files!");
}
Ok(())
}
/**
* Create a new region based on the given RegionOptions
*/
pub async fn create<P: AsRef<Path>>(
dir: P,
options: RegionOptions,
log: Logger,
) -> Result<Region> {
Self::create_with_backend(dir, options, Backend::RawFile, log).await
}
pub async fn create_with_backend<P: AsRef<Path>>(
dir: P,
options: RegionOptions,
backend: Backend,
log: Logger,
) -> Result<Region> {
options.validate()?;
let def = RegionDefinition::from_options(&options).unwrap();
Self::set_max_open_files_rlimit(&log, &def)?;
let cp = config_path(dir.as_ref());
/*
* If the file exists, then exit now with error. If the caller
* wants a new region, they have to delete the old one first.
*/
if Path::new(&cp).exists() {
bail!("Config file already exists {:?}", cp);
}
mkdir_for_file(&cp)?;
write_json(&cp, &def, false)?;
info!(log, "Created new region file {:?}", cp);
let mut region = Region {
dir: dir.as_ref().to_path_buf(),
def,
extents: Vec::new(),
dirty_extents: HashSet::new(),
read_only: false,
log,
backend,
};
region.open_extents(true).await?;
Ok(region)
}
/**
* Open an existing region file
*/
pub async fn open<P: AsRef<Path>>(
dir: P,
options: RegionOptions,
verbose: bool,
read_only: bool,
log: &Logger,
) -> Result<Region> {
Self::open_with_backend(
dir,
options,
verbose,
read_only,
Backend::RawFile,
log,
)
.await
}
pub async fn open_with_backend<P: AsRef<Path>>(
dir: P,
options: RegionOptions,
verbose: bool,
read_only: bool,
backend: Backend,
log: &Logger,
) -> Result<Region> {
options.validate()?;
let cp = config_path(&dir);
/*
* We are expecting to find a region config file and extent files.
* If we do not, then report error and exit.
*/
let def: crucible_common::RegionDefinition = match read_json(&cp) {
Ok(def) => def,
Err(e) => bail!("Error {:?} opening region config {:?}", e, cp),
};
Self::set_max_open_files_rlimit(log, &def)?;
if verbose {
info!(log, "Opened existing region file {:?}", cp);
}
if def.database_read_version() != crucible_common::DATABASE_READ_VERSION
{
bail!(
"Database read version mismatch, expected {}, got {}",
crucible_common::DATABASE_READ_VERSION,
def.database_read_version(),
);
}
if verbose {
info!(log, "Database read version {}", def.database_read_version());
}
if def.database_write_version()
!= crucible_common::DATABASE_WRITE_VERSION
{
bail!(
"Database write version mismatch, expected {}, got {}",
crucible_common::DATABASE_WRITE_VERSION,
def.database_write_version(),
);
}
if verbose {
info!(
log,
"Database write version {}",
def.database_write_version()
);
}
/*
* Open every extent that presently exists.
*/
let mut region = Region {
dir: dir.as_ref().to_path_buf(),
def,
extents: Vec::new(),
dirty_extents: HashSet::new(),
read_only,
log: log.clone(),
backend,
};
region.open_extents(false).await?;
Ok(region)
}
pub fn encrypted(&self) -> bool {
self.def.get_encrypted()
}
fn get_opened_extent_mut(&mut self, eid: usize) -> &mut Extent {
match &mut self.extents[eid] {
ExtentState::Opened(extent) => extent,
ExtentState::Closed => {
panic!("attempting to get closed extent {}", eid)
}
}
}
fn get_opened_extent(&self, eid: usize) -> &Extent {
match &self.extents[eid] {
ExtentState::Opened(extent) => extent,
ExtentState::Closed => {
panic!("attempting to get closed extent {}", eid)
}
}
}
/**
* If our extent_count is higher than the number of populated entries
* we have in our extents Vec, then open all the new extent files and
* load their content into the extent Vec.
*
* If create is false, we expect the extent files to exist at the
* expected location and will return error if they are not found.
*
* If create is true, we expect to create new extent files, and will
* return error if the file is already present.
*/
async fn open_extents(&mut self, create: bool) -> Result<()> {
let next_eid = self.extents.len() as u32;
let eid_range = next_eid..self.def.extent_count();
let mut these_extents = Vec::with_capacity(eid_range.len());
for eid in eid_range {
let extent = if create {
Extent::create(&self.dir, &self.def, eid, self.backend)?
} else {
let extent = Extent::open(
&self.dir,
&self.def,
eid,
self.read_only,
self.backend,
&self.log,
)?;
if extent.dirty().await {
self.dirty_extents.insert(eid as usize);
}
extent
};
these_extents.push(ExtentState::Opened(extent));
}
self.extents.extend(these_extents);
for eid in next_eid..self.def.extent_count() {
assert_eq!(self.get_opened_extent(eid as usize).number, eid);
}
assert_eq!(self.def.extent_count() as usize, self.extents.len());
Ok(())
}
/// Walk the list of extents and close each one.
///
/// If we fail to close an extent, we exit right away, leaving the
/// remaining extents alone.
pub async fn close_all_extents(&mut self) -> Result<()> {
for eid in 0..self.def.extent_count() as usize {
if let Err(e) = self.close_extent(eid).await {
bail!("Failed closing extent {eid} with {e}");
}
}
Ok(())
}
/**
* Walk the list of all extents and find any that are not open.
* Open any extents that are not.
*/
pub async fn reopen_all_extents(&mut self) -> Result<()> {
let mut to_open = Vec::new();
for (i, extent) in self.extents.iter().enumerate() {
if matches!(extent, ExtentState::Closed) {
to_open.push(i);
}
}
for eid in to_open {
self.reopen_extent(eid).await?;
}
Ok(())
}
/**
* Re open an extent that was previously closed
*/
pub async fn reopen_extent(
&mut self,
eid: usize,
) -> Result<(), CrucibleError> {
/*
* Make sure the extent :
*
* - is currently closed
* - matches our eid
* - is not read-only
*/
let mg = &mut self.extents[eid];
assert!(matches!(mg, ExtentState::Closed));
assert!(!self.read_only);
let new_extent = Extent::open(
&self.dir,
&self.def,
eid as u32,
self.read_only,
Backend::RawFile,
&self.log,
)?;
if new_extent.dirty().await {
self.dirty_extents.insert(eid);
}
*mg = ExtentState::Opened(new_extent);
Ok(())
}
pub async fn close_extent(
&mut self,
eid: usize,
) -> Result<(u64, u64, bool), CrucibleError> {
let extent_state = &mut self.extents[eid];
let open_extent = std::mem::replace(extent_state, ExtentState::Closed);
match open_extent {
ExtentState::Opened(extent) => extent.close().await,
ExtentState::Closed => {
panic!("close on closed extent {}!", eid);
}
}
}
/**
* Repair an extent from another downstairs
*
* We need to repair an extent in such a way that an interruption
* at any time can be recovered from.
*
* Let us assume we are repairing extent 012
* 1. Make new 012.copy dir (extent name plus: .copy)
* 2. Get all extent files from source side, put in 012.copy directory.
* Verify after the copy completes that the remote side still has
* the extent closed (or the region is read only).
* 3. fsync files we just downloaded
* 4. Rename 012.copy dir to 012.replace dir
* 5. fsync extent directory ( 00/000/ where the extent files live)
* 6. Replace current extent 012 files with copied files of same name
* from 012.replace dir
* 7. Remove any files in extent dir that don't exist in replacing dir
* For example, if the replacement extent has 012 and 012.db, but
* the current (bad) extent has 012 012.db 012.db-shm
* and 012.db-wal, we want to remove the 012.db-shm and 012.db-wal
* files when we replace 012 and 012.db with the new versions.
* 8. fsync files after copying them (new location).
* 9. fsync containing extent dir
* 10. Rename 012.replace dir to 012.completed dir.
* 11. fsync extent dir again (so dir rename is persisted)
* 12. Delete completed dir.
* 13. fsync extent dir again (so dir rename is persisted)
*
* This also requires the following behavior on every extent open:
* A. If xxx.copy directory found, delete it.
* B. If xxx.completed directory found, delete it.
* C. If xxx.replace dir found start at step 4 above and continue
* on through 6.
* D. Only then, open extent.
*
* If clone == true, then we are replacing our extent files
* with ones from a remote downstairs. We make a few different
* decisions as that remote downstairs might have a different
* backend than our region was created with.
*/
pub async fn repair_extent(
&self,
eid: usize,
repair_addr: SocketAddr,
clone: bool,
) -> Result<(), CrucibleError> {
// Make sure the extent:
// is currently closed, matches our eid, is not read-only
assert!(matches!(self.extents[eid], ExtentState::Closed));
// If this is not a clone, then we must not be read_only
if !clone {
assert!(!self.read_only);
}
self.get_extent_copy(eid, repair_addr, clone).await?;
// Returning from get_extent_copy means we have copied all our
// files and moved the copy directory to replace directory.
// Now, replace the current extent files with the replacement ones.
move_replacement_extent(&self.dir, eid, &self.log, clone)?;
Ok(())
}
/**
* Connect to the source and pull over all the extent files for the
* given extent ID.
* The files are loaded into the copy_dir for the given extent.
* After all the files have been copied locally, we rename the
* copy_dir to replace_dir.
*/
pub async fn get_extent_copy(
&self,
eid: usize,
repair_addr: SocketAddr,
clone: bool,
) -> Result<(), CrucibleError> {
// An extent must be closed before we replace its files.
assert!(matches!(self.extents[eid], ExtentState::Closed));
// Make sure copy, replace, and cleanup directories don't exist yet.
// We don't need them yet, but if they do exist, then something
// is wrong.
let rd = replace_dir(&self.dir, eid as u32);
if rd.exists() {
crucible_bail!(
IoError,
"Replace directory: {:?} already exists",
rd,
);
}
let copy_dir = Self::create_copy_dir(&self.dir, eid)?;
info!(self.log, "Created copy dir {:?}", copy_dir);
// XXX TLS someday? Authentication?
let url = format!("http://{:?}", repair_addr);
let repair_server = Client::new(&url);
let mut repair_files =
match repair_server.get_files_for_extent(eid as u32).await {
Ok(f) => f.into_inner(),
Err(e) => {
crucible_bail!(
RepairRequestError,
"Failed to get repair files: {:?}",
e,
);
}
};
repair_files.sort();
info!(
self.log,
"eid:{} Found repair files: {:?}", eid, repair_files
);
// Depending on if this is a clone or not, we have a different
// set of files we expect to find.
if clone {
if !validate_clone_files(eid, &repair_files) {
crucible_bail!(
RepairFilesInvalid,
"Invalid clone file list: {:?}",
repair_files,
);
}
} else if !validate_repair_files(eid, &repair_files) {
crucible_bail!(
RepairFilesInvalid,
"Invalid repair file list: {:?}",
repair_files,
);
}
// Replace local files with their remote copies.
// If we are replacing our region with one from an older version
// that contained SQLite files, then we need to copy those files
// over as well.
let mut count = 0;
for opt_file in &[
ExtentType::Data,
ExtentType::Db,
ExtentType::DbShm,
ExtentType::DbWal,
] {
let filename = extent_file_name(eid as u32, *opt_file);
if !repair_files.contains(&filename) {
continue;
}
let local_file =
Self::create_copy_file(copy_dir.clone(), eid, *opt_file)?;
let repair_stream = match repair_server
.get_extent_file(eid as u32, opt_file.to_file_type())
.await
{
Ok(rs) => rs,
Err(e) => {
crucible_bail!(
RepairRequestError,
"Failed to get extent {} {} file: {:?}",
eid,
opt_file,
e,
);
}
};
save_stream_to_file(local_file, repair_stream.into_inner()).await?;
count += 1;
}
// We have copied over the extent. Verify that the remote side
// still believes that it is valid for repair so we know we have
// received a valid copy.
info!(self.log, "Verify extent {eid} still ready for copy");
let rc = match repair_server.extent_repair_ready(eid as u32).await {
Ok(rc) => rc.into_inner(),
Err(e) => {
crucible_bail!(
RepairRequestError,
"Failed to verify extent is still valid for repair {:?}",
e,
);
}
};
if !rc {
warn!(self.log, "The repair of {eid} is being aborted.");
crucible_bail!(
RepairRequestError,
"Extent {eid} on remote repair server is in incorrect state",
);
}
// After we have all files: move the repair dir.
info!(
self.log,
"{count} repair files downloaded, move directory {:?} to {:?}",
copy_dir,
rd
);
rename(copy_dir.clone(), rd.clone())?;
// Files are synced in save_stream_to_file(). Now make sure
// the parent directory containing the repair directory has
// been synced so that change is persistent.
let current_dir = extent_dir(&self.dir, eid as u32);
sync_path(current_dir, &self.log)?;
Ok(())
}
/**
* if there is a difference between what our actual extent_count is
* and what is requested, go out and create the new extent files.
*/
pub async fn extend(&mut self, newsize: u32) -> Result<()> {
if self.read_only {
// XXX return CrucibleError instead of anyhow?
bail!(CrucibleError::ModifyingReadOnlyRegion.to_string());
}
if newsize < self.def.extent_count() {
bail!(
"will not truncate {} -> {} for now",
self.def.extent_count(),
newsize
);
}
if newsize > self.def.extent_count() {
self.def.set_extent_count(newsize);
write_json(config_path(&self.dir), &self.def, true)?;
self.open_extents(true).await?;
}
Ok(())
}
pub fn region_def(&self) -> (u64, Block, u32) {
(
self.def.block_size(),
self.def.extent_size(),
self.def.extent_count(),
)
}
pub fn def(&self) -> RegionDefinition {
self.def
}
pub async fn meta_info(&self) -> Result<Vec<ExtentMeta>> {
let mut result = Vec::with_capacity(self.extents.len());
for eid in 0..self.extents.len() {
let extent = self.get_opened_extent(eid);
result.push(extent.get_meta_info().await)
}
Ok(result)
}
pub fn validate_hashes(
&self,
writes: &[crucible_protocol::Write],
) -> Result<(), CrucibleError> {
for write in writes {
let computed_hash = if let Some(encryption_context) =
&write.block_context.encryption_context
{
integrity_hash(&[
&encryption_context.nonce[..],
&encryption_context.tag[..],
&write.data[..],
])
} else {
integrity_hash(&[&write.data[..]])
};
if computed_hash != write.block_context.hash {
error!(self.log, "Failed write hash validation");
// TODO: print out the extent and block where this failed!!
crucible_bail!(HashMismatch);
}
}
Ok(())
}
#[instrument]
pub async fn region_write(
&mut self,
writes: &[crucible_protocol::Write],
job_id: JobId,
only_write_unwritten: bool,
) -> Result<(), CrucibleError> {
if self.read_only {
crucible_bail!(ModifyingReadOnlyRegion);
}
/*
* Before anything, validate hashes
*/
self.validate_hashes(writes)?;
/*
* Batch writes so they can all be sent to the appropriate extent
* together.
*/
let mut batched_writes: HashMap<usize, Vec<crucible_protocol::Write>> =
HashMap::new();
for write in writes {
let extent_vec =
batched_writes.entry(write.eid as usize).or_default();
extent_vec.push(write.clone());
}
if only_write_unwritten {
cdt::os__writeunwritten__start!(|| job_id.0);
} else {
cdt::os__write__start!(|| job_id.0);
}
for eid in batched_writes.keys() {
let extent = self.get_opened_extent_mut(*eid);
let writes = batched_writes.get(eid).unwrap();
extent
.write(job_id, &writes[..], only_write_unwritten)
.await?;
}
// Mark any extents we sent a write-command to as potentially dirty
self.dirty_extents.extend(batched_writes.keys());
if only_write_unwritten {
cdt::os__writeunwritten__done!(|| job_id.0);
} else {
cdt::os__write__done!(|| job_id.0);
}
Ok(())
}
#[instrument]
pub async fn region_read(
&mut self,
requests: &[crucible_protocol::ReadRequest],
job_id: JobId,
) -> Result<Vec<crucible_protocol::ReadResponse>, CrucibleError> {
let mut responses = Vec::with_capacity(requests.len());
/*
* Batch reads so they can all be sent to the appropriate extent
* together.
*
* Note: Have to maintain order with reads! The Upstairs expects read
* responses to be in the same order as read requests, so we can't
* use a hashmap in the same way that batching writes can.
*/
let mut eid: Option<u64> = None;
let mut batched_reads = Vec::with_capacity(requests.len());
cdt::os__read__start!(|| job_id.0);
for request in requests {
if let Some(_eid) = eid {
if request.eid == _eid {
batched_reads.push(request.clone());
} else {
let extent = self.get_opened_extent_mut(_eid as usize);
responses
.extend(extent.read(job_id, &batched_reads[..]).await?);
eid = Some(request.eid);
batched_reads.clear();
batched_reads.push(request.clone());
}
} else {
eid = Some(request.eid);
batched_reads.clear();
batched_reads.push(request.clone());
}
}
if let Some(_eid) = eid {
let extent = self.get_opened_extent_mut(_eid as usize);
responses.extend(extent.read(job_id, &batched_reads[..]).await?);
}
cdt::os__read__done!(|| job_id.0);
Ok(responses)
}
/*
* Send a flush to just the given extent. The provided flush number is
* what an extent should use if a flush is required.
*/
#[instrument]
pub(crate) async fn region_flush_extent<
I: Into<JobOrReconciliationId> + Debug,
>(
&mut self,
eid: usize,
gen_number: u64,
flush_number: u64,
job_id: I, // only used for logging
) -> Result<(), CrucibleError> {
debug!(
self.log,
"Flush just extent {} with f:{} and g:{}",
eid,
flush_number,
gen_number
);
let log = self.log.clone();
let extent = self.get_opened_extent_mut(eid);
extent.flush(flush_number, gen_number, job_id, &log).await?;
Ok(())
}
/*
* Send a flush to all extents. The provided flush number is
* what an extent should use if a flush is required.
*/
#[instrument]
pub async fn region_flush(
&mut self,
flush_number: u64,
gen_number: u64,
snapshot_details: &Option<SnapshotDetails>,
job_id: JobId,
extent_limit: Option<usize>,
) -> Result<(), CrucibleError> {
// It should be ok to Flush a read-only region, but not take a snapshot.
// Most likely this read-only region *is* a snapshot, so that's
// redundant :)
if self.read_only && snapshot_details.is_some() {
crucible_bail!(ModifyingReadOnlyRegion);
}
cdt::os__flush__start!(|| job_id.0);
// Select extents we're going to flush, while respecting the
// extent_limit if one was provided. This must be ordered, because
// we're going to walk through the extent slice.
let dirty_extents: BTreeSet<usize> = match extent_limit {
None => self.dirty_extents.iter().copied().collect(),
Some(el) => {
if el > self.def.extent_count().try_into().unwrap() {
crucible_bail!(InvalidExtent);
}
self.dirty_extents
.iter()
.copied()
.filter(|x| *x <= el)
.collect()
}
};
// This is a bit sneaky: we want to perform each flush in a separate
// task for *parallelism*, but can't call `self.get_opened_extent_mut`
// multiple times. In addition, we can't use the tokio thread pool to
// spawn a task, because that requires a 'static lifetime, which we
// can't get from a borrowed Extent.
//
// We'll combine two tricks to work around the issue:
// - Do the work in the rayon thread pool instead of using tokio tasks
// - Carefully walk self.extents.as_mut_slice() to mutably borrow
// multiple at the same time.
let mut results = vec![Ok(()); dirty_extents.len()];
let log = self.log.clone();
let mut f = || {
let mut slice_start = 0;
let mut slice = self.extents.as_mut_slice();
let h = tokio::runtime::Handle::current();
rayon::scope(|s| {
for (eid, r) in dirty_extents.iter().zip(results.iter_mut()) {
let next = eid - slice_start;
slice = &mut slice[next..];
let (extent, rest) = slice.split_first_mut().unwrap();
let ExtentState::Opened(extent) = extent else {
panic!("can't flush closed extent");
};
slice = rest;
slice_start += next + 1;
let log = log.clone();
s.spawn(|_| {
h.block_on(async move {
*r = extent
.flush(flush_number, gen_number, job_id, &log)
.await
});
});
}
})
};
if matches!(
tokio::runtime::Handle::try_current().map(|r| r.runtime_flavor()),