synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / blockdev_tests.rs
| 1 | //! R1 raw block store tests (issue #47): device refusal rules, superblock fallback, |
| 2 | //! slot exhaustion, and the power-cut simulation. The A2 crash suite itself runs |
| 3 | //! unchanged against the device in `blockdev_a2_suite.rs`. |
| 4 | //! |
| 5 | //! Power-cut simulation: a workload runs on an in-memory device that records every |
| 6 | //! write and every flush. Crash images are rebuilt from that log for every cut point, |
| 7 | //! under four models of what reached the medium: |
| 8 | //! |
| 9 | //! * prefix tear: every write before the cut landed, the write at the cut landed for its |
| 10 | //! first `k` 512-byte sectors, for every `k`; |
| 11 | //! * suffix tear: the same with only the last `k` sectors landed; |
| 12 | //! * lost write: one write issued since the last flush did not land at all (the drive |
| 13 | //! may persist unflushed writes in any order), for every such write; |
| 14 | //! * hole: the write at the cut landed except for one sector in its middle. |
| 15 | //! |
| 16 | //! Every acknowledged change must survive the first three models under |
| 17 | //! `TruncateTornTail` (strict recovery may refuse only with `WalTornFrame`). A hole may |
| 18 | //! make recovery fail closed (the A2 limit documented at `wal2::torn_evidence`), but it |
| 19 | //! must never open with an acknowledged change missing. |
| 20 | |
| 21 | use super::blockdev::*; |
| 22 | use super::tests::make_signed_changeset; |
| 23 | use super::*; |
| 24 | use ed25519_dalek::SigningKey; |
| 25 | use std::sync::{Arc, Mutex}; |
| 26 | |
| 27 | /// File in a test store directory that turns it into a raw block store. |
| 28 | pub(crate) const TEST_DEVICE_FILE: &str = "raw.device"; |
| 29 | /// Size of the test devices (sparse files). |
| 30 | pub(crate) const TEST_DEVICE_BYTES: u64 = 16 << 20; |
| 31 | /// Metadata region size of the test devices. |
| 32 | pub(crate) const TEST_META_BYTES: u64 = 1 << 20; |
| 33 | |
| 34 | /// Test hook of [`SynapseStore::open`]: a directory holding [`TEST_DEVICE_FILE`] is |
| 35 | /// opened as a raw block store on that file. |
| 36 | pub(crate) fn redirect(root: &Path) -> Option<BlockDeviceConfig> { |
| 37 | let path = root.join(TEST_DEVICE_FILE); |
| 38 | path.is_file().then_some(BlockDeviceConfig { |
| 39 | path, |
| 40 | format: FormatPolicy::FormatIfBlank, |
| 41 | meta_region_bytes: TEST_META_BYTES, |
| 42 | allow_foreign_signature: false, |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | /// Create a zero-filled (sparse) test device file of `len` bytes. |
| 47 | pub(crate) fn make_device_file(path: &Path, len: u64) { |
| 48 | let f = File::create(path).unwrap(); |
| 49 | f.set_len(len).unwrap(); |
| 50 | f.sync_all().unwrap(); |
| 51 | } |
| 52 | |
| 53 | fn temp_dir(label: &str) -> PathBuf { |
| 54 | super::tests::temp_store_dir(&format!("r1-{label}")) |
| 55 | } |
| 56 | |
| 57 | // --- in-memory device with a write log ------------------------------------------- |
| 58 | |
| 59 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 60 | enum Op { |
| 61 | Write { off: u64, data: Vec<u8> }, |
| 62 | Flush, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug)] |
| 66 | struct Rec { |
| 67 | image: Vec<u8>, |
| 68 | ops: Vec<Op>, |
| 69 | fail_flushes: bool, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Clone)] |
| 73 | struct MemIo(Arc<Mutex<Rec>>); |
| 74 | |
| 75 | impl MemIo { |
| 76 | fn new(image: Vec<u8>) -> Self { |
| 77 | Self(Arc::new(Mutex::new(Rec { |
| 78 | image, |
| 79 | ops: Vec::new(), |
| 80 | fail_flushes: false, |
| 81 | }))) |
| 82 | } |
| 83 | fn rec(&self) -> std::sync::MutexGuard<'_, Rec> { |
| 84 | self.0.lock().unwrap() |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | impl BlockIo for MemIo { |
| 89 | fn len(&self) -> u64 { |
| 90 | self.rec().image.len() as u64 |
| 91 | } |
| 92 | fn read_at(&self, buf: &mut [u8], off: u64) -> std::io::Result<()> { |
| 93 | let r = self.rec(); |
| 94 | let src = r |
| 95 | .image |
| 96 | .get(off as usize..off as usize + buf.len()) |
| 97 | .ok_or_else(|| std::io::Error::other("read past the end"))?; |
| 98 | buf.copy_from_slice(src); |
| 99 | Ok(()) |
| 100 | } |
| 101 | fn write_at(&self, data: &[u8], off: u64) -> std::io::Result<()> { |
| 102 | let mut r = self.rec(); |
| 103 | let dst = r |
| 104 | .image |
| 105 | .get_mut(off as usize..off as usize + data.len()) |
| 106 | .ok_or_else(|| std::io::Error::other("write past the end"))?; |
| 107 | dst.copy_from_slice(data); |
| 108 | r.ops.push(Op::Write { |
| 109 | off, |
| 110 | data: data.to_vec(), |
| 111 | }); |
| 112 | Ok(()) |
| 113 | } |
| 114 | fn flush(&self) -> std::io::Result<()> { |
| 115 | let mut r = self.rec(); |
| 116 | if r.fail_flushes { |
| 117 | return Err(std::io::Error::other("injected flush failure")); |
| 118 | } |
| 119 | r.ops.push(Op::Flush); |
| 120 | Ok(()) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn mem_cfg(format: FormatPolicy, meta: u64) -> BlockDeviceConfig { |
| 125 | BlockDeviceConfig { |
| 126 | path: PathBuf::from("/r1-test/in-memory"), |
| 127 | format, |
| 128 | meta_region_bytes: meta, |
| 129 | allow_foreign_signature: false, |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// Deterministic non-zero filler (xorshift), standing in for stale bytes from an |
| 134 | /// earlier use of the device. |
| 135 | fn garbage(len: usize, mut x: u64) -> Vec<u8> { |
| 136 | let mut v = Vec::with_capacity(len); |
| 137 | while v.len() < len { |
| 138 | x ^= x << 13; |
| 139 | x ^= x >> 7; |
| 140 | x ^= x << 17; |
| 141 | v.extend_from_slice(&x.to_le_bytes()); |
| 142 | } |
| 143 | v.truncate(len); |
| 144 | v |
| 145 | } |
| 146 | |
| 147 | // --- store helpers --------------------------------------------------------------- |
| 148 | |
| 149 | const SEG: u64 = 64 * 1024; |
| 150 | const BLOB: usize = 6000; |
| 151 | const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; |
| 152 | const TRUNCATE: RecoveryPolicy = RecoveryPolicy::TruncateTornTail; |
| 153 | |
| 154 | fn limits() -> StoreLimits { |
| 155 | StoreLimits { |
| 156 | segment_bytes: SEG, |
| 157 | wal_prealloc_bytes: 16 * 1024, |
| 158 | ..Default::default() |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn key(n: u8) -> SigningKey { |
| 163 | SigningKey::from_bytes(&[n; 32]) |
| 164 | } |
| 165 | |
| 166 | fn commit(store: &mut SynapseStore, key: &SigningKey, label: &str) -> SynapseResult<WalSeq> { |
| 167 | let mut content = format!("// {label}\n").into_bytes(); |
| 168 | let mut x: u8 = label |
| 169 | .bytes() |
| 170 | .fold(7u8, |a, b| a.wrapping_mul(31).wrapping_add(b)); |
| 171 | while content.len() < BLOB { |
| 172 | x = x.wrapping_mul(13).wrapping_add(1); |
| 173 | content.push(b'a' + x % 26); |
| 174 | } |
| 175 | let (env, blobs) = make_signed_changeset( |
| 176 | key, |
| 177 | label, |
| 178 | &format!("src/{label}.rs"), |
| 179 | &content, |
| 180 | vec![], |
| 181 | 1000, |
| 182 | ); |
| 183 | match store.ingest_changeset(env, &blobs)? { |
| 184 | IngestOutcome::Committed { |
| 185 | wal_seq, |
| 186 | durability, |
| 187 | .. |
| 188 | } => { |
| 189 | assert_eq!(durability, DurabilityGuarantee::FsyncBeforeAck); |
| 190 | Ok(wal_seq) |
| 191 | } |
| 192 | other => panic!("expected Committed, got {other:?}"), |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// Every changeset is listed and every blob reads back with its digest. |
| 197 | fn check_readable(store: &SynapseStore) -> Result<usize, String> { |
| 198 | let all = store |
| 199 | .list_changesets(None, None, None) |
| 200 | .map_err(|e| format!("list: {e:?}"))?; |
| 201 | for c in &all { |
| 202 | for m in &c.envelope.mutations { |
| 203 | if let MutationOp::Upsert { |
| 204 | blob_digest, |
| 205 | size_bytes, |
| 206 | .. |
| 207 | } = &m.op |
| 208 | { |
| 209 | let bytes = store |
| 210 | .get_blob_visible(*blob_digest, None, None) |
| 211 | .map_err(|e| format!("blob {blob_digest}: {e:?}"))?; |
| 212 | if bytes.len() as u64 != *size_bytes { |
| 213 | return Err(format!("blob {blob_digest}: wrong length")); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | Ok(all.len()) |
| 219 | } |
| 220 | |
| 221 | // --- refusal rules --------------------------------------------------------------- |
| 222 | |
| 223 | #[test] |
| 224 | fn r1_refuses_a_device_carrying_a_filesystem_or_partition_signature() { |
| 225 | let dir = temp_dir("sig"); |
| 226 | let cases: [(&str, usize, &[u8]); 4] = [ |
| 227 | ("ext4", 1080, &[0x53, 0xEF]), |
| 228 | ("gpt", 512, b"EFI PART"), |
| 229 | ("xfs", 0, b"XFSB"), |
| 230 | ("luks", 0, b"LUKS\xba\xbe"), |
| 231 | ]; |
| 232 | for (name, off, sig) in cases { |
| 233 | let path = dir.join(format!("{name}.img")); |
| 234 | make_device_file(&path, TEST_DEVICE_BYTES); |
| 235 | { |
| 236 | use std::os::unix::fs::FileExt; |
| 237 | let f = OpenOptions::new().write(true).open(&path).unwrap(); |
| 238 | f.write_all_at(sig, off as u64).unwrap(); |
| 239 | f.write_all_at(b"user data that must survive", 64 * 1024 + 7) |
| 240 | .unwrap(); |
| 241 | } |
| 242 | let before = fs::read(&path).unwrap(); |
| 243 | let cfg = BlockDeviceConfig { |
| 244 | format: FormatPolicy::FormatIfBlank, |
| 245 | meta_region_bytes: TEST_META_BYTES, |
| 246 | ..BlockDeviceConfig::new(&path) |
| 247 | }; |
| 248 | let err = SynapseStore::open_block_device( |
| 249 | &cfg, |
| 250 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 251 | STRICT, |
| 252 | limits(), |
| 253 | ) |
| 254 | .err() |
| 255 | .unwrap_or_else(|| panic!("{name}: a device with a signature was opened")); |
| 256 | assert_eq!(err.code, RefusalCode::IoFailure, "{name}: {err:?}"); |
| 257 | assert!(err.message.contains("carries a"), "{name}: {}", err.message); |
| 258 | assert_eq!( |
| 259 | fs::read(&path).unwrap(), |
| 260 | before, |
| 261 | "{name}: refused device changed" |
| 262 | ); |
| 263 | // The explicit override formats over it. |
| 264 | let cfg = BlockDeviceConfig { |
| 265 | allow_foreign_signature: true, |
| 266 | ..cfg |
| 267 | }; |
| 268 | let mut s = SynapseStore::open_block_device( |
| 269 | &cfg, |
| 270 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 271 | STRICT, |
| 272 | limits(), |
| 273 | ) |
| 274 | .unwrap_or_else(|e| panic!("{name}: override refused: {e:?}")); |
| 275 | assert_eq!(commit(&mut s, &key(1), name).unwrap(), WalSeq(1)); |
| 276 | drop(s); |
| 277 | let dev = DirectFile::open(&path).unwrap(); |
| 278 | assert_eq!( |
| 279 | classify_device(&dev).unwrap(), |
| 280 | DeviceLabel::Synapse, |
| 281 | "{name}" |
| 282 | ); |
| 283 | } |
| 284 | let _ = fs::remove_dir_all(&dir); |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn r1_refuses_unknown_label_bytes_and_blank_devices_without_format() { |
| 289 | let dir = temp_dir("unknown"); |
| 290 | let path = dir.join("dev.img"); |
| 291 | make_device_file(&path, TEST_DEVICE_BYTES); |
| 292 | let cfg = BlockDeviceConfig { |
| 293 | format: FormatPolicy::OpenExisting, |
| 294 | ..BlockDeviceConfig::new(&path) |
| 295 | }; |
| 296 | let err = BlockDevice::open_path(&cfg, SEG).unwrap_err(); |
| 297 | assert!(err.message.contains("blank"), "{}", err.message); |
| 298 | { |
| 299 | use std::os::unix::fs::FileExt; |
| 300 | let f = OpenOptions::new().write(true).open(&path).unwrap(); |
| 301 | f.write_all_at(b"\x01", 100 * 1024).unwrap(); |
| 302 | } |
| 303 | let cfg = BlockDeviceConfig::new(&path); |
| 304 | let err = BlockDevice::open_path(&cfg, SEG).unwrap_err(); |
| 305 | assert!(err.message.contains("not blank"), "{}", err.message); |
| 306 | let _ = fs::remove_dir_all(&dir); |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn r1_opens_only_the_configured_path() { |
| 311 | let dir = temp_dir("paths"); |
| 312 | let path = dir.join("dev.img"); |
| 313 | make_device_file(&path, TEST_DEVICE_BYTES); |
| 314 | // Relative path. |
| 315 | let err = DirectFile::open(Path::new("dev.img")).unwrap_err(); |
| 316 | assert!(err.message.contains("absolute"), "{}", err.message); |
| 317 | // A directory. |
| 318 | let err = DirectFile::open(&dir).unwrap_err(); |
| 319 | assert!(err.message.contains("neither"), "{}", err.message); |
| 320 | // A symbolic link to a valid device file. |
| 321 | let link = dir.join("link.img"); |
| 322 | std::os::unix::fs::symlink(&path, &link).unwrap(); |
| 323 | let err = DirectFile::open(&link).unwrap_err(); |
| 324 | assert!(err.message.contains("symbolic"), "{}", err.message); |
| 325 | // Missing file: nothing is created. |
| 326 | let missing = dir.join("missing.img"); |
| 327 | assert!(DirectFile::open(&missing).is_err()); |
| 328 | assert!(!missing.exists()); |
| 329 | // Length not a multiple of the block size. |
| 330 | let odd = dir.join("odd.img"); |
| 331 | make_device_file(&odd, TEST_DEVICE_BYTES + 512); |
| 332 | let err = DirectFile::open(&odd).unwrap_err(); |
| 333 | assert!(err.message.contains("multiple"), "{}", err.message); |
| 334 | // The configured file itself opens, and unaligned I/O round-trips through O_DIRECT. |
| 335 | let d = DirectFile::open(&path).unwrap(); |
| 336 | d.write_at(b"0123456789", 4090).unwrap(); |
| 337 | d.flush().unwrap(); |
| 338 | let mut b = [0u8; 12]; |
| 339 | d.read_at(&mut b, 4089).unwrap(); |
| 340 | assert_eq!(&b, b"\x000123456789\x00"); |
| 341 | let _ = fs::remove_dir_all(&dir); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn r1_classifies_known_signatures() { |
| 346 | let label = |patches: Vec<(u64, Vec<u8>)>| { |
| 347 | classify_device(&SparseIo { |
| 348 | len: LABEL_BYTES, |
| 349 | patches, |
| 350 | }) |
| 351 | .unwrap() |
| 352 | }; |
| 353 | assert_eq!(label(vec![]), DeviceLabel::Blank); |
| 354 | assert_eq!(label(vec![(100 * 1024, vec![1])]), DeviceLabel::Unknown); |
| 355 | assert_eq!( |
| 356 | label(vec![(4096, SUPERBLOCK_MAGIC.to_vec())]), |
| 357 | DeviceLabel::Synapse |
| 358 | ); |
| 359 | // A GPT disk carries a protective MBR too: the GPT name wins. |
| 360 | assert_eq!( |
| 361 | label(vec![(510, vec![0x55, 0xAA]), (512, b"EFI PART".to_vec())]), |
| 362 | DeviceLabel::Foreign("GPT partition table") |
| 363 | ); |
| 364 | } |
| 365 | |
| 366 | /// A sparse read-only device: zeros except for `patches`. |
| 367 | #[derive(Debug)] |
| 368 | struct SparseIo { |
| 369 | len: u64, |
| 370 | patches: Vec<(u64, Vec<u8>)>, |
| 371 | } |
| 372 | |
| 373 | impl BlockIo for SparseIo { |
| 374 | fn len(&self) -> u64 { |
| 375 | self.len |
| 376 | } |
| 377 | fn read_at(&self, buf: &mut [u8], off: u64) -> std::io::Result<()> { |
| 378 | buf.fill(0); |
| 379 | let end = off + buf.len() as u64; |
| 380 | for (at, bytes) in &self.patches { |
| 381 | for (i, b) in bytes.iter().enumerate() { |
| 382 | let p = at + i as u64; |
| 383 | if p >= off && p < end { |
| 384 | buf[(p - off) as usize] = *b; |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | Ok(()) |
| 389 | } |
| 390 | fn write_at(&self, _: &[u8], _: u64) -> std::io::Result<()> { |
| 391 | Err(std::io::Error::other("read-only")) |
| 392 | } |
| 393 | fn flush(&self) -> std::io::Result<()> { |
| 394 | Ok(()) |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | /// Large enough for every offset (btrfs's 256 GiB mirror) and not a multiple of 64 KiB, |
| 399 | /// so the MD RAID and ZFS end rounding is exercised. |
| 400 | const PIN_LEN: u64 = (300 << 30) + (12 << 20) + 3 * 4096; |
| 401 | const PIN_ZFS_END: u64 = PIN_LEN & !(256 * 1024 - 1); |
| 402 | const PIN_MD: &[u8] = &[0xFC, 0x4E, 0x2B, 0xA9]; |
| 403 | const PIN_ZFS_LE: &[u8] = &[0x0C, 0xB1, 0xBA, 0, 0, 0, 0, 0]; |
| 404 | const PIN_ZFS_BE: &[u8] = &[0, 0, 0, 0, 0, 0xBA, 0xB1, 0x0C]; |
| 405 | |
| 406 | /// A device carrying only `magic` at `off` is refused as `name`. |
| 407 | fn pinned(name: &str, off: u64, magic: &[u8]) { |
| 408 | let io = SparseIo { |
| 409 | len: PIN_LEN, |
| 410 | patches: vec![(off, magic.to_vec())], |
| 411 | }; |
| 412 | match classify_device(&io).unwrap() { |
| 413 | DeviceLabel::Foreign(n) => assert_eq!(n, name), |
| 414 | other => panic!("{name}: classified {other:?}"), |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | // One test per signature, written independently of `SIGNATURES`: deleting or moving an |
| 419 | // entry turns its test red. |
| 420 | macro_rules! pin { |
| 421 | ($($t:ident: $name:expr, $off:expr, $magic:expr;)*) => { |
| 422 | $(#[test] fn $t() { pinned($name, $off, $magic) })* |
| 423 | }; |
| 424 | } |
| 425 | |
| 426 | pin! { |
| 427 | r1_sig_gpt: "GPT partition table", 512, b"EFI PART"; |
| 428 | r1_sig_gpt_4k: "GPT partition table (4 KiB sectors)", 4096, b"EFI PART"; |
| 429 | r1_sig_gpt_backup: "GPT backup header", PIN_LEN - 512, b"EFI PART"; |
| 430 | r1_sig_gpt_backup_4k: "GPT backup header (4 KiB sectors)", PIN_LEN - 4096, b"EFI PART"; |
| 431 | r1_sig_ext: "ext2/ext3/ext4", 1080, &[0x53, 0xEF]; |
| 432 | r1_sig_xfs: "XFS", 0, b"XFSB"; |
| 433 | r1_sig_btrfs: "btrfs", 0x1_0040, b"_BHRfS_M"; |
| 434 | r1_sig_btrfs_64m: "btrfs (mirror at 64 MiB)", 64 * 1024 * 1024 + 0x40, b"_BHRfS_M"; |
| 435 | r1_sig_btrfs_256g: "btrfs (mirror at 256 GiB)", (256 << 30) + 0x40, b"_BHRfS_M"; |
| 436 | r1_sig_ntfs: "NTFS", 3, b"NTFS "; |
| 437 | r1_sig_exfat: "exFAT", 3, b"EXFAT "; |
| 438 | r1_sig_fat16: "FAT12/FAT16", 54, b"FAT1"; |
| 439 | r1_sig_fat32: "FAT32", 82, b"FAT32 "; |
| 440 | r1_sig_luks: "LUKS", 0, b"LUKS\xba\xbe"; |
| 441 | r1_sig_lvm0: "LVM2 physical volume (sector 0)", 0, b"LABELONE"; |
| 442 | r1_sig_lvm1: "LVM2 physical volume (sector 1)", 512, b"LABELONE"; |
| 443 | r1_sig_lvm2: "LVM2 physical volume (sector 2)", 1024, b"LABELONE"; |
| 444 | r1_sig_lvm3: "LVM2 physical volume (sector 3)", 1536, b"LABELONE"; |
| 445 | r1_sig_swap: "Linux swap (4 KiB pages)", 4086, b"SWAPSPACE2"; |
| 446 | r1_sig_swap_old: "Linux swap, old (4 KiB pages)", 4086, b"SWAP-SPACE"; |
| 447 | r1_sig_swap_16k: "Linux swap (16 KiB pages)", 16374, b"SWAPSPACE2"; |
| 448 | r1_sig_swap_64k: "Linux swap (64 KiB pages)", 65526, b"SWAPSPACE2"; |
| 449 | r1_sig_iso9660: "ISO 9660", 0x8001, b"CD001"; |
| 450 | r1_sig_squashfs: "squashfs", 0, b"hsqs"; |
| 451 | r1_sig_f2fs: "F2FS", 1024, &[0x10, 0x20, 0xF5, 0xF2]; |
| 452 | r1_sig_md_1_2: "Linux MD RAID (1.2)", 4096, PIN_MD; |
| 453 | r1_sig_md_1_1: "Linux MD RAID (1.1)", 0, PIN_MD; |
| 454 | r1_sig_md_1_0: "Linux MD RAID (1.0)", (PIN_LEN - 8192) & !4095, PIN_MD; |
| 455 | r1_sig_md_0_90: "Linux MD RAID (0.90)", (PIN_LEN & !0xFFFF) - 0x10000, PIN_MD; |
| 456 | r1_sig_zfs_l0: "ZFS label L0", 128 * 1024 + 5 * 1024, PIN_ZFS_LE; |
| 457 | r1_sig_zfs_l0_be: "ZFS label L0 (big-endian)", 255 * 1024, PIN_ZFS_BE; |
| 458 | r1_sig_zfs_l1: "ZFS label L1", 384 * 1024, PIN_ZFS_LE; |
| 459 | r1_sig_zfs_l1_be: "ZFS label L1 (big-endian)", 400 * 1024, PIN_ZFS_BE; |
| 460 | r1_sig_zfs_l2: "ZFS label L2", PIN_ZFS_END - 512 * 1024 + 192 * 1024, PIN_ZFS_LE; |
| 461 | r1_sig_zfs_l2_be: "ZFS label L2 (big-endian)", PIN_ZFS_END - 384 * 1024, PIN_ZFS_BE; |
| 462 | r1_sig_zfs_l3: "ZFS label L3", PIN_ZFS_END - 128 * 1024, PIN_ZFS_LE; |
| 463 | r1_sig_zfs_l3_be: "ZFS label L3 (big-endian)", PIN_ZFS_END - 1024, PIN_ZFS_BE; |
| 464 | r1_sig_mbr: "MBR or boot sector", 510, &[0x55, 0xAA]; |
| 465 | } |
| 466 | |
| 467 | /// The pinned list and `SIGNATURES` have the same size: a new entry needs a pin test. |
| 468 | #[test] |
| 469 | fn r1_every_signature_has_a_pin_test() { |
| 470 | assert_eq!(SIGNATURES.len(), 38); |
| 471 | } |
| 472 | |
| 473 | // --- superblock and metadata commits ---------------------------------------------- |
| 474 | |
| 475 | #[test] |
| 476 | fn r1_superblock_falls_back_to_the_older_copy_when_the_newest_is_damaged() { |
| 477 | let io = MemIo::new(vec![0u8; 8 << 20]); |
| 478 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, 64 * 1024); |
| 479 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 480 | dev.write_named("a", b"first").unwrap(); |
| 481 | dev.write_named("b", b"second").unwrap(); |
| 482 | let g = dev.generation(); |
| 483 | let geo = dev.geometry(); |
| 484 | drop(dev); |
| 485 | let reopen = |io: &MemIo| { |
| 486 | BlockDevice::open( |
| 487 | Box::new(MemIo::new(io.rec().image.clone())), |
| 488 | &mem_cfg(FormatPolicy::OpenExisting, 64 * 1024), |
| 489 | SEG, |
| 490 | ) |
| 491 | }; |
| 492 | let d = reopen(&io).unwrap(); |
| 493 | assert_eq!(d.read_named("b").as_deref(), Some(&b"second"[..])); |
| 494 | // Damage the newest superblock copy: the older one (without "b") is used. |
| 495 | let newest = (g % 2 * BLOCK) as usize; |
| 496 | let saved = io.rec().image[newest + 40]; |
| 497 | io.rec().image[newest + 40] ^= 0xFF; |
| 498 | let d = reopen(&io).unwrap(); |
| 499 | assert_eq!(d.generation(), g - 1); |
| 500 | assert_eq!(d.read_named("a").as_deref(), Some(&b"first"[..])); |
| 501 | assert_eq!(d.read_named("b"), None); |
| 502 | io.rec().image[newest + 40] = saved; |
| 503 | // Damage the metadata region the newest copy points at: same fallback. The byte is |
| 504 | // the last byte of "second" ("SBM1", count, then "a" and "b" entries: 41 bytes), so |
| 505 | // the region still decodes and only its digest catches the damage. |
| 506 | let d = reopen(&io).unwrap(); |
| 507 | assert_eq!(d.generation(), g); |
| 508 | let slot = d.meta_slot() as usize; |
| 509 | let region = geo.meta_offset[slot] as usize; |
| 510 | io.rec().image[region + 40] ^= 0x01; |
| 511 | let d = reopen(&io).unwrap(); |
| 512 | assert_eq!(d.generation(), g - 1); |
| 513 | assert_eq!(d.read_named("b"), None); |
| 514 | // Both copies damaged: refused, never formatted over. |
| 515 | let other = ((g - 1) % 2 * BLOCK) as usize; |
| 516 | io.rec().image[other + 40] ^= 0xFF; |
| 517 | let err = reopen(&io).unwrap_err(); |
| 518 | assert_eq!(err.code, RefusalCode::CheckpointCorrupt, "{err:?}"); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn r1_full_device_refuses_the_batch_and_keeps_every_ack() { |
| 523 | // Room for exactly 2 slots of 64 KiB after 2 MiB of label and metadata. |
| 524 | let io = MemIo::new(vec![0u8; (2 << 20) + 2 * (BLOCK + SEG) as usize]); |
| 525 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, 256 * 1024); |
| 526 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 527 | assert_eq!(dev.geometry().slot_count, 2); |
| 528 | let mut s = SynapseStore::open_on_device(dev, cfg.path.clone(), STRICT, limits()).unwrap(); |
| 529 | let mut acked = 0; |
| 530 | let err = loop { |
| 531 | match commit(&mut s, &key(5), &format!("full-{acked}")) { |
| 532 | Ok(seq) => acked = seq.0, |
| 533 | Err(e) => break e, |
| 534 | } |
| 535 | }; |
| 536 | assert_eq!(acked, 16, "two slots of 8 batches"); |
| 537 | assert_eq!(err.code, RefusalCode::IoFailure, "{err:?}"); |
| 538 | assert!(err.message.contains("device full"), "{}", err.message); |
| 539 | assert!(s.poisoned().is_none()); |
| 540 | assert_eq!(check_readable(&s).unwrap(), 16); |
| 541 | drop(s); |
| 542 | let dev = BlockDevice::open( |
| 543 | Box::new(MemIo::new(io.rec().image.clone())), |
| 544 | &mem_cfg(FormatPolicy::OpenExisting, 256 * 1024), |
| 545 | SEG, |
| 546 | ) |
| 547 | .unwrap(); |
| 548 | let s = SynapseStore::open_on_device(dev, cfg.path, STRICT, limits()).unwrap(); |
| 549 | assert_eq!(s.committed_seq(), WalSeq(16)); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn r1_failed_device_flush_acknowledges_nothing() { |
| 554 | let io = MemIo::new(vec![0u8; 4 << 20]); |
| 555 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, 256 * 1024); |
| 556 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 557 | let mut s = SynapseStore::open_on_device(dev, cfg.path.clone(), STRICT, limits()).unwrap(); |
| 558 | for i in 0..3 { |
| 559 | commit(&mut s, &key(6), &format!("ff-{i}")).unwrap(); |
| 560 | } |
| 561 | io.rec().fail_flushes = true; |
| 562 | let err = commit(&mut s, &key(6), "ff-fail").unwrap_err(); |
| 563 | assert_eq!(err.code, RefusalCode::IoFailure, "{err:?}"); |
| 564 | assert_eq!(s.committed_seq(), WalSeq(3)); |
| 565 | io.rec().fail_flushes = false; |
| 566 | drop(s); |
| 567 | let dev = BlockDevice::open( |
| 568 | Box::new(MemIo::new(io.rec().image.clone())), |
| 569 | &mem_cfg(FormatPolicy::OpenExisting, 256 * 1024), |
| 570 | SEG, |
| 571 | ) |
| 572 | .unwrap(); |
| 573 | let mut s = SynapseStore::open_on_device(dev, cfg.path, TRUNCATE, limits()).unwrap(); |
| 574 | assert!(s.committed_seq() == WalSeq(3) || s.committed_seq() == WalSeq(4)); |
| 575 | let next = commit(&mut s, &key(6), "ff-after").unwrap(); |
| 576 | assert_eq!(next.0, s.committed_seq().0); |
| 577 | assert_eq!(check_readable(&s).unwrap() as u64, next.0); |
| 578 | } |
| 579 | |
| 580 | // --- power-cut simulation ----------------------------------------------------------- |
| 581 | |
| 582 | const PC_DEVICE: usize = 4 << 20; |
| 583 | const PC_META: u64 = 256 * 1024; |
| 584 | const SECTOR: usize = 512; |
| 585 | |
| 586 | struct Workload { |
| 587 | base: Vec<u8>, |
| 588 | ops: Vec<Op>, |
| 589 | /// `(ops completed when the ack returned, acknowledged seq)`. |
| 590 | acks: Vec<(usize, u64)>, |
| 591 | max_seq: u64, |
| 592 | } |
| 593 | |
| 594 | /// Format, 20 commits across three segments, a checkpoint, 6 more commits, reopen, |
| 595 | /// 2 more commits: every device write and flush is logged. |
| 596 | fn record_workload() -> Workload { |
| 597 | let mut base = vec![0u8; PC_DEVICE]; |
| 598 | base[LABEL_BYTES as usize..].copy_from_slice(&garbage(PC_DEVICE - LABEL_BYTES as usize, 47)); |
| 599 | let io = MemIo::new(base.clone()); |
| 600 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, PC_META); |
| 601 | let mut acks = Vec::new(); |
| 602 | let mut n = 0u64; |
| 603 | let mut run = |s: &mut SynapseStore, count: usize, acks: &mut Vec<(usize, u64)>| { |
| 604 | for _ in 0..count { |
| 605 | let seq = commit(s, &key(9), &format!("pc-{n}")).unwrap(); |
| 606 | n += 1; |
| 607 | acks.push((io.rec().ops.len(), seq.0)); |
| 608 | } |
| 609 | }; |
| 610 | { |
| 611 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 612 | let mut s = SynapseStore::open_on_device(dev, cfg.path.clone(), STRICT, limits()).unwrap(); |
| 613 | run(&mut s, 20, &mut acks); |
| 614 | s.checkpoint_and_compact(1000).unwrap(); |
| 615 | // The checkpoint acknowledges nothing new, but its commits are cut points too. |
| 616 | run(&mut s, 6, &mut acks); |
| 617 | } |
| 618 | { |
| 619 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 620 | let mut s = SynapseStore::open_on_device(dev, cfg.path.clone(), STRICT, limits()).unwrap(); |
| 621 | run(&mut s, 2, &mut acks); |
| 622 | } |
| 623 | let ops = io.rec().ops.clone(); |
| 624 | let max_seq = acks.last().unwrap().1; |
| 625 | Workload { |
| 626 | base, |
| 627 | ops, |
| 628 | acks, |
| 629 | max_seq, |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | fn apply(img: &mut [u8], op: &Op) { |
| 634 | if let Op::Write { off, data } = op { |
| 635 | img[*off as usize..*off as usize + data.len()].copy_from_slice(data); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[derive(Debug, Default)] |
| 640 | struct Tally { |
| 641 | states: usize, |
| 642 | opened: usize, |
| 643 | strict_torn_refusals: usize, |
| 644 | fail_closed: usize, |
| 645 | continued: usize, |
| 646 | } |
| 647 | |
| 648 | /// Recover a crash image and check it. `must_open`: the image must open (with every |
| 649 | /// ack) under `TruncateTornTail`; otherwise failing closed is allowed. |
| 650 | fn check_image(img: &[u8], acked: u64, max_seq: u64, must_open: bool, what: &str, t: &mut Tally) { |
| 651 | t.states += 1; |
| 652 | let open = |policy| -> SynapseResult<SynapseStore> { |
| 653 | let dev = BlockDevice::open( |
| 654 | Box::new(MemIo::new(img.to_vec())), |
| 655 | &mem_cfg(FormatPolicy::OpenExisting, PC_META), |
| 656 | SEG, |
| 657 | )?; |
| 658 | SynapseStore::open_on_device(dev, PathBuf::from("/r1-test/in-memory"), policy, limits()) |
| 659 | }; |
| 660 | let verify = |s: &SynapseStore, policy: &str| { |
| 661 | let c = s.committed_seq().0; |
| 662 | assert!( |
| 663 | c >= acked && c <= max_seq, |
| 664 | "{what} ({policy}): committed {c}, acknowledged {acked}, written {max_seq}" |
| 665 | ); |
| 666 | let listed = check_readable(s).unwrap_or_else(|e| panic!("{what} ({policy}): {e}")); |
| 667 | assert_eq!(listed as u64, c, "{what} ({policy}): changesets listed"); |
| 668 | }; |
| 669 | match open(TRUNCATE) { |
| 670 | Ok(mut s) => { |
| 671 | t.opened += 1; |
| 672 | verify(&s, "truncate"); |
| 673 | // Sample: the recovered store keeps working and reopens. |
| 674 | if t.states.is_multiple_of(23) { |
| 675 | let next = commit(&mut s, &key(10), &format!("after-{}", t.states)) |
| 676 | .unwrap_or_else(|e| panic!("{what}: commit after recovery: {e:?}")); |
| 677 | assert_eq!(next.0, s.committed_seq().0); |
| 678 | t.continued += 1; |
| 679 | } |
| 680 | } |
| 681 | Err(e) if acked == 0 => { |
| 682 | // Before the first acknowledgment (the format flush has not returned) a |
| 683 | // device may refuse to open; nothing was promised. |
| 684 | let _ = e; |
| 685 | } |
| 686 | Err(e) if !must_open => { |
| 687 | t.fail_closed += 1; |
| 688 | let _ = e; |
| 689 | } |
| 690 | Err(e) => panic!("{what}: truncating recovery refused with acks up to {acked}: {e:?}"), |
| 691 | } |
| 692 | match open(STRICT) { |
| 693 | Ok(s) => verify(&s, "strict"), |
| 694 | Err(e) if e.code == RefusalCode::WalTornFrame => t.strict_torn_refusals += 1, |
| 695 | Err(_) if acked == 0 || !must_open => {} |
| 696 | Err(e) => panic!("{what}: strict recovery refused other than as torn: {e:?}"), |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | fn acked_at(w: &Workload, completed_ops: usize) -> u64 { |
| 701 | w.acks |
| 702 | .iter() |
| 703 | .filter(|(at, _)| *at <= completed_ops) |
| 704 | .map(|(_, s)| *s) |
| 705 | .max() |
| 706 | .unwrap_or(0) |
| 707 | } |
| 708 | |
| 709 | #[test] |
| 710 | fn r1_power_cut_at_every_write_boundary_keeps_every_ack() { |
| 711 | let w = record_workload(); |
| 712 | let writes = w |
| 713 | .ops |
| 714 | .iter() |
| 715 | .filter(|o| matches!(o, Op::Write { .. })) |
| 716 | .count(); |
| 717 | let flushes = w.ops.len() - writes; |
| 718 | let mut prefix = Tally::default(); |
| 719 | let mut suffix = Tally::default(); |
| 720 | let mut lost = Tally::default(); |
| 721 | let mut hole = Tally::default(); |
| 722 | let mut img = w.base.clone(); |
| 723 | let mut last_flush = 0usize; // ops[..last_flush] are durable for sure |
| 724 | for (i, op) in w.ops.iter().enumerate() { |
| 725 | // Cut while op `i` is in flight: ops[..i] were issued and completed. |
| 726 | let acked = acked_at(&w, i); |
| 727 | if let Op::Write { off, data } = op { |
| 728 | let sectors = data.len().div_ceil(SECTOR); |
| 729 | for k in 0..sectors { |
| 730 | let mut c = img.clone(); |
| 731 | let n = k * SECTOR; |
| 732 | c[*off as usize..*off as usize + n].copy_from_slice(&data[..n]); |
| 733 | check_image( |
| 734 | &c, |
| 735 | acked, |
| 736 | w.max_seq, |
| 737 | true, |
| 738 | &format!("op {i} prefix {k}/{sectors}"), |
| 739 | &mut prefix, |
| 740 | ); |
| 741 | let mut c = img.clone(); |
| 742 | let from = data.len() - n; |
| 743 | c[*off as usize + from..*off as usize + data.len()].copy_from_slice(&data[from..]); |
| 744 | check_image( |
| 745 | &c, |
| 746 | acked, |
| 747 | w.max_seq, |
| 748 | true, |
| 749 | &format!("op {i} suffix {k}/{sectors}"), |
| 750 | &mut suffix, |
| 751 | ); |
| 752 | } |
| 753 | for k in 1..sectors.saturating_sub(1) { |
| 754 | let mut c = img.clone(); |
| 755 | apply(&mut c, op); |
| 756 | let at = *off as usize + k * SECTOR; |
| 757 | let end = (at + SECTOR).min(*off as usize + data.len()); |
| 758 | c[at..end].copy_from_slice(&w_before(&w, i, at, end)); |
| 759 | check_image( |
| 760 | &c, |
| 761 | acked, |
| 762 | w.max_seq, |
| 763 | false, |
| 764 | &format!("op {i} hole {k}/{sectors}"), |
| 765 | &mut hole, |
| 766 | ); |
| 767 | } |
| 768 | } |
| 769 | // Lost write: one write issued since the last flush never landed. |
| 770 | for j in last_flush..i { |
| 771 | if !matches!(w.ops[j], Op::Write { .. }) { |
| 772 | continue; |
| 773 | } |
| 774 | let mut c = w.base.clone(); |
| 775 | for (m, o) in w.ops[..i].iter().enumerate() { |
| 776 | if m != j { |
| 777 | apply(&mut c, o); |
| 778 | } |
| 779 | } |
| 780 | check_image( |
| 781 | &c, |
| 782 | acked, |
| 783 | w.max_seq, |
| 784 | true, |
| 785 | &format!("cut {i} lost write {j}"), |
| 786 | &mut lost, |
| 787 | ); |
| 788 | } |
| 789 | apply(&mut img, op); |
| 790 | if matches!(op, Op::Flush) { |
| 791 | last_flush = i + 1; |
| 792 | } |
| 793 | } |
| 794 | // The finished workload. |
| 795 | check_image(&img, w.max_seq, w.max_seq, true, "complete", &mut prefix); |
| 796 | eprintln!( |
| 797 | "R1 power-cut simulation: {} device writes, {flushes} flushes, {} acks; \ |
| 798 | prefix {prefix:?}; suffix {suffix:?}; lost-write {lost:?}; hole {hole:?}", |
| 799 | writes, |
| 800 | w.acks.len() |
| 801 | ); |
| 802 | assert!(prefix.states > 1000 && suffix.states > 1000 && lost.states > 20); |
| 803 | assert_eq!( |
| 804 | prefix.fail_closed + suffix.fail_closed + lost.fail_closed, |
| 805 | 0 |
| 806 | ); |
| 807 | } |
| 808 | |
| 809 | /// Bytes `at..end` of the device just before op `i` (for the hole model). |
| 810 | fn w_before(w: &Workload, i: usize, at: usize, end: usize) -> Vec<u8> { |
| 811 | let mut v = w.base[at..end].to_vec(); |
| 812 | for o in &w.ops[..i] { |
| 813 | if let Op::Write { off, data } = o { |
| 814 | let (o0, o1) = (*off as usize, *off as usize + data.len()); |
| 815 | let (s, e) = (at.max(o0), end.min(o1)); |
| 816 | if s < e { |
| 817 | v[s - at..e - at].copy_from_slice(&data[s - o0..e - o0]); |
| 818 | } |
| 819 | } |
| 820 | } |
| 821 | v |
| 822 | } |
| 823 | |
| 824 | // --- review of PR #103 ---------------------------------------------------------------- |
| 825 | |
| 826 | /// Reviewer's scenario (B2): 10 acknowledged changes across two slots, then one damaged |
| 827 | /// byte in the newest superblock copy (the rotation commit that raised the segment |
| 828 | /// count). Recovery may refuse loudly; it must never open with fewer changes. |
| 829 | #[test] |
| 830 | fn r1_lost_newest_superblock_never_drops_acknowledged_changes() { |
| 831 | let io = MemIo::new(vec![0u8; 4 << 20]); |
| 832 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, 256 * 1024); |
| 833 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 834 | let mut s = SynapseStore::open_on_device(dev, cfg.path.clone(), TRUNCATE, limits()).unwrap(); |
| 835 | for i in 0..10 { |
| 836 | commit(&mut s, &key(8), &format!("lost-sb-{i}")).unwrap(); |
| 837 | } |
| 838 | drop(s); |
| 839 | let reopen_dev = |io: &MemIo| { |
| 840 | BlockDevice::open( |
| 841 | Box::new(MemIo::new(io.rec().image.clone())), |
| 842 | &mem_cfg(FormatPolicy::OpenExisting, 256 * 1024), |
| 843 | SEG, |
| 844 | ) |
| 845 | }; |
| 846 | let dev = reopen_dev(&io).unwrap(); |
| 847 | assert_eq!( |
| 848 | dev.segment_count(), |
| 849 | 2, |
| 850 | "8 batches per slot: 10 changes use 2 slots" |
| 851 | ); |
| 852 | let newest = (dev.generation() % 2 * BLOCK) as usize; |
| 853 | drop(dev); |
| 854 | io.rec().image[newest + 40] ^= 0xFF; |
| 855 | for policy in [TRUNCATE, STRICT] { |
| 856 | let opened = reopen_dev(&io) |
| 857 | .and_then(|dev| SynapseStore::open_on_device(dev, cfg.path.clone(), policy, limits())); |
| 858 | match opened { |
| 859 | Ok(s) => { |
| 860 | assert_eq!( |
| 861 | s.committed_seq(), |
| 862 | WalSeq(10), |
| 863 | "{policy:?}: acknowledged changes lost" |
| 864 | ); |
| 865 | assert_eq!(check_readable(&s).unwrap(), 10, "{policy:?}"); |
| 866 | } |
| 867 | Err(e) => assert_eq!(e.code, RefusalCode::CheckpointCorrupt, "{policy:?}: {e:?}"), |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | /// N4: a second opener of the same device (here a device file) is refused while the |
| 873 | /// first holds it. |
| 874 | #[test] |
| 875 | fn r1_a_second_opener_of_the_device_is_refused() { |
| 876 | let dir = temp_dir("lock"); |
| 877 | let path = dir.join("dev.img"); |
| 878 | make_device_file(&path, TEST_DEVICE_BYTES); |
| 879 | let first = DirectFile::open(&path).unwrap(); |
| 880 | let err = DirectFile::open(&path).unwrap_err(); |
| 881 | assert!(err.message.contains("in use"), "{}", err.message); |
| 882 | drop(first); |
| 883 | DirectFile::open(&path).unwrap(); |
| 884 | let _ = fs::remove_dir_all(&dir); |
| 885 | } |
| 886 | |
| 887 | /// N1: a device whose label area is zero but that carries a signature near its end |
| 888 | /// (backup GPT header, MD RAID 0.90 or 1.0 superblock, ZFS label L2 or L3) is refused |
| 889 | /// and left unchanged, even with `FormatIfBlank`. |
| 890 | #[test] |
| 891 | fn r1_refuses_a_device_whose_signature_is_only_at_its_end() { |
| 892 | let dir = temp_dir("endsig"); |
| 893 | let len = TEST_DEVICE_BYTES; |
| 894 | let md = [0xFC, 0x4E, 0x2B, 0xA9]; |
| 895 | let zfs_le = 0x00ba_b10c_u64.to_le_bytes(); |
| 896 | let zfs_end = len & !(256 * 1024 - 1); |
| 897 | let cases: [(&str, u64, &[u8]); 5] = [ |
| 898 | ("gpt-backup", len - 512, b"EFI PART"), |
| 899 | ("md-0.90", (len & !0xFFFF) - 0x10000, &md), |
| 900 | ("md-1.0", (len - 8192) & !4095, &md), |
| 901 | ("zfs-l2", zfs_end - 512 * 1024 + 128 * 1024, &zfs_le), |
| 902 | ( |
| 903 | "zfs-l3", |
| 904 | zfs_end - 256 * 1024 + 128 * 1024 + 3 * 1024, |
| 905 | &zfs_le, |
| 906 | ), |
| 907 | ]; |
| 908 | for (name, off, sig) in cases { |
| 909 | let path = dir.join(format!("{name}.img")); |
| 910 | make_device_file(&path, len); |
| 911 | { |
| 912 | use std::os::unix::fs::FileExt; |
| 913 | let f = OpenOptions::new().write(true).open(&path).unwrap(); |
| 914 | f.write_all_at(sig, off).unwrap(); |
| 915 | f.write_all_at(b"user data that must survive", 2 << 20) |
| 916 | .unwrap(); |
| 917 | } |
| 918 | let before = fs::read(&path).unwrap(); |
| 919 | let cfg = BlockDeviceConfig { |
| 920 | format: FormatPolicy::FormatIfBlank, |
| 921 | meta_region_bytes: TEST_META_BYTES, |
| 922 | ..BlockDeviceConfig::new(&path) |
| 923 | }; |
| 924 | let opened = SynapseStore::open_block_device( |
| 925 | &cfg, |
| 926 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 927 | STRICT, |
| 928 | limits(), |
| 929 | ); |
| 930 | assert!( |
| 931 | opened.is_err(), |
| 932 | "{name}: a device with an end signature was formatted" |
| 933 | ); |
| 934 | assert_eq!( |
| 935 | fs::read(&path).unwrap(), |
| 936 | before, |
| 937 | "{name}: refused device changed" |
| 938 | ); |
| 939 | } |
| 940 | let _ = fs::remove_dir_all(&dir); |
| 941 | } |
| 942 | |
| 943 | // --- repair tool (issue #105) ----------------------------------------------------- |
| 944 | |
| 945 | mod repair_tests { |
| 946 | use super::*; |
| 947 | use crate::blockdev::repair::*; |
| 948 | use ed25519_dalek::Signer; |
| 949 | |
| 950 | const META: u64 = 256 * 1024; |
| 951 | const NOW: u64 = 1_790_000_000; |
| 952 | |
| 953 | fn operator() -> SigningKey { |
| 954 | SigningKey::from_bytes(&[0x0B; 32]) |
| 955 | } |
| 956 | |
| 957 | fn sha(b: &[u8]) -> [u8; 32] { |
| 958 | Sha256::digest(b).into() |
| 959 | } |
| 960 | |
| 961 | /// 10 acknowledged changes over two slots (8 batches per slot), then the newest |
| 962 | /// superblock copy (the rotation commit that raised the count to 2) damaged. |
| 963 | /// Returns the device, the damaged image, and the image before the damage. |
| 964 | fn damaged_fixture() -> (MemIo, Vec<u8>, Vec<u8>) { |
| 965 | let io = MemIo::new(vec![0u8; 4 << 20]); |
| 966 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, META); |
| 967 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 968 | let mut s = |
| 969 | SynapseStore::open_on_device(dev, cfg.path.clone(), TRUNCATE, limits()).unwrap(); |
| 970 | for i in 0..10 { |
| 971 | commit(&mut s, &key(9), &format!("repair-{i}")).unwrap(); |
| 972 | } |
| 973 | drop(s); |
| 974 | let pristine = io.rec().image.clone(); |
| 975 | let g = { |
| 976 | let d = BlockDevice::open( |
| 977 | Box::new(MemIo::new(pristine.clone())), |
| 978 | &mem_cfg(FormatPolicy::OpenExisting, META), |
| 979 | SEG, |
| 980 | ) |
| 981 | .unwrap(); |
| 982 | assert_eq!(d.segment_count(), 2); |
| 983 | d.generation() |
| 984 | }; |
| 985 | io.rec().image[(g % 2 * BLOCK) as usize + 40] ^= 0xFF; |
| 986 | let damaged = io.rec().image.clone(); |
| 987 | (io, damaged, pristine) |
| 988 | } |
| 989 | |
| 990 | fn open_dev(image: Vec<u8>) -> SynapseResult<Arc<BlockDevice>> { |
| 991 | BlockDevice::open( |
| 992 | Box::new(MemIo::new(image)), |
| 993 | &mem_cfg(FormatPolicy::OpenExisting, META), |
| 994 | SEG, |
| 995 | ) |
| 996 | } |
| 997 | |
| 998 | fn open_store(image: Vec<u8>) -> SynapseResult<SynapseStore> { |
| 999 | open_dev(image).and_then(|dev| { |
| 1000 | SynapseStore::open_on_device( |
| 1001 | dev, |
| 1002 | PathBuf::from("/r1-test/in-memory"), |
| 1003 | TRUNCATE, |
| 1004 | limits(), |
| 1005 | ) |
| 1006 | }) |
| 1007 | } |
| 1008 | |
| 1009 | fn open_seq(image: Vec<u8>) -> Result<u64, RefusalCode> { |
| 1010 | open_store(image) |
| 1011 | .map(|s| s.committed_seq().0) |
| 1012 | .map_err(|e| e.code) |
| 1013 | } |
| 1014 | |
| 1015 | /// Every changeset in seq order with the bytes of every blob it names. |
| 1016 | fn contents(s: &SynapseStore) -> Vec<(String, Vec<Vec<u8>>)> { |
| 1017 | let mut out = Vec::new(); |
| 1018 | for c in s.list_changesets(None, None, None).unwrap() { |
| 1019 | let mut blobs = Vec::new(); |
| 1020 | for m in &c.envelope.mutations { |
| 1021 | if let MutationOp::Upsert { blob_digest, .. } = &m.op { |
| 1022 | blobs.push(s.get_blob_visible(*blob_digest, None, None).unwrap()); |
| 1023 | } |
| 1024 | } |
| 1025 | out.push((format!("{:?}", c.envelope), blobs)); |
| 1026 | } |
| 1027 | out |
| 1028 | } |
| 1029 | |
| 1030 | fn writes(io: &MemIo) -> usize { |
| 1031 | io.rec() |
| 1032 | .ops |
| 1033 | .iter() |
| 1034 | .filter(|o| matches!(o, Op::Write { .. })) |
| 1035 | .count() |
| 1036 | } |
| 1037 | |
| 1038 | fn image(io: &MemIo) -> Vec<u8> { |
| 1039 | io.rec().image.clone() |
| 1040 | } |
| 1041 | |
| 1042 | #[test] |
| 1043 | fn r1_repair_report_lists_the_records_past_the_older_checkpoint() { |
| 1044 | let (io, damaged, _) = damaged_fixture(); |
| 1045 | assert_eq!( |
| 1046 | open_seq(damaged.clone()), |
| 1047 | Err(RefusalCode::CheckpointCorrupt) |
| 1048 | ); |
| 1049 | let before = writes(&io); |
| 1050 | let r = diagnose(&io).unwrap(); |
| 1051 | assert_eq!(writes(&io), before, "diagnose must not write"); |
| 1052 | assert_eq!(image(&io), damaged); |
| 1053 | assert_eq!(r.verdict, Verdict::OlderCheckpointLosesRange); |
| 1054 | assert_eq!(r.segment_count, 1); |
| 1055 | assert_eq!(r.lost.len(), 1); |
| 1056 | assert_eq!(r.lost[0].slot, 2); |
| 1057 | // Changes 9 and 10 sit past the older checkpoint, one batch each. |
| 1058 | let seqs: Vec<(u64, u32)> = r.lost[0] |
| 1059 | .batches |
| 1060 | .iter() |
| 1061 | .map(|b| (b.first_seq, b.records)) |
| 1062 | .collect(); |
| 1063 | assert_eq!(seqs, vec![(9, 1), (10, 1)]); |
| 1064 | assert!(r.history.is_empty()); |
| 1065 | let text = r.to_string(); |
| 1066 | assert!(text.contains("CORRUPT, CRC-32C mismatch"), "{text}"); |
| 1067 | assert!(text.contains("1 committed segments"), "{text}"); |
| 1068 | assert!( |
| 1069 | text.contains(&format!( |
| 1070 | "segment slot 2: device bytes {}..{}", |
| 1071 | r.lost[0].start, r.lost[0].end |
| 1072 | )), |
| 1073 | "{text}" |
| 1074 | ); |
| 1075 | assert!(text.contains("2 batches, 2 records"), "{text}"); |
| 1076 | assert!(text.contains("records 9..=9"), "{text}"); |
| 1077 | assert!(text.contains("records 10..=10"), "{text}"); |
| 1078 | assert!(text.contains("repair history: none"), "{text}"); |
| 1079 | assert!(text.contains("nothing was written"), "{text}"); |
| 1080 | assert!(text.contains("--roll-forward"), "{text}"); |
| 1081 | assert!(text.contains("--adopt-older-checkpoint"), "{text}"); |
| 1082 | } |
| 1083 | |
| 1084 | #[test] |
| 1085 | fn r1_repair_roll_forward_recovers_every_record_byte_identical() { |
| 1086 | let (io, damaged, pristine) = damaged_fixture(); |
| 1087 | // Red: the damaged image refuses to open. |
| 1088 | assert_eq!( |
| 1089 | open_seq(damaged.clone()), |
| 1090 | Err(RefusalCode::CheckpointCorrupt) |
| 1091 | ); |
| 1092 | let want = contents(&open_store(pristine.clone()).unwrap()); |
| 1093 | assert_eq!(want.len(), 10); |
| 1094 | let geo = open_dev(pristine).unwrap().geometry(); |
| 1095 | |
| 1096 | let dir = temp_dir("repair-roll"); |
| 1097 | let backup = dir.join("backup.bin"); |
| 1098 | let receipt = repair(&io, RepairAction::RollForward, &operator(), &backup, NOW).unwrap(); |
| 1099 | assert!(receipt.wrote); |
| 1100 | let after = image(&io); |
| 1101 | |
| 1102 | // Green: the store opens with all 10 changes, byte for byte the ones acknowledged. |
| 1103 | let s = open_store(after.clone()).unwrap(); |
| 1104 | assert_eq!(s.committed_seq().0, 10); |
| 1105 | assert_eq!(check_readable(&s), Ok(10)); |
| 1106 | assert_eq!(contents(&s), want); |
| 1107 | // The log itself was not touched: every segment slot byte is as it was. |
| 1108 | let d = geo.data_offset as usize; |
| 1109 | assert_eq!(sha(&after[d..]), sha(&damaged[d..])); |
| 1110 | |
| 1111 | // The signed receipt names the action and the range it kept. |
| 1112 | let e = receipt.entry.clone().unwrap(); |
| 1113 | assert_eq!(e.action, RepairAction::RollForward); |
| 1114 | assert_eq!((e.segment_count_before, e.segment_count_after), (1, 2)); |
| 1115 | assert_eq!(e.operator_key, operator().verifying_key().to_bytes()); |
| 1116 | assert_eq!(e.ranges.len(), 1); |
| 1117 | assert_eq!((e.ranges[0].slot, e.ranges[0].records), (2, 2)); |
| 1118 | assert_eq!(e.ranges[0].first_seq, 9); |
| 1119 | let (a, b) = (e.ranges[0].start as usize, e.ranges[0].end as usize); |
| 1120 | assert_eq!(e.ranges[0].bytes_sha256, sha(&damaged[a..b])); |
| 1121 | assert!(receipt.to_string().contains("roll forward (kept)")); |
| 1122 | // Replay shows it: the repair log of the reopened device holds that one entry. |
| 1123 | let dev = open_dev(after.clone()).unwrap(); |
| 1124 | assert_eq!(dev.repair_log().unwrap(), vec![e.clone()]); |
| 1125 | assert_eq!(dev.segment_count(), 2); |
| 1126 | |
| 1127 | // The backup holds what was overwritten: both superblocks (the damaged one |
| 1128 | // included) and the spare metadata region bytes. |
| 1129 | let bk = read_backup(&backup).unwrap(); |
| 1130 | assert_eq!(bk.sections[0].offset, 0); |
| 1131 | assert_eq!(bk.sections[0].bytes, damaged[..2 * BLOCK as usize]); |
| 1132 | assert_eq!(bk.sections.len(), 2); |
| 1133 | let (o, n) = (bk.sections[1].offset as usize, bk.sections[1].bytes.len()); |
| 1134 | assert_eq!(bk.sections[1].bytes, damaged[o..o + n]); |
| 1135 | // Nothing outside the backed-up ranges changed. |
| 1136 | for (i, (x, y)) in damaged.iter().zip(&after).enumerate() { |
| 1137 | if x != y { |
| 1138 | assert!( |
| 1139 | i < 2 * BLOCK as usize || (o..o + n).contains(&i), |
| 1140 | "byte {i} changed outside the backed-up ranges" |
| 1141 | ); |
| 1142 | } |
| 1143 | } |
| 1144 | |
| 1145 | // A second run has nothing to do and writes nothing. |
| 1146 | let w = writes(&io); |
| 1147 | let again = repair( |
| 1148 | &io, |
| 1149 | RepairAction::RollForward, |
| 1150 | &operator(), |
| 1151 | &dir.join("b2"), |
| 1152 | NOW, |
| 1153 | ) |
| 1154 | .unwrap(); |
| 1155 | assert!(!again.wrote); |
| 1156 | assert_eq!(again.report.verdict, Verdict::Healthy); |
| 1157 | assert_eq!(again.report.history, vec![e]); |
| 1158 | assert_eq!(writes(&io), w); |
| 1159 | assert!(!dir.join("b2").exists()); |
| 1160 | // And the store keeps working after the repair: a new change commits on top. |
| 1161 | let mut s = open_store(after).unwrap(); |
| 1162 | assert_eq!(commit(&mut s, &key(9), "after-repair").unwrap().0, 11); |
| 1163 | } |
| 1164 | |
| 1165 | #[test] |
| 1166 | fn r1_repair_adopt_older_backs_up_drops_only_the_range_and_records_it() { |
| 1167 | let (io, damaged, _) = damaged_fixture(); |
| 1168 | let dir = temp_dir("repair-adopt"); |
| 1169 | let backup = dir.join("backup.bin"); |
| 1170 | let report = diagnose(&io).unwrap(); |
| 1171 | let l = &report.lost[0]; |
| 1172 | let (a, e) = (l.start / BLOCK * BLOCK, l.end.div_ceil(BLOCK) * BLOCK); |
| 1173 | let receipt = repair( |
| 1174 | &io, |
| 1175 | RepairAction::AdoptOlderCheckpoint, |
| 1176 | &operator(), |
| 1177 | &backup, |
| 1178 | NOW, |
| 1179 | ) |
| 1180 | .unwrap(); |
| 1181 | let after = image(&io); |
| 1182 | // The store opens with the older checkpoint: slot 1's 8 changes. |
| 1183 | assert_eq!(open_seq(after.clone()), Ok(8)); |
| 1184 | assert!(after[a as usize..e as usize].iter().all(|x| *x == 0)); |
| 1185 | // The record names exactly what was dropped, with the digest of those bytes. |
| 1186 | let entry = receipt.entry.clone().unwrap(); |
| 1187 | assert_eq!(entry.action, RepairAction::AdoptOlderCheckpoint); |
| 1188 | assert_eq!( |
| 1189 | (entry.segment_count_before, entry.segment_count_after), |
| 1190 | (1, 1) |
| 1191 | ); |
| 1192 | let r = &entry.ranges[0]; |
| 1193 | assert_eq!( |
| 1194 | (r.slot, r.start, r.end, r.records, r.first_seq), |
| 1195 | (2, a, e, 2, 9) |
| 1196 | ); |
| 1197 | assert_eq!(r.bytes_sha256, sha(&damaged[a as usize..e as usize])); |
| 1198 | assert!(receipt.to_string().contains("DROPPED")); |
| 1199 | assert_eq!( |
| 1200 | open_dev(after.clone()).unwrap().repair_log().unwrap(), |
| 1201 | vec![entry] |
| 1202 | ); |
| 1203 | // The backup holds the dropped bytes, so the loss can still be undone by hand. |
| 1204 | let bk = read_backup(&backup).unwrap(); |
| 1205 | let s = bk.sections.iter().find(|s| s.offset == a).unwrap(); |
| 1206 | assert_eq!(s.bytes, damaged[a as usize..e as usize]); |
| 1207 | assert!(s.bytes.iter().any(|x| *x != 0)); |
| 1208 | // Changed bytes lie only in the backed-up ranges. |
| 1209 | for (i, (x, y)) in damaged.iter().zip(&after).enumerate() { |
| 1210 | if x != y { |
| 1211 | assert!( |
| 1212 | bk.sections |
| 1213 | .iter() |
| 1214 | .any(|s| (s.offset..s.offset + s.bytes.len() as u64).contains(&(i as u64))), |
| 1215 | "byte {i} changed outside the backed-up ranges" |
| 1216 | ); |
| 1217 | } |
| 1218 | } |
| 1219 | // The backup file is never overwritten. |
| 1220 | assert!(repair( |
| 1221 | &io, |
| 1222 | RepairAction::AdoptOlderCheckpoint, |
| 1223 | &operator(), |
| 1224 | &backup, |
| 1225 | NOW |
| 1226 | ) |
| 1227 | .is_ok_and(|r| !r.wrote)); |
| 1228 | } |
| 1229 | |
| 1230 | #[test] |
| 1231 | fn r1_repair_interrupted_adopt_finishes_without_a_second_record() { |
| 1232 | let (io, damaged, _) = damaged_fixture(); |
| 1233 | let dir = temp_dir("repair-resume"); |
| 1234 | let first = repair( |
| 1235 | &io, |
| 1236 | RepairAction::AdoptOlderCheckpoint, |
| 1237 | &operator(), |
| 1238 | &dir.join("b1"), |
| 1239 | NOW, |
| 1240 | ) |
| 1241 | .unwrap(); |
| 1242 | // Power cut after the record committed but before the zeroing reached the |
| 1243 | // device: put the slot bytes back. |
| 1244 | let l = &first.report.lost[0]; |
| 1245 | let (a, e) = ( |
| 1246 | (l.start / BLOCK * BLOCK) as usize, |
| 1247 | (l.end.div_ceil(BLOCK) * BLOCK) as usize, |
| 1248 | ); |
| 1249 | io.rec().image[a..e].copy_from_slice(&damaged[a..e]); |
| 1250 | assert_eq!( |
| 1251 | open_seq(image(&io)), |
| 1252 | Err(RefusalCode::CheckpointCorrupt), |
| 1253 | "still refuses: the drop is recorded but not done" |
| 1254 | ); |
| 1255 | // Rolling forward over a recorded drop is refused and writes nothing. |
| 1256 | let w = writes(&io); |
| 1257 | let err = repair( |
| 1258 | &io, |
| 1259 | RepairAction::RollForward, |
| 1260 | &operator(), |
| 1261 | &dir.join("b2"), |
| 1262 | NOW, |
| 1263 | ) |
| 1264 | .unwrap_err(); |
| 1265 | assert!(err.message.contains("did not finish"), "{err:?}"); |
| 1266 | assert_eq!(writes(&io), w); |
| 1267 | // The same action finishes it; the log still holds exactly one entry. |
| 1268 | let second = repair( |
| 1269 | &io, |
| 1270 | RepairAction::AdoptOlderCheckpoint, |
| 1271 | &operator(), |
| 1272 | &dir.join("b3"), |
| 1273 | NOW + 1, |
| 1274 | ) |
| 1275 | .unwrap(); |
| 1276 | assert_eq!(second.entry, first.entry); |
| 1277 | assert_eq!(open_seq(image(&io)), Ok(8)); |
| 1278 | let log = open_dev(image(&io)).unwrap().repair_log().unwrap(); |
| 1279 | assert_eq!(log, vec![first.entry.unwrap()]); |
| 1280 | } |
| 1281 | |
| 1282 | #[test] |
| 1283 | fn r1_repair_refuses_to_roll_forward_a_slot_without_batches() { |
| 1284 | let (io, _, _) = damaged_fixture(); |
| 1285 | let start = diagnose(&io).unwrap().lost[0].batches[0].offset as usize; |
| 1286 | // The first batch header no longer parses: there is nothing to roll forward. |
| 1287 | io.rec().image[start] ^= 0xFF; |
| 1288 | let img = image(&io); |
| 1289 | let w = writes(&io); |
| 1290 | let dir = temp_dir("repair-nobatch"); |
| 1291 | let err = repair( |
| 1292 | &io, |
| 1293 | RepairAction::RollForward, |
| 1294 | &operator(), |
| 1295 | &dir.join("b"), |
| 1296 | NOW, |
| 1297 | ) |
| 1298 | .unwrap_err(); |
| 1299 | assert!(err.message.contains("no WAL v2 batch header"), "{err:?}"); |
| 1300 | assert_eq!((image(&io), writes(&io)), (img, w)); |
| 1301 | assert!(!dir.join("b").exists()); |
| 1302 | } |
| 1303 | |
| 1304 | /// Negative control: an intact image has nothing to repair, and neither action |
| 1305 | /// writes a byte (device SHA-256 before and after). |
| 1306 | #[test] |
| 1307 | fn r1_repair_intact_image_has_nothing_to_do_and_never_writes() { |
| 1308 | let io = MemIo::new(vec![0u8; 4 << 20]); |
| 1309 | let cfg = mem_cfg(FormatPolicy::FormatIfBlank, META); |
| 1310 | let dev = BlockDevice::open(Box::new(io.clone()), &cfg, SEG).unwrap(); |
| 1311 | let mut s = |
| 1312 | SynapseStore::open_on_device(dev, cfg.path.clone(), TRUNCATE, limits()).unwrap(); |
| 1313 | for i in 0..10 { |
| 1314 | commit(&mut s, &key(9), &format!("intact-{i}")).unwrap(); |
| 1315 | } |
| 1316 | drop(s); |
| 1317 | // Two statements: the guard from io.rec() would otherwise live to the end of the |
| 1318 | // tuple expression while writes(&io) takes the same lock on this thread. |
| 1319 | let before = sha(&image(&io)); |
| 1320 | let w = writes(&io); |
| 1321 | let dir = temp_dir("repair-intact"); |
| 1322 | let r = diagnose(&io).unwrap(); |
| 1323 | assert_eq!(r.verdict, Verdict::Healthy); |
| 1324 | assert!(r.lost.is_empty()); |
| 1325 | for (i, action) in [ |
| 1326 | RepairAction::RollForward, |
| 1327 | RepairAction::AdoptOlderCheckpoint, |
| 1328 | ] |
| 1329 | .into_iter() |
| 1330 | .enumerate() |
| 1331 | { |
| 1332 | let b = dir.join(format!("b{i}")); |
| 1333 | let receipt = repair(&io, action, &operator(), &b, NOW).unwrap(); |
| 1334 | assert!(!receipt.wrote); |
| 1335 | assert_eq!(receipt.entry, None); |
| 1336 | assert!(!b.exists()); |
| 1337 | } |
| 1338 | assert_eq!(sha(&image(&io)), before); |
| 1339 | assert_eq!(writes(&io), w); |
| 1340 | } |
| 1341 | |
| 1342 | #[test] |
| 1343 | fn r1_repair_log_that_does_not_verify_refuses_the_mount() { |
| 1344 | let (io, _, _) = damaged_fixture(); |
| 1345 | let dir = temp_dir("repair-tamper"); |
| 1346 | repair( |
| 1347 | &io, |
| 1348 | RepairAction::RollForward, |
| 1349 | &operator(), |
| 1350 | &dir.join("b"), |
| 1351 | NOW, |
| 1352 | ) |
| 1353 | .unwrap(); |
| 1354 | let good = image(&io); |
| 1355 | let log = open_dev(good.clone()) |
| 1356 | .unwrap() |
| 1357 | .read_named(REPAIR_LOG_NAME) |
| 1358 | .unwrap(); |
| 1359 | |
| 1360 | // Rewrite the log through an ordinary metadata commit (its region digest holds), |
| 1361 | // so only the repair log's own checks can catch each change. |
| 1362 | let rewritten = |log: Vec<u8>| { |
| 1363 | let mem = MemIo::new(good.clone()); |
| 1364 | let d = BlockDevice::open( |
| 1365 | Box::new(mem.clone()), |
| 1366 | &mem_cfg(FormatPolicy::OpenExisting, META), |
| 1367 | SEG, |
| 1368 | ) |
| 1369 | .unwrap(); |
| 1370 | d.write_named(REPAIR_LOG_NAME, &log).unwrap(); |
| 1371 | drop(d); |
| 1372 | image(&mem) |
| 1373 | }; |
| 1374 | // A flipped signature bit. |
| 1375 | let mut bad_sig = log.clone(); |
| 1376 | *bad_sig.last_mut().unwrap() ^= 1; |
| 1377 | // A changed range (the signature no longer covers it). |
| 1378 | let mut bad_range = log.clone(); |
| 1379 | bad_range[4 + 4 + 2 + 2 + 16 + 32 + 64 + 4 + 8] ^= 1; |
| 1380 | // A second entry signed correctly but not chained to the first. |
| 1381 | let entry = verify_repair_log(&log, &open_dev(good.clone()).unwrap().geometry().uuid) |
| 1382 | .unwrap() |
| 1383 | .remove(0); |
| 1384 | let mut forged = entry.clone(); |
| 1385 | forged.generation += 10; |
| 1386 | forged.signature = operator().sign(&forged.signable_bytes()).to_bytes(); |
| 1387 | let mut unchained = log.clone(); |
| 1388 | let enc_len = log.len() - 4; |
| 1389 | unchained.extend_from_slice(&(enc_len as u32).to_le_bytes()); |
| 1390 | let mut forged_bytes = forged.signable_bytes()[DOMAIN_R1_REPAIR_SIGN_V1.len()..].to_vec(); |
| 1391 | forged_bytes.extend_from_slice(&forged.signature); |
| 1392 | unchained.extend_from_slice(&forged_bytes); |
| 1393 | |
| 1394 | for (what, bytes, needle) in [ |
| 1395 | ("signature", bad_sig, "signature does not verify"), |
| 1396 | ("range", bad_range, "signature does not verify"), |
| 1397 | ("chain", unchained, "breaks the hash chain"), |
| 1398 | ] { |
| 1399 | let img = rewritten(bytes); |
| 1400 | let err = open_dev(img.clone()).unwrap_err(); |
| 1401 | assert_eq!(err.code, RefusalCode::CheckpointCorrupt, "{what}"); |
| 1402 | assert!(err.message.contains(needle), "{what}: {err:?}"); |
| 1403 | match diagnose(&MemIo::new(img)).unwrap().verdict { |
| 1404 | Verdict::Unrepairable(why) => assert!(why.contains(needle), "{what}: {why}"), |
| 1405 | v => panic!("{what}: {v:?}"), |
| 1406 | } |
| 1407 | } |
| 1408 | // Control: the untouched log mounts. |
| 1409 | assert!(open_dev(rewritten(log)).is_ok()); |
| 1410 | } |
| 1411 | |
| 1412 | #[test] |
| 1413 | fn r1_repair_bare_relative_backup_is_created_and_verified() { |
| 1414 | let (io, _, _) = damaged_fixture(); |
| 1415 | let nonce = std::time::SystemTime::now() |
| 1416 | .duration_since(std::time::UNIX_EPOCH) |
| 1417 | .unwrap() |
| 1418 | .as_nanos(); |
| 1419 | let backup = PathBuf::from(format!( |
| 1420 | "relative-repair-backup-{}-{nonce}.bin", |
| 1421 | std::process::id() |
| 1422 | )); |
| 1423 | assert!(!backup.exists()); |
| 1424 | let receipt = repair(&io, RepairAction::RollForward, &operator(), &backup, NOW).unwrap(); |
| 1425 | assert!(receipt.wrote); |
| 1426 | assert!(!read_backup(&backup).unwrap().sections.is_empty()); |
| 1427 | fs::remove_file(&backup).unwrap(); |
| 1428 | // The paired syscall-trace regression additionally requires the real parent |
| 1429 | // directory fsync after the backup file fsync, including for this bare name. |
| 1430 | } |
| 1431 | |
| 1432 | #[test] |
| 1433 | fn r1_repair_backup_overflow_length_is_refused_without_panicking() { |
| 1434 | let dir = temp_dir("repair-backup-overflow"); |
| 1435 | let path = dir.join("overflow.backup"); |
| 1436 | let mut body = b"SYNREPAIRBAK001\n".to_vec(); |
| 1437 | body.extend_from_slice(&[0u8; 16]); |
| 1438 | body.extend_from_slice(&1u32.to_le_bytes()); |
| 1439 | body.extend_from_slice(&0u64.to_le_bytes()); |
| 1440 | body.extend_from_slice(&u64::MAX.to_le_bytes()); |
| 1441 | let digest = sha(&body); |
| 1442 | body.extend_from_slice(&digest); |
| 1443 | fs::write(&path, &body).unwrap(); |
| 1444 | assert!( |
| 1445 | read_backup(&path).is_err(), |
| 1446 | "an impossible section length must be refused" |
| 1447 | ); |
| 1448 | assert_eq!( |
| 1449 | fs::read(&path).unwrap(), |
| 1450 | body, |
| 1451 | "a refused backup must not change" |
| 1452 | ); |
| 1453 | let _ = fs::remove_dir_all(&dir); |
| 1454 | } |
| 1455 | |
| 1456 | #[test] |
| 1457 | fn r1_repair_refuses_a_foreign_device() { |
| 1458 | let mut img = vec![0u8; 4 << 20]; |
| 1459 | img[510] = 0x55; |
| 1460 | img[511] = 0xAA; // MBR |
| 1461 | let io = MemIo::new(img); |
| 1462 | assert!(diagnose(&io).is_err()); |
| 1463 | let b = temp_dir("repair-foreign").join("b"); |
| 1464 | assert!(repair(&io, RepairAction::RollForward, &operator(), &b, NOW).is_err()); |
| 1465 | assert_eq!(writes(&io), 0); |
| 1466 | assert!(!b.exists()); |
| 1467 | } |
| 1468 | |
| 1469 | #[cfg(target_os = "linux")] |
| 1470 | #[test] |
| 1471 | fn r1_repair_parent_drop_releases_lock_despite_inherited_helper_fd() { |
| 1472 | let dir = temp_dir("repair-inherited-lock"); |
| 1473 | let path = dir.join("device.img"); |
| 1474 | fs::File::create(&path).unwrap().set_len(4 * BLOCK).unwrap(); |
| 1475 | let io = DirectFile::open(&path).unwrap(); |
| 1476 | let mut ready = [0i32; 2]; |
| 1477 | let mut release = [0i32; 2]; |
| 1478 | // The child models a helper between fork and exec. It runs only async-signal-safe |
| 1479 | // libc calls, never accesses the device, and closes on parent EOF as well. |
| 1480 | unsafe { |
| 1481 | assert_eq!(libc::pipe2(ready.as_mut_ptr(), libc::O_CLOEXEC), 0); |
| 1482 | assert_eq!(libc::pipe2(release.as_mut_ptr(), libc::O_CLOEXEC), 0); |
| 1483 | let pid = libc::fork(); |
| 1484 | if pid == 0 { |
| 1485 | libc::close(ready[0]); |
| 1486 | libc::close(release[1]); |
| 1487 | let sent = libc::write(ready[1], b"r".as_ptr().cast(), 1); |
| 1488 | libc::close(ready[1]); |
| 1489 | let mut byte = 0u8; |
| 1490 | let received = libc::read(release[0], (&mut byte as *mut u8).cast(), 1); |
| 1491 | libc::close(release[0]); |
| 1492 | libc::_exit(if sent == 1 && received == 1 { 0 } else { 1 }); |
| 1493 | } |
| 1494 | if pid < 0 { |
| 1495 | for fd in ready.into_iter().chain(release) { |
| 1496 | libc::close(fd); |
| 1497 | } |
| 1498 | panic!("fork failed"); |
| 1499 | } |
| 1500 | libc::close(ready[1]); |
| 1501 | libc::close(release[0]); |
| 1502 | let mut byte = 0u8; |
| 1503 | let received = libc::read(ready[0], (&mut byte as *mut u8).cast(), 1); |
| 1504 | libc::close(ready[0]); |
| 1505 | // The helper is alive with the inherited descriptor, but the actual owner |
| 1506 | // is gone. Capture the result, then reap the child before any assertion. |
| 1507 | drop(io); |
| 1508 | let reopened = DirectFile::open(&path); |
| 1509 | let sent = libc::write(release[1], b"x".as_ptr().cast(), 1); |
| 1510 | libc::close(release[1]); |
| 1511 | let mut status = 0; |
| 1512 | let waited = libc::waitpid(pid, &mut status, 0); |
| 1513 | assert_eq!((received, sent, waited, status), (1, 1, pid, 0)); |
| 1514 | assert!(reopened.is_ok(), "a helper that never uses the device retained the departed owner's lock: {reopened:?}"); |
| 1515 | } |
| 1516 | let _ = fs::remove_dir_all(&dir); |
| 1517 | } |
| 1518 | |
| 1519 | #[test] |
| 1520 | fn r1_repair_holds_the_exclusive_lock() { |
| 1521 | let dir = temp_dir("repair-lock"); |
| 1522 | let path = dir.join(TEST_DEVICE_FILE); |
| 1523 | make_device_file(&path, TEST_DEVICE_BYTES); |
| 1524 | let cfg = BlockDeviceConfig { |
| 1525 | path: path.clone(), |
| 1526 | format: FormatPolicy::FormatIfBlank, |
| 1527 | meta_region_bytes: TEST_META_BYTES, |
| 1528 | allow_foreign_signature: false, |
| 1529 | }; |
| 1530 | let held = BlockDevice::open_path(&cfg, SEG).unwrap(); |
| 1531 | assert!(diagnose_path(&path).is_err()); |
| 1532 | let b = dir.join("b"); |
| 1533 | assert!(repair_path(&path, RepairAction::RollForward, &operator(), &b, NOW).is_err()); |
| 1534 | assert!(!b.exists()); |
| 1535 | drop(held); |
| 1536 | // Control: once the store is closed the lock is free and the device diagnoses. |
| 1537 | assert_eq!(diagnose_path(&path).unwrap().verdict, Verdict::Healthy); |
| 1538 | let _ = fs::remove_dir_all(&dir); |
| 1539 | } |
| 1540 | } |