| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Checking a whole store. |
| 5 | //! |
| 6 | //! fsck reads everything from disk, independently of what the handle has |
| 7 | //! cached. Leftovers of crashes are expected and only counted: the end of a |
| 8 | //! record cut short in a segment or in the op log, journal entries that fail |
| 9 | //! their CRC, records no entry points at, temporary files. Everything that |
| 10 | //! could make the store return wrong data or lose data is a [`Problem`]. |
| 11 | //! |
| 12 | //! Records stored whole are decoded as each segment is read. Deltas and |
| 13 | //! chunked blobs need other objects, so they are checked once every segment |
| 14 | //! has been read: a delta's base must be an object stored whole, a chunked |
| 15 | //! blob's chunks must be blobs of the sizes its list gives, and what they |
| 16 | //! decode to must hash to the record's id. |
| 17 | |
| 18 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 19 | use std::fmt; |
| 20 | use std::fs::{self, File}; |
| 21 | use std::io; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::Arc; |
| 24 | |
| 25 | use braid_format::{IdHasher, Kind, ObjectId}; |
| 26 | |
| 27 | use crate::chunks; |
| 28 | use crate::delta; |
| 29 | use crate::error::Error; |
| 30 | use crate::fsutil::{count_temps, read_range}; |
| 31 | use crate::index::{Header as IndexHeader, IndexError}; |
| 32 | use crate::journal::{self, Entry}; |
| 33 | use crate::oplog::{Bad, decode_checkpoint, next_record, not_in_transaction, parse_record}; |
| 34 | use crate::record::{self, CODEC_CHUNKED, CODEC_DELTA, Header}; |
| 35 | use crate::segments::{BaseCache, Files, Listing, list, segment_path}; |
| 36 | use crate::{Store, format_file, index, scan}; |
| 37 | |
| 38 | /// What fsck found. |
| 39 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 40 | pub struct FsckReport { |
| 41 | /// Segment files. |
| 42 | pub segments: usize, |
| 43 | /// Segments that are sealed. |
| 44 | pub sealed_segments: usize, |
| 45 | /// Records whose checksum is valid. |
| 46 | pub records: u64, |
| 47 | /// Of those, records holding a delta against a base object. |
| 48 | pub delta_records: u64, |
| 49 | /// Of those, records holding the chunk list of a blob stored in chunks. |
| 50 | pub chunked_records: u64, |
| 51 | /// Distinct objects that an index or a journal leads to. |
| 52 | pub objects: u64, |
| 53 | /// Valid records that no index or journal entry points at: appends whose |
| 54 | /// journal entry a crash prevented, or copies left out of an index. |
| 55 | pub unindexed_records: u64, |
| 56 | /// Bytes of segments that are not part of any valid record: appends cut |
| 57 | /// short by a crash. They are skipped. |
| 58 | pub torn_segment_bytes: u64, |
| 59 | /// Journal entries that fail their checksum. They are skipped. |
| 60 | pub torn_journal_entries: u64, |
| 61 | /// Operations in the op log. |
| 62 | pub operations: u64, |
| 63 | /// Bytes after the last operation record: an append cut short by a crash. |
| 64 | /// Readers skip them, and the next transaction cuts them off. |
| 65 | pub torn_log_bytes: u64, |
| 66 | /// Checkpoints checked. |
| 67 | pub checkpoints: usize, |
| 68 | /// Refs as of the newest operation. |
| 69 | pub refs: usize, |
| 70 | /// Temporary files: being written now, or left by writers that died. |
| 71 | pub temporary_files: usize, |
| 72 | /// Everything that is wrong. Empty for a healthy store. |
| 73 | pub problems: Vec<Problem>, |
| 74 | } |
| 75 | |
| 76 | impl FsckReport { |
| 77 | /// Whether no problem was found. Leftovers of crashes do not count. |
| 78 | pub fn is_clean(&self) -> bool { |
| 79 | self.problems.is_empty() |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Something wrong in a store. |
| 84 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 85 | #[non_exhaustive] |
| 86 | pub enum Problem { |
| 87 | /// The `format` file is missing, unreadable, or names another format. |
| 88 | Format { |
| 89 | /// What is wrong with it. |
| 90 | detail: String, |
| 91 | }, |
| 92 | /// A file or directory that could not be read. |
| 93 | Unreadable { |
| 94 | /// Its path within the store. |
| 95 | path: String, |
| 96 | /// The error. |
| 97 | detail: String, |
| 98 | }, |
| 99 | /// A record with a valid checksum whose content cannot be decoded or does |
| 100 | /// not hash to its id. |
| 101 | BadRecord { |
| 102 | /// The segment's name. |
| 103 | segment: String, |
| 104 | /// Where the record starts. |
| 105 | offset: u64, |
| 106 | /// What failed. |
| 107 | detail: String, |
| 108 | }, |
| 109 | /// An index or journal entry that does not lead to a whole record of its |
| 110 | /// object. |
| 111 | BadEntry { |
| 112 | /// The segment's name. |
| 113 | segment: String, |
| 114 | /// The object the entry names. |
| 115 | id: ObjectId, |
| 116 | /// Where the entry says the record is. |
| 117 | offset: u64, |
| 118 | /// What failed. |
| 119 | detail: String, |
| 120 | }, |
| 121 | /// An index that fails its checksum or its structure checks, or a |
| 122 | /// sealed segment that no index covers. Lookups work around it by |
| 123 | /// scanning the segment. |
| 124 | BadIndex { |
| 125 | /// The segment's name. |
| 126 | segment: String, |
| 127 | /// What failed. |
| 128 | detail: String, |
| 129 | }, |
| 130 | /// A merged index that fails its checksums or its structure checks, or |
| 131 | /// names a segment that is missing. Lookups work around it by scanning |
| 132 | /// the segments it covers. |
| 133 | BadMergedIndex { |
| 134 | /// The merged index's name. |
| 135 | name: String, |
| 136 | /// What failed. |
| 137 | detail: String, |
| 138 | }, |
| 139 | /// An op log record that is damaged with valid records after it, out of |
| 140 | /// sequence, or inconsistent with the refs before it. |
| 141 | BadOperation { |
| 142 | /// Where the record starts in the log. |
| 143 | offset: u64, |
| 144 | /// What failed. |
| 145 | detail: String, |
| 146 | }, |
| 147 | /// A checkpoint that cannot be read or disagrees with the log. |
| 148 | BadCheckpoint { |
| 149 | /// The checkpoint's file name. |
| 150 | file: String, |
| 151 | /// What failed. |
| 152 | detail: String, |
| 153 | }, |
| 154 | /// A ref whose target is not in the store. |
| 155 | MissingObject { |
| 156 | /// The ref. |
| 157 | name: String, |
| 158 | /// The object it points at. |
| 159 | id: ObjectId, |
| 160 | }, |
| 161 | /// A journal or an index that a newer version of braid wrote, in a store |
| 162 | /// whose `format` file does not say so. Its segment is not checked. |
| 163 | Newer { |
| 164 | /// Its path within the store. |
| 165 | path: String, |
| 166 | /// What this version does not know. |
| 167 | detail: String, |
| 168 | }, |
| 169 | } |
| 170 | |
| 171 | impl fmt::Display for Problem { |
| 172 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 173 | match self { |
| 174 | Problem::Format { detail } => write!(f, "format file: {detail}"), |
| 175 | Problem::Newer { path, detail } => { |
| 176 | write!(f, "{path}: written by a newer version of braid: {detail}") |
| 177 | } |
| 178 | Problem::Unreadable { path, detail } => write!(f, "{path}: cannot read: {detail}"), |
| 179 | Problem::BadRecord { |
| 180 | segment, |
| 181 | offset, |
| 182 | detail, |
| 183 | } => write!(f, "segment {segment}, record at byte {offset}: {detail}"), |
| 184 | Problem::BadEntry { |
| 185 | segment, |
| 186 | id, |
| 187 | offset, |
| 188 | detail, |
| 189 | } => write!( |
| 190 | f, |
| 191 | "segment {segment}, entry for {id} at byte {offset}: {detail}" |
| 192 | ), |
| 193 | Problem::BadIndex { segment, detail } => { |
| 194 | write!(f, "segment {segment}, index: {detail}") |
| 195 | } |
| 196 | Problem::BadMergedIndex { name, detail } => { |
| 197 | write!(f, "merged index {name}: {detail}") |
| 198 | } |
| 199 | Problem::BadOperation { offset, detail } => { |
| 200 | write!(f, "op log, record at byte {offset}: {detail}") |
| 201 | } |
| 202 | Problem::BadCheckpoint { file, detail } => write!(f, "op log, {file}: {detail}"), |
| 203 | Problem::MissingObject { name, id } => { |
| 204 | write!(f, "ref {name:?} points at {id}, which is not in the store") |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | /// A record found by scanning, and whether its content checks out. |
| 211 | struct Found { |
| 212 | header: Header, |
| 213 | crc: u32, |
| 214 | content: Content, |
| 215 | } |
| 216 | |
| 217 | /// Whether a record's content checks out. |
| 218 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 219 | enum Content { |
| 220 | /// It decodes and hashes to its id. |
| 221 | Good, |
| 222 | /// It does not. |
| 223 | Bad, |
| 224 | /// A delta or a chunk list: checked once every segment is read. |
| 225 | Later, |
| 226 | } |
| 227 | |
| 228 | /// A record that an entry leads to, by segment number and offset. |
| 229 | #[derive(Clone, Copy, Debug)] |
| 230 | struct Located { |
| 231 | segment: usize, |
| 232 | offset: u64, |
| 233 | header: Header, |
| 234 | } |
| 235 | |
| 236 | /// What the first pass over the segments collects for the second. |
| 237 | #[derive(Default)] |
| 238 | struct Collected { |
| 239 | /// Segment paths, by number. |
| 240 | segments: Vec<PathBuf>, |
| 241 | /// Objects an entry leads to, whose content checks out. |
| 242 | objects: HashSet<ObjectId>, |
| 243 | /// Of those, a copy stored whole of each object. |
| 244 | whole: HashMap<ObjectId, Located>, |
| 245 | /// Deltas and chunk lists that an entry leads to, to check. |
| 246 | later: Vec<Located>, |
| 247 | /// Of those, the deltas that checked out, for chunks stored as deltas. |
| 248 | deltas: HashMap<ObjectId, Located>, |
| 249 | } |
| 250 | |
| 251 | impl Store { |
| 252 | /// Checks the whole store: every segment record (checksum, and that its |
| 253 | /// content hashes to its id), every journal and index entry (it leads to |
| 254 | /// a whole record of the same object), every delta (its base is an |
| 255 | /// object stored whole, and applying it gives its id), every chunked |
| 256 | /// blob (its chunks are there with the sizes it lists, and together hash |
| 257 | /// to its id), every op log record (checksum, sequence, and that each |
| 258 | /// update's old value matches), every checkpoint, and that every ref |
| 259 | /// points at an object in the store. |
| 260 | /// |
| 261 | /// It can run while other processes use the store. Errors are only |
| 262 | /// returned when fsck itself cannot run; damage goes in the report. Like |
| 263 | /// the other op log reads, it cannot run inside a transaction's closure. |
| 264 | pub fn fsck(&self) -> Result<FsckReport, Error> { |
| 265 | not_in_transaction()?; |
| 266 | let mut report = FsckReport::default(); |
| 267 | let storage = self.check_format(&mut report); |
| 268 | // The op log first: every object a record points at was durable |
| 269 | // before the record, so the segments listed afterwards hold it. |
| 270 | let refs = self.check_oplog(&mut report)?; |
| 271 | let objects = self.check_segments(&mut report); |
| 272 | // Records that need a storage version the store does not declare |
| 273 | // could be read by a version of braid that does not know them. |
| 274 | if let Some(storage) = storage |
| 275 | && storage < 2 |
| 276 | && report.delta_records + report.chunked_records > 0 |
| 277 | { |
| 278 | report.problems.push(Problem::Format { |
| 279 | detail: format!( |
| 280 | "it says storage version {storage}, but the store holds deltas or chunked \ |
| 281 | blobs, which need version 2" |
| 282 | ), |
| 283 | }); |
| 284 | } |
| 285 | report.objects = objects.len() as u64; |
| 286 | report.refs = refs.len(); |
| 287 | for (name, id) in refs { |
| 288 | if !objects.contains(&id) { |
| 289 | report.problems.push(Problem::MissingObject { name, id }); |
| 290 | } |
| 291 | } |
| 292 | report.temporary_files = [ |
| 293 | self.root.clone(), |
| 294 | self.root.join("seg"), |
| 295 | self.root.join("oplog"), |
| 296 | ] |
| 297 | .iter() |
| 298 | .map(|dir| count_temps(dir)) |
| 299 | .sum(); |
| 300 | Ok(report) |
| 301 | } |
| 302 | |
| 303 | /// Checks the `format` file, and returns the storage version it says. |
| 304 | fn check_format(&self, report: &mut FsckReport) -> Option<u32> { |
| 305 | match format_file::read(&self.root) { |
| 306 | Ok(storage) => Some(storage), |
| 307 | Err(err) => { |
| 308 | report.problems.push(Problem::Format { |
| 309 | detail: err.to_string(), |
| 310 | }); |
| 311 | None |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /// Replays the whole log and checks the checkpoints against it. Returns |
| 317 | /// the refs as of the newest operation. |
| 318 | fn check_oplog(&self, report: &mut FsckReport) -> Result<BTreeMap<String, ObjectId>, Error> { |
| 319 | // Shared: no transaction runs while the log and checkpoints are read. |
| 320 | let _shared = self.oplog.lock(false)?; |
| 321 | let mut refs = BTreeMap::new(); |
| 322 | let bytes = match fs::read(self.oplog.log_path()) { |
| 323 | Ok(bytes) => bytes, |
| 324 | Err(err) if err.kind() == io::ErrorKind::NotFound => Vec::new(), |
| 325 | Err(err) => { |
| 326 | report.problems.push(unreadable("oplog/log", &err)); |
| 327 | return Ok(refs); |
| 328 | } |
| 329 | }; |
| 330 | let checkpoints = match self.oplog.checkpoints() { |
| 331 | Ok(checkpoints) => checkpoints, |
| 332 | Err(err) => { |
| 333 | report.problems.push(Problem::Unreadable { |
| 334 | path: "oplog".to_owned(), |
| 335 | detail: err.to_string(), |
| 336 | }); |
| 337 | Vec::new() |
| 338 | } |
| 339 | }; |
| 340 | let wanted: HashSet<u64> = checkpoints.iter().map(|(seq, _)| *seq).collect(); |
| 341 | let mut snapshots = HashMap::new(); |
| 342 | |
| 343 | let mut seq = 0u64; |
| 344 | let mut at = 0usize; |
| 345 | while at < bytes.len() { |
| 346 | let offset = at as u64; |
| 347 | match parse_record(&bytes[at..]) { |
| 348 | Ok((op, len)) => { |
| 349 | if op.seq != seq + 1 { |
| 350 | report.problems.push(Problem::BadOperation { |
| 351 | offset, |
| 352 | detail: format!("operation {} follows operation {seq}", op.seq), |
| 353 | }); |
| 354 | } |
| 355 | for update in &op.updates { |
| 356 | let current = refs.get(&update.name).copied(); |
| 357 | if current != update.old { |
| 358 | report.problems.push(Problem::BadOperation { |
| 359 | offset, |
| 360 | detail: format!( |
| 361 | "operation {} expects ref {:?} at {}, but it was at {}", |
| 362 | op.seq, |
| 363 | update.name, |
| 364 | show(update.old), |
| 365 | show(current) |
| 366 | ), |
| 367 | }); |
| 368 | } |
| 369 | match update.new { |
| 370 | Some(id) => refs.insert(update.name.clone(), id), |
| 371 | None => refs.remove(&update.name), |
| 372 | }; |
| 373 | } |
| 374 | seq = op.seq; |
| 375 | at += len as usize; |
| 376 | report.operations += 1; |
| 377 | if wanted.contains(&seq) { |
| 378 | snapshots.insert(seq, (refs.clone(), at as u64)); |
| 379 | } |
| 380 | } |
| 381 | Err(Bad::Damaged(detail, len)) => { |
| 382 | report.problems.push(Problem::BadOperation { |
| 383 | offset, |
| 384 | detail: detail.to_owned(), |
| 385 | }); |
| 386 | at += len as usize; |
| 387 | } |
| 388 | Err(Bad::Torn) => match next_record(&bytes, at + 1, seq) { |
| 389 | Some(next) => { |
| 390 | report.problems.push(Problem::BadOperation { |
| 391 | offset, |
| 392 | detail: "damaged record with valid records after it".to_owned(), |
| 393 | }); |
| 394 | at = next; |
| 395 | } |
| 396 | None => { |
| 397 | report.torn_log_bytes = (bytes.len() - at) as u64; |
| 398 | break; |
| 399 | } |
| 400 | }, |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | for (checkpoint_seq, path) in checkpoints { |
| 405 | let file = format!("ckpt.{checkpoint_seq}"); |
| 406 | let bytes = match fs::read(&path) { |
| 407 | Ok(bytes) => bytes, |
| 408 | // Removed since the listing: a newer one replaced it. |
| 409 | Err(err) if err.kind() == io::ErrorKind::NotFound => continue, |
| 410 | Err(err) => { |
| 411 | report |
| 412 | .problems |
| 413 | .push(unreadable(&format!("oplog/{file}"), &err)); |
| 414 | continue; |
| 415 | } |
| 416 | }; |
| 417 | report.checkpoints += 1; |
| 418 | let detail = match decode_checkpoint(&bytes) { |
| 419 | Err(detail) => detail.to_owned(), |
| 420 | Ok(checkpoint) if checkpoint.refs.seq() != checkpoint_seq => { |
| 421 | format!("holds the refs of operation {}", checkpoint.refs.seq()) |
| 422 | } |
| 423 | Ok(checkpoint) => match snapshots.get(&checkpoint_seq) { |
| 424 | None => "names an operation that is not in the log".to_owned(), |
| 425 | Some((expected, end)) |
| 426 | if *expected == *checkpoint.refs.as_map() && *end == checkpoint.end => |
| 427 | { |
| 428 | continue; |
| 429 | } |
| 430 | Some(_) => "disagrees with the log".to_owned(), |
| 431 | }, |
| 432 | }; |
| 433 | report |
| 434 | .problems |
| 435 | .push(Problem::BadCheckpoint { file, detail }); |
| 436 | } |
| 437 | Ok(refs) |
| 438 | } |
| 439 | |
| 440 | /// Checks every segment and index. Returns the objects that an entry |
| 441 | /// leads to and whose content checks out. |
| 442 | fn check_segments(&self, report: &mut FsckReport) -> HashSet<ObjectId> { |
| 443 | let dir = self.root.join("seg"); |
| 444 | let mut collected = Collected::default(); |
| 445 | let listing = match list(&dir) { |
| 446 | Ok(listing) => listing, |
| 447 | Err(err) => { |
| 448 | report.problems.push(Problem::Unreadable { |
| 449 | path: "seg".to_owned(), |
| 450 | detail: err.to_string(), |
| 451 | }); |
| 452 | return collected.objects; |
| 453 | } |
| 454 | }; |
| 455 | let mut merged = check_merged(&dir, &listing, report); |
| 456 | for (name, files) in &listing.segments { |
| 457 | let covered = merged.remove(name.as_str()).unwrap_or_default(); |
| 458 | if !files.seg { |
| 459 | if files.idx || !covered.is_empty() { |
| 460 | report.problems.push(Problem::BadIndex { |
| 461 | segment: name.clone(), |
| 462 | detail: "the segment file is missing".to_owned(), |
| 463 | }); |
| 464 | } |
| 465 | continue; |
| 466 | } |
| 467 | report.segments += 1; |
| 468 | check_segment(&dir, name, *files, covered, report, &mut collected); |
| 469 | } |
| 470 | for (segment, sets) in merged { |
| 471 | for set in sets { |
| 472 | report.problems.push(Problem::BadMergedIndex { |
| 473 | name: set.merged.unwrap_or_default(), |
| 474 | detail: format!("it covers segment {segment}, whose file is missing"), |
| 475 | }); |
| 476 | } |
| 477 | } |
| 478 | collected.check_later(report); |
| 479 | collected.objects |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// Reads and checks every merged index whole, and returns what each says |
| 484 | /// of the segments it covers, by segment. |
| 485 | fn check_merged( |
| 486 | dir: &Path, |
| 487 | listing: &Listing, |
| 488 | report: &mut FsckReport, |
| 489 | ) -> HashMap<String, Vec<Entries>> { |
| 490 | let mut out: HashMap<String, Vec<Entries>> = HashMap::new(); |
| 491 | for name in &listing.merged { |
| 492 | let shown = format!("seg/{name}.midx"); |
| 493 | let bytes = match fs::read(segment_path(dir, name, "midx")) { |
| 494 | Ok(bytes) => bytes, |
| 495 | // Merged into another one since the listing. |
| 496 | Err(err) if err.kind() == io::ErrorKind::NotFound => continue, |
| 497 | Err(err) => { |
| 498 | report.problems.push(unreadable(&shown, &err)); |
| 499 | continue; |
| 500 | } |
| 501 | }; |
| 502 | match index::decode(&bytes, None) { |
| 503 | Ok(decoded) => { |
| 504 | let mut sets: Vec<Entries> = decoded |
| 505 | .covered |
| 506 | .iter() |
| 507 | .map(|segment| Entries { |
| 508 | entries: Vec::new(), |
| 509 | rebuild: false, |
| 510 | sealed_len: Some(segment.len), |
| 511 | merged: Some(name.clone()), |
| 512 | }) |
| 513 | .collect(); |
| 514 | for (entry, segment) in decoded.entries { |
| 515 | sets[usize::from(segment)].entries.push(entry); |
| 516 | } |
| 517 | for (segment, set) in decoded.covered.into_iter().zip(sets) { |
| 518 | out.entry(segment.name).or_default().push(set); |
| 519 | } |
| 520 | } |
| 521 | Err(IndexError::Newer(detail)) => report.problems.push(Problem::Newer { |
| 522 | path: shown, |
| 523 | detail: format!("it holds {detail}"), |
| 524 | }), |
| 525 | Err(IndexError::Damaged(detail)) => { |
| 526 | report.problems.push(Problem::BadMergedIndex { |
| 527 | name: name.clone(), |
| 528 | detail: detail.to_owned(), |
| 529 | }); |
| 530 | // Its segments are checked from their records, as lookups |
| 531 | // read them, if its head still says which they are. |
| 532 | let head = match index::header(&bytes) { |
| 533 | Ok(IndexHeader::V2 { segments, .. }) => bytes |
| 534 | .get(..IndexHeader::head_len(segments)) |
| 535 | .and_then(|head| index::head(head).ok()), |
| 536 | _ => None, |
| 537 | }; |
| 538 | for segment in head.map(|head| head.covered).unwrap_or_default() { |
| 539 | out.entry(segment.name).or_default().push(Entries { |
| 540 | entries: Vec::new(), |
| 541 | rebuild: true, |
| 542 | sealed_len: None, |
| 543 | merged: Some(name.clone()), |
| 544 | }); |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | } |
| 549 | out |
| 550 | } |
| 551 | |
| 552 | fn check_segment( |
| 553 | dir: &Path, |
| 554 | name: &str, |
| 555 | files: Files, |
| 556 | merged: Vec<Entries>, |
| 557 | report: &mut FsckReport, |
| 558 | collected: &mut Collected, |
| 559 | ) { |
| 560 | // Entries before records: an entry is written after its record, so every |
| 561 | // record an entry read now points at is already in the segment. |
| 562 | let mut sets = merged; |
| 563 | let own = segment_entries(dir, name, files, !sets.is_empty(), report); |
| 564 | let Some(own) = own else { |
| 565 | return; |
| 566 | }; |
| 567 | sets.extend(own); |
| 568 | |
| 569 | let seg_path = segment_path(dir, name, "seg"); |
| 570 | let seg_name = format!("seg/{name}.seg"); |
| 571 | let file = match File::open(&seg_path) { |
| 572 | Ok(file) => file, |
| 573 | Err(err) => { |
| 574 | report.problems.push(unreadable(&seg_name, &err)); |
| 575 | return; |
| 576 | } |
| 577 | }; |
| 578 | let len = match file.metadata() { |
| 579 | Ok(meta) => meta.len(), |
| 580 | Err(err) => { |
| 581 | report.problems.push(unreadable(&seg_name, &err)); |
| 582 | return; |
| 583 | } |
| 584 | }; |
| 585 | for set in &sets { |
| 586 | if let Some(sealed_len) = set.sealed_len |
| 587 | && sealed_len != len |
| 588 | { |
| 589 | let detail = format!("the segment was {sealed_len} bytes when sealed and is {len} now"); |
| 590 | report.problems.push(match &set.merged { |
| 591 | Some(merged) => Problem::BadMergedIndex { |
| 592 | name: merged.clone(), |
| 593 | detail: format!("segment {name}: {detail}"), |
| 594 | }, |
| 595 | None => Problem::BadIndex { |
| 596 | segment: name.to_owned(), |
| 597 | detail, |
| 598 | }, |
| 599 | }); |
| 600 | } |
| 601 | } |
| 602 | // A sealed segment that no index covers: its records are read by |
| 603 | // scanning, as lookups do. |
| 604 | if sets.is_empty() && len > 0 { |
| 605 | report.problems.push(Problem::BadIndex { |
| 606 | segment: name.to_owned(), |
| 607 | detail: "no index or journal covers this segment".to_owned(), |
| 608 | }); |
| 609 | sets.push(Entries { |
| 610 | entries: Vec::new(), |
| 611 | rebuild: true, |
| 612 | sealed_len: None, |
| 613 | merged: None, |
| 614 | }); |
| 615 | } |
| 616 | let mut records = BTreeMap::new(); |
| 617 | let mut problems = Vec::new(); |
| 618 | let scanned = scan::scan(&file, len, |offset, found| { |
| 619 | let codec = found.header.codec; |
| 620 | let content = if codec == CODEC_DELTA || codec == CODEC_CHUNKED { |
| 621 | Content::Later |
| 622 | } else { |
| 623 | match record::decode(&found.header, found.stored) { |
| 624 | Ok(_) => Content::Good, |
| 625 | Err(detail) => { |
| 626 | problems.push(Problem::BadRecord { |
| 627 | segment: name.to_owned(), |
| 628 | offset, |
| 629 | detail: format!("object {}: {detail}", found.header.id), |
| 630 | }); |
| 631 | Content::Bad |
| 632 | } |
| 633 | } |
| 634 | }; |
| 635 | records.insert( |
| 636 | offset, |
| 637 | Found { |
| 638 | header: found.header, |
| 639 | crc: found.crc, |
| 640 | content, |
| 641 | }, |
| 642 | ); |
| 643 | }); |
| 644 | match scanned { |
| 645 | Ok(scanned) => { |
| 646 | report.records += scanned.records; |
| 647 | report.torn_segment_bytes += scanned.junk; |
| 648 | } |
| 649 | Err(err) => { |
| 650 | report.problems.push(unreadable(&seg_name, &err)); |
| 651 | return; |
| 652 | } |
| 653 | } |
| 654 | report.problems.append(&mut problems); |
| 655 | for found in records.values() { |
| 656 | match found.header.codec { |
| 657 | CODEC_DELTA => report.delta_records += 1, |
| 658 | CODEC_CHUNKED => report.chunked_records += 1, |
| 659 | _ => {} |
| 660 | } |
| 661 | } |
| 662 | let segment = collected.segments.len(); |
| 663 | collected.segments.push(seg_path); |
| 664 | |
| 665 | // A damaged index is worked around by scanning, as lookups do. |
| 666 | let mut entries = Vec::new(); |
| 667 | for set in sets { |
| 668 | if set.rebuild { |
| 669 | entries.extend( |
| 670 | records |
| 671 | .iter() |
| 672 | .map(|(offset, found)| Entry::new(*offset, &found.header, found.crc)), |
| 673 | ); |
| 674 | } else { |
| 675 | entries.extend(set.entries); |
| 676 | } |
| 677 | } |
| 678 | let mut referenced = HashSet::new(); |
| 679 | for entry in &entries { |
| 680 | let bad_entry = |detail: &str| Problem::BadEntry { |
| 681 | segment: name.to_owned(), |
| 682 | id: entry.id, |
| 683 | offset: entry.offset, |
| 684 | detail: detail.to_owned(), |
| 685 | }; |
| 686 | match records.get(&entry.offset) { |
| 687 | None => report |
| 688 | .problems |
| 689 | .push(bad_entry("no whole record starts there")), |
| 690 | Some(found) => { |
| 691 | referenced.insert(entry.offset); |
| 692 | if found.header != entry.header() || found.crc != entry.crc { |
| 693 | report |
| 694 | .problems |
| 695 | .push(bad_entry("the record there is another one")); |
| 696 | continue; |
| 697 | } |
| 698 | let copy = Located { |
| 699 | segment, |
| 700 | offset: entry.offset, |
| 701 | header: found.header, |
| 702 | }; |
| 703 | match found.content { |
| 704 | Content::Good => { |
| 705 | collected.objects.insert(entry.id); |
| 706 | collected.whole.entry(entry.id).or_insert(copy); |
| 707 | } |
| 708 | Content::Later => collected.later.push(copy), |
| 709 | Content::Bad => {} |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | } |
| 714 | report.unindexed_records += (records.len() - referenced.len()) as u64; |
| 715 | } |
| 716 | |
| 717 | impl Collected { |
| 718 | /// The second pass: deltas, then chunked blobs, whose chunks may be |
| 719 | /// deltas. A record that checks out adds its object; one that does not |
| 720 | /// is a bad record. |
| 721 | fn check_later(&mut self, report: &mut FsckReport) { |
| 722 | let named = self.named(); |
| 723 | let mut reader = Reader { |
| 724 | segments: &self.segments, |
| 725 | files: HashMap::new(), |
| 726 | bases: BaseCache::default(), |
| 727 | }; |
| 728 | let (deltas, lists): (Vec<Located>, Vec<Located>) = std::mem::take(&mut self.later) |
| 729 | .into_iter() |
| 730 | .partition(|copy| copy.header.codec == CODEC_DELTA); |
| 731 | let mut problems = Vec::new(); |
| 732 | for copy in deltas { |
| 733 | match reader.delta(©, &self.whole, &named) { |
| 734 | Ok(_) => { |
| 735 | self.objects.insert(copy.header.id); |
| 736 | self.deltas.entry(copy.header.id).or_insert(copy); |
| 737 | } |
| 738 | Err(detail) => problems.push(reader.bad_record(©, &detail)), |
| 739 | } |
| 740 | } |
| 741 | for copy in lists { |
| 742 | match reader.chunked(©, &self.whole, &self.deltas, &named) { |
| 743 | Ok(()) => { |
| 744 | self.objects.insert(copy.header.id); |
| 745 | } |
| 746 | Err(detail) => problems.push(reader.bad_record(©, &detail)), |
| 747 | } |
| 748 | } |
| 749 | report.problems.append(&mut problems); |
| 750 | } |
| 751 | |
| 752 | /// Every object an entry leads to, whatever its content. |
| 753 | fn named(&self) -> HashSet<ObjectId> { |
| 754 | self.whole |
| 755 | .keys() |
| 756 | .chain(self.later.iter().map(|copy| ©.header.id)) |
| 757 | .copied() |
| 758 | .collect() |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// Reads records for the second pass. |
| 763 | struct Reader<'a> { |
| 764 | segments: &'a [PathBuf], |
| 765 | files: HashMap<usize, File>, |
| 766 | bases: BaseCache, |
| 767 | } |
| 768 | |
| 769 | impl Reader<'_> { |
| 770 | /// The bytes of a record, checked again. |
| 771 | fn record(&mut self, copy: &Located) -> Result<Vec<u8>, String> { |
| 772 | let path = &self.segments[copy.segment]; |
| 773 | let file = match self.files.entry(copy.segment) { |
| 774 | std::collections::hash_map::Entry::Occupied(slot) => slot.into_mut(), |
| 775 | std::collections::hash_map::Entry::Vacant(slot) => { |
| 776 | slot.insert(File::open(path).map_err(|err| err.to_string())?) |
| 777 | } |
| 778 | }; |
| 779 | let bytes = read_range(file, copy.offset, copy.header.unpadded_len()) |
| 780 | .map_err(|err| format!("cannot read it again: {err}"))?; |
| 781 | match record::check(&bytes) { |
| 782 | Ok(found) if found.header == copy.header => Ok(bytes), |
| 783 | _ => Err("its record changed while fsck ran".to_owned()), |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | /// The payload of an object stored whole. |
| 788 | fn whole(&mut self, copy: &Located) -> Result<Arc<Vec<u8>>, String> { |
| 789 | if let Some(payload) = self.bases.get(©.header.id) { |
| 790 | return Ok(payload); |
| 791 | } |
| 792 | let bytes = self.record(copy)?; |
| 793 | let found = record::check(&bytes).map_err(str::to_owned)?; |
| 794 | let payload = Arc::new(record::decode(&found.header, found.stored).map_err(str::to_owned)?); |
| 795 | self.bases.insert(copy.header.id, Arc::clone(&payload)); |
| 796 | Ok(payload) |
| 797 | } |
| 798 | |
| 799 | /// The payload of a delta, checked against its base and its id. |
| 800 | fn delta( |
| 801 | &mut self, |
| 802 | copy: &Located, |
| 803 | whole: &HashMap<ObjectId, Located>, |
| 804 | named: &HashSet<ObjectId>, |
| 805 | ) -> Result<Vec<u8>, String> { |
| 806 | let bytes = self.record(copy)?; |
| 807 | let found = record::check(&bytes).map_err(str::to_owned)?; |
| 808 | let base = found.reference.ok_or("a delta without a base")?; |
| 809 | let base_copy = match whole.get(&base) { |
| 810 | Some(base_copy) => base_copy, |
| 811 | None if named.contains(&base) => { |
| 812 | return Err(format!("its base {base} has no good copy stored whole")); |
| 813 | } |
| 814 | None => return Err(format!("its base {base} is missing")), |
| 815 | }; |
| 816 | let base_payload = self |
| 817 | .whole(base_copy) |
| 818 | .map_err(|detail| format!("its base {base}: {detail}"))?; |
| 819 | delta::decode(&found.header, found.stored, &base_payload).map_err(str::to_owned) |
| 820 | } |
| 821 | |
| 822 | /// Checks a chunked blob: every chunk is a blob of the size the list |
| 823 | /// gives, stored whole or as a delta, and together they hash to the |
| 824 | /// blob's id. |
| 825 | fn chunked( |
| 826 | &mut self, |
| 827 | copy: &Located, |
| 828 | whole: &HashMap<ObjectId, Located>, |
| 829 | deltas: &HashMap<ObjectId, Located>, |
| 830 | named: &HashSet<ObjectId>, |
| 831 | ) -> Result<(), String> { |
| 832 | let bytes = self.record(copy)?; |
| 833 | let found = record::check(&bytes).map_err(str::to_owned)?; |
| 834 | let chunks = |
| 835 | chunks::decode_list(found.stored, found.header.raw_len).map_err(str::to_owned)?; |
| 836 | let mut hasher = IdHasher::new(Kind::Blob); |
| 837 | for chunk in &chunks { |
| 838 | let fits = |candidate: &Located| { |
| 839 | candidate.header.kind == Kind::Blob && candidate.header.raw_len == chunk.size |
| 840 | }; |
| 841 | let payload = match (whole.get(&chunk.id), deltas.get(&chunk.id)) { |
| 842 | (Some(chunk_copy), _) if fits(chunk_copy) => self.whole(chunk_copy)?.to_vec(), |
| 843 | (_, Some(chunk_copy)) if fits(chunk_copy) => { |
| 844 | self.delta(chunk_copy, whole, named)? |
| 845 | } |
| 846 | _ => { |
| 847 | return Err(format!( |
| 848 | "its chunk {} has no good copy as a blob of {} bytes", |
| 849 | chunk.id, chunk.size |
| 850 | )); |
| 851 | } |
| 852 | }; |
| 853 | hasher.update(&payload); |
| 854 | } |
| 855 | if hasher.finalize() != found.header.id { |
| 856 | return Err("its chunks do not hash to its id".to_owned()); |
| 857 | } |
| 858 | Ok(()) |
| 859 | } |
| 860 | |
| 861 | fn bad_record(&self, copy: &Located, detail: &str) -> Problem { |
| 862 | let segment = self.segments[copy.segment] |
| 863 | .file_stem() |
| 864 | .map(|stem| stem.to_string_lossy().into_owned()) |
| 865 | .unwrap_or_default(); |
| 866 | Problem::BadRecord { |
| 867 | segment, |
| 868 | offset: copy.offset, |
| 869 | detail: format!("object {}: {detail}", copy.header.id), |
| 870 | } |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | /// What an index or a journal says of one segment. |
| 875 | #[derive(Default)] |
| 876 | struct Entries { |
| 877 | entries: Vec<Entry>, |
| 878 | /// The index is damaged: rebuild the entries from the records, as lookups do. |
| 879 | rebuild: bool, |
| 880 | /// The segment's length when it was sealed. |
| 881 | sealed_len: Option<u64>, |
| 882 | /// The merged index it comes from, if it does. |
| 883 | merged: Option<String>, |
| 884 | } |
| 885 | |
| 886 | /// The entries of a segment from its own index, if it has one, else from |
| 887 | /// its journal, unless `merged` says a merged index covers it: none for a |
| 888 | /// segment that has neither. `None` if they cannot be read, and the segment |
| 889 | /// is not checked. |
| 890 | fn segment_entries( |
| 891 | dir: &Path, |
| 892 | name: &str, |
| 893 | files: Files, |
| 894 | merged: bool, |
| 895 | report: &mut FsckReport, |
| 896 | ) -> Option<Vec<Entries>> { |
| 897 | if merged { |
| 898 | report.sealed_segments += 1; |
| 899 | } |
| 900 | if !files.idx && files.jrn && !merged { |
| 901 | let path = segment_path(dir, name, "jrn"); |
| 902 | let shown = format!("seg/{name}.jrn"); |
| 903 | match File::open(&path) { |
| 904 | Ok(file) => { |
| 905 | return match journal::read(&file, 0, &path) { |
| 906 | Ok(read) => { |
| 907 | report.torn_journal_entries += read.invalid; |
| 908 | Some(vec![Entries { |
| 909 | entries: read.entries, |
| 910 | ..Entries::default() |
| 911 | }]) |
| 912 | } |
| 913 | Err(Error::NewerStore { detail, .. }) => { |
| 914 | report.problems.push(Problem::Newer { |
| 915 | path: shown, |
| 916 | detail, |
| 917 | }); |
| 918 | None |
| 919 | } |
| 920 | Err(err) => { |
| 921 | report.problems.push(Problem::Unreadable { |
| 922 | path: shown, |
| 923 | detail: err.to_string(), |
| 924 | }); |
| 925 | None |
| 926 | } |
| 927 | }; |
| 928 | } |
| 929 | // Sealed since the listing: read the index instead. |
| 930 | Err(err) if err.kind() == io::ErrorKind::NotFound => {} |
| 931 | Err(err) => { |
| 932 | report.problems.push(unreadable(&shown, &err)); |
| 933 | return None; |
| 934 | } |
| 935 | } |
| 936 | } |
| 937 | let path = segment_path(dir, name, "idx"); |
| 938 | match fs::read(&path) { |
| 939 | Ok(bytes) => { |
| 940 | if !merged { |
| 941 | report.sealed_segments += 1; |
| 942 | } |
| 943 | match index::decode(&bytes, Some(name)) { |
| 944 | Ok(index) => Some(vec![Entries { |
| 945 | entries: index.entries.into_iter().map(|(entry, _)| entry).collect(), |
| 946 | sealed_len: index.covered.first().map(|segment| segment.len), |
| 947 | ..Entries::default() |
| 948 | }]), |
| 949 | Err(IndexError::Newer(detail)) => { |
| 950 | report.problems.push(Problem::Newer { |
| 951 | path: format!("seg/{name}.idx"), |
| 952 | detail: format!("it holds {detail}"), |
| 953 | }); |
| 954 | None |
| 955 | } |
| 956 | Err(IndexError::Damaged(detail)) => { |
| 957 | report.problems.push(Problem::BadIndex { |
| 958 | segment: name.to_owned(), |
| 959 | detail: detail.to_owned(), |
| 960 | }); |
| 961 | Some(vec![Entries { |
| 962 | rebuild: true, |
| 963 | ..Entries::default() |
| 964 | }]) |
| 965 | } |
| 966 | } |
| 967 | } |
| 968 | // Merged since the listing: its records are read by scanning. |
| 969 | Err(err) if err.kind() == io::ErrorKind::NotFound && (files.idx || files.jrn) => { |
| 970 | Some(vec![Entries { |
| 971 | rebuild: true, |
| 972 | ..Entries::default() |
| 973 | }]) |
| 974 | } |
| 975 | // No index of its own: merged, or never written to. |
| 976 | Err(err) if err.kind() == io::ErrorKind::NotFound => Some(Vec::new()), |
| 977 | Err(err) => { |
| 978 | report |
| 979 | .problems |
| 980 | .push(unreadable(&format!("seg/{name}.idx"), &err)); |
| 981 | None |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | fn unreadable(path: &str, err: &io::Error) -> Problem { |
| 987 | Problem::Unreadable { |
| 988 | path: path.to_owned(), |
| 989 | detail: err.to_string(), |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | fn show(id: Option<ObjectId>) -> String { |
| 994 | id.map_or_else(|| "nothing".to_owned(), |id| id.to_hex()) |
| 995 | } |