Restart the server from the admin page and follow it back without a reload
Browse files at this commitc80f705c25bb8943e70076e40961320595f6ce81Parent: 0d7e1e1- feat
- restart the server from the admin page and follow it back without a reload
2 changed files +219 -1
crates/forge-web/src/pages/admin_server.rsmodified+199 -1
| @@ -7,11 +7,18 @@ | |||
| 7 | //! A field with an override has "Reset to file value". Secret fields are write-only: the page | 7 | //! A field with an override has "Reset to file value". Secret fields are write-only: the page |
| 8 | //! shows only whether they are set. See `forge_core::server_settings` for the rules. | 8 | //! shows only whether they are set. See `forge_core::server_settings` for the rules. |
| 9 | //! Saving and resetting are audited, with the keys but never the values. | 9 | //! Saving and resetting are audited, with the keys but never the values. |
| 10 | +//! | ||
| 11 | +//! "Restart server" asks for a graceful stop through the self-update path: the process exits with | ||
| 12 | +//! `RESTART_EXIT_CODE` and systemd (`Restart=on-failure`) starts the binary again, which picks up a | ||
| 13 | +//! newly installed one. The page that follows shows "Restarting" and follows an event stream. The | ||
| 14 | +//! stream sends the server's boot id when it connects, so the browser's own reconnect after the | ||
| 15 | +//! restart brings a new id, and the page then re-renders itself with no reload and no polling. | ||
| 10 | 16 | ||
| 11 | use std::collections::{BTreeMap, HashMap}; | 17 | use std::collections::{BTreeMap, HashMap}; |
| 12 | 18 | ||
| 13 | use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty}; | 19 | use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty}; |
| 14 | use forge_core::{AuditAction, Error}; | 20 | use forge_core::{AuditAction, Error}; |
| 21 | +use futures_util::StreamExt; | ||
| 15 | use serde::Deserialize; | 22 | use serde::Deserialize; |
| 16 | use topcoat::Result; | 23 | use topcoat::Result; |
| 17 | use topcoat::context::{Cx, app_context}; | 24 | use topcoat::context::{Cx, app_context}; |
| @@ -26,6 +33,8 @@ use crate::auth::check_csrf; | |||
| 26 | use crate::i18n::admin::{self as g, K}; | 33 | use crate::i18n::admin::{self as g, K}; |
| 27 | use crate::i18n::{self, Key, Lang}; | 34 | use crate::i18n::{self, Key, Lang}; |
| 28 | use crate::pages::admin_users::admin_only; | 35 | use crate::pages::admin_users::admin_only; |
| 36 | +use crate::pages::ci_runs::{changed_event, events_response}; | ||
| 37 | +use crate::self_update; | ||
| 29 | use crate::state::AppState; | 38 | use crate::state::AppState; |
| 30 | use crate::views::{enc, shell}; | 39 | use crate::views::{enc, shell}; |
| 31 | 40 | ||
| @@ -33,6 +42,39 @@ use crate::views::{enc, shell}; | |||
| 33 | pub(crate) struct ServerQuery { | 42 | pub(crate) struct ServerQuery { |
| 34 | notice: Option<String>, | 43 | notice: Option<String>, |
| 35 | tab: Option<String>, | 44 | tab: Option<String>, |
| 45 | + /// The boot id of the server that was asked to restart. | ||
| 46 | + restarting: Option<String>, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// Picks the English or Turkish text. | ||
| 50 | +fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { | ||
| 51 | + match lang { | ||
| 52 | + Lang::En => en, | ||
| 53 | + Lang::Tr => tr, | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// How long the restart waits after the request is answered, so the redirect that follows is | ||
| 58 | +/// served by the old process. | ||
| 59 | +const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750); | ||
| 60 | + | ||
| 61 | +/// Where the page stands in a restart. | ||
| 62 | +#[derive(Clone, Copy, PartialEq, Eq)] | ||
| 63 | +enum Restart { | ||
| 64 | + /// No restart was asked from this page. | ||
| 65 | + None, | ||
| 66 | + /// Asked, and this process is still the old one or on its way down. | ||
| 67 | + Pending, | ||
| 68 | + /// Asked, and a new process answered. | ||
| 69 | + Done, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +fn restart_state(asked: Option<&str>) -> Restart { | ||
| 73 | + match asked { | ||
| 74 | + None | Some("") => Restart::None, | ||
| 75 | + Some(id) if id == self_update::boot_id() => Restart::Pending, | ||
| 76 | + Some(_) => Restart::Done, | ||
| 77 | + } | ||
| 36 | } | 78 | } |
| 37 | 79 | ||
| 38 | struct OptionRow { | 80 | struct OptionRow { |
| @@ -170,15 +212,27 @@ async fn server_view( | |||
| 170 | group: Group, | 212 | group: Group, |
| 171 | rows: Vec<Row>, | 213 | rows: Vec<Row>, |
| 172 | notice: Option<String>, | 214 | notice: Option<String>, |
| 215 | + restart: Restart, | ||
| 173 | ) -> Result<impl View> { | 216 | ) -> Result<impl View> { |
| 174 | let tab = group.slug(); | 217 | let tab = group.slug(); |
| 175 | let any_editable = rows.iter().any(|r| !r.fixed); | 218 | let any_editable = rows.iter().any(|r| !r.fixed); |
| 219 | + let live = (restart == Restart::Pending).then_some("/admin/server/events"); | ||
| 176 | Ok(view! { | 220 | Ok(view! { |
| 221 | + <div data-live=(live)> | ||
| 177 | <section class="page-head"> | 222 | <section class="page-head"> |
| 178 | <h1>(g::t(lang, K::ServerSettings))</h1> | 223 | <h1>(g::t(lang, K::ServerSettings))</h1> |
| 179 | <p class="muted">(g::t(lang, K::ServerSettingsIntro))</p> | 224 | <p class="muted">(g::t(lang, K::ServerSettingsIntro))</p> |
| 180 | <p class="muted small">(match lang { Lang::Tr => "Sürüm", _ => "Version" }) " " (forge_ci::build::display())</p> | 225 | <p class="muted small">(match lang { Lang::Tr => "Sürüm", _ => "Version" }) " " (forge_ci::build::display())</p> |
| 181 | </section> | 226 | </section> |
| 227 | + if restart == Restart::Pending { | ||
| 228 | + <section class="card notice srv-restarting" role="status" aria-live="polite"> | ||
| 229 | + <p><strong>(s(lang, "Restarting...", "Yeniden başlatılıyor..."))</strong> " " (s(lang, "This page comes back by itself when the server is up again.", "Sunucu tekrar ayağa kalkınca bu sayfa kendiliğinden geri gelir."))</p> | ||
| 230 | + </section> | ||
| 231 | + } else if restart == Restart::Done { | ||
| 232 | + <section class="card notice" role="status"> | ||
| 233 | + <p>(s(lang, "The server restarted. Settings that needed a restart are applied now.", "Sunucu yeniden başladı. Yeniden başlatma gerektiren ayarlar artık uygulandı."))</p> | ||
| 234 | + </section> | ||
| 235 | + } | ||
| 182 | <nav class="subnav" aria-label=(g::t(lang, K::ServerSettings))> | 236 | <nav class="subnav" aria-label=(g::t(lang, K::ServerSettings))> |
| 183 | for g_tab in Group::ALL.into_iter() { | 237 | for g_tab in Group::ALL.into_iter() { |
| 184 | <a class=(tab_class(g_tab == group)) href=(format!("/admin/server?tab={}", g_tab.slug()))>(tab_label(lang, g_tab))</a> | 238 | <a class=(tab_class(g_tab == group)) href=(format!("/admin/server?tab={}", g_tab.slug()))>(tab_label(lang, g_tab))</a> |
| @@ -247,6 +301,27 @@ async fn server_view( | |||
| 247 | <input type="hidden" name="tab" value=(tab)> | 301 | <input type="hidden" name="tab" value=(tab)> |
| 248 | </form> | 302 | </form> |
| 249 | </section> | 303 | </section> |
| 304 | + <section class="card"> | ||
| 305 | + <h2>(s(lang, "Restart server", "Sunucuyu yeniden başlat"))</h2> | ||
| 306 | + <p class="muted small">(s(lang, "Stops gracefully and starts again, so a newly installed binary and every setting marked restart needed take effect. Needs a supervisor such as systemd to start it again.", "Düzgünce durdurup yeniden başlatır; böylece yeni kurulan ikili ve \"yeniden başlatma gerekli\" işaretli her ayar devreye girer. Yeniden başlatmak için systemd gibi bir gözetmen gerekir."))</p> | ||
| 307 | + if restart == Restart::Pending { | ||
| 308 | + <p class="muted small">(s(lang, "A restart is in progress.", "Yeniden başlatma sürüyor."))</p> | ||
| 309 | + } else { | ||
| 310 | + <details class="confirm-inline"> | ||
| 311 | + <summary class="button danger">(s(lang, "Restart server", "Sunucuyu yeniden başlat"))</summary> | ||
| 312 | + <div class="confirm-pop"> | ||
| 313 | + <p>(s(lang, "Restart the server now? Requests in flight finish first, and the site is unavailable for a few seconds.", "Sunucu şimdi yeniden başlatılsın mı? Süren istekler önce biter, site birkaç saniye kullanılamaz."))</p> | ||
| 314 | + <form method="post" action="/admin/server/restart"> | ||
| 315 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 316 | + <input type="hidden" name="tab" value=(tab)> | ||
| 317 | + <button type="submit" class="danger">(s(lang, "Yes, restart", "Evet, yeniden başlat"))</button> | ||
| 318 | + <button type="button" data-close-details="">(s(lang, "Cancel", "Vazgeç"))</button> | ||
| 319 | + </form> | ||
| 320 | + </div> | ||
| 321 | + </details> | ||
| 322 | + } | ||
| 323 | + </section> | ||
| 324 | + </div> | ||
| 250 | }) | 325 | }) |
| 251 | } | 326 | } |
| 252 | 327 | ||
| @@ -265,7 +340,7 @@ async fn server_page(cx: &Cx) -> Result<impl View> { | |||
| 265 | let csrf = viewer.1.csrf_token.clone(); | 340 | let csrf = viewer.1.csrf_token.clone(); |
| 266 | let title = g::t(lang, K::ServerSettings); | 341 | let title = g::t(lang, K::ServerSettings); |
| 267 | Ok(view! { | 342 | Ok(view! { |
| 268 | - shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone())) | 343 | + shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone(), restart: restart_state(query.restarting.as_deref()))) |
| 269 | }) | 344 | }) |
| 270 | } | 345 | } |
| 271 | 346 | ||
| @@ -342,6 +417,63 @@ async fn save( | |||
| 342 | Ok(Some(())) | 417 | Ok(Some(())) |
| 343 | } | 418 | } |
| 344 | 419 | ||
| 420 | +#[derive(Deserialize, Default)] | ||
| 421 | +struct RestartForm { | ||
| 422 | + #[serde(default)] | ||
| 423 | + csrf: String, | ||
| 424 | + #[serde(default)] | ||
| 425 | + tab: String, | ||
| 426 | +} | ||
| 427 | + | ||
| 428 | +/// Audits the request, answers with the page that shows "Restarting", and a moment later asks the | ||
| 429 | +/// server to stop gracefully. The process then exits with `RESTART_EXIT_CODE` and systemd starts it. | ||
| 430 | +#[route(POST "/admin/server/restart")] | ||
| 431 | +async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Response> { | ||
| 432 | + let viewer = admin_only(cx).await?; | ||
| 433 | + if !check_csrf(&viewer.1, &form.csrf) { | ||
| 434 | + return Err(forbidden().into()); | ||
| 435 | + } | ||
| 436 | + let state = app_context::<AppState>(cx); | ||
| 437 | + let group = Group::parse(&form.tab).unwrap_or(Group::General); | ||
| 438 | + audit::record( | ||
| 439 | + &state.store, | ||
| 440 | + Some(cx), | ||
| 441 | + Actor::User(&viewer.0), | ||
| 442 | + AuditAction::ServerRestarted, | ||
| 443 | + Target { | ||
| 444 | + kind: "server", | ||
| 445 | + id: "", | ||
| 446 | + name: "", | ||
| 447 | + }, | ||
| 448 | + serde_json::json!({ "boot_id": self_update::boot_id() }), | ||
| 449 | + ) | ||
| 450 | + .await; | ||
| 451 | + tracing::info!(actor_id = %viewer.0.id, "server restart requested from the admin page"); | ||
| 452 | + tokio::spawn(async { | ||
| 453 | + tokio::time::sleep(RESTART_GRACE).await; | ||
| 454 | + self_update::request_restart(); | ||
| 455 | + }); | ||
| 456 | + Err(see_other(format!( | ||
| 457 | + "/admin/server?tab={}&restarting={}", | ||
| 458 | + group.slug(), | ||
| 459 | + enc(self_update::boot_id()) | ||
| 460 | + )) | ||
| 461 | + .into()) | ||
| 462 | +} | ||
| 463 | + | ||
| 464 | +/// The stream of the "Restarting" page. It sends one `changed` event with the boot id when it | ||
| 465 | +/// connects and then stays quiet. The server going down closes it, the browser reconnects by | ||
| 466 | +/// itself, and the first event of the new process re-renders the page. | ||
| 467 | +#[route(GET "/admin/server/events")] | ||
| 468 | +async fn server_events(cx: &Cx) -> Result<Response> { | ||
| 469 | + admin_only(cx).await?; | ||
| 470 | + let events = futures_util::stream::once(std::future::ready(changed_event( | ||
| 471 | + self_update::boot_id().to_owned(), | ||
| 472 | + ))) | ||
| 473 | + .chain(futures_util::stream::pending()); | ||
| 474 | + events_response(cx, events) | ||
| 475 | +} | ||
| 476 | + | ||
| 345 | #[derive(Deserialize, Default)] | 477 | #[derive(Deserialize, Default)] |
| 346 | struct ResetForm { | 478 | struct ResetForm { |
| 347 | #[serde(default)] | 479 | #[serde(default)] |
| @@ -670,6 +802,72 @@ mod tests { | |||
| 670 | assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); | 802 | assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); |
| 671 | } | 803 | } |
| 672 | 804 | ||
| 805 | + #[tokio::test] | ||
| 806 | + async fn restart_is_admin_only_audited_and_the_page_shows_the_restarting_state() { | ||
| 807 | + let fx = fixture().await; | ||
| 808 | + for token in [None, Some(USER_TOKEN)] { | ||
| 809 | + let form = format!("csrf={CSRF}&tab=general"); | ||
| 810 | + let (status, _, _) = send( | ||
| 811 | + &fx.router, | ||
| 812 | + "POST", | ||
| 813 | + "/admin/server/restart", | ||
| 814 | + token, | ||
| 815 | + Some(form), | ||
| 816 | + ) | ||
| 817 | + .await; | ||
| 818 | + assert_eq!(status, 404); | ||
| 819 | + let (status, _, _) = send(&fx.router, "GET", "/admin/server/events", token, None).await; | ||
| 820 | + assert_eq!(status, 404); | ||
| 821 | + } | ||
| 822 | + let (status, _, _) = send( | ||
| 823 | + &fx.router, | ||
| 824 | + "POST", | ||
| 825 | + "/admin/server/restart", | ||
| 826 | + Some(ADMIN_TOKEN), | ||
| 827 | + Some("csrf=wrong&tab=general".to_owned()), | ||
| 828 | + ) | ||
| 829 | + .await; | ||
| 830 | + assert_eq!(status, 403); | ||
| 831 | + | ||
| 832 | + // The page offers the button with a confirm step. | ||
| 833 | + let page = admin_get(&fx, "/admin/server").await; | ||
| 834 | + assert!(page.contains("Restart server")); | ||
| 835 | + assert!(page.contains("confirm-inline")); | ||
| 836 | + assert!(!page.contains("Restarting...")); | ||
| 837 | + | ||
| 838 | + let form = format!("csrf={CSRF}&tab=general"); | ||
| 839 | + let (status, _, location) = send( | ||
| 840 | + &fx.router, | ||
| 841 | + "POST", | ||
| 842 | + "/admin/server/restart", | ||
| 843 | + Some(ADMIN_TOKEN), | ||
| 844 | + Some(form), | ||
| 845 | + ) | ||
| 846 | + .await; | ||
| 847 | + assert_eq!(status, 303); | ||
| 848 | + assert!(location.contains(&format!("restarting={}", self_update::boot_id()))); | ||
| 849 | + let entries = fx | ||
| 850 | + .state | ||
| 851 | + .store | ||
| 852 | + .list_audit(&Default::default(), None, 50) | ||
| 853 | + .await | ||
| 854 | + .unwrap(); | ||
| 855 | + assert!( | ||
| 856 | + entries | ||
| 857 | + .iter() | ||
| 858 | + .any(|e| e.action == AuditAction::ServerRestarted) | ||
| 859 | + ); | ||
| 860 | + | ||
| 861 | + // Same process: "Restarting" with the event stream. A new process: back to normal. | ||
| 862 | + let page = admin_get(&fx, &location).await; | ||
| 863 | + assert!(page.contains("Restarting...")); | ||
| 864 | + assert!(page.contains(r#"data-live="/admin/server/events""#)); | ||
| 865 | + let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; | ||
| 866 | + assert!(!page.contains("Restarting...")); | ||
| 867 | + assert!(!page.contains("data-live=")); | ||
| 868 | + assert!(page.contains("The server restarted")); | ||
| 869 | + } | ||
| 870 | + | ||
| 673 | #[tokio::test] | 871 | #[tokio::test] |
| 674 | async fn saving_is_audited_without_values() { | 872 | async fn saving_is_audited_without_values() { |
| 675 | let fx = fixture().await; | 873 | let fx = fixture().await; |
crates/forge-web/src/self_update.rsmodified+20 -0
| @@ -88,6 +88,26 @@ pub async fn restart_requested() { | |||
| 88 | RESTART.notified().await; | 88 | RESTART.notified().await; |
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | +/// Asks the server to stop gracefully and exit with `RESTART_EXIT_CODE`, so the supervisor starts | ||
| 92 | +/// the binary again. The same path a self-update swap takes, without a swap. Used by the admin | ||
| 93 | +/// "Restart server" button. | ||
| 94 | +pub fn request_restart() { | ||
| 95 | + RESTART_REQUESTED.store(true, Ordering::SeqCst); | ||
| 96 | + RESTART.notify_one(); | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// An id that is new for every process start. A page that sees it change knows the server | ||
| 100 | +/// restarted. | ||
| 101 | +pub fn boot_id() -> &'static str { | ||
| 102 | + static ID: OnceLock<String> = OnceLock::new(); | ||
| 103 | + ID.get_or_init(|| { | ||
| 104 | + let nanos = std::time::SystemTime::now() | ||
| 105 | + .duration_since(std::time::UNIX_EPOCH) | ||
| 106 | + .map_or(0, |d| d.as_nanos()); | ||
| 107 | + format!("{:x}{nanos:x}", std::process::id()) | ||
| 108 | + }) | ||
| 109 | +} | ||
| 110 | + | ||
| 91 | /// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`. | 111 | /// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`. |
| 92 | pub fn restart_pending() -> bool { | 112 | pub fn restart_pending() -> bool { |
| 93 | RESTART_REQUESTED.load(Ordering::SeqCst) | 113 | RESTART_REQUESTED.load(Ordering::SeqCst) |