writerslogic_warm/core/
failpoint.rs1use std::io;
20
21pub const EXIT_CODE: i32 = 86;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Fault {
27 Exit,
29 NoSpace,
31 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 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 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 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 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 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}