forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

backups.rs198 lines, 7.2 KiBHistoryRawDownload
1//! Scheduled backups: when a run is due, the set is written, older sets are pruned, and the outcome is
2//! recorded and sent to the dead-man URL.
3//!
4//! The worker runs only when `[backup] dir` is set. A run is due when none was attempted yet, or when the
5//! last attempt is at least `interval_hours` old. The attempt time is recorded before the run, so a failing
6//! run is retried at the interval and not every minute. The same [`run_and_record`] serves `im backup now`.
7//!
8//! The admin health page asks for a run now through [`BackupTrigger`]. At most one run is pending or running:
9//! a request made meanwhile starts nothing. `im backup now` is still the way to back up while the server is
10//! stopped, because it cannot run beside the server's data directory lock.
11//!
12//! The dead-man URL gets `<url>/start` before a run, `<url>` after a good run and `<url>/fail` after a bad
13//! one. A ping that fails is logged and never fails the backup.
14
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::time::Duration;
17
18use im_core::backup;
19use im_core::config::Config;
20use im_core::store::Store;
21use im_core::time::{now_stamp, unix_now, unix_seconds};
22use tokio::sync::Notify;
23use tokio::task::JoinHandle;
24
25use crate::backchannel::http_client;
26use crate::live::stopped;
27use crate::state::AppState;
28
29/// How often the worker checks whether a run is due.
30const TICK: Duration = Duration::from_secs(60);
31
32/// Asks the backup worker for a run now. A run is pending or running at most once: a request made while one is
33/// pending or running starts nothing.
34#[derive(Default)]
35pub struct BackupTrigger {
36 /// True from a request, or from the start of a due scheduled run, until that run ends.
37 busy: AtomicBool,
38 /// Wakes the worker out of its tick when a request arrives.
39 wake: Notify,
40}
41
42impl BackupTrigger {
43 /// Asks for a run now. Returns true when this request starts one, false when one is already pending or
44 /// running.
45 pub fn request(&self) -> bool {
46 if self.busy.swap(true, Ordering::AcqRel) {
47 return false;
48 }
49 self.wake.notify_one();
50 true
51 }
52
53 /// True when a run was requested and has not started yet.
54 fn requested(&self) -> bool {
55 self.busy.load(Ordering::Acquire)
56 }
57
58 /// Marks a run as running, so requests made meanwhile start nothing.
59 fn begin(&self) {
60 self.busy.store(true, Ordering::Release);
61 }
62
63 /// Marks the run as ended. A request made after this starts a new run.
64 fn finish(&self) {
65 self.busy.store(false, Ordering::Release);
66 }
67}
68
69/// Settings key: when a run was last attempted (a stamp).
70pub const LAST_ATTEMPT: &str = "backup.last_attempt";
71/// Settings key: when a run last succeeded (a stamp).
72pub const LAST_SUCCESS: &str = "backup.last_success";
73/// Settings key: the reason the last run failed, when it did. Never a path to a secret.
74pub const LAST_ERROR: &str = "backup.last_error";
75
76/// Starts the worker when backups are configured. Returns `None` when they are off. The task ends when
77/// the stop flag is set.
78pub fn spawn(state: AppState) -> Option<JoinHandle<()>> {
79 if !state.config.backup.enabled() {
80 return None;
81 }
82 let mut stop = state.stop.clone();
83 Some(tokio::spawn(async move {
84 loop {
85 tokio::select! {
86 () = tokio::time::sleep(TICK) => {}
87 () = state.backup.wake.notified() => {}
88 () = stopped(&mut stop) => break,
89 }
90 if state.backup.requested() || due(&state.store, &state.config).await {
91 state.backup.begin();
92 // `run_and_record` logs and records its own failure, so the result is not needed here.
93 let _ = run_and_record(&state.config, &state.store, &state.key).await;
94 state.backup.finish();
95 }
96 }
97 }))
98}
99
100/// True when no run was attempted yet, or the last attempt is at least `interval_hours` old.
101async fn due(store: &Store, config: &Config) -> bool {
102 let Ok(last) = store.setting(LAST_ATTEMPT).await else {
103 return false;
104 };
105 let Some(last) = last.and_then(|stamp| unix_seconds(&stamp)) else {
106 return true;
107 };
108 let interval =
109 i64::try_from(config.backup.interval_hours.saturating_mul(3600)).unwrap_or(i64::MAX);
110 unix_now().saturating_sub(last) >= interval
111}
112
113/// Writes one set, prunes the old ones and records the outcome. Returns the set's directory on success.
114///
115/// The outcome is recorded in `settings`, so the health page can show it. A failure is returned to the
116/// caller as well, so `im backup now` can exit with status 1.
117pub async fn run_and_record(
118 config: &Config,
119 store: &Store,
120 key: &[u8; 32],
121) -> im_core::Result<std::path::PathBuf> {
122 let http = http_client();
123 let base = config
124 .backup
125 .healthcheck_url
126 .trim_end_matches('/')
127 .to_owned();
128 let has_ping = !base.is_empty();
129 let stamp = now_stamp().replace([':', '.'], "-");
130 if let Err(error) = store.set_setting(LAST_ATTEMPT, &now_stamp()).await {
131 tracing::error!(error = %error, "backup attempt not recorded");
132 }
133 if has_ping {
134 ping(&http, &format!("{base}/start")).await;
135 }
136 let outcome = write_and_prune(config, store, key, &stamp).await;
137 match &outcome {
138 Ok(set) => {
139 tracing::info!(set = %set.display(), "backup written");
140 let _ = store.set_setting(LAST_SUCCESS, &now_stamp()).await;
141 let _ = store.set_setting(LAST_ERROR, "").await;
142 if has_ping {
143 ping(&http, &base).await;
144 }
145 }
146 Err(error) => {
147 tracing::error!(error = %error, "backup failed");
148 let _ = store.set_setting(LAST_ERROR, &error.to_string()).await;
149 if has_ping {
150 ping(&http, &format!("{base}/fail")).await;
151 }
152 }
153 }
154 outcome
155}
156
157/// Writes the set and removes the sets beyond `keep`.
158async fn write_and_prune(
159 config: &Config,
160 store: &Store,
161 key: &[u8; 32],
162 stamp: &str,
163) -> im_core::Result<std::path::PathBuf> {
164 let set = backup::write_set(store, &config.data_dir, &config.backup.dir, stamp, key).await?;
165 let removed = backup::prune(&config.backup.dir, config.backup.keep as usize)?;
166 if removed > 0 {
167 tracing::info!(removed, "old backup sets removed");
168 }
169 Ok(set)
170}
171
172/// Sends one dead-man ping. Failures are logged; they never fail the backup. The URL holds the healthcheck
173/// id, a secret, so a transport error is logged without it.
174async fn ping(http: &reqwest::Client, url: &str) {
175 match http.get(url).send().await {
176 Ok(response) if response.status().is_success() => {}
177 Ok(response) => {
178 tracing::warn!(status = %response.status(), "dead-man ping answered with an error");
179 }
180 Err(error) => tracing::warn!(error = %error.without_url(), "dead-man ping failed"),
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::BackupTrigger;
187
188 #[test]
189 fn a_second_request_while_one_is_pending_starts_nothing() {
190 let trigger = BackupTrigger::default();
191 assert!(trigger.request());
192 assert!(!trigger.request());
193 trigger.begin();
194 assert!(!trigger.request());
195 trigger.finish();
196 assert!(trigger.request());
197 }
198}