use std::collections::BTreeMap;
use std::io::{Read, Seek};
use crate::finding::{Deviation, Family, Finding, Findings, Severity, project};
use super::ondisk::{ItemType, objectid};
use super::volume::{Mirror, ReadError};
pub type ScanReport = crate::ScanReport<Anomaly>;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Category {
Superblock,
ChunkMap,
Tree,
Item,
Data,
Source,
}
impl Category {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Category::Superblock => "superblock",
Category::ChunkMap => "chunk-map",
Category::Tree => "tree",
Category::Item => "item",
Category::Data => "data",
Category::Source => "source",
}
}
}
crate::naming::serialize_as_name!(Category);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Anomaly {
pub category: Category,
pub severity: Severity,
pub tree: Option<u64>,
pub logical: Option<u64>,
pub detail: String,
}
impl Deviation for Anomaly {
fn severity(&self) -> Severity {
self.severity
}
fn is_source_failure(&self) -> bool {
self.category == Category::Source
}
fn to_finding(&self, _unit: u32) -> Finding {
project(
self.severity,
Family::Btrfs,
self.category.as_str(),
&[("tree", self.tree), ("logical", self.logical)],
None,
0,
&self.detail,
)
}
}
pub(super) struct Scan {
pub(super) found: Findings<Anomaly>,
unknown: BTreeMap<u8, u64>,
}
impl Scan {
pub(super) fn new(cap: usize) -> Self {
Self {
found: Findings::new(cap),
unknown: BTreeMap::new(),
}
}
pub(super) fn at(
&mut self,
category: Category,
severity: Severity,
tree: Option<u64>,
logical: Option<u64>,
detail: String,
) {
self.found.push(Anomaly {
category,
severity,
tree,
logical,
detail,
});
}
pub(super) fn met_unknown(&mut self, kind: ItemType) {
if kind.name().is_none() {
*self.unknown.entry(kind.value()).or_default() += 1;
}
}
pub(super) fn finish(mut self) -> ScanReport {
let unknown = std::mem::take(&mut self.unknown);
for (kind, count) in unknown {
self.at(
Category::Item,
Severity::Cosmetic,
None,
None,
format!(
"{count} record{} of item type {kind}, which this release of the format has \
not given a meaning this reader knows; each was skipped",
if count == 1 { "" } else { "s" }
),
);
}
self.found.into_report(0)
}
}
pub(super) fn mirror_anomaly(state: Mirror, live: u64) -> Option<(Severity, &'static str)> {
match state {
Mirror::OutsideDevice => None,
Mirror::Present { generation } if generation == live => None,
Mirror::Present { .. } => Some((
Severity::Conformance,
"a copy of the superblock is behind the live one",
)),
Mirror::Truncated => Some((
Severity::Structural,
"the source is shorter than the device it describes, so this copy is not in it",
)),
Mirror::Absent => Some((
Severity::Integrity,
"a copy of the superblock the device has room for is missing",
)),
Mirror::Damaged => Some((
Severity::Integrity,
"a copy of the superblock fails its own checksum",
)),
Mirror::Misplaced { .. } => Some((
Severity::Integrity,
"a copy of the superblock records another place as its own, which is what an image \
carved out of a disk at the wrong offset looks like",
)),
Mirror::Diverged { .. } => Some((
Severity::Integrity,
"a copy of the superblock at the live generation differs from the live one outside \
its checksum and its own location, so it is not a copy of it",
)),
Mirror::Foreign => Some((
Severity::Integrity,
"a copy of the superblock the device has room for belongs to another filesystem",
)),
}
}
pub(super) fn walk_anomaly(err: &ReadError) -> (Category, Severity) {
match err {
ReadError::Io { kind, .. } if *kind != std::io::ErrorKind::UnexpectedEof => {
(Category::Source, Severity::Structural)
}
ReadError::BadChecksum { .. } | ReadError::DataChecksum { .. } => {
(Category::Tree, Severity::Integrity)
}
ReadError::BadItem { .. } | ReadError::BadRootItem { .. } => {
(Category::Item, Severity::Structural)
}
ReadError::UnmappedLogical { .. }
| ReadError::ChunkOverlap { .. }
| ReadError::BadChunk { .. }
| ReadError::BadBootstrap { .. } => (Category::ChunkMap, Severity::Structural),
_ => (Category::Tree, Severity::Structural),
}
}
#[must_use]
pub fn tree_name(objectid: u64) -> String {
objectid::name(objectid).map_or_else(|| format!("subvolume {objectid}"), str::to_string)
}
pub(super) fn has_live_log<R: Read + Seek>(volume: &super::Volume<R>) -> bool {
volume.superblock().log_root != 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_anomaly_reports_its_address_as_a_coordinate_and_never_as_an_offset() {
let anomaly = Anomaly {
category: Category::Tree,
severity: Severity::Integrity,
tree: Some(objectid::FS_TREE),
logical: Some(30_605_312),
detail: "the checksum does not cover it".to_string(),
};
let finding = anomaly.to_finding(4096);
assert_eq!(finding.offset, None);
assert_eq!(finding.category, "tree");
assert_eq!(finding.severity, Severity::Integrity);
let named: Vec<(&str, u64)> = finding
.coordinates
.iter()
.map(|(name, value)| (name.as_ref(), *value))
.collect();
assert_eq!(named, vec![("tree", 5), ("logical", 30_605_312)]);
}
#[test]
fn an_anomaly_with_no_address_reports_no_coordinate_for_one() {
let anomaly = Anomaly {
category: Category::Superblock,
severity: Severity::Cosmetic,
tree: None,
logical: None,
detail: "a log tree is live".to_string(),
};
assert!(anomaly.to_finding(4096).coordinates.is_empty());
}
#[test]
fn every_record_of_a_type_this_reader_does_not_interpret_is_one_finding() {
let mut scan = Scan::new(64);
for _ in 0..1000 {
scan.met_unknown(ItemType::from_value(77));
}
scan.met_unknown(ItemType::from_value(201));
scan.met_unknown(ItemType::QGROUP_INFO);
let report = scan.finish();
assert_eq!(report.anomalies().len(), 2);
assert!(report.anomalies()[0].detail.contains("1000 records"));
assert!(report.anomalies()[0].detail.contains("item type 77"));
assert!(
report.anomalies()[1]
.detail
.contains("1 record of item type 201")
);
assert!(
report
.anomalies()
.iter()
.all(|a| a.severity == Severity::Cosmetic)
);
}
#[test]
fn the_live_copy_of_the_superblock_is_not_a_finding_and_every_other_state_is() {
assert!(mirror_anomaly(Mirror::OutsideDevice, 8).is_none());
assert!(mirror_anomaly(Mirror::Present { generation: 8 }, 8).is_none());
for state in [
Mirror::Present { generation: 7 },
Mirror::Truncated,
Mirror::Absent,
Mirror::Damaged,
Mirror::Misplaced { bytenr: 0 },
Mirror::Diverged { generation: 8 },
] {
assert!(mirror_anomaly(state, 8).is_some(), "{state:?}");
}
}
#[test]
fn a_tree_is_reported_by_the_name_the_format_gives_it_or_by_its_own_id() {
assert_eq!(tree_name(objectid::FS_TREE), "FS_TREE");
assert_eq!(tree_name(objectid::CSUM_TREE), "CSUM_TREE");
assert_eq!(tree_name(257), "subvolume 257");
}
}