🩹 fsck --quarantine moves old orphan blobs aside; restore refusals read plainly and create nothing
Browse files at this commit1fa884bdde1aeb91ab8b5fafb0c65a1529eea8b1Parent: d4353ee5 changed files +226 -33
- README.md +3 -3
- crates/in-core/src/backup.rs +36 -7
- crates/in-core/src/fsck.rs +107 -12
- crates/in-web/src/cli.rs +77 -9
- docs/architecture.md +3 -2
README.mdmodified+3 -3
| @@ -129,8 +129,8 @@ with its own versioning. The manifest is what lets `in fsck --hash` and a restor | |||
| 129 | 129 | ||
| 130 | It checks the manifest's MAC against `in.key` first (a set without that key, or one that was edited, is | 130 | It checks the manifest's MAC against `in.key` first (a set without that key, or one that was edited, is |
| 131 | refused), then the manifest format, the snapshot's size and hash, and the snapshot's integrity before it | 131 | refused), then the manifest format, the snapshot's size and hash, and the snapshot's integrity before it |
| 132 | - changes anything. A set that fails a check is refused and nothing is replaced. The database it replaces is moved to | 132 | + changes anything. A set that fails a check is refused with a plain message, and nothing is replaced or created in |
| 133 | - `data_dir/restore-<time>/` and is not deleted. | 133 | + the data directory. The database it replaces is moved to `data_dir/restore-<time>/` and is not deleted. |
| 134 | 3. Run `in fsck` to see whether every row has its blob. Blobs listed in the manifest but missing from the blob | 134 | 3. Run `in fsck` to see whether every row has its blob. Blobs listed in the manifest but missing from the blob |
| 135 | tree are reported by the restore; they were deleted after the set was written. | 135 | tree are reported by the restore; they were deleted after the set was written. |
| 136 | 4. Start the service. | 136 | 4. Start the service. |
| @@ -143,7 +143,7 @@ The database must lie inside `data_dir`. Restore does not replace anything outsi | |||
| 143 | |---|---| | 143 | |---|---| |
| 144 | | `in serve` | Runs the server. A bare `in` does the same. | | 144 | | `in serve` | Runs the server. A bare `in` does the same. | |
| 145 | | `in export --member <sub or email> --out <dir>` | Copies one person's live files into `<dir>` as a folder tree with their names. Names are sanitized so nothing is written outside `<dir>`. Each file is hashed as it is copied and checked against its row. | | 145 | | `in export --member <sub or email> --out <dir>` | Copies one person's live files into `<dir>` as a folder tree with their names. Names are sanitized so nothing is written outside `<dir>`. Each file is hashed as it is copied and checked against its row. | |
| 146 | -| `in fsck [--hash]` | Checks `PRAGMA integrity_check`, that every file, ready thumbnail and object has a blob of the recorded size, and with `--hash` the SHA-256 of every blob. Lists orphan blobs. Changes nothing. Exit status 1 when a problem is found. | | 146 | +| `in fsck [--hash] [--quarantine]` | Checks `PRAGMA integrity_check`, that every file, ready thumbnail and object has a blob of the recorded size, and with `--hash` the SHA-256 of every blob. Lists orphan blobs. Changes nothing unless `--quarantine` is given: then each orphan blob whose modification time is over an hour old is moved (not deleted) from `blobs/` to the same path under `quarantine/` in the data directory, and each move is printed. Younger orphans stay in place, so an upload that is still finishing is never touched. Local storage only. Exit status 1 when a problem is found. | |
| 147 | | `in restore --from <set>` | Replaces the database with the one in a backup set, after verification (see *Restore*). | | 147 | | `in restore --from <set>` | Replaces the database with the one in a backup set, after verification (see *Restore*). | |
| 148 | | `in quota recompute` | Recomputes every person's used bytes from their files and prints the ones that were wrong. | | 148 | | `in quota recompute` | Recomputes every person's used bytes from their files and prints the ones that were wrong. | |
| 149 | 149 | ||
crates/in-core/src/backup.rsmodified+36 -7
| @@ -21,6 +21,7 @@ use std::fs::OpenOptions; | |||
| 21 | use std::io::Write; | 21 | use std::io::Write; |
| 22 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | 22 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; |
| 23 | use std::path::{Path, PathBuf}; | 23 | use std::path::{Path, PathBuf}; |
| 24 | +use std::sync::Arc; | ||
| 24 | 25 | ||
| 25 | use hmac::{Hmac, KeyInit, Mac}; | 26 | use hmac::{Hmac, KeyInit, Mac}; |
| 26 | use serde::{Deserialize, Serialize}; | 27 | use serde::{Deserialize, Serialize}; |
| @@ -262,12 +263,13 @@ pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result<Manifest> { | |||
| 262 | /// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the | 263 | /// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the |
| 263 | /// manifest's MAC under `key`, then the manifest, the snapshot's size and hash, and its integrity before | 264 | /// manifest's MAC under `key`, then the manifest, the snapshot's size and hash, and its integrity before |
| 264 | /// replacing anything. The previous database, with its sidecar files, is moved into | 265 | /// replacing anything. The previous database, with its sidecar files, is moved into |
| 265 | -/// `data_dir/restore-<stamp>/`. | 266 | +/// `data_dir/restore-<stamp>/`. `open_blobs` is called only once the set has passed every check, so a |
| 267 | +/// refused restore never creates the blob tree; it is called before the database is replaced. | ||
| 266 | pub async fn restore( | 268 | pub async fn restore( |
| 267 | data_dir: &Path, | 269 | data_dir: &Path, |
| 268 | database: &Path, | 270 | database: &Path, |
| 269 | set: &Path, | 271 | set: &Path, |
| 270 | - blobs: &dyn BlobStore, | 272 | + open_blobs: impl FnOnce() -> Result<Arc<dyn BlobStore>>, |
| 271 | key: &[u8; 32], | 273 | key: &[u8; 32], |
| 272 | stamp: &str, | 274 | stamp: &str, |
| 273 | ) -> Result<RestoreOutcome> { | 275 | ) -> Result<RestoreOutcome> { |
| @@ -303,6 +305,7 @@ pub async fn restore( | |||
| 303 | true => {} | 305 | true => {} |
| 304 | false => return Err(Error::Invalid("backup_integrity".into())), | 306 | false => return Err(Error::Invalid("backup_integrity".into())), |
| 305 | } | 307 | } |
| 308 | + let blobs = open_blobs()?; | ||
| 306 | 309 | ||
| 307 | // Keep the database we replace: move it aside, then move the verified copy into place. | 310 | // Keep the database we replace: move it aside, then move the verified copy into place. |
| 308 | let previous = if database.exists() { | 311 | let previous = if database.exists() { |
| @@ -377,6 +380,11 @@ mod tests { | |||
| 377 | /// Stands in for the instance key in these tests. | 380 | /// Stands in for the instance key in these tests. |
| 378 | const KEY: [u8; 32] = [9u8; 32]; | 381 | const KEY: [u8; 32] = [9u8; 32]; |
| 379 | 382 | ||
| 383 | + /// Stands in for opening the blob tree in the refusal tests, which must never reach it. | ||
| 384 | + fn never_opened() -> Result<Arc<dyn BlobStore>> { | ||
| 385 | + unreachable!("a refused restore opens no blob tree") | ||
| 386 | + } | ||
| 387 | + | ||
| 380 | /// Writes `manifest` into `set` and signs it with [`KEY`], as the writer would. | 388 | /// Writes `manifest` into `set` and signs it with [`KEY`], as the writer would. |
| 381 | fn sign_manifest(set: &Path, manifest: &Manifest) { | 389 | fn sign_manifest(set: &Path, manifest: &Manifest) { |
| 382 | let text = serde_json::to_string_pretty(manifest).unwrap(); | 390 | let text = serde_json::to_string_pretty(manifest).unwrap(); |
| @@ -407,7 +415,7 @@ mod tests { | |||
| 407 | 415 | ||
| 408 | #[tokio::test] | 416 | #[tokio::test] |
| 409 | async fn restore_refuses_a_manifest_with_a_wrong_hash() { | 417 | async fn restore_refuses_a_manifest_with_a_wrong_hash() { |
| 410 | - let (dir, _store, blobs, set) = source_with_set().await; | 418 | + let (dir, _store, _blobs, set) = source_with_set().await; |
| 411 | let mut manifest = read_manifest(&set, &KEY).unwrap(); | 419 | let mut manifest = read_manifest(&set, &KEY).unwrap(); |
| 412 | manifest.database.sha256 = "0".repeat(64); | 420 | manifest.database.sha256 = "0".repeat(64); |
| 413 | // Signed with the right key, so only the snapshot hash check can refuse it. | 421 | // Signed with the right key, so only the snapshot hash check can refuse it. |
| @@ -416,7 +424,15 @@ mod tests { | |||
| 416 | let data = dir.path().join("data"); | 424 | let data = dir.path().join("data"); |
| 417 | std::fs::create_dir_all(&data).unwrap(); | 425 | std::fs::create_dir_all(&data).unwrap(); |
| 418 | let database = data.join("in.db"); | 426 | let database = data.join("in.db"); |
| 419 | - let refused = restore(&data, &database, &set, &blobs, &KEY, "20261028T000000Z").await; | 427 | + let refused = restore( |
| 428 | + &data, | ||
| 429 | + &database, | ||
| 430 | + &set, | ||
| 431 | + never_opened, | ||
| 432 | + &KEY, | ||
| 433 | + "20261028T000000Z", | ||
| 434 | + ) | ||
| 435 | + .await; | ||
| 420 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); | 436 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); |
| 421 | assert!( | 437 | assert!( |
| 422 | !database.exists(), | 438 | !database.exists(), |
| @@ -426,7 +442,7 @@ mod tests { | |||
| 426 | 442 | ||
| 427 | #[tokio::test] | 443 | #[tokio::test] |
| 428 | async fn restore_refuses_a_manifest_changed_without_the_key() { | 444 | async fn restore_refuses_a_manifest_changed_without_the_key() { |
| 429 | - let (dir, _store, blobs, set) = source_with_set().await; | 445 | + let (dir, _store, _blobs, set) = source_with_set().await; |
| 430 | // Someone with write access edits the manifest and fixes the snapshot hash, but cannot re-sign it. | 446 | // Someone with write access edits the manifest and fixes the snapshot hash, but cannot re-sign it. |
| 431 | let mut manifest = read_manifest(&set, &KEY).unwrap(); | 447 | let mut manifest = read_manifest(&set, &KEY).unwrap(); |
| 432 | manifest.database.sha256 = "0".repeat(64); | 448 | manifest.database.sha256 = "0".repeat(64); |
| @@ -439,9 +455,21 @@ mod tests { | |||
| 439 | let data = dir.path().join("data"); | 455 | let data = dir.path().join("data"); |
| 440 | std::fs::create_dir_all(&data).unwrap(); | 456 | std::fs::create_dir_all(&data).unwrap(); |
| 441 | let database = data.join("in.db"); | 457 | let database = data.join("in.db"); |
| 442 | - let refused = restore(&data, &database, &set, &blobs, &KEY, "20261028T000002Z").await; | 458 | + let refused = restore( |
| 459 | + &data, | ||
| 460 | + &database, | ||
| 461 | + &set, | ||
| 462 | + never_opened, | ||
| 463 | + &KEY, | ||
| 464 | + "20261028T000002Z", | ||
| 465 | + ) | ||
| 466 | + .await; | ||
| 443 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_mac_bad")); | 467 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_mac_bad")); |
| 444 | assert!(!database.exists()); | 468 | assert!(!database.exists()); |
| 469 | + assert!( | ||
| 470 | + !data.join("blobs").exists(), | ||
| 471 | + "a refused restore creates no blob tree" | ||
| 472 | + ); | ||
| 445 | } | 473 | } |
| 446 | 474 | ||
| 447 | #[tokio::test] | 475 | #[tokio::test] |
| @@ -453,7 +481,8 @@ mod tests { | |||
| 453 | let database = data.join("in.db"); | 481 | let database = data.join("in.db"); |
| 454 | std::fs::write(&database, b"not a database").unwrap(); | 482 | std::fs::write(&database, b"not a database").unwrap(); |
| 455 | 483 | ||
| 456 | - let outcome = restore(&data, &database, &set, &blobs, &KEY, "20261028T000001Z") | 484 | + let open = || Ok(Arc::new(blobs.clone()) as Arc<dyn BlobStore>); |
| 485 | + let outcome = restore(&data, &database, &set, open, &KEY, "20261028T000001Z") | ||
| 457 | .await | 486 | .await |
| 458 | .unwrap(); | 487 | .unwrap(); |
| 459 | assert_eq!(outcome.blobs_listed, 1); | 488 | assert_eq!(outcome.blobs_listed, 1); |
crates/in-core/src/fsck.rsmodified+107 -12
| @@ -2,19 +2,27 @@ | |||
| 2 | //! | 2 | //! |
| 3 | //! It reads only. Every row that names a blob (a file's bytes, a ready thumbnail, an object's bytes) must | 3 | //! It reads only. Every row that names a blob (a file's bytes, a ready thumbnail, an object's bytes) must |
| 4 | //! find a blob of the recorded size; with `verify_hash` the bytes are also hashed and compared with the | 4 | //! find a blob of the recorded size; with `verify_hash` the bytes are also hashed and compared with the |
| 5 | -//! row's SHA-256. A blob that no row names is an orphan, which is reported and never removed here: the | 5 | +//! row's SHA-256. A blob that no row names is an orphan, which is reported. `quarantine` moves orphans out of |
| 6 | -//! sweeper decides about orphans, and only after they are a day old. `PRAGMA integrity_check` runs first. | 6 | +//! the blob tree, and only when they are an hour old and the caller asks for it; nothing is ever deleted here: |
| 7 | +//! the sweeper decides about orphans, and only after they are a day old. `PRAGMA integrity_check` runs first. | ||
| 7 | //! The run needs the server stopped, because the database must not change under it. | 8 | //! The run needs the server stopped, because the database must not change under it. |
| 8 | 9 | ||
| 9 | use std::collections::HashSet; | 10 | use std::collections::HashSet; |
| 11 | +use std::os::unix::fs::DirBuilderExt; | ||
| 12 | +use std::path::Path; | ||
| 13 | +use std::time::{Duration, SystemTime}; | ||
| 10 | 14 | ||
| 11 | -use crate::blob::{self, BlobStore}; | 15 | +use crate::blob::{self, BlobEntry, BlobStore}; |
| 12 | -use crate::error::Result; | 16 | +use crate::error::{Error, Result}; |
| 13 | use crate::store::files::thumb_blob_key; | 17 | use crate::store::files::thumb_blob_key; |
| 14 | use crate::store::{Store, col_int, col_text, fetch_all}; | 18 | use crate::store::{Store, col_int, col_text, fetch_all}; |
| 15 | 19 | ||
| 16 | /// How many keys of each kind the report lists. The counts are always exact. | 20 | /// How many keys of each kind the report lists. The counts are always exact. |
| 17 | const LISTED: usize = 50; | 21 | const LISTED: usize = 50; |
| 22 | +/// Orphans younger than this are never quarantined: an upload that is finishing may own them. | ||
| 23 | +pub const QUARANTINE_AGE: Duration = Duration::from_secs(60 * 60); | ||
| 24 | +/// Directory under the data directory that quarantined orphans are moved into, keeping their key paths. | ||
| 25 | +pub const QUARANTINE_DIR: &str = "quarantine"; | ||
| 18 | 26 | ||
| 19 | /// What `fsck` found. | 27 | /// What `fsck` found. |
| 20 | #[derive(Debug, Default, Clone, PartialEq, Eq)] | 28 | #[derive(Debug, Default, Clone, PartialEq, Eq)] |
| @@ -81,17 +89,61 @@ pub async fn check(store: &Store, blobs: &dyn BlobStore, verify_hash: bool) -> R | |||
| 81 | check_blob(&mut report, blobs, &key, size, &sha256, verify_hash).await?; | 89 | check_blob(&mut report, blobs, &key, size, &sha256, verify_hash).await?; |
| 82 | } | 90 | } |
| 83 | 91 | ||
| 84 | - // Orphans: blobs that no row names. | 92 | + let found = orphans(store, blobs).await?; |
| 93 | + report.orphan_count = found.len() as u64; | ||
| 94 | + report.orphans = found | ||
| 95 | + .into_iter() | ||
| 96 | + .take(LISTED) | ||
| 97 | + .map(|(key, _, _)| key) | ||
| 98 | + .collect(); | ||
| 99 | + Ok(report) | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +/// Every blob that no row names, with its size and modification time. | ||
| 103 | +pub async fn orphans(store: &Store, blobs: &dyn BlobStore) -> Result<Vec<BlobEntry>> { | ||
| 85 | let referenced: HashSet<String> = store.referenced_blob_keys().await?.into_iter().collect(); | 104 | let referenced: HashSet<String> = store.referenced_blob_keys().await?.into_iter().collect(); |
| 86 | - for (key, _, _) in blobs.list("").await? { | 105 | + let all = blobs.list("").await?; |
| 87 | - if !referenced.contains(&key) { | 106 | + Ok(all |
| 88 | - report.orphan_count += 1; | 107 | + .into_iter() |
| 89 | - if report.orphans.len() < LISTED { | 108 | + .filter(|(key, _, _)| !referenced.contains(key)) |
| 90 | - report.orphans.push(key); | 109 | + .collect()) |
| 91 | - } | 110 | +} |
| 111 | + | ||
| 112 | +/// Moves each orphan at least [`QUARANTINE_AGE`] old from `blob_root` to the same key under `quarantine_root`, | ||
| 113 | +/// creating parent directories. Younger orphans stay where they are. Nothing is deleted: a destination that | ||
| 114 | +/// already exists stops the whole run before the first move, so no blob is overwritten. Returns the keys moved. | ||
| 115 | +pub fn quarantine( | ||
| 116 | + blob_root: &Path, | ||
| 117 | + quarantine_root: &Path, | ||
| 118 | + orphans: &[BlobEntry], | ||
| 119 | + now: SystemTime, | ||
| 120 | +) -> Result<Vec<String>> { | ||
| 121 | + let old: Vec<&String> = orphans | ||
| 122 | + .iter() | ||
| 123 | + .filter(|(_, _, modified)| { | ||
| 124 | + now.duration_since(*modified) | ||
| 125 | + .is_ok_and(|age| age >= QUARANTINE_AGE) | ||
| 126 | + }) | ||
| 127 | + .map(|(key, _, _)| key) | ||
| 128 | + .collect(); | ||
| 129 | + for key in &old { | ||
| 130 | + if std::fs::symlink_metadata(quarantine_root.join(key)).is_ok() { | ||
| 131 | + return Err(Error::Conflict(format!("{key} is already in quarantine"))); | ||
| 92 | } | 132 | } |
| 93 | } | 133 | } |
| 94 | - Ok(report) | 134 | + let mut moved = Vec::new(); |
| 135 | + for key in old { | ||
| 136 | + let dest = quarantine_root.join(key); | ||
| 137 | + if let Some(parent) = dest.parent() { | ||
| 138 | + std::fs::DirBuilder::new() | ||
| 139 | + .recursive(true) | ||
| 140 | + .mode(0o700) | ||
| 141 | + .create(parent)?; | ||
| 142 | + } | ||
| 143 | + std::fs::rename(blob_root.join(key), &dest)?; | ||
| 144 | + moved.push(key.clone()); | ||
| 145 | + } | ||
| 146 | + Ok(moved) | ||
| 95 | } | 147 | } |
| 96 | 148 | ||
| 97 | /// Runs `PRAGMA integrity_check` and joins its rows. | 149 | /// Runs `PRAGMA integrity_check` and joins its rows. |
| @@ -180,4 +232,47 @@ mod tests { | |||
| 180 | "orphans alone do not make a report unclean" | 232 | "orphans alone do not make a report unclean" |
| 181 | ); | 233 | ); |
| 182 | } | 234 | } |
| 235 | + | ||
| 236 | + #[tokio::test] | ||
| 237 | + async fn quarantine_moves_only_old_orphans_and_never_overwrites() { | ||
| 238 | + let dir = tempfile::tempdir().unwrap(); | ||
| 239 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 240 | + let src = dir.path().join("src.bin"); | ||
| 241 | + std::fs::write(&src, b"old").unwrap(); | ||
| 242 | + blobs.put_file("files/aa/old", &src).await.unwrap(); | ||
| 243 | + std::fs::write(&src, b"new").unwrap(); | ||
| 244 | + blobs.put_file("files/aa/new", &src).await.unwrap(); | ||
| 245 | + let two_hours_ago = SystemTime::now() - Duration::from_secs(2 * 60 * 60); | ||
| 246 | + std::fs::File::options() | ||
| 247 | + .write(true) | ||
| 248 | + .open(dir.path().join("blobs/files/aa/old")) | ||
| 249 | + .unwrap() | ||
| 250 | + .set_modified(two_hours_ago) | ||
| 251 | + .unwrap(); | ||
| 252 | + | ||
| 253 | + let found = blobs.list("").await.unwrap(); | ||
| 254 | + let quarantine_root = dir.path().join(QUARANTINE_DIR); | ||
| 255 | + let moved = quarantine( | ||
| 256 | + &dir.path().join("blobs"), | ||
| 257 | + &quarantine_root, | ||
| 258 | + &found, | ||
| 259 | + SystemTime::now(), | ||
| 260 | + ) | ||
| 261 | + .unwrap(); | ||
| 262 | + assert_eq!(moved, ["files/aa/old"]); | ||
| 263 | + assert!(quarantine_root.join("files/aa/old").exists()); | ||
| 264 | + assert!(dir.path().join("blobs/files/aa/new").exists()); | ||
| 265 | + | ||
| 266 | + // A second run finds the same old key in quarantine and refuses before moving anything. | ||
| 267 | + std::fs::write(dir.path().join("blobs/files/aa/old"), b"again").unwrap(); | ||
| 268 | + let again = blobs.list("").await.unwrap(); | ||
| 269 | + let refused = quarantine( | ||
| 270 | + &dir.path().join("blobs"), | ||
| 271 | + &quarantine_root, | ||
| 272 | + &again, | ||
| 273 | + SystemTime::now() + Duration::from_secs(3 * 60 * 60), | ||
| 274 | + ); | ||
| 275 | + assert!(refused.is_err()); | ||
| 276 | + assert!(dir.path().join("blobs/files/aa/new").exists()); | ||
| 277 | + } | ||
| 183 | } | 278 | } |
crates/in-web/src/cli.rsmodified+77 -9
| @@ -7,9 +7,11 @@ | |||
| 7 | 7 | ||
| 8 | use std::path::{Path, PathBuf}; | 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::process::ExitCode; | 9 | use std::process::ExitCode; |
| 10 | +use std::time::SystemTime; | ||
| 10 | 11 | ||
| 11 | use clap::{Parser, Subcommand}; | 12 | use clap::{Parser, Subcommand}; |
| 12 | use in_core::backup; | 13 | use in_core::backup; |
| 14 | +use in_core::config::{Backend, Config}; | ||
| 13 | use in_core::error::Error; | 15 | use in_core::error::Error; |
| 14 | use in_core::export::export_member; | 16 | use in_core::export::export_member; |
| 15 | use in_core::fsck; | 17 | use in_core::fsck; |
| @@ -44,11 +46,15 @@ pub enum Command { | |||
| 44 | #[arg(long, value_name = "DIR")] | 46 | #[arg(long, value_name = "DIR")] |
| 45 | out: PathBuf, | 47 | out: PathBuf, |
| 46 | }, | 48 | }, |
| 47 | - /// Check the database and the blob tree against each other. Changes nothing. | 49 | + /// Check the database and the blob tree against each other. Changes nothing unless `--quarantine` is given. |
| 48 | Fsck { | 50 | Fsck { |
| 49 | /// Also hash every blob and compare it with its row. Reads every byte, so it is slow. | 51 | /// Also hash every blob and compare it with its row. Reads every byte, so it is slow. |
| 50 | #[arg(long)] | 52 | #[arg(long)] |
| 51 | hash: bool, | 53 | hash: bool, |
| 54 | + /// Move orphan blobs that are over an hour old into `quarantine/` under the data directory. Local | ||
| 55 | + /// storage only. Nothing is deleted. | ||
| 56 | + #[arg(long)] | ||
| 57 | + quarantine: bool, | ||
| 52 | }, | 58 | }, |
| 53 | /// Replace the database with the one in a backup set. The server must be stopped. | 59 | /// Replace the database with the one in a backup set. The server must be stopped. |
| 54 | Restore { | 60 | Restore { |
| @@ -76,7 +82,7 @@ pub async fn run(config: &Path, command: Command) -> ExitCode { | |||
| 76 | let outcome = match command { | 82 | let outcome = match command { |
| 77 | Command::Serve => return serve(config).await, | 83 | Command::Serve => return serve(config).await, |
| 78 | Command::Export { member, out } => export(config, &member, &out).await, | 84 | Command::Export { member, out } => export(config, &member, &out).await, |
| 79 | - Command::Fsck { hash } => fsck_cmd(config, hash).await, | 85 | + Command::Fsck { hash, quarantine } => fsck_cmd(config, hash, quarantine).await, |
| 80 | Command::Restore { from } => restore(config, &from).await, | 86 | Command::Restore { from } => restore(config, &from).await, |
| 81 | Command::Quota { | 87 | Command::Quota { |
| 82 | action: QuotaCommand::Recompute, | 88 | action: QuotaCommand::Recompute, |
| @@ -147,8 +153,14 @@ async fn export(config: &Path, who: &str, out: &Path) -> Result<bool, Error> { | |||
| 147 | } | 153 | } |
| 148 | 154 | ||
| 149 | /// `in fsck`. True when the check found nothing wrong. Orphans are reported but do not fail the check. | 155 | /// `in fsck`. True when the check found nothing wrong. Orphans are reported but do not fail the check. |
| 150 | -async fn fsck_cmd(config: &Path, hash: bool) -> Result<bool, Error> { | 156 | +async fn fsck_cmd(config_path: &Path, hash: bool, quarantine: bool) -> Result<bool, Error> { |
| 151 | - let offline = boot::open_offline(config).await?; | 157 | + let config = Config::load(config_path)?; |
| 158 | + if quarantine && !matches!(config.storage.backend, Backend::Local) { | ||
| 159 | + return Err(Error::Config( | ||
| 160 | + "fsck --quarantine moves files on local disk, so it works only with the local blob backend".into(), | ||
| 161 | + )); | ||
| 162 | + } | ||
| 163 | + let offline = boot::open_offline(config_path).await?; | ||
| 152 | let report = fsck::check(&offline.store, offline.blobs.as_ref(), hash).await?; | 164 | let report = fsck::check(&offline.store, offline.blobs.as_ref(), hash).await?; |
| 153 | println!("database: {}", report.integrity.replace('\n', "; ")); | 165 | println!("database: {}", report.integrity.replace('\n', "; ")); |
| 154 | println!("rows checked: {}", report.rows_checked); | 166 | println!("rows checked: {}", report.rows_checked); |
| @@ -170,29 +182,65 @@ async fn fsck_cmd(config: &Path, hash: bool) -> Result<bool, Error> { | |||
| 170 | for key in &report.orphans { | 182 | for key in &report.orphans { |
| 171 | println!(" orphan {key}"); | 183 | println!(" orphan {key}"); |
| 172 | } | 184 | } |
| 185 | + if quarantine { | ||
| 186 | + quarantine_orphans(&config, &offline).await?; | ||
| 187 | + } | ||
| 173 | Ok(report.is_clean()) | 188 | Ok(report.is_clean()) |
| 174 | } | 189 | } |
| 175 | 190 | ||
| 191 | +/// Moves the orphan blobs that are at least an hour old into the quarantine directory, and prints each one. | ||
| 192 | +async fn quarantine_orphans(config: &Config, offline: &boot::Offline) -> Result<(), Error> { | ||
| 193 | + let data_dir = config.data_dir.canonicalize()?; | ||
| 194 | + let found = fsck::orphans(&offline.store, offline.blobs.as_ref()).await?; | ||
| 195 | + let moved = fsck::quarantine( | ||
| 196 | + &data_dir.join(boot::BLOB_DIR), | ||
| 197 | + &data_dir.join(fsck::QUARANTINE_DIR), | ||
| 198 | + &found, | ||
| 199 | + SystemTime::now(), | ||
| 200 | + )?; | ||
| 201 | + println!( | ||
| 202 | + "quarantined {} orphan blobs to {}; {} younger than an hour were left in place", | ||
| 203 | + moved.len(), | ||
| 204 | + data_dir.join(fsck::QUARANTINE_DIR).display(), | ||
| 205 | + found.len() - moved.len() | ||
| 206 | + ); | ||
| 207 | + for key in &moved { | ||
| 208 | + println!(" moved {key}"); | ||
| 209 | + } | ||
| 210 | + Ok(()) | ||
| 211 | +} | ||
| 212 | + | ||
| 176 | /// `in restore`. Opens nothing of the database itself: the manifest's MAC is checked first (with the instance | 213 | /// `in restore`. Opens nothing of the database itself: the manifest's MAC is checked first (with the instance |
| 177 | /// key, which must already exist), then the snapshot is verified, and only then is the file replaced. True | 214 | /// key, which must already exist), then the snapshot is verified, and only then is the file replaced. True |
| 178 | /// when the restore completed. | 215 | /// when the restore completed. |
| 179 | async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { | 216 | async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { |
| 180 | - let config = in_core::config::Config::load(config_path)?; | 217 | + let config = Config::load(config_path)?; |
| 181 | let _lock = boot::lock_data_dir(&config.data_dir)?; | 218 | let _lock = boot::lock_data_dir(&config.data_dir)?; |
| 182 | let data_dir = config.data_dir.canonicalize()?; | 219 | let data_dir = config.data_dir.canonicalize()?; |
| 183 | // Read, never create: a missing key would make every set fail its MAC, and creating one here would hide that. | 220 | // Read, never create: a missing key would make every set fail its MAC, and creating one here would hide that. |
| 184 | let key = in_core::secret::read_key(&data_dir.join(boot::KEY_FILE))?; | 221 | let key = in_core::secret::read_key(&data_dir.join(boot::KEY_FILE))?; |
| 185 | - let blobs = boot::open_blobs(&config, &data_dir)?; | ||
| 186 | let stamp = now_stamp().replace([':', '.'], "-"); | 222 | let stamp = now_stamp().replace([':', '.'], "-"); |
| 187 | - let outcome = backup::restore( | 223 | + // The blob tree is opened only after the set has passed its checks, so a refusal creates nothing in it. |
| 224 | + let outcome = match backup::restore( | ||
| 188 | &data_dir, | 225 | &data_dir, |
| 189 | &config.database, | 226 | &config.database, |
| 190 | from, | 227 | from, |
| 191 | - blobs.as_ref(), | 228 | + || boot::open_blobs(&config, &data_dir), |
| 192 | &key, | 229 | &key, |
| 193 | &stamp, | 230 | &stamp, |
| 194 | ) | 231 | ) |
| 195 | - .await?; | 232 | + .await |
| 233 | + { | ||
| 234 | + Ok(outcome) => outcome, | ||
| 235 | + Err(Error::Invalid(code)) => match refusal_words(&code) { | ||
| 236 | + Some(words) => { | ||
| 237 | + eprintln!("in: {words}"); | ||
| 238 | + return Ok(false); | ||
| 239 | + } | ||
| 240 | + None => return Err(Error::Invalid(code)), | ||
| 241 | + }, | ||
| 242 | + Err(error) => return Err(error), | ||
| 243 | + }; | ||
| 196 | println!( | 244 | println!( |
| 197 | "restored from {}: {} blobs listed, {} not in the blob tree", | 245 | "restored from {}: {} blobs listed, {} not in the blob tree", |
| 198 | from.display(), | 246 | from.display(), |
| @@ -205,6 +253,26 @@ async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { | |||
| 205 | Ok(true) | 253 | Ok(true) |
| 206 | } | 254 | } |
| 207 | 255 | ||
| 256 | +/// The plain words for a refused restore. The codes are what `in-core` returns and its tests match on them. | ||
| 257 | +fn refusal_words(code: &str) -> Option<&'static str> { | ||
| 258 | + Some(match code { | ||
| 259 | + "backup_hash" => { | ||
| 260 | + "the backup's database does not match its manifest hash: the set is damaged" | ||
| 261 | + } | ||
| 262 | + "backup_mac_bad" => { | ||
| 263 | + "the backup manifest's MAC does not verify: the set was changed, or this is not the instance key it was made with" | ||
| 264 | + } | ||
| 265 | + "backup_mac_missing" => "the backup set has no manifest MAC: the set is incomplete", | ||
| 266 | + "backup_manifest_missing" => "the backup set has no manifest: the set is incomplete", | ||
| 267 | + "backup_manifest_bad" => { | ||
| 268 | + "the backup manifest is unreadable or from another format: the set cannot be restored by this build" | ||
| 269 | + } | ||
| 270 | + "backup_snapshot_missing" => "the backup set has no database file: the set is incomplete", | ||
| 271 | + "backup_integrity" => "the backup's database fails its integrity check: the set is damaged", | ||
| 272 | + _ => return None, | ||
| 273 | + }) | ||
| 274 | +} | ||
| 275 | + | ||
| 208 | /// `in quota recompute`. True when it ran; drift that it corrected is printed, not failed. | 276 | /// `in quota recompute`. True when it ran; drift that it corrected is printed, not failed. |
| 209 | async fn recompute(config: &Path) -> Result<bool, Error> { | 277 | async fn recompute(config: &Path) -> Result<bool, Error> { |
| 210 | let offline = boot::open_offline(config).await?; | 278 | let offline = boot::open_offline(config).await?; |
docs/architecture.mdmodified+3 -2
| @@ -264,8 +264,9 @@ credentials (S3 secret sealed) are Restart settings. | |||
| 264 | 264 | ||
| 265 | A bare `in` (or `in serve`) runs the server. Backups are written by the server's backup worker. | 265 | A bare `in` (or `in serve`) runs the server. Backups are written by the server's backup worker. |
| 266 | `in restore --from SET` replaces the database with a verified set (server stopped; needs the same `in.key`). | 266 | `in restore --from SET` replaces the database with a verified set (server stopped; needs the same `in.key`). |
| 267 | -`in export --member <sub|email> --out DIR` writes a plain tree with real names. `in fsck [--hash]` checks | 267 | +`in export --member <sub|email> --out DIR` writes a plain tree with real names. `in fsck [--hash] [--quarantine]` |
| 268 | -that every row has its blob and every blob has a row (sizes, and hashes with `--hash`); it changes nothing. | 268 | +checks that every row has its blob and every blob has a row (sizes, and hashes with `--hash`); it changes nothing, |
| 269 | +except that `--quarantine` moves orphan blobs over an hour old into `data_dir/quarantine/` (never deletes). | ||
| 269 | `in quota recompute` recomputes used bytes. | 270 | `in quota recompute` recomputes used bytes. |
| 270 | 271 | ||
| 271 | --- | 272 | --- |