diff --git a/docs/4-implementation/swarm/matrix-provisioning.md b/docs/4-implementation/swarm/matrix-provisioning.md index ed1e608df..5ee6b94f4 100644 --- a/docs/4-implementation/swarm/matrix-provisioning.md +++ b/docs/4-implementation/swarm/matrix-provisioning.md @@ -69,9 +69,14 @@ container's tmpfs, before tuwunel starts. A render that can't reach the store fails and retries, and tuwunel, which fails to start without the registration, retries until one has landed. `appservice sync` runs beside tuwunel on a timer. The store's tokens win: when they differ from the rendered copy, it rewrites it. It -restarts tuwunel whenever the registration is newer than tuwunel's last -start, so the next run retries one that failed after writing, and starts -one that failed because `render` couldn't reach the store. A store that +restarts tuwunel when it's not running on the registration on disk: the +text it loaded (systemd's copy of the credential, made at its start) differs +from the file, however old the file is, so a boot's rewrite of the same text +restarts nothing. Where `sync` can't read that copy it goes by the file's time +against tuwunel's last start. It never stops a tuwunel that's still +starting, which has no start time yet; the next run decides. The next run +also retries one that failed after writing, and starts one that failed +because `render` couldn't reach the store. A store that holds none takes the tokens an earlier version kept in `/var/lib/swarm-matrix-appservice` with a create-only write, so a running swarm keeps its value; the files stay, unused. A host with neither files nor stored tokens mints a pair. `sync` then writes the `as_token` diff --git a/nix/host-modules/hive-matrix.nix b/nix/host-modules/hive-matrix.nix index 12e8a845b..1ed68bcc6 100644 --- a/nix/host-modules/hive-matrix.nix +++ b/nix/host-modules/hive-matrix.nix @@ -1156,9 +1156,10 @@ in # Keeps the rendered registration in step with the store, and # publishes the `as_token` to the path `swarm-controller` reads, # under matrix-ctl's identity (the grants are in ./swarm-bao.nix). - # When the registration is newer than tuwunel's last start, this - # restarts tuwunel onto it; a tuwunel that failed because the render - # did is started the same way. + # When tuwunel is not running on the registration on disk (the text + # it loaded differs), this restarts it onto it, and never while it is + # still starting; a tuwunel that failed because the render did is + # started the same way. # # `wants`, not `requires`, the render: this unit must still run when # the render has failed, since it is what brings the homeserver up @@ -1186,6 +1187,9 @@ in }; environment = appserviceEnv // { MATRIX_APPSERVICE_RESTART_UNIT = "tuwunel.service"; + # systemd's copy of the registration, made when tuwunel starts: what + # it loaded, which the sync compares with the file instead of times. + MATRIX_APPSERVICE_LOADED_REGISTRATION = "/run/credentials/tuwunel.service/${swarmAppserviceCredentialId}"; }; }; diff --git a/swarm-matrix-ctl/README.md b/swarm-matrix-ctl/README.md index 181ccf86f..6d7b46750 100644 --- a/swarm-matrix-ctl/README.md +++ b/swarm-matrix-ctl/README.md @@ -22,8 +22,8 @@ first when the store holds none; the files stay, unused. ### `appservice sync` The store holds the registration's tokens. This rewrites the rendered copy -when they differ, restarts the homeserver whenever the registration is -newer than its last start, and publishes the `as_token` for `swarm-controller`. +when they differ, restarts the homeserver when it is not running on the +registration on disk (never while it is starting), and publishes the `as_token` for `swarm-controller`. It runs the same reconciliation as `render`, and starts a homeserver that failed because `render` could not reach the store. diff --git a/swarm-matrix-ctl/src/appservice.rs b/swarm-matrix-ctl/src/appservice.rs index a84490cc6..a64212be3 100644 --- a/swarm-matrix-ctl/src/appservice.rs +++ b/swarm-matrix-ctl/src/appservice.rs @@ -11,8 +11,8 @@ //! answers and holds none. //! - [`sync`] runs beside the homeserver and follows the store: it rewrites //! the file when the store's tokens differ, restarts the homeserver -//! whenever the registration is newer than the homeserver's last start, and -//! publishes the `as_token` for the controller. +//! when it is not running on the registration on disk (never while it is +//! starting), and publishes the `as_token` for the controller. //! //! Where the store holds none, both first store the tokens an earlier version //! kept in the legacy state dir (see [`resolve`]), so a host that has run for @@ -46,9 +46,14 @@ const ENV_SENDER: &str = "MATRIX_APPSERVICE_SENDER"; const ENV_USER_REGEX: &str = "MATRIX_APPSERVICE_USER_REGEX"; /// Role on the store's `cert` auth mount that both verbs log in with. const ENV_CERT_ROLE: &str = "MATRIX_APPSERVICE_CERT_ROLE"; -/// The unit that loads the registration, which [`sync`] restarts when the -/// registration is newer than its last start. +/// The unit that loads the registration, which [`sync`] restarts when it is +/// not running on the registration on disk. const ENV_RESTART_UNIT: &str = "MATRIX_APPSERVICE_RESTART_UNIT"; +/// Where that unit's copy of the registration is: the one its running process +/// loaded, which systemd keeps apart from the file in [`ENV_RUNTIME_DIR`] +/// (a credential is copied when the unit starts). Optional; without it the +/// sync falls back to the times of the file and of the start. +const ENV_LOADED_REGISTRATION: &str = "MATRIX_APPSERVICE_LOADED_REGISTRATION"; /// The registration's `id`. const ID: &str = "swarm"; @@ -250,25 +255,21 @@ pub async fn sync() -> Result<()> { let legacy = PathBuf::from(required(&get, ENV_LEGACY_DIR)?); let sender = required(&get, ENV_SENDER)?; let regex = required(&get, ENV_USER_REGEX)?; - let unit = required(&get, ENV_RESTART_UNIT)?; + let unit = Systemd { + unit: required(&get, ENV_RESTART_UNIT)?, + loaded: get(ENV_LOADED_REGISTRATION) + .filter(|p| !p.is_empty()) + .map(PathBuf::from), + }; let store = connect(&required(&get, ENV_CERT_ROLE)?).await?; - sync_with( - &store, - &runtime, - &legacy, - &sender, - ®ex, - mint, - &Systemd(unit), - ) - .await + sync_with(&store, &runtime, &legacy, &sender, ®ex, mint, &unit).await } /// [`sync`] against an explicit store, directories and homeserver unit. /// -/// The homeserver is restarted whenever the registration was written after it -/// last started, so a run that failed between the write and the restart is -/// finished by the next. +/// The homeserver is restarted when it is not running on the registration on +/// disk (see `restart_if_stale`), so a run that failed between the write and +/// the restart is finished by the next. async fn sync_with( store: &impl Store, runtime: &Path, @@ -359,12 +360,26 @@ trait Homeserver { /// When the unit last became active, in microseconds since the epoch; /// `None` when it never has. fn started_us(&self) -> Result>; + /// Whether it is starting up now, which is not a time to stop it: a start + /// that has not finished has no start time yet, and a stop in the middle of + /// it is a stop of whatever the process is doing, such as opening a database. + fn starting(&self) -> Result { + Ok(false) + } + /// The registration the running process loaded, when that can be told. + fn loaded_registration(&self) -> Result> { + Ok(None) + } /// Restart it onto the registration on disk. fn restart(&self) -> Result<()>; } /// The real unit, through `systemctl`. -struct Systemd(String); +struct Systemd { + unit: String, + /// Where it keeps the registration it loaded, if that is known. + loaded: Option, +} impl Homeserver for Systemd { fn started_us(&self) -> Result> { @@ -376,43 +391,113 @@ impl Homeserver for Systemd { "ActiveEnterTimestamp", "--value", ]) - .arg(&self.0) + .arg(&self.unit) .output() .context("running systemctl show")?; if !out.status.success() { - bail!("systemctl show {} exited with {}", self.0, out.status); + bail!("systemctl show {} exited with {}", self.unit, out.status); } parse_timestamp_us(String::from_utf8_lossy(&out.stdout).trim()) } + fn starting(&self) -> Result { + let out = std::process::Command::new("systemctl") + .args(["show", "-p", "ActiveState", "--value"]) + .arg(&self.unit) + .output() + .context("running systemctl show")?; + if !out.status.success() { + bail!("systemctl show {} exited with {}", self.unit, out.status); + } + Ok(matches!( + String::from_utf8_lossy(&out.stdout).trim(), + "activating" | "reloading" + )) + } + + fn loaded_registration(&self) -> Result> { + let Some(path) = &self.loaded else { + return Ok(None); + }; + match std::fs::read_to_string(path) { + Ok(text) => Ok(Some(text)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).with_context(|| format!("reading {}", path.display())), + } + } + fn restart(&self) -> Result<()> { - restart_via(&self.0, systemctl) + restart_via(&self.unit, systemctl) } } -/// Restart the homeserver when the registration on disk is newer than its last -/// start. Derived from the files and the unit on every run rather than from +/// Restart the homeserver onto the registration on disk when it is not running +/// on it. Derived from the files and the unit on every run rather than from /// what this run wrote, so a run that failed after writing is retried by the -/// next. A start time that cannot be read leaves the unit as it is: the next -/// run decides again. +/// next. +/// +/// A homeserver that is still starting is left alone: stopping it then lands +/// in the middle of its start. One that is running has a copy of the +/// registration it loaded, and the registration is current when the two are +/// the same text, however recently the file was written; the sync rewrites +/// the file at every boot, after the homeserver has started, so its time says +/// nothing. Where that copy cannot be read, the file's time against the start +/// time decides. A start time that cannot be read leaves the unit as it is: +/// the next run decides again. fn restart_if_stale(unit: &impl Homeserver, registration: &Path) -> Result<()> { + match unit.starting() { + Ok(true) => { + tracing::info!("the homeserver is still starting; leaving it to finish"); + return Ok(()); + } + Ok(false) => {} + Err(e) => { + tracing::warn!(error = %e, "cannot tell whether the homeserver is starting; leaving it as it is"); + return Ok(()); + } + } let started = match unit.started_us() { - Ok(started) => started.unwrap_or(0), + Ok(started) => started, Err(e) => { tracing::warn!(error = %e, "cannot tell when the homeserver last started; leaving it as it is"); return Ok(()); } }; - let written = std::fs::metadata(registration) - .and_then(|m| m.modified()) - .with_context(|| format!("reading the time of {}", registration.display()))? - .duration_since(std::time::UNIX_EPOCH) - .context("the registration is dated before the epoch")? - .as_micros(); - if written <= u128::from(started) { - return Ok(()); + if started.is_some() { + let current = std::fs::read_to_string(registration) + .with_context(|| format!("reading {}", registration.display()))?; + match unit.loaded_registration() { + Ok(Some(loaded)) => { + if loaded == current { + return Ok(()); + } + tracing::info!( + "the homeserver loaded another registration than the one on disk; restarting it" + ); + return unit + .restart() + .context("restarting the homeserver onto the new registration"); + } + Ok(None) => {} + Err(e) => { + tracing::warn!(error = %e, "cannot read the registration the homeserver loaded; going by file times"); + } + } + let written = std::fs::metadata(registration) + .and_then(|m| m.modified()) + .with_context(|| format!("reading the time of {}", registration.display()))? + .duration_since(std::time::UNIX_EPOCH) + .context("the registration is dated before the epoch")? + .as_micros(); + if written <= u128::from(started.unwrap_or(0)) { + return Ok(()); + } + tracing::info!("the registration is newer than the homeserver's start; restarting it"); + } else { + tracing::info!( + "the homeserver has not started since the registration was written; starting it" + ); } - tracing::info!("the registration is newer than the homeserver's start; restarting it"); unit.restart() .context("restarting the homeserver onto the new registration") } @@ -628,6 +713,10 @@ mod tests { started: Cell>, fail_restart: Cell, restarts: Cell, + /// Still coming up: `started` is `None` and a stop would land mid-start. + starting: Cell, + /// The registration its process loaded, where that can be told. + loaded: RefCell>, } impl Unit { @@ -646,6 +735,8 @@ mod tests { started: Cell::new(at), fail_restart: Cell::new(false), restarts: Cell::new(0), + starting: Cell::new(false), + loaded: RefCell::new(None), } } } @@ -655,6 +746,14 @@ mod tests { Ok(self.started.get()) } + fn starting(&self) -> Result { + Ok(self.starting.get()) + } + + fn loaded_registration(&self) -> Result> { + Ok(self.loaded.borrow().clone()) + } + fn restart(&self) -> Result<()> { self.restarts.set(self.restarts.get() + 1); if self.fail_restart.get() { @@ -906,6 +1005,61 @@ mod tests { cleanup(&runtime); } + #[tokio::test] + async fn a_homeserver_running_on_this_registration_is_not_restarted_for_a_newer_file() { + let (runtime, legacy) = scratch(); + let store = Fake::holding(reg("store")); + std::fs::write(runtime.join(REGISTRATION), yaml_for(®("store"))).expect("rendered"); + + // started long before the file was written, as at every boot + let unit = Unit::long_running(); + *unit.loaded.borrow_mut() = Some(yaml_for(®("store"))); + let (out, _) = run(&store, &runtime, &legacy, &unit).await; + + out.expect("syncs"); + assert_eq!(unit.restarts.get(), 0, "the same text needs no restart"); + cleanup(&runtime); + } + + #[tokio::test] + async fn a_homeserver_that_loaded_another_registration_is_restarted() { + let (runtime, legacy) = scratch(); + let store = Fake::holding(reg("store")); + std::fs::write(runtime.join(REGISTRATION), yaml_for(®("store"))).expect("rendered"); + + let unit = Unit::just_started(); + *unit.loaded.borrow_mut() = Some(yaml_for(®("old"))); + let (out, _) = run(&store, &runtime, &legacy, &unit).await; + + out.expect("syncs"); + assert_eq!( + unit.restarts.get(), + 1, + "it runs on tokens the store no longer holds" + ); + cleanup(&runtime); + } + + #[tokio::test] + async fn a_homeserver_that_is_still_starting_is_left_alone() { + let (runtime, legacy) = scratch(); + let store = Fake::holding(reg("store")); + std::fs::write(runtime.join(REGISTRATION), yaml_for(®("old"))).expect("rendered"); + + // no start time yet, and a registration that differs: both say restart + let unit = Unit::started(None); + unit.starting.set(true); + let (out, _) = run(&store, &runtime, &legacy, &unit).await; + + out.expect("syncs"); + assert_eq!( + unit.restarts.get(), + 0, + "a stop would land in the middle of its start" + ); + cleanup(&runtime); + } + #[tokio::test] async fn a_store_that_is_down_leaves_the_rendered_copy_as_it_is() { let (runtime, legacy) = scratch(); diff --git a/swarm-matrix-ctl/src/main.rs b/swarm-matrix-ctl/src/main.rs index ee21b5e7d..9b6c45360 100644 --- a/swarm-matrix-ctl/src/main.rs +++ b/swarm-matrix-ctl/src/main.rs @@ -44,8 +44,9 @@ enum Appservice { /// down until the store answers. Render, /// Make the rendered registration match the store's, restart the homeserver - /// when the registration is newer than its last start, and publish the - /// `as_token` for `swarm-controller`. Runs beside the homeserver. + /// when it is not running on the registration on disk (never while it is + /// starting), and publish the `as_token` for `swarm-controller`. Runs + /// beside the homeserver. Sync, }