forge
Explore
Log in

Don't you dare go Hollow

Back up now from the settings page while the server runs

Browse files at this commit

72da983d5b91d8bd45703cc26a05ccddcff2104dAhmet Kaan GümüşParent: 0307c6b
  • feat
    • back up now from the settings page while the server runs
Show full message
✨ feat: back up now from the settings page while the server runs
README.mdmodified+4 -0
@@ -142,6 +142,10 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou
142 - `manifest.json`: a SHA-256 for each file, and142 - `manifest.json`: a SHA-256 for each file, and
143 - `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`.143 - `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`.
144 144
145+While the server runs, an administrator can start a backup from the Settings page with the "Back up now" button
146+(it appears when `[backup] dir` is set). The running backup worker writes the set in the background. Only one run
147+is pending or running at a time: a press while one is pending or running starts nothing. The button is audited.
148+
145 Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked149 Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked
146 and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused.150 and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused.
147 151
crates/iz-web/src/backup.rsmodified+54 -2
@@ -8,9 +8,14 @@
8 //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.8 //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.
9 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever9 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever
10 //! deleted. Nothing is written in place.10 //! deleted. Nothing is written in place.
11+//!
12+//! The admin settings page can ask for a run now through [`BackupTrigger`]. At most one run is pending or
13+//! running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the busy flag, so
14+//! they never overlap.
11 15
12 use std::os::unix::fs::DirBuilderExt;16 use std::os::unix::fs::DirBuilderExt;
13 use std::path::{Path, PathBuf};17 use std::path::{Path, PathBuf};
18+use std::sync::atomic::{AtomicBool, Ordering};
14 use std::time::Duration;19 use std::time::Duration;
15 20
16 use iz_core::clock::stamp_of;21 use iz_core::clock::stamp_of;
@@ -19,10 +24,42 @@ use iz_core::manifest::{self, MANIFEST_NAME};
19 use iz_core::staging::{ATTACHMENTS_DIR, blob_path};24 use iz_core::staging::{ATTACHMENTS_DIR, blob_path};
20 use iz_core::store::{Store, new_id};25 use iz_core::store::{Store, new_id};
21 use iz_core::{Error, Result};26 use iz_core::{Error, Result};
22-use tokio::sync::watch;27+use tokio::sync::{Notify, watch};
23 28
24 use crate::state::AppState;29 use crate::state::AppState;
25 30
31+/// Asks the backup worker for a run now. A run is pending or running at most once: a request made while one is
32+/// pending or running starts nothing.
33+#[derive(Default)]
34+pub struct BackupTrigger {
35+ /// True from a request, or from the start of a scheduled run, until that run ends.
36+ busy: AtomicBool,
37+ /// Wakes the worker out of its wait when a request arrives.
38+ wake: Notify,
39+}
40+
41+impl BackupTrigger {
42+ /// Asks for a run now. Returns true when this request starts one, false when one is already pending or
43+ /// running.
44+ pub fn request(&self) -> bool {
45+ if self.busy.swap(true, Ordering::AcqRel) {
46+ return false;
47+ }
48+ self.wake.notify_one();
49+ true
50+ }
51+
52+ /// Marks a run as running, so requests made meanwhile start nothing.
53+ fn begin(&self) {
54+ self.busy.store(true, Ordering::Release);
55+ }
56+
57+ /// Marks the run as ended. A request made after this starts a new run.
58+ fn finish(&self) {
59+ self.busy.store(false, Ordering::Release);
60+ }
61+}
62+
26 /// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory.63 /// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory.
27 const TMP_PREFIX: &str = ".tmp-";64 const TMP_PREFIX: &str = ".tmp-";
28 /// The database copy inside a set.65 /// The database copy inside a set.
@@ -35,7 +72,8 @@ const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ";
35 const SET_NAME_LEN: usize = 16;72 const SET_NAME_LEN: usize = 16;
36 73
37 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.74 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.
38-/// The first backup runs at once, then one every `interval_hours`.75+/// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for
76+/// one (see [`BackupTrigger`]).
39 pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {77 pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
40 let Some(policy) = state.config.backup.clone() else {78 let Some(policy) = state.config.backup.clone() else {
41 return;79 return;
@@ -54,9 +92,12 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
54 };92 };
55 let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600);93 let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600);
56 loop {94 loop {
95+ state.backup.begin();
57 run_once(&state, &policy, client.as_ref(), &mut stop).await;96 run_once(&state, &policy, client.as_ref(), &mut stop).await;
97+ state.backup.finish();
58 tokio::select! {98 tokio::select! {
59 () = tokio::time::sleep(interval) => {}99 () = tokio::time::sleep(interval) => {}
100+ () = state.backup.wake.notified() => {}
60 _ = stop.wait_for(|stopped| *stopped) => break,101 _ = stop.wait_for(|stopped| *stopped) => break,
61 }102 }
62 }103 }
@@ -231,6 +272,17 @@ async fn ping(client: &reqwest::Client, url: &str) {
231 mod tests {272 mod tests {
232 use super::*;273 use super::*;
233 274
275+ #[test]
276+ fn a_second_request_while_one_is_pending_or_running_starts_nothing() {
277+ let trigger = BackupTrigger::default();
278+ assert!(trigger.request());
279+ assert!(!trigger.request());
280+ trigger.begin();
281+ assert!(!trigger.request());
282+ trigger.finish();
283+ assert!(trigger.request());
284+ }
285+
234 /// A finished set on disk: a directory with a manifest, named by its stamp.286 /// A finished set on disk: a directory with a manifest, named by its stamp.
235 fn fake_set(dir: &Path, name: &str) {287 fn fake_set(dir: &Path, name: &str) {
236 let set = dir.join(name);288 let set = dir.join(name);
crates/iz-web/src/boot.rsmodified+2 -0
@@ -123,6 +123,7 @@ async fn open_state(config: Config) -> iz_core::Result<AppState> {
123 family: Arc::default(),123 family: Arc::default(),
124 in_store,124 in_store,
125 blob_lock: Arc::default(),125 blob_lock: Arc::default(),
126+ backup: Arc::default(),
126 })127 })
127 }128 }
128 129
@@ -202,6 +203,7 @@ mod tests {
202 family: Arc::default(),203 family: Arc::default(),
203 in_store: None,204 in_store: None,
204 blob_lock: Arc::default(),205 blob_lock: Arc::default(),
206+ backup: Arc::default(),
205 };207 };
206 (dir, state)208 (dir, state)
207 }209 }
crates/iz-web/src/family.rsmodified+1 -0
@@ -237,6 +237,7 @@ mod tests {
237 family: std::sync::Arc::default(),237 family: std::sync::Arc::default(),
238 in_store: None,238 in_store: None,
239 blob_lock: std::sync::Arc::default(),239 blob_lock: std::sync::Arc::default(),
240+ backup: std::sync::Arc::default(),
240 };241 };
241 let request = http::Request::get("/no/such/page")242 let request = http::Request::get("/no/such/page")
242 .header(http::header::ACCEPT, "text/html")243 .header(http::header::ACCEPT, "text/html")
crates/iz-web/src/i18n/admin.rsmodified+31 -0
@@ -51,6 +51,11 @@ pub enum K {
51 MessageSubject,51 MessageSubject,
52 MessageBody,52 MessageBody,
53 SendMessage,53 SendMessage,
54+ // Backups
55+ BackupHeading,
56+ BackupHelp,
57+ BackupOff,
58+ BackupNow,
54 // Notices59 // Notices
55 NoticeSenderSaved,60 NoticeSenderSaved,
56 NoticeCheckOk,61 NoticeCheckOk,
@@ -61,6 +66,7 @@ pub enum K {
61 NoticeRuleDeleted,66 NoticeRuleDeleted,
62 NoticeRuleSwitched,67 NoticeRuleSwitched,
63 NoticeRetried,68 NoticeRetried,
69+ NoticeBackupStarted,
64 // Rules70 // Rules
65 RulesTitle,71 RulesTitle,
66 RulesHelp,72 RulesHelp,
@@ -131,6 +137,7 @@ pub enum K {
131 ReasonProject,137 ReasonProject,
132 FilterKind,138 FilterKind,
133 // Errors139 // Errors
140+ ErrBackupOff,
134 }141 }
135 142
136 /// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`].143 /// The text of `key` in `lang`. Placeholders are `{}` and are filled by [`fill`].
@@ -245,6 +252,30 @@ pub fn t(lang: Lang, key: K) -> &'static str {
245 (K::NoticeRuleSwitched, Tr) => "Kural değiştirildi.",252 (K::NoticeRuleSwitched, Tr) => "Kural değiştirildi.",
246 (K::NoticeRetried, En) => "Queued again.",253 (K::NoticeRetried, En) => "Queued again.",
247 (K::NoticeRetried, Tr) => "Yeniden kuyruğa alındı.",254 (K::NoticeRetried, Tr) => "Yeniden kuyruğa alındı.",
255+ (K::NoticeBackupStarted, En) => "Backup started.",
256+ (K::NoticeBackupStarted, Tr) => "Yedekleme başlatıldı.",
257+ (K::BackupHeading, En) => "Backups",
258+ (K::BackupHeading, Tr) => "Yedeklemeler",
259+ (K::BackupHelp, En) => {
260+ "Backups run on the schedule in the [backup] section. Back up now starts one run in the background, and the server keeps running."
261+ }
262+ (K::BackupHelp, Tr) => {
263+ "Yedeklemeler [backup] bölümündeki takvimde çalışır. Şimdi yedekle arka planda bir yedekleme başlatır ve sunucu çalışmaya devam eder."
264+ }
265+ (K::BackupOff, En) => {
266+ "Backups are off. Set [backup] dir in the config file to turn them on."
267+ }
268+ (K::BackupOff, Tr) => {
269+ "Yedekleme kapalı. Açmak için yapılandırma dosyasında [backup] dir ayarlayın."
270+ }
271+ (K::BackupNow, En) => "Back up now",
272+ (K::BackupNow, Tr) => "Şimdi yedekle",
273+ (K::ErrBackupOff, En) => {
274+ "Backups are off, so there is nothing to start. Set [backup] dir first."
275+ }
276+ (K::ErrBackupOff, Tr) => {
277+ "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın."
278+ }
248 (K::RulesTitle, En) => "Mail rules",279 (K::RulesTitle, En) => "Mail rules",
249 (K::RulesTitle, Tr) => "Mail kuralları",280 (K::RulesTitle, Tr) => "Mail kuralları",
250 (K::RulesHelp, En) => "A rule mails people when something happens on the board.",281 (K::RulesHelp, En) => "A rule mails people when something happens on the board.",
crates/iz-web/src/pages/admin.rsmodified+1 -0
@@ -53,6 +53,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option<Strin
53 "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(),53 "rule_deleted" => t(lang, K::NoticeRuleDeleted).to_owned(),
54 "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(),54 "rule_switched" => t(lang, K::NoticeRuleSwitched).to_owned(),
55 "retried" => t(lang, K::NoticeRetried).to_owned(),55 "retried" => t(lang, K::NoticeRetried).to_owned(),
56+ "backup" => t(lang, K::NoticeBackupStarted).to_owned(),
56 "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(),57 "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(),
57 "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(),58 "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(),
58 "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(),59 "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(),
crates/iz-web/src/pages/settings.rsmodified+28 -1
@@ -25,7 +25,7 @@ use crate::i18n::admin::{K, t};
25 use crate::i18n::{Lang, lang};25 use crate::i18n::{Lang, lang};
26 use crate::live::{AdminSection, Topic};26 use crate::live::{AdminSection, Topic};
27 use crate::mail;27 use crate::mail;
28-use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewer_of};28+use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, record, user_text, viewer_of};
29 use crate::pages::board::the_board;29 use crate::pages::board::the_board;
30 use crate::state::AppState;30 use crate::state::AppState;
31 use crate::views::admin::{SenderForm, SettingsView, settings_content};31 use crate::views::admin::{SenderForm, SettingsView, settings_content};
@@ -137,6 +137,7 @@ async fn settings_view(
137 extensions,137 extensions,
138 server: server_info(state).await?,138 server: server_info(state).await?,
139 storage,139 storage,
140+ backups: state.config.backup.is_some(),
140 })141 })
141 }142 }
142 143
@@ -375,6 +376,32 @@ async fn send_test(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
375 }376 }
376 }377 }
377 378
379+/// `POST /settings/backup`: asks the backup worker for a backup now. Refused when `[backup] dir` is not set. A
380+/// request made while a run is pending or running starts nothing, and gets the same notice.
381+#[route(POST "/settings/backup")]
382+async fn back_up_now(cx: &Cx, form: Option<Form<CsrfForm>>) -> Result<Response> {
383+ let state = app_context::<AppState>(cx);
384+ let form = form.map(|Form(form)| form).unwrap_or_default();
385+ let me = require_csrf(cx, Need::Admin, &form.csrf).await?;
386+ let language = lang(cx, me.member.locale_override.as_deref());
387+ if state.config.backup.is_none() {
388+ let alert = t(language, K::ErrBackupOff).to_owned();
389+ let page = settings_view(state, language, None, None, Some(alert)).await?;
390+ return render(cx, &me, page, REFUSED).await;
391+ }
392+ let started = state.backup.request();
393+ record(
394+ state,
395+ &me,
396+ "backup.requested",
397+ "settings",
398+ None,
399+ serde_json::json!({ "started": started }),
400+ )
401+ .await;
402+ back("/settings?notice=backup")
403+}
404+
378 /// `POST /settings/reminders`: the lead time (0 is off) and the cap per member per hour.405 /// `POST /settings/reminders`: the lead time (0 is off) and the cap per member per hour.
379 #[route(POST "/settings/reminders")]406 #[route(POST "/settings/reminders")]
380 async fn save_reminders(cx: &Cx, form: Option<Form<RemindersSubmit>>) -> Result<Response> {407 async fn save_reminders(cx: &Cx, form: Option<Form<RemindersSubmit>>) -> Result<Response> {
crates/iz-web/src/state.rsmodified+3 -0
@@ -5,6 +5,7 @@ use std::sync::Arc;
5 use iz_core::config::Config;5 use iz_core::config::Config;
6 use iz_core::store::Store;6 use iz_core::store::Store;
7 7
8+use crate::backup::BackupTrigger;
8 use crate::family::FamilyCache;9 use crate::family::FamilyCache;
9 use crate::in_store::InStore;10 use crate::in_store::InStore;
10 use crate::live::LiveHub;11 use crate::live::LiveHub;
@@ -32,4 +33,6 @@ pub struct AppState {
32 /// local copy's removal, and a Files copy's deletion. The mover and the deleter take it, so a stale record33 /// local copy's removal, and a Files copy's deletion. The mover and the deleter take it, so a stale record
33 /// can never remove the live copy (see `attachments.rs`).34 /// can never remove the live copy (see `attachments.rs`).
34 pub blob_lock: Arc<tokio::sync::Mutex<()>>,35 pub blob_lock: Arc<tokio::sync::Mutex<()>>,
36+ /// Asks the backup worker for a run now (the settings page). Shared with the worker.
37+ pub backup: Arc<BackupTrigger>,
35 }38 }
crates/iz-web/src/views/admin.rsmodified+14 -0
@@ -138,6 +138,8 @@ pub struct SettingsView {
138 pub server: crate::views::structure::ServerInfo,138 pub server: crate::views::structure::ServerInfo,
139 /// Where attachments are kept and how far the move between places has got.139 /// Where attachments are kept and how far the move between places has got.
140 pub storage: crate::views::structure::StorageInfo,140 pub storage: crate::views::structure::StorageInfo,
141+ /// Whether scheduled backups are on (`[backup] dir` is set), so the "Back up now" button is shown.
142+ pub backups: bool,
141 }143 }
142 144
143 /// The rules page: the list, the form (new or editing), and the choices of the form.145 /// The rules page: the list, the form (new or editing), and the choices of the form.
@@ -312,6 +314,18 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result<impl Vi
312 <button class="button" type="submit">(t(lang, K::SendMessage))</button>314 <button class="button" type="submit">(t(lang, K::SendMessage))</button>
313 </form>315 </form>
314 </section>316 </section>
317+ <section class="card" id="backups">
318+ <h2>(t(lang, K::BackupHeading))</h2>
319+ if page.backups {
320+ <p class="field-hint">(t(lang, K::BackupHelp))</p>
321+ <form method="post" action="/settings/backup">
322+ <input type="hidden" name="csrf" value=(csrf)>
323+ <button class="button" type="submit">(t(lang, K::BackupNow))</button>
324+ </form>
325+ } else {
326+ <p class="field-hint">(t(lang, K::BackupOff))</p>
327+ }
328+ </section>
315 members_section(lang: lang, members: &page.members, csrf: csrf)329 members_section(lang: lang, members: &page.members, csrf: csrf)
316 storage_section(lang: lang, info: &page.storage, csrf: csrf)330 storage_section(lang: lang, info: &page.storage, csrf: csrf)
317 limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf)331 limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf)
docs/architecture.mdmodified+4 -2
@@ -147,7 +147,7 @@ Pages (session; Viewer may read, writes need Member, admin pages need Admin; all
147 | `GET /columns` + POSTs | columns (admin) |147 | `GET /columns` + POSTs | columns (admin) |
148 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |148 | `GET /rules` + POSTs | mail rules (admin), sentence rendering, enable switch, edit |
149 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |149 | `GET /logs` | admin: outbox (retry), decisions, activity (filters, keyset paging) |
150-| `GET /settings` + POSTs | profile/preferences (all); members & roles, sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin) |150+| `GET /settings` + POSTs | profile/preferences (all); members & roles, sender (check, test), limits, attachment storage (+ migration status), message to members, server (admin); `POST /settings/backup` "Back up now" (admin, CSRF, audited, 303 back with a notice, 422 with an alert when `[backup]` is off) |
151 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |151 | `GET /avatar/{sub}` | photo proxy with disk cache, only for members of this board |
152 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |152 | OIDC client routes, `/-/alive`, live streams, `/healthz`, `/assets/*` | |
153 153
@@ -201,7 +201,9 @@ Member, or Admin. Truth-table tested.
201 ## 8. Workers201 ## 8. Workers
202 202
203 directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of203 directory mirror, family list, mail outbox, reminders, attachment mover, sweeper (sessions, JTIs, retention of
204-activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batches of 500, orphaned temp files), optional backup. All stop with the stop flag.204+activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batches of 500, orphaned temp files), optional backup. The backup worker is also woken by "Back up now" on the settings page:
205+`BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends)
206+and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag.
205 207
206 ---208 ---
207 209