forge
Explore
Log in

Don't you dare go Hollow

Back up now from the admin health page while the server runs

Browse files at this commit

7f1e12a612d723e9b21131dc0be5230893aa3007Ahmet Kaan GümüşParent: c7a3c1d
  • feat
    • back up now from the admin health page while the server runs
Show full message
✨ feat: back up now from the admin health page while the server runs
README.mdmodified+9 -1
@@ -105,8 +105,16 @@ every file. `interval_hours` sets the schedule and `keep` how many sets are kept
105 only when they are real sets with a manifest. An optional `healthcheck_url` is pinged after each run, with105 only when they are real sets with a manifest. An optional `healthcheck_url` is pinged after each run, with
106 the failure URL on error (a dead-man check).106 the failure URL on error (a dead-man check).
107 107
108+While the server runs, an administrator can start a backup from the admin Health page with the "Back up now"
109+button (it appears when `[backup] dir` is set). The running backup worker writes the set in the background, and
110+the page shows the last success or error once the run ends. Only one backup runs at a time: a press while one is
111+pending or running starts nothing. The button is audited.
112+
113+`im backup now` writes a set from the command line, but only while the server is stopped, because the command
114+needs the data directory's lock.
115+
108 ```sh116 ```sh
109-im --config /etc/im/im.toml backup now # write a set now117+im --config /etc/im/im.toml backup now # write a set now (server stopped only)
110 im --config /etc/im/im.toml fsck # check the database and the signing keys118 im --config /etc/im/im.toml fsck # check the database and the signing keys
111 im --config /etc/im/im.toml restore --from <set> # verify, then restore119 im --config /etc/im/im.toml restore --from <set> # verify, then restore
112 ```120 ```
crates/im-core/src/model.rsmodified+3 -0
@@ -198,6 +198,8 @@ pub enum AuditAction {
198 KeyRetired,198 KeyRetired,
199 /// A backup set was written (scheduled, or by `im backup now`).199 /// A backup set was written (scheduled, or by `im backup now`).
200 BackupWritten,200 BackupWritten,
201+ /// An administrator asked for a backup now from the admin health page.
202+ BackupRequested,
201 }203 }
202 204
203 impl AuditAction {205 impl AuditAction {
@@ -247,6 +249,7 @@ impl AuditAction {
247 AuditAction::KeyRotated => "keys.rotated",249 AuditAction::KeyRotated => "keys.rotated",
248 AuditAction::KeyRetired => "keys.retired",250 AuditAction::KeyRetired => "keys.retired",
249 AuditAction::BackupWritten => "backup.written",251 AuditAction::BackupWritten => "backup.written",
252+ AuditAction::BackupRequested => "backup.requested",
250 }253 }
251 }254 }
252 }255 }
crates/im-web/src/backups.rsmodified+65 -4
@@ -5,15 +5,21 @@
5 //! last attempt is at least `interval_hours` old. The attempt time is recorded before the run, so a failing5 //! 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`.6 //! run is retried at the interval and not every minute. The same [`run_and_record`] serves `im backup now`.
7 //!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+//!
8 //! The dead-man URL gets `<url>/start` before a run, `<url>` after a good run and `<url>/fail` after a bad12 //! The dead-man URL gets `<url>/start` before a run, `<url>` after a good run and `<url>/fail` after a bad
9 //! one. A ping that fails is logged and never fails the backup.13 //! one. A ping that fails is logged and never fails the backup.
10 14
15+use std::sync::atomic::{AtomicBool, Ordering};
11 use std::time::Duration;16 use std::time::Duration;
12 17
13 use im_core::backup;18 use im_core::backup;
14 use im_core::config::Config;19 use im_core::config::Config;
15 use im_core::store::Store;20 use im_core::store::Store;
16 use im_core::time::{now_stamp, unix_now, unix_seconds};21 use im_core::time::{now_stamp, unix_now, unix_seconds};
22+use tokio::sync::Notify;
17 use tokio::task::JoinHandle;23 use tokio::task::JoinHandle;
18 24
19 use crate::backchannel::http_client;25 use crate::backchannel::http_client;
@@ -23,6 +29,43 @@ use crate::state::AppState;
23 /// How often the worker checks whether a run is due.29 /// How often the worker checks whether a run is due.
24 const TICK: Duration = Duration::from_secs(60);30 const TICK: Duration = Duration::from_secs(60);
25 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)]
35+pub 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+
42+impl 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+
26 /// Settings key: when a run was last attempted (a stamp).69 /// Settings key: when a run was last attempted (a stamp).
27 pub const LAST_ATTEMPT: &str = "backup.last_attempt";70 pub const LAST_ATTEMPT: &str = "backup.last_attempt";
28 /// Settings key: when a run last succeeded (a stamp).71 /// Settings key: when a run last succeeded (a stamp).
@@ -41,12 +84,14 @@ pub fn spawn(state: AppState) -> Option<JoinHandle<()>> {
41 loop {84 loop {
42 tokio::select! {85 tokio::select! {
43 () = tokio::time::sleep(TICK) => {}86 () = tokio::time::sleep(TICK) => {}
87+ () = state.backup.wake.notified() => {}
44 () = stopped(&mut stop) => break,88 () = stopped(&mut stop) => break,
45 }89 }
46- if due(&state.store, &state.config).await90+ if state.backup.requested() || due(&state.store, &state.config).await {
47- && let Err(error) = run_and_record(&state.config, &state.store, &state.key).await91+ state.backup.begin();
48- {92+ // `run_and_record` logs and records its own failure, so the result is not needed here.
49- tracing::error!(error = %error, "scheduled backup failed");93+ let _ = run_and_record(&state.config, &state.store, &state.key).await;
94+ state.backup.finish();
50 }95 }
51 }96 }
52 }))97 }))
@@ -134,3 +179,19 @@ async fn ping(http: &reqwest::Client, url: &str) {
134 Err(error) => tracing::warn!(error = %error, "dead-man ping failed"),179 Err(error) => tracing::warn!(error = %error, "dead-man ping failed"),
135 }180 }
136 }181 }
182+
183+#[cfg(test)]
184+mod tests {
185+ use super::BackupTrigger;
186+
187+ #[test]
188+ fn a_second_request_while_one_is_pending_starts_nothing() {
189+ let trigger = BackupTrigger::default();
190+ assert!(trigger.request());
191+ assert!(!trigger.request());
192+ trigger.begin();
193+ assert!(!trigger.request());
194+ trigger.finish();
195+ assert!(trigger.request());
196+ }
197+}
crates/im-web/src/boot.rsmodified+3 -0
@@ -22,6 +22,7 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService
22 22
23 use crate::api::directory::StreamSlots;23 use crate::api::directory::StreamSlots;
24 use crate::backchannel;24 use crate::backchannel;
25+use crate::backups::BackupTrigger;
25 use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS};26 use crate::live::{LiveHub, MAX_ANONYMOUS_STREAMS};
26 use crate::mail;27 use crate::mail;
27 use crate::oidc::signing;28 use crate::oidc::signing;
@@ -162,6 +163,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result<AppState> {
162 store,163 store,
163 key: Arc::new(key),164 key: Arc::new(key),
164 live: Arc::new(LiveHub::default()),165 live: Arc::new(LiveHub::default()),
166+ backup: Arc::new(BackupTrigger::default()),
165 throttle: Arc::new(Throttle::default()),167 throttle: Arc::new(Throttle::default()),
166 photo_uploads: Arc::new(Throttle::photo_uploads()),168 photo_uploads: Arc::new(Throttle::photo_uploads()),
167 email_changes: Arc::new(Throttle::email_changes()),169 email_changes: Arc::new(Throttle::email_changes()),
@@ -286,6 +288,7 @@ mod tests {
286 store,288 store,
287 key: Arc::new(key),289 key: Arc::new(key),
288 live: Arc::new(LiveHub::default()),290 live: Arc::new(LiveHub::default()),
291+ backup: Arc::new(BackupTrigger::default()),
289 throttle: Arc::new(Throttle::default()),292 throttle: Arc::new(Throttle::default()),
290 photo_uploads: Arc::new(Throttle::photo_uploads()),293 photo_uploads: Arc::new(Throttle::photo_uploads()),
291 email_changes: Arc::new(Throttle::email_changes()),294 email_changes: Arc::new(Throttle::email_changes()),
crates/im-web/src/i18n/admin.rsmodified+9 -0
@@ -228,6 +228,9 @@ pub enum A {
228 HealthBackupLast,228 HealthBackupLast,
229 HealthBackupError,229 HealthBackupError,
230 HealthBackupOff,230 HealthBackupOff,
231+ BackupNow,
232+ NoticeBackupStarted,
233+ ErrBackupOff,
231 HealthUsers,234 HealthUsers,
232 HealthAdmins,235 HealthAdmins,
233 HealthBytes,236 HealthBytes,
@@ -656,6 +659,12 @@ fn pair(key: A) -> (&'static str, &'static str) {
656 "Backups are off. Set [backup] dir to turn them on.",659 "Backups are off. Set [backup] dir to turn them on.",
657 "Yedekleme kapalı. Açmak için [backup] dir ayarlayın.",660 "Yedekleme kapalı. Açmak için [backup] dir ayarlayın.",
658 ),661 ),
662+ A::BackupNow => ("Back up now", "Şimdi yedekle"),
663+ A::NoticeBackupStarted => ("Backup started", "Yedekleme başlatıldı"),
664+ A::ErrBackupOff => (
665+ "Backups are off, so there is nothing to start. Set [backup] dir first.",
666+ "Yedekleme kapalı, başlatılacak bir şey yok. Önce [backup] dir ayarlayın.",
667+ ),
659 A::HealthUsers => ("Accounts", "Hesaplar"),668 A::HealthUsers => ("Accounts", "Hesaplar"),
660 A::HealthAdmins => ("Enabled administrators", "Etkin yöneticiler"),669 A::HealthAdmins => ("Enabled administrators", "Etkin yöneticiler"),
661 A::HealthBytes => ("Database size", "Veritabanı boyutu"),670 A::HealthBytes => ("Database size", "Veritabanı boyutu"),
crates/im-web/src/pages/admin/health.rsmodified+53 -4
@@ -2,22 +2,42 @@
2 //! and the account counts. Read only; nothing here changes anything.2 //! and the account counts. Read only; nothing here changes anything.
3 //!3 //!
4 //! A service shows the answer of its last health probe, or "not checked" before the first one.4 //! A service shows the answer of its last health probe, or "not checked" before the first one.
5+//!
6+//! When backups are on, the backups section has a "Back up now" button (`POST /admin/health/backup`). It asks the
7+//! running backup worker for one run, and redirects back with a notice; the run itself happens in the background,
8+//! and the last outcome shows here once it ends. Only one run is pending or running at a time.
5 9
10+use im_core::model::AuditAction;
11+use serde::Deserialize;
12+use serde_json::json;
6 use topcoat::Result;13 use topcoat::Result;
7 use topcoat::context::{Cx, app_context};14 use topcoat::context::{Cx, app_context};
8-use topcoat::router::page;15+use topcoat::router::content::Form;
16+use topcoat::router::error::SeeOther;
17+use topcoat::router::{page, route};
9 use topcoat::view::{View, component, view};18 use topcoat::view::{View, component, view};
10 19
11-use crate::auth::require_admin;20+use crate::audit::{Actor, record};
21+use crate::auth::{require_admin, require_admin_csrf};
12 use crate::i18n::Lang;22 use crate::i18n::Lang;
13 use crate::i18n::admin::{A, text};23 use crate::i18n::admin::{A, text};
14-use crate::pages::admin::{Tab, frame_info, tabs};24+use crate::pages::admin::{
25+ FlashQuery, Tab, action_button, done, error_text, flash_messages, frame_info, notice_text,
26+ refused, tabs,
27+};
15 use crate::state::AppState;28 use crate::state::AppState;
16 use crate::views::{ViewerInfo, shell};29 use crate::views::{ViewerInfo, shell};
17 30
31+/// The form of the backup button: only the CSRF token.
32+#[derive(Deserialize, Default)]
33+struct CsrfForm {
34+ #[serde(default)]
35+ csrf: String,
36+}
37+
18 /// `GET /admin/health`.38 /// `GET /admin/health`.
19 #[page("/admin/health")]39 #[page("/admin/health")]
20-async fn health_page(cx: &Cx) -> Result<impl View> {40+async fn health_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> {
21 let viewer = require_admin(cx).await?;41 let viewer = require_admin(cx).await?;
22 let state = app_context::<AppState>(cx);42 let state = app_context::<AppState>(cx);
23 let (lang, info) = frame_info(cx, &viewer);43 let (lang, info) = frame_info(cx, &viewer);
@@ -40,6 +60,9 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
40 cx,60 cx,
41 lang,61 lang,
42 info,62 info,
63+ viewer.session.csrf_token.clone(),
64+ notice_text(lang, &query.notice).map(str::to_owned),
65+ error_text(lang, &query.error).map(str::to_owned),
43 services66 services
44 .into_iter()67 .into_iter()
45 .map(|service| ServiceRow {68 .map(|service| ServiceRow {
@@ -56,6 +79,27 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
56 ))79 ))
57 }80 }
58 81
82+/// `POST /admin/health/backup`: asks the backup worker for a backup now. Refused when backups are off. A request
83+/// made while a run is pending or running starts nothing, and gets the same notice.
84+#[route(POST "/admin/health/backup")]
85+async fn back_up_now(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
86+ let viewer = require_admin_csrf(cx, &form.csrf).await?;
87+ let state = app_context::<AppState>(cx);
88+ if !state.config.backup.enabled() {
89+ return Ok(refused("/admin/health", "backup-off"));
90+ }
91+ let started = state.backup.request();
92+ record(
93+ cx,
94+ Actor::User(&viewer.user.id),
95+ AuditAction::BackupRequested,
96+ None,
97+ json!({ "started": started }),
98+ )
99+ .await;
100+ Ok(done("/admin/health", "backup-started"))
101+}
102+
59 /// The backup settings as the page reads them.103 /// The backup settings as the page reads them.
60 struct Backups {104 struct Backups {
61 last_success: Option<String>,105 last_success: Option<String>,
@@ -75,6 +119,9 @@ fn health_view(
75 cx: &Cx,119 cx: &Cx,
76 lang: Lang,120 lang: Lang,
77 info: ViewerInfo,121 info: ViewerInfo,
122+ csrf: String,
123+ success: Option<String>,
124+ problem: Option<String>,
78 services: Vec<ServiceRow>,125 services: Vec<ServiceRow>,
79 outbox: Vec<(String, i64)>,126 outbox: Vec<(String, i64)>,
80 users: u64,127 users: u64,
@@ -88,6 +135,7 @@ fn health_view(
88 <section class="stack">135 <section class="stack">
89 <h1>(text(lang, A::HealthTitle))</h1>136 <h1>(text(lang, A::HealthTitle))</h1>
90 <p class="muted">(text(lang, A::HealthIntro))</p>137 <p class="muted">(text(lang, A::HealthIntro))</p>
138+ flash_messages(success: success, problem: problem)
91 <h2>(text(lang, A::HealthServices))</h2>139 <h2>(text(lang, A::HealthServices))</h2>
92 if services.is_empty() {140 if services.is_empty() {
93 <p class="muted">(text(lang, A::NoServices))</p>141 <p class="muted">(text(lang, A::NoServices))</p>
@@ -116,6 +164,7 @@ fn health_view(
116 <dt>(text(lang, A::HealthBackupError))</dt><dd>(error)</dd>164 <dt>(text(lang, A::HealthBackupError))</dt><dd>(error)</dd>
117 }165 }
118 </dl>166 </dl>
167+ action_button(action: "/admin/health/backup".to_owned(), csrf: csrf, label: text(lang, A::BackupNow), class: "button primary", on: "")
119 } else {168 } else {
120 <p class="muted">(text(lang, A::HealthBackupOff))</p>169 <p class="muted">(text(lang, A::HealthBackupOff))</p>
121 }170 }
crates/im-web/src/pages/admin/mod.rsmodified+2 -0
@@ -120,6 +120,7 @@ pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> {
120 "key-retired" => A::NoticeKeyRetired,120 "key-retired" => A::NoticeKeyRetired,
121 "file-value" => A::NoticeFileValue,121 "file-value" => A::NoticeFileValue,
122 "message-sent" => A::NoticeMessageSent,122 "message-sent" => A::NoticeMessageSent,
123+ "backup-started" => A::NoticeBackupStarted,
123 _ => return None,124 _ => return None,
124 };125 };
125 Some(text(lang, key))126 Some(text(lang, key))
@@ -142,6 +143,7 @@ pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> {
142 "message-email" => A::ErrMessageEmailInvalid,143 "message-email" => A::ErrMessageEmailInvalid,
143 "rate-limited" => A::ErrMessageRateLimited,144 "rate-limited" => A::ErrMessageRateLimited,
144 "key-current" => A::ErrKeyNotRetirable,145 "key-current" => A::ErrKeyNotRetirable,
146+ "backup-off" => A::ErrBackupOff,
145 "invite-gone" => A::ErrInviteGone,147 "invite-gone" => A::ErrInviteGone,
146 "no-client" => A::ErrNoSuchClient,148 "no-client" => A::ErrNoSuchClient,
147 "settings" => A::ErrSettingsInvalid,149 "settings" => A::ErrSettingsInvalid,
crates/im-web/src/state.rsmodified+3 -0
@@ -7,6 +7,7 @@ use im_core::store::Store;
7 use tokio::sync::{Semaphore, watch};7 use tokio::sync::{Semaphore, watch};
8 8
9 use crate::api::directory::StreamSlots;9 use crate::api::directory::StreamSlots;
10+use crate::backups::BackupTrigger;
10 use crate::live::LiveHub;11 use crate::live::LiveHub;
11 use crate::throttle::Throttle;12 use crate::throttle::Throttle;
12 13
@@ -25,6 +26,8 @@ pub struct AppState {
25 pub key: Arc<[u8; 32]>,26 pub key: Arc<[u8; 32]>,
26 /// The change counters of the live pages.27 /// The change counters of the live pages.
27 pub live: Arc<LiveHub>,28 pub live: Arc<LiveHub>,
29+ /// Asks the backup worker for a run now (the admin health page). Shared with the worker.
30+ pub backup: Arc<BackupTrigger>,
28 /// Failed sign-in and second-factor counters.31 /// Failed sign-in and second-factor counters.
29 pub throttle: Arc<Throttle>,32 pub throttle: Arc<Throttle>,
30 /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).33 /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`).
docs/architecture.mdmodified+5 -1
@@ -180,6 +180,7 @@ Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written b
180 | `GET /admin/keys` + POST rotate | admin | signing keys and their state |180 | `GET /admin/keys` + POST rotate | admin | signing keys and their state |
181 | `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging |181 | `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging |
182 | `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup |182 | `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup |
183+| `POST /admin/health/backup` | admin | "Back up now": asks the backup worker for one run (ignored while one is pending or running); audited; 303 back with a notice |
183 | `GET /photo/{id}` | user | photo bytes or initials SVG |184 | `GET /photo/{id}` | user | photo bytes or initials SVG |
184 | `GET /-/alive`, `GET /.../events` | per page | live streams |185 | `GET /-/alive`, `GET /.../events` | per page | live streams |
185 | `GET /healthz`, `GET /assets/*` | anyone | |186 | `GET /healthz`, `GET /assets/*` | anyone | |
@@ -262,7 +263,10 @@ in the store as single conditional statements so they cannot race.
262 sent mail older than 30 days, failed and abandoned mail older than 30 days, back-channel deliveries finished263 sent mail older than 30 days, failed and abandoned mail older than 30 days, back-channel deliveries finished
263 more than 7 days ago, and audit entries older than 365 days.264 more than 7 days ago, and audit entries older than 365 days.
264 - **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N,265 - **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N,
265- pings a dead-man URL (`/start`, success, `/fail`).266+ pings a dead-man URL (`/start`, success, `/fail`). It also wakes on a request from the admin health page
267+ (`BackupTrigger` on `AppState`: an atomic "pending or running" flag plus a `Notify`). At most one run is pending
268+ or running; a request meanwhile starts nothing. `im backup now` runs the same code only while the server is
269+ stopped, because it needs the data directory lock.
266 270
267 ---271 ---
268 272