Skip to main content

writerslogic_warm/core/
failpoint.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Fault injection at the store's durability points, for the crash and disk-fault tests.
5//!
6//! Every write-back, sync, rename, scrub and unlink of the commit and purge paths calls
7//! `hit` with a stable name. Without the `failpoints` feature `hit` is an inlined `Ok(())`.
8//! With it, the n-th hit (counted across all names, from 1) can be made to
9//!
10//! - `exit`: end the process at once with [`EXIT_CODE`] and no unwinding, which is what a
11//!   killed process looks like to the files (the page cache survives, nothing is flushed);
12//! - `enospc` or `eio`: return that I/O error, once (`:once`, the default) or from then on
13//!   (`:sticky`, a disk that stays full or broken).
14//!
15//! A child process arms itself from `WARM_FAILPOINT=<kind>[:sticky]@<n>`;
16//! `WARM_FAILPOINT_TRACE=<path>` appends each hit's name to a file. A test in the same process
17//! uses `arm`, `disarm` and `hits`.
18
19use std::io;
20
21/// Exit status of a process ended by an `exit` failpoint.
22pub const EXIT_CODE: i32 = 86;
23
24/// What the armed hit does.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Fault {
27    /// End the process without unwinding.
28    Exit,
29    /// Fail with "no space left on device".
30    NoSpace,
31    /// Fail with an I/O error.
32    Io,
33}
34
35#[cfg(not(feature = "failpoints"))]
36#[inline(always)]
37pub(crate) fn hit(_name: &'static str) -> io::Result<()> {
38    Ok(())
39}
40
41#[cfg(feature = "failpoints")]
42pub(crate) use enabled::hit;
43#[cfg(feature = "failpoints")]
44pub use enabled::{arm, disarm, hits};
45
46#[cfg(feature = "failpoints")]
47mod enabled {
48    use super::{io, Fault, EXIT_CODE};
49    use std::io::Write;
50    use std::sync::Mutex;
51
52    struct State {
53        hits: u64,
54        at: Option<(Fault, u64, bool)>,
55        trace: Option<std::path::PathBuf>,
56        env_read: bool,
57    }
58
59    static STATE: Mutex<State> = Mutex::new(State {
60        hits: 0,
61        at: None,
62        trace: None,
63        env_read: false,
64    });
65
66    fn parse(spec: &str) -> Option<(Fault, u64, bool)> {
67        let (kind, n) = spec.split_once('@')?;
68        let (kind, sticky) = match kind.strip_suffix(":sticky") {
69            Some(kind) => (kind, true),
70            None => (kind.strip_suffix(":once").unwrap_or(kind), false),
71        };
72        let fault = match kind {
73            "exit" => Fault::Exit,
74            "enospc" => Fault::NoSpace,
75            "eio" => Fault::Io,
76            _ => return None,
77        };
78        Some((fault, n.parse().ok()?, sticky))
79    }
80
81    /// Arms the `n`-th hit from now (1 is the next) to inject `fault`; `sticky` keeps failing
82    /// every hit after it. Resets the hit counter.
83    pub fn arm(fault: Fault, n: u64, sticky: bool) {
84        let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
85        state.hits = 0;
86        state.env_read = true;
87        state.at = Some((fault, n, sticky));
88    }
89
90    /// Clears any armed fault and resets the hit counter.
91    pub fn disarm() {
92        let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
93        state.hits = 0;
94        state.env_read = true;
95        state.at = None;
96    }
97
98    /// Hits since the last [`arm`] or [`disarm`].
99    pub fn hits() -> u64 {
100        STATE.lock().unwrap_or_else(|e| e.into_inner()).hits
101    }
102
103    #[cfg(windows)]
104    fn error(fault: Fault) -> io::Error {
105        // ERROR_DISK_FULL, ERROR_IO_DEVICE.
106        io::Error::from_raw_os_error(if fault == Fault::NoSpace { 112 } else { 1117 })
107    }
108
109    #[cfg(not(windows))]
110    fn error(fault: Fault) -> io::Error {
111        // ENOSPC and EIO have the same numbers on Linux, macOS and the BSDs.
112        io::Error::from_raw_os_error(if fault == Fault::NoSpace { 28 } else { 5 })
113    }
114
115    pub(crate) fn hit(name: &'static str) -> io::Result<()> {
116        let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
117        if !state.env_read {
118            state.env_read = true;
119            state.at = std::env::var("WARM_FAILPOINT")
120                .ok()
121                .and_then(|spec| parse(&spec));
122            state.trace = std::env::var_os("WARM_FAILPOINT_TRACE").map(Into::into);
123        }
124        state.hits += 1;
125        if let Some(path) = &state.trace {
126            if let Ok(mut file) = std::fs::OpenOptions::new()
127                .create(true)
128                .append(true)
129                .open(path)
130            {
131                let _ = writeln!(file, "{name}");
132            }
133        }
134        let Some((fault, at, sticky)) = state.at else {
135            return Ok(());
136        };
137        if state.hits < at || (state.hits > at && !sticky) {
138            return Ok(());
139        }
140        if fault == Fault::Exit {
141            std::process::exit(EXIT_CODE);
142        }
143        drop(state);
144        Err(error(fault))
145    }
146}