forked from oxidecomputer/crucible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextent_inner_sqlite.rs
1835 lines (1611 loc) · 64.3 KB
/
extent_inner_sqlite.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 crate::{
cdt,
extent::{check_input, extent_path, DownstairsBlockContext, ExtentInner},
extent_inner_raw_common::pwrite_all,
integrity_hash,
region::JobOrReconciliationId,
Block, BlockContext, CrucibleError, ExtentReadRequest, ExtentReadResponse,
ExtentWrite, JobId, RegionDefinition,
};
use crucible_common::{crucible_bail, ExtentId};
use crucible_protocol::{EncryptionContext, ReadBlockContext};
use anyhow::{bail, Result};
use itertools::Itertools;
use rusqlite::{params, Connection, Transaction};
use slog::{error, Logger};
use std::collections::{BTreeMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Read, Seek, SeekFrom};
use std::os::fd::{AsFd, AsRawFd};
use std::path::Path;
#[derive(Debug)]
pub struct SqliteInner(std::sync::Mutex<SqliteMoreInner>);
impl ExtentInner for SqliteInner {
fn gen_number(&self) -> Result<u64, CrucibleError> {
let v = self.0.lock().unwrap().gen_number()?;
Ok(v)
}
fn flush_number(&self) -> Result<u64, CrucibleError> {
let v = self.0.lock().unwrap().flush_number()?;
Ok(v)
}
fn dirty(&self) -> Result<bool, CrucibleError> {
Ok(self.0.lock().unwrap().dirty())
}
fn pre_flush(
&mut self,
new_flush: u64,
new_gen: u64,
job_id: JobOrReconciliationId,
) -> Result<(), CrucibleError> {
self.0.lock().unwrap().pre_flush(new_flush, new_gen, job_id);
Ok(())
}
fn flush_inner(
&mut self,
job_id: JobOrReconciliationId,
) -> Result<(), CrucibleError> {
self.0.lock().unwrap().flush_inner(job_id)
}
fn post_flush(
&mut self,
new_flush: u64,
new_gen: u64,
job_id: JobOrReconciliationId,
) -> Result<(), CrucibleError> {
self.0
.lock()
.unwrap()
.post_flush(new_flush, new_gen, job_id)?;
Ok(())
}
fn read(
&mut self,
job_id: JobId,
req: ExtentReadRequest,
_iov_max: usize, // unused by SQLite backend
) -> Result<ExtentReadResponse, CrucibleError> {
self.0.lock().unwrap().read(job_id, req)
}
fn write(
&mut self,
job_id: JobId,
write: &ExtentWrite,
only_write_unwritten: bool,
iov_max: usize,
) -> Result<(), CrucibleError> {
self.0.lock().unwrap().write(
job_id,
write,
only_write_unwritten,
iov_max,
)?;
Ok(())
}
#[cfg(test)]
fn get_block_contexts(
&mut self,
block: u64,
count: u64,
) -> Result<Vec<Option<DownstairsBlockContext>>, CrucibleError> {
let bc = self.0.lock().unwrap().get_block_contexts(block, count)?;
Ok(bc)
}
#[cfg(test)]
fn set_dirty_and_block_context(
&mut self,
block_context: &DownstairsBlockContext,
) -> Result<(), CrucibleError> {
self.0
.lock()
.unwrap()
.set_dirty_and_block_context(block_context)
}
}
impl SqliteInner {
#[cfg(any(test, feature = "integration-tests"))]
pub fn create(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
) -> Result<Self> {
let i = SqliteMoreInner::create(dir, def, extent_number)?;
Ok(Self(i.into()))
}
pub fn open(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
read_only: bool,
log: &Logger,
) -> Result<Self> {
let i = SqliteMoreInner::open(dir, def, extent_number, read_only, log)?;
Ok(Self(i.into()))
}
pub fn export_contexts(
&mut self,
) -> Result<Vec<Option<DownstairsBlockContext>>> {
self.0.lock().unwrap().export_contexts()
}
#[cfg(test)]
pub fn fully_rehash_and_clean_all_stale_contexts(
&mut self,
force_override_dirty: bool,
) -> Result<(), CrucibleError> {
self.0
.lock()
.unwrap()
.fully_rehash_and_clean_all_stale_contexts(force_override_dirty)
}
#[cfg(test)]
fn truncate_encryption_contexts_and_hashes(
&self,
extent_block_indexes_and_hashes: &[(usize, u64)],
) -> Result<()> {
self.0
.lock()
.unwrap()
.truncate_encryption_contexts_and_hashes(
extent_block_indexes_and_hashes,
)?;
Ok(())
}
}
#[derive(Debug)]
struct SqliteMoreInner {
file: File,
metadb: Connection,
/// Our extent number
extent_number: ExtentId,
/// Extent size, in blocks
extent_size: Block,
/// Flag indicating whether the `dirty` bit is set
///
/// This is cached locally to avoid an expensive SQLite operation when it is
/// already true, and is a `Cell` for interior mutability.
dirty: std::cell::Cell<bool>,
/// Set of blocks that have been written since last flush.
///
/// If the hash is known, then it's also recorded here. It _should_ always
/// be known, unless the write failed.
dirty_blocks: BTreeMap<usize, Option<u64>>,
}
// To avoid CrucibleError having a Rusqlite variant, use an "inner" error
// variant and convert it to CrucibleError for the ExtentInner function
// implementations.
#[derive(thiserror::Error, Debug)]
enum SqliteMoreInnerError {
#[error("crucible error")]
Crucible(#[from] CrucibleError),
#[error("rusqlite error")]
Rusqlite(#[from] rusqlite::Error),
#[error("io error")]
Io(#[from] std::io::Error),
#[error("anyhow error")]
Anyhow(#[from] anyhow::Error),
}
impl From<SqliteMoreInnerError> for CrucibleError {
fn from(e: SqliteMoreInnerError) -> CrucibleError {
match e {
SqliteMoreInnerError::Crucible(e) => e,
SqliteMoreInnerError::Rusqlite(e) => {
CrucibleError::GenericError(format!("{:?}", e))
}
SqliteMoreInnerError::Io(e) => e.into(),
SqliteMoreInnerError::Anyhow(e) => e.into(),
}
}
}
impl SqliteMoreInner {
fn gen_number(&self) -> Result<u64, SqliteMoreInnerError> {
let mut stmt = self.metadb.prepare_cached(
"SELECT value FROM metadata where name='gen_number'",
)?;
let mut gen_number_iter = stmt.query_map([], |row| row.get(0))?;
let gen_number = gen_number_iter.next().unwrap()?;
assert!(gen_number_iter.next().is_none());
Ok(gen_number)
}
fn flush_number(&self) -> Result<u64, SqliteMoreInnerError> {
let mut stmt = self.metadb.prepare_cached(
"SELECT value FROM metadata where name='flush_number'",
)?;
let mut flush_number_iter = stmt.query_map([], |row| row.get(0))?;
let flush_number = flush_number_iter.next().unwrap()?;
assert!(flush_number_iter.next().is_none());
Ok(flush_number)
}
fn dirty(&self) -> bool {
self.dirty.get()
}
fn pre_flush(
&mut self,
_new_flush: u64,
_new_gen: u64,
job_id: JobOrReconciliationId,
) {
// Used for profiling
let n_dirty_blocks = self.dirty_blocks.len() as u64;
cdt::extent__flush__start!(|| {
(job_id.get(), self.extent_number.0, n_dirty_blocks)
});
}
fn flush_inner(
&mut self,
job_id: JobOrReconciliationId,
) -> Result<(), CrucibleError> {
/*
* We must first fsync to get any outstanding data written to disk.
* This must be done before we update the flush number.
*/
cdt::extent__flush__file__start!(|| {
(job_id.get(), self.extent_number.0)
});
if let Err(e) = self.file.sync_all() {
/*
* XXX Retry? Mark extent as broken?
*/
crucible_bail!(
IoError,
"extent {}: fsync 1 failure: {e:?}",
self.extent_number,
);
}
cdt::extent__flush__file__done!(|| {
(job_id.get(), self.extent_number.0)
});
Ok(())
}
fn post_flush(
&mut self,
new_flush: u64,
new_gen: u64,
job_id: JobOrReconciliationId,
) -> Result<(), SqliteMoreInnerError> {
// Clear old block contexts. In order to be crash consistent, only
// perform this after the extent fsync is done. For each block
// written since the last flush, remove all block context rows where
// the integrity hash does not map the last-written value. This is
// safe, because we know the process has not crashed since those
// values were written. When the region is first opened, the entire
// file is rehashed, since in that case we don't have that luxury.
cdt::extent__flush__collect__hashes__start!(|| {
(job_id.get(), self.extent_number.0)
});
// Rehash any parts of the file that we *may have written* data to since
// the last flush. (If we know that we wrote the data, then we don't
// bother rehashing)
let n_rehashed = self.rehash_dirty_blocks()?;
cdt::extent__flush__collect__hashes__done!(|| {
(job_id.get(), self.extent_number.0, n_rehashed as u64)
});
cdt::extent__flush__sqlite__insert__start!(|| {
(job_id.get(), self.extent_number.0)
});
// We put all of our metadb updates into a single transaction to
// assure that we have a single sync.
let tx = self.metadb.unchecked_transaction()?;
self.truncate_encryption_contexts_and_hashes_with_tx(
self.dirty_blocks
.iter()
.map(|(block, hash)| (*block, hash.unwrap())),
&tx,
)?;
cdt::extent__flush__sqlite__insert__done!(|| {
(job_id.get(), self.extent_number.0)
});
self.set_flush_number(new_flush, new_gen)?;
tx.commit()?;
self.dirty_blocks.clear();
// Finally, reset the file's seek offset to 0
self.file.seek(SeekFrom::Start(0))?;
cdt::extent__flush__done!(|| { (job_id.get(), self.extent_number.0) });
Ok(())
}
fn read(
&mut self,
job_id: JobId,
req: ExtentReadRequest,
) -> Result<ExtentReadResponse, CrucibleError> {
let mut buf = req.data;
let block_size = self.extent_size.block_size_in_bytes() as u64;
let num_blocks = buf.capacity() as u64 / block_size;
check_input(self.extent_size, req.offset, buf.capacity())?;
// Query the block metadata
cdt::extent__read__get__contexts__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
let block_contexts =
self.get_block_contexts(req.offset.0, num_blocks)?;
cdt::extent__read__get__contexts__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// Convert from DownstairsBlockContext -> ReadBlockContext
let blocks = block_contexts
.into_iter()
.map(|bs| match bs {
None => ReadBlockContext::Empty,
Some(b) => match b.block_context.encryption_context {
Some(ctx) => ReadBlockContext::Encrypted { ctx },
None => ReadBlockContext::Unencrypted {
hash: b.block_context.hash,
},
},
})
.collect();
// To avoid a `memset`, we're reading directly into uninitialized
// memory in the buffer. This is fine; we sized the buffer
// appropriately in advance (and will panic here if we messed up).
assert!(buf.is_empty());
// Finally we get to read the actual data. That's why we're here
cdt::extent__read__file__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// SAFETY: the buffer has sufficient capacity, and this is a valid
// file descriptor.
let expected_bytes = buf.capacity();
let r = unsafe {
libc::pread(
self.file.as_raw_fd(),
buf.spare_capacity_mut().as_mut_ptr() as *mut libc::c_void,
expected_bytes as libc::size_t,
req.offset.0 as i64 * block_size as i64,
)
};
// Check against the expected number of bytes. We could do more
// robust error handling here (e.g. retrying in a loop), but for
// now, simply bailing out seems wise.
let r = nix::errno::Errno::result(r).map(|r| r as usize);
let num_bytes = r.map_err(|e| {
CrucibleError::IoError(format!(
"extent {}: read failed: {e}",
self.extent_number
))
})?;
if num_bytes != expected_bytes {
return Err(CrucibleError::IoError(format!(
"extent {}: incomplete read \
(expected {expected_bytes}, got {num_bytes})",
self.extent_number
)));
}
// SAFETY: we just initialized this chunk of the buffer
unsafe {
buf.set_len(expected_bytes);
}
cdt::extent__read__file__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
Ok(ExtentReadResponse { data: buf, blocks })
}
fn write(
&mut self,
job_id: JobId,
write: &ExtentWrite,
only_write_unwritten: bool,
_iov_max: usize,
) -> Result<(), SqliteMoreInnerError> {
check_input(self.extent_size, write.offset, write.data.len())?;
/*
* In order to be crash consistent, perform the following steps in
* order:
*
* 1) set the dirty bit
* 2) for each write:
* a) write out encryption context first
* b) write out hashes second
* c) write out extent data third
*
* If encryption context is written after the extent data, a crash or
* interruption before extent data is written would potentially leave
* data on the disk that cannot be decrypted.
*
* If hash is written after extent data, same thing - a crash or
* interruption would leave data on disk that would fail the
* integrity hash check.
*
* Note that writing extent data here does not assume that it is
* durably on disk - the only guarantee of that is returning
* ok from fsync. The data is only potentially on disk and
* this depends on operating system implementation.
*
* To minimize the performance hit of sending many transactions to
* sqlite, as much as possible is written at the same time. This
* means multiple loops are required. The steps now look like:
*
* 1) set the dirty bit
* 2) gather and write all encryption contexts + hashes
* 3) write all extent data
*
* If "only_write_unwritten" is true, then we only issue a write for
* a block if that block has not been written to yet. Note
* that we can have a write that is "sparse" if the range of
* blocks it contains has a mix of written an unwritten
* blocks.
*
* We define a block being written to or not has if that block has
* a checksum or not. So it is required that a written block has
* a checksum.
*/
let num_blocks = write.block_contexts.len() as u64;
let block_size = self.extent_size.block_size_in_bytes() as u64;
// If `only_write_written`, we need to skip writing to blocks that
// already contain data. We'll first query the metadata to see which
// blocks have hashes
let mut writes_to_skip = HashSet::new();
if only_write_unwritten {
cdt::extent__write__get__hashes__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// Query hashes for the write range.
// TODO we should consider adding a query that doesnt actually
// give us back the data, just checks for its presence.
let block_contexts =
self.get_block_contexts(write.offset.0, num_blocks)?;
for (i, block_contexts) in block_contexts.iter().enumerate() {
if block_contexts.is_some() {
writes_to_skip.insert(i);
}
}
cdt::extent__write__get__hashes__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
if writes_to_skip.len() == write.block_contexts.len() {
// Nothing to do
return Ok(());
}
}
// We do all of our metadb updates in a single transaction to minimize
// syncs. (Note that the "unchecked" in the signature merely denotes
// that we are taking responsibility for assuring that we are not
// in a nested transaction, accepting that it will fail at run-time
// if we are.)
let tx = self.metadb.unchecked_transaction()?;
self.set_dirty()?;
// Write all the metadata to the DB
// TODO right now we're including the integrity_hash() time in the sqlite time. It's small in
// comparison right now, but worth being aware of when looking at dtrace numbers
cdt::extent__write__sqlite__insert__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
let mut hashes_to_write =
Vec::with_capacity(write.block_contexts.len());
for (i, ctx) in write.block_contexts.iter().enumerate() {
if writes_to_skip.contains(&i) {
hashes_to_write.push(None);
continue;
}
// TODO it would be nice if we could profile what % of time we're
// spending on hashes locally vs sqlite
let on_disk_hash =
integrity_hash(&[&write.data[i * block_size as usize..]
[..block_size as usize]]);
let offset = i as u64 + write.offset.0;
self.set_block_context(&DownstairsBlockContext {
block_context: *ctx,
block: offset,
on_disk_hash,
})?;
// Worth some thought: this could happen inside
// tx_set_block_context, if we passed a reference to dirty_blocks
// into that function too. This might be nice, since then a block
// context could never be set without marking the block as dirty.
// On the other paw, our test suite very much likes the fact that
// tx_set_block_context doesn't mark blocks as dirty, since it
// lets us easily test specific edge-cases of the database state.
// Could make another function that wraps tx_set_block_context
// and handles this as well.
self.dirty_blocks.insert(offset as usize, None);
hashes_to_write.push(Some(on_disk_hash));
}
tx.commit()?;
cdt::extent__write__sqlite__insert__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// PERFORMANCE TODO:
//
// Something worth considering for small writes is that, based on
// my memory of conversations we had with propolis folks about what
// OSes expect out of an NVMe driver, I believe our contract with the
// upstairs doesn't require us to have the writes inside the file
// until after a flush() returns. If that is indeed true, we could
// buffer a certain amount of writes, only actually writing that
// buffer when either a flush is issued or the buffer exceeds some
// set size (based on our memory constraints). This would have
// benefits on any workload that frequently writes to the same block
// between flushes, would have benefits for small contiguous writes
// issued over multiple write commands by letting us batch them into
// a larger write, and (speculation) may benefit non-contiguous writes
// by cutting down the number of sqlite transactions. But, it
// introduces complexity. The time spent implementing that would
// probably better be spent switching to aio or something like that.
cdt::extent__write__file__start!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// Perform writes, which may be broken up by skipped blocks
for (skip, mut group) in (0..write.block_contexts.len())
.chunk_by(|i| writes_to_skip.contains(i))
.into_iter()
{
if skip {
continue;
}
let start = group.next().unwrap();
let count = group.count() + 1;
let data = &write.data[start * block_size as usize..]
[..count * block_size as usize];
let start_block = write.offset.0 + start as u64;
pwrite_all(
self.file.as_fd(),
data,
(start_block * block_size) as i64,
)
.map_err(|e| CrucibleError::IoError(e.to_string()))?;
}
cdt::extent__write__file__done!(|| {
(job_id.0, self.extent_number.0, num_blocks)
});
// At this point, we know that the written data for the target blocks
// must match the integrity hashes calculated above (and stored to
// SQLite). We can therefore store pre-computed hash values for these
// dirty blocks, allowing us to skip rehashing during a flush operation.
for (i, hash) in (0..num_blocks).zip(&hashes_to_write) {
let offset = i + write.offset.0;
if let Some(h) = hash {
// This overwrites the `None` value written above!
let prev = self.dirty_blocks.insert(offset as usize, Some(*h));
assert_eq!(prev, Some(None));
}
}
Ok(())
}
#[cfg(test)]
fn set_dirty_and_block_context(
&mut self,
block_context: &DownstairsBlockContext,
) -> Result<(), CrucibleError> {
self.set_dirty()?;
self.set_block_context(block_context)?;
Ok(())
}
/// Exports context slots for every block in the file
fn export_contexts(
&mut self,
) -> Result<Vec<Option<DownstairsBlockContext>>> {
let out = self.get_block_contexts(0, self.extent_size.value)?;
Ok(out)
}
fn get_block_contexts(
&self,
block: u64,
count: u64,
) -> Result<Vec<Option<DownstairsBlockContext>>, SqliteMoreInnerError> {
let stmt =
"SELECT block, hash, nonce, tag, on_disk_hash FROM block_context \
WHERE block BETWEEN ?1 AND ?2";
let mut stmt = self.metadb.prepare_cached(stmt)?;
let stmt_iter =
stmt.query_map(params![block, block + count - 1], |row| {
let block_index: u64 = row.get(0)?;
let hash: i64 = row.get(1)?;
let nonce: Option<[u8; 12]> = row.get(2)?;
let tag: Option<[u8; 16]> = row.get(3)?;
let on_disk_hash: i64 = row.get(4)?;
Ok((block_index, hash, nonce, tag, on_disk_hash))
})?;
let mut results: Vec<Option<DownstairsBlockContext>> =
vec![None; count as usize];
let mut known_hashes: Vec<Option<u64>> = vec![None; count as usize];
let block_size = self.extent_size.block_size_in_bytes();
let mut buffer = vec![0u8; block_size as usize];
for row in stmt_iter {
let (block_index, hash, nonce, tag, on_disk_hash) = row?;
let encryption_context = if let Some(nonce) = nonce {
tag.map(|tag| EncryptionContext { nonce, tag })
} else {
None
};
let ctx = DownstairsBlockContext {
block_context: BlockContext {
hash: hash as u64,
encryption_context,
},
block: block_index,
on_disk_hash: on_disk_hash as u64,
};
// If we've stored multiple contexts for this block, then select
// whichever one has a matching hash, or `None` if no contexts have
// a matching hash. Otherwise, assume that the single context is
// correct (without checking, because that's slow).
let i = (ctx.block - block) as usize;
if let Some(prev_result) = results[i] {
// Make sure we have the true hash stored in known_hashes
// (caching in case we have > 2 rows for this block)
let hash = if let Some(h) = known_hashes[i] {
h
} else {
let r = unsafe {
libc::pread(
self.file.as_raw_fd(),
buffer.as_mut_ptr() as *mut libc::c_void,
block_size as libc::size_t,
ctx.block as i64 * block_size as i64,
)
};
let r = nix::errno::Errno::result(r).map(|r| r as usize);
let num_bytes = r.map_err(|e| {
CrucibleError::IoError(format!(
"extent {}: read failed: {e}",
self.extent_number
))
})?;
if num_bytes != block_size as usize {
return Err(CrucibleError::IoError(format!(
"extent {}: incomplete read \
(expected {block_size}, got {num_bytes})",
self.extent_number
))
.into());
}
let hash = integrity_hash(&[&buffer]);
known_hashes[i] = Some(hash);
hash
};
// Now, compare the on-disk hash with what's stored in the
// database, to see which row is correct
if prev_result.on_disk_hash == hash {
// Previous result is valid, leave it be
} else if ctx.on_disk_hash == hash {
// New hash is valid
results[i] = Some(ctx);
} else {
// Neither hash is valid, so clear it
results[i] = None;
}
} else if let Some(h) = known_hashes[i] {
// If we have computed the hash, then only return rows where the
// hash actually matches.
if h == ctx.on_disk_hash {
results[i] = Some(ctx);
}
} else {
// Otherwise, assume that the hash is valid (because there's
// only one row, and we don't want to recheck every time).
results[i] = Some(ctx);
}
}
Ok(results)
}
// We should never create a new SQLite-backed extent in production code,
// because we should be using raw extents everywhere. However, we'll create
// them during tests to check that our automatic migration system works.
#[cfg(any(test, feature = "integration-tests"))]
fn create(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
) -> Result<Self> {
use crate::{
extent::{ExtentMeta, EXTENT_META_SQLITE},
mkdir_for_file,
};
let mut path = extent_path(dir, extent_number);
let bcount = def.extent_size().value;
let size = def.block_size().checked_mul(bcount).unwrap();
mkdir_for_file(&path)?;
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)?;
file.set_len(size)?;
file.seek(SeekFrom::Start(0))?;
let mut seed = dir.to_path_buf();
seed.push("seed");
seed.set_extension("db");
path.set_extension("db");
// Instead of creating the sqlite db for every extent, create it only
// once, and copy from a seed db when creating other extents. This
// minimizes Region create time.
let metadb = if Path::new(&seed).exists() {
std::fs::copy(&seed, &path)?;
open_sqlite_connection(&path)?
} else {
/*
* Create the metadata db
*/
let metadb = open_sqlite_connection(&path)?;
/*
* Create tables and insert base data
*/
metadb.execute(
"CREATE TABLE metadata (
name TEXT PRIMARY KEY,
value INTEGER NOT NULL
)",
[],
)?;
let meta = ExtentMeta::new(EXTENT_META_SQLITE);
metadb.execute(
"INSERT INTO metadata
(name, value) VALUES (?1, ?2)",
params!["ext_version", meta.ext_version],
)?;
metadb.execute(
"INSERT INTO metadata
(name, value) VALUES (?1, ?2)",
params!["gen_number", meta.gen_number],
)?;
metadb.execute(
"INSERT INTO metadata (name, value) VALUES (?1, ?2)",
params!["flush_number", meta.flush_number],
)?;
metadb.execute(
"INSERT INTO metadata (name, value) VALUES (?1, ?2)",
params!["dirty", meta.dirty],
)?;
// Within an extent, store a context row for each block.
//
// The Upstairs will send either an integrity hash, or an integrity
// hash along with some encryption context (a nonce and tag).
//
// The Downstairs will have to record multiple context rows for each
// block, because while what is committed to sqlite is durable (due
// to the write-ahead logging and the fact that we set PRAGMA
// SYNCHRONOUS), what is written to the extent file is not durable
// until a flush of that file is performed.
//
// Any of the context rows written between flushes could be valid
// until we call flush and remove context rows where the integrity
// hash does not match what was actually flushed to disk.
// in WITHOUT ROWID mode, SQLite arranges the tables on-disk ordered
// by the primary key. since we're always doing operations on
// contiguous ranges of blocks, this is great for us. The only catch
// is that you can actually see worse performance with large rows
// (not a problem for us).
//
// From https://www.sqlite.org/withoutrowid.html:
// > WITHOUT ROWID tables work best when individual rows are not too
// > large. A good rule-of-thumb is that the average size of a
// > single row in a WITHOUT ROWID table should be less than about
// > 1/20th the size of a database page. That means that rows should
// > not contain more than about 50 bytes each for a 1KiB page size
// > or about 200 bytes each for 4KiB page size.
//
// The default SQLite page size is 4KiB, per
// https://sqlite.org/pgszchng2016.html
//
// The primary key is also a uniqueness constraint. Because the
// on_disk_hash is a hash of the data AFTER encryption, we only need
// (block, on_disk_hash). A duplicate write with a different
// encryption context necessarily results in a different on disk
// hash.
metadb.execute(
"CREATE TABLE block_context (
block INTEGER,
hash INTEGER,
nonce BLOB,
tag BLOB,
on_disk_hash INTEGER,
PRIMARY KEY (block, on_disk_hash)
) WITHOUT ROWID",
[],
)?;
// write out
metadb.close().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("metadb.close() failed! {}", e.1),
)
})?;
// Save it as DB seed
std::fs::copy(&path, &seed)?;
open_sqlite_connection(&path)?
};
// The seed DB or default metadata should not have dirty set, but we'll
// check here for completeness.
let dirty = Self::get_dirty_from_metadb(&metadb)?;
assert!(!dirty);
/*
* Complete the construction of our new extent
*/
Ok(Self {
file,
dirty: dirty.into(),
extent_size: def.extent_size(),
metadb,
extent_number,
dirty_blocks: BTreeMap::new(),
})
}
fn open(
dir: &Path,
def: &RegionDefinition,
extent_number: ExtentId,
read_only: bool,
log: &Logger,
) -> Result<Self> {
let mut path = extent_path(dir, extent_number);
let bcount = def.extent_size().value;
let size = def.block_size().checked_mul(bcount).unwrap();
/*
* Open the extent file and verify the size is as we expect.
*/
let file =
match OpenOptions::new().read(true).write(!read_only).open(&path) {
Err(e) => {
error!(
log,
"Open of {path:?} for extent#{extent_number} \
returned: {e}",
);
bail!(
"Open of {path:?} for extent#{extent_number} \
returned: {e}",
);
}
Ok(f) => {
let cur_size = f.metadata().unwrap().len();
if size != cur_size {
bail!(
"File size {size:?} does not match \
expected {cur_size:?}",
);
}
f
}
};
/*
* Open a connection to the metadata db
*/
path.set_extension("db");
let metadb = match open_sqlite_connection(&path) {
Err(e) => {
error!(
log,
"Error: Open of db file {path:?} for \
extent#{extent_number} returned: {e}",
);
bail!(
"Open of db file {path:?} for extent#{extent_number} \
returned: {e}",
);
}
Ok(m) => m,
};
let dirty = Self::get_dirty_from_metadb(&metadb)?;
let mut out = Self {
file,
metadb,
extent_size: def.extent_size(),
dirty: dirty.into(),
extent_number,
dirty_blocks: BTreeMap::new(),
};
// Clean out any irrelevant block contexts, which may be present
// if downstairs crashed between a write() and a flush().