forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

backup.rs260 lines, 10.4 KiBHistoryRawDownload
1//! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`)
2//! when one is due, keeps the newest `keep` sets, and pings the dead-man URL after each good run.
3//!
4//! A run is due when no attempt is recorded yet, or the last attempt is at least `interval_hours` old (see
5//! [`is_due`]). The worker checks every [`TICK`]. The attempt time is written before the run starts, and it lives
6//! in the database, so a restart does not reset the interval, and a crash-looping server cannot write a set on
7//! every start. A failing run is retried at the interval, not every tick.
8//!
9//! The admin page can ask for a run now through [`BackupTrigger`]. At most one run is pending or running: a request
10//! made meanwhile starts nothing, and a scheduled run that is already going counts as running too.
11//!
12//! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing
13//! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]`
14//! table.
15//!
16//! After every run, scheduled or manual, the outcome is recorded in the `settings` table (see [`record_outcome`])
17//! so the admin page can show the last success, the last attempt and the error of a failed run. The recorded
18//! error is short text, never the ping URL.
19
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::time::Duration;
22
23use in_core::backup;
24use in_core::config::Backup;
25use in_core::error::Error;
26use in_core::store::Store;
27use in_core::time::{now_stamp, stamp_before};
28use tokio::sync::{Notify, watch};
29
30use crate::state::AppState;
31
32/// How long the dead-man ping may take.
33pub const PING_TIMEOUT: Duration = Duration::from_secs(10);
34
35/// How often the worker checks whether a run is due. A minute is short enough that a run starts close to its time,
36/// and a check reads one setting, so it costs nothing.
37const TICK: Duration = Duration::from_secs(60);
38
39/// Settings key: when a run was last attempted (a stamp). Written before every run, so a run that is cut short
40/// still counts as an attempt.
41pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at";
42/// Settings key: when a run last succeeded (a stamp).
43pub const LAST_SUCCESS_AT: &str = "backup.last_success_at";
44/// Settings key: the short error of the latest run. Present only while the latest run failed.
45pub const LAST_ERROR: &str = "backup.last_error";
46/// The longest error text that is stored, in characters. Long errors are cut so the admin page stays short.
47const ERROR_CHARS: usize = 200;
48/// The shortest time without a successful backup before the admin page warns: two days, in seconds. The
49/// limit is never shorter than two backup intervals (see [`is_stale`]).
50pub const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 60 * 60);
51
52/// Asks the backup worker for a run now. At most one run is pending or running: a request made while one is
53/// pending or running starts nothing.
54#[derive(Default)]
55pub struct BackupTrigger {
56 /// True from a request, or from the start of a run, until that run ends.
57 busy: AtomicBool,
58 /// Wakes the worker out of its wait when a request arrives.
59 wake: Notify,
60}
61
62impl BackupTrigger {
63 /// Asks for a run now. Returns true when this request starts one, false when one is already pending or
64 /// running.
65 pub fn request(&self) -> bool {
66 if self.busy.swap(true, Ordering::AcqRel) {
67 return false;
68 }
69 self.wake.notify_one();
70 true
71 }
72
73 /// True when a run was requested and has not started yet.
74 fn requested(&self) -> bool {
75 self.busy.load(Ordering::Acquire)
76 }
77
78 /// Marks a run as running, so requests made meanwhile start nothing.
79 fn begin(&self) {
80 self.busy.store(true, Ordering::Release);
81 }
82
83 /// Marks the run as ended. A request made after this starts a new run.
84 fn finish(&self) {
85 self.busy.store(false, Ordering::Release);
86 }
87}
88
89/// Runs one backup now and returns the new set's directory.
90async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result<std::path::PathBuf> {
91 // The stamp names the set; `:` and `.` are not wanted in file names.
92 let stamp = now_stamp().replace([':', '.'], "-");
93 let set = backup::write_set(
94 &state.store,
95 state.blobs.as_ref(),
96 &config.dir,
97 &stamp,
98 &state.key,
99 )
100 .await?;
101 let removed = backup::prune(&config.dir, config.keep as usize)?;
102 tracing::info!(set = %set.display(), pruned = removed, "backup: set written");
103 Ok(set)
104}
105
106/// The short text of a failed run: the first line of its error, without control characters, cut to
107/// [`ERROR_CHARS`] characters.
108fn short_error(error: &Error) -> String {
109 let text = error.to_string();
110 let line = text.lines().next().unwrap_or_default();
111 line.chars()
112 .filter(|c| !c.is_control())
113 .take(ERROR_CHARS)
114 .collect()
115}
116
117/// Stores the attempt time before a run starts. A store failure is logged and never stops the run.
118async fn record_attempt(store: &Store) {
119 if let Err(error) = store.set_setting(LAST_ATTEMPT_AT, &now_stamp()).await {
120 tracing::error!(error = %error, "backup: the attempt was not recorded");
121 }
122}
123
124/// Stores the outcome of one run: on success the success time and no error; on failure the short error. A store
125/// failure is logged and never fails the run.
126async fn record_outcome(store: &Store, outcome: &in_core::error::Result<std::path::PathBuf>) {
127 let now = now_stamp();
128 let recorded: in_core::error::Result<()> = async {
129 match outcome {
130 Ok(_) => {
131 store.set_setting(LAST_SUCCESS_AT, &now).await?;
132 store.clear_setting(LAST_ERROR).await
133 }
134 Err(error) => store.set_setting(LAST_ERROR, &short_error(error)).await,
135 }
136 }
137 .await;
138 if let Err(error) = recorded {
139 tracing::error!(error = %error, "backup: the outcome was not recorded");
140 }
141}
142
143/// True when a run is due: none was attempted, or the last attempt is at least `interval_hours` old. The stamps
144/// have a fixed width, so comparing them as text compares their times.
145pub fn is_due(last_attempt: Option<&str>, interval_hours: u32) -> bool {
146 let interval = Duration::from_secs(u64::from(interval_hours) * 60 * 60);
147 // An attempt stamped in the future means the clock went back: run rather than wait for it.
148 let now = now_stamp();
149 last_attempt.is_none_or(|stamp| stamp < stamp_before(interval).as_str() || stamp > now.as_str())
150}
151
152/// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals,
153/// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so
154/// comparing them as text compares their times.
155pub fn is_stale(last_success: Option<&str>, interval_hours: u32) -> bool {
156 let interval = Duration::from_secs(u64::from(interval_hours) * 2 * 60 * 60);
157 let limit = STALE_AFTER.max(interval);
158 last_success.is_none_or(|stamp| stamp < stamp_before(limit).as_str())
159}
160
161/// Pings the dead-man URL once. Only failures are logged, and the URL itself never is.
162async fn ping(url: &str) {
163 let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() {
164 Ok(client) => client,
165 Err(error) => {
166 tracing::warn!(error = %error, "backup: could not prepare the dead-man ping");
167 return;
168 }
169 };
170 match client.get(url).send().await {
171 Ok(response) if response.status().is_success() => {}
172 Ok(response) => {
173 tracing::warn!(status = %response.status(), "backup: dead-man ping was not accepted")
174 }
175 Err(error) => tracing::warn!(error = %error.without_url(), "backup: dead-man ping failed"),
176 }
177}
178
179/// Runs backups until the stop flag is set. Every [`TICK`] it checks whether a run is due (see [`is_due`]); a
180/// request from the admin page starts a run at once.
181pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
182 let Some(config) = state.config.backup.clone() else {
183 return;
184 };
185 loop {
186 tokio::select! {
187 _ = stop.wait_for(|stopped| *stopped) => return,
188 () = tokio::time::sleep(TICK) => {}
189 () = state.backup.wake.notified() => {}
190 }
191 if !state.backup.requested() && !due(&state.store, &config).await {
192 continue;
193 }
194 state.backup.begin();
195 record_attempt(&state.store).await;
196 let outcome = run_once(&state, &config).await;
197 record_outcome(&state.store, &outcome).await;
198 match outcome {
199 Ok(_) => {
200 if let Some(url) = &config.healthcheck_url {
201 ping(url).await;
202 }
203 }
204 Err(error) => tracing::error!(error = %error, "backup: the run failed"),
205 }
206 state.backup.finish();
207 }
208}
209
210/// True when a scheduled run is due, by the attempt recorded in the database. A store failure is logged and
211/// counts as not due, so the next tick tries again.
212async fn due(store: &Store, config: &Backup) -> bool {
213 match store.get_setting(LAST_ATTEMPT_AT).await {
214 Ok(last) => is_due(last.as_deref(), config.interval_hours),
215 Err(error) => {
216 tracing::error!(error = %error, "backup: the last attempt could not be read");
217 false
218 }
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use std::time::Duration;
225
226 use in_core::time::{now_stamp, stamp_before};
227
228 use super::{BackupTrigger, is_due, is_stale};
229
230 #[test]
231 fn a_second_request_while_one_is_pending_starts_nothing() {
232 let trigger = BackupTrigger::default();
233 assert!(trigger.request());
234 assert!(!trigger.request());
235 trigger.begin();
236 assert!(!trigger.request());
237 trigger.finish();
238 assert!(trigger.request());
239 }
240
241 #[test]
242 fn no_success_within_the_limit_is_stale() {
243 assert!(is_stale(None, 24));
244 assert!(!is_stale(Some(&now_stamp()), 24));
245 // Three days ago: stale on a daily schedule, not on a weekly one (limit two weeks).
246 let three_days = stamp_before(Duration::from_secs(3 * 86_400));
247 assert!(is_stale(Some(&three_days), 24));
248 assert!(!is_stale(Some(&three_days), 168));
249 }
250
251 #[test]
252 fn a_fresh_attempt_makes_the_next_tick_not_due() {
253 assert!(is_due(None, 24));
254 assert!(!is_due(Some(&now_stamp()), 24));
255 assert!(is_due(
256 Some(&stamp_before(Duration::from_secs(25 * 3600))),
257 24
258 ));
259 }
260}