diff --git a/src/control_plane.rs b/src/control_plane.rs index dc4bb63..e663d7a 100644 --- a/src/control_plane.rs +++ b/src/control_plane.rs @@ -1,6 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::env; use std::fs::{self, File, OpenOptions}; +use std::io::Write; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -2476,7 +2477,12 @@ pub fn run(args: impl Iterator) -> Result<()> { state_store, incident_store, command_id, - } => status(&state_store, &incident_store, command_id.as_deref()), + } => status( + &mut std::io::stdout().lock(), + &state_store, + &incident_store, + command_id.as_deref(), + ), Command::Cancel { state_store, command_id, @@ -4112,7 +4118,12 @@ fn submit( } } -fn status(store_path: &Path, incident_store: &Path, command_id: Option<&str>) -> Result<()> { +fn status( + out: &mut impl Write, + store_path: &Path, + incident_store: &Path, + command_id: Option<&str>, +) -> Result<()> { let snapshot = ControlSnapshot::read(store_path)?; // Commands stay resident; their finished transactions do not. Without // history a completed command would report as though it had never run, @@ -4140,10 +4151,11 @@ fn status(store_path: &Path, incident_store: &Path, command_id: Option<&str>) -> ); transactions.sort_by_key(|value| value.ordinal); let (state, detail) = derived_command_status(&transactions); - println!( + writeln!( + out, "{} {} {} {}", command.command_id, command.selector, state, detail - ); + )?; // Naming one command asks about that command, so print what a stuck // transaction is actually waiting on. A gate reason lives in // `last_error` and was never rendered anywhere, which left "Sealing" @@ -4152,49 +4164,53 @@ fn status(store_path: &Path, incident_store: &Path, command_id: Option<&str>) -> // ids are here because they are exactly what a brake release must name. if command_id.is_some() { for transaction in transactions { - println!(" transaction {}", transaction.transaction_id); - println!( + writeln!(out, " transaction {}", transaction.transaction_id)?; + writeln!( + out, " target {} phase {:?}", transaction.target, transaction.phase - ); + )?; if let Some(expected) = &transaction.expected { - println!(" runtime {}", expected.runtime_id); - println!(" release {}", expected.sealed_release_id); + writeln!(out, " runtime {}", expected.runtime_id)?; + writeln!(out, " release {}", expected.sealed_release_id)?; } - println!( + writeln!( + out, " odin publisher cursor {}", transaction.odin_publisher_sequence_cursor - ); + )?; if let Some(evidence) = &transaction.latest_odin_observation { - println!( + writeln!( + out, " latest odin observation sequence {}", evidence.publisher_sequence - ); + )?; } if let Some(reason) = &transaction.last_error { - println!(" waiting on {reason}"); + writeln!(out, " waiting on {reason}")?; } // A Complete transaction that is not terminal still owns its // target through unfinished cleanup. Without this an operator // sees "Complete" and a stale reason and cannot tell what is // holding the target. if let Some(completion) = &transaction.completion { - println!(" completion {completion:?}"); + writeln!(out, " completion {completion:?}")?; } if let Some(abort) = &transaction.pre_fencing_abort { - println!(" pre-fencing abort {abort:?}"); + writeln!(out, " pre-fencing abort {abort:?}")?; } if let Some(abort) = &transaction.post_fencing_abort { - println!(" post-fencing abort {abort:?}"); + writeln!(out, " post-fencing abort {abort:?}")?; } if let Some(cleanup) = &transaction.post_commit_cleanup { - println!(" post-commit cleanup {cleanup:?}"); + writeln!(out, " post-commit cleanup {cleanup:?}")?; } - println!( + writeln!( + out, " terminal {} owns-target {}", transaction.is_terminal(), transaction.blocks_new_target_mutation() - ); + )?; } } } @@ -4202,7 +4218,7 @@ fn status(store_path: &Path, incident_store: &Path, command_id: Option<&str>) -> // generations and the metered targets, so a target that has only been // deployed to (no generation yet) still shows what it has used. for line in render_targets(&snapshot, incident_store, now_millis()?) { - println!("{line}"); + writeln!(out, "{line}")?; } Ok(()) } @@ -4648,7 +4664,7 @@ impl Engine { /// decides exactly as it would have with a healthy store. It names the /// operation and the root cause and never a path or a value. Incident /// writes are never progress. - fn record_incident(&self, operation: &str, outcome: Result) { + fn record_incident(&self, operation: &str, outcome: Result) { let key = format!("incident-store:{operation}"); match outcome { Ok(_) => self.clear_fault(&key), @@ -4662,21 +4678,18 @@ impl Engine { } } - /// Close every open incident whose target is no longer admitted, then - /// retire what has been closed past retention. + /// Close every open incident whose subject is a target that is no longer + /// admitted, then retire what has been closed past retention. fn reconcile_incidents(&self, snapshot: &ControlSnapshot) { let store = self.incidents(); - let close_unadmitted = || -> Result { + let close_unadmitted = || -> Result<()> { let now = now_millis()?; - let mut closed = false; for record in store.read()? { if record.is_open() - && !snapshot - .admitted - .iter() - .any(|stored| stored.value.target == record.subject) + && record.condition.ends_with_admission() + && snapshot.admitted_for(&record.subject).is_none() { - closed |= store.close( + store.close( record.condition, &record.subject, CloseReason::NoLongerAdmitted, @@ -4684,7 +4697,7 @@ impl Engine { )?; } } - Ok(closed) + Ok(()) }; self.record_incident("close", close_unadmitted()); self.record_incident("retire", now_millis().and_then(|now| store.retire_closed(now))); @@ -5121,7 +5134,13 @@ fn boot(options: RuntimeOptions) -> Result<(ProcessLock, Engine)> { fn serve(options: RuntimeOptions) -> Result<()> { let (_lock, engine) = boot(options)?; - loop { + serve_while(&engine, || true) +} + +/// The daemon's loop: tick, sleep, and go again while `again` says so. `serve` +/// says so forever; a test says so a few times. +fn serve_while(engine: &Engine, mut again: impl FnMut() -> bool) -> Result<()> { + while again() { match engine.run_scheduler_tick() { Ok(true) => continue, Ok(false) => {} @@ -5136,6 +5155,7 @@ fn serve(options: RuntimeOptions) -> Result<()> { } thread::sleep(Duration::from_millis(engine.options.poll_millis)); } + Ok(()) } impl Engine { @@ -5714,11 +5734,21 @@ impl Engine { }; if observation.is_some() { // The admitted workload was seen running: the only evidence - // that ends an exhaustion incident. The restart window sliding - // is not health and never closes one. + // that ends an exhaustion incident, once the window no longer holds it. + // The window sliding alone is not health and never closes one. self.record_incident( "close", now_millis().and_then(|now| { + // Running is not enough while the window still holds + // the restarts that exhausted it: a release that + // survives one poll after each restart is still the + // same incident. + if snapshot + .supervision_or_new(¤t.value.target) + .restarts_exhausted(now) + { + return Ok(false); + } self.incidents().close( IncidentCondition::ContinuityExhausted, ¤t.value.target, @@ -14899,6 +14929,177 @@ mod tests { assert_eq!(incident_store, PathBuf::from("/tmp/j.cc")); } + #[test] + fn a_release_that_runs_one_pass_after_each_restart_keeps_one_incident() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + admit_incumbent(&world)?; + + // Each cycle: the restarts are spent, the release dies, is seen running + // for one pass (its last restart took), and dies again. + for _ in 0..4 { + workload.kill(); + spend_the_window(&world)?; + world.engine.supervise_one_admitted_generation()?; + workload.revive(); + world.engine.supervise_one_admitted_generation()?; + let records = incidents_of(&world)?; + assert_eq!(records.len(), 1, "a flapping release opened another incident"); + assert!(records[0].is_open(), "running while still exhausted closed the incident"); + } + + // Real recovery: running, and the window no longer holds the restarts. + slide_the_window(&world)?; + world.engine.supervise_one_admitted_generation()?; + let records = incidents_of(&world)?; + assert_eq!(records.len(), 1); + assert_eq!(records[0].close_reason, Some(CloseReason::Recovered)); + assert_control_store_holds_no_incident(&world) + } + + #[test] + fn a_target_leaving_admission_closes_only_its_own_incident() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + let service = admit_incumbent(&world)?; + let store = IncidentStore::new(&incident_path(&world)); + let condition = IncidentCondition::ContinuityExhausted; + let now = now_millis()?; + for subject in ["service", "neighbour", "gone"] { + assert!(store.open(condition, subject, now)?); + } + + // Two targets are admitted: service, and a neighbour. Only the target + // that is not admitted has its incident closed. + let mut snapshot = ControlSnapshot::read(&world.state_store)?; + let envelope = snapshot + .admitted_for("service") + .context("no admitted generation")? + .envelope + .clone(); + snapshot.admitted.push(Stored { + envelope, + value: AdmittedGeneration { + target: "neighbour".into(), + ..service + }, + }); + world.engine.reconcile_incidents(&snapshot); + + let closed = |subject: &str| -> Result> { + Ok(incidents_of(&world)? + .into_iter() + .find(|record| record.subject == subject) + .context("no such incident")? + .close_reason) + }; + assert_eq!(closed("service")?, None); + assert_eq!(closed("neighbour")?, None); + assert_eq!(closed("gone")?, Some(CloseReason::NoLongerAdmitted)); + Ok(()) + } + + #[cfg(unix)] + #[test] + fn a_held_incident_lock_changes_nothing_continuity_decides() -> Result<()> { + use crate::incident::tests::{hold_lock_of, run_while_held}; + + let healthy_workload = SwitchWorkload::new(); + let healthy = EngineFixture::with_workload(healthy_workload.clone())?; + admit_incumbent(&healthy)?; + let expected = continuity_decisions(&healthy, &healthy.engine, &healthy_workload)?; + + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + admit_incumbent(&world)?; + let path = incident_path(&world); + let actual = run_while_held(hold_lock_of(&path), || { + continuity_decisions(&world, &world.engine, &workload) + })?; + assert_eq!(actual, expected, "a held incident lock changed a continuity decision"); + assert!(!path.exists(), "a contended write landed"); + + // Every refused write is a traced fault naming no path. + { + let reports = world.engine.fault_reports.lock().unwrap(); + let faults = reports + .iter() + .filter(|(key, _)| key.starts_with("incident-store:")) + .map(|(_, report)| report.last.lock().unwrap().clone().unwrap_or_default()) + .collect::>(); + assert!(!faults.is_empty()); + let root = world.root.display().to_string(); + assert!(faults.iter().all(|fault| !fault.contains(&root)), "{faults:?}"); + } + + // The lock is free again: the next pass retries and the incident lands. + world.engine.supervise_one_admitted_generation()?; + assert!(incidents_of(&world)?.iter().any(|record| record.is_open())); + assert_control_store_holds_no_incident(&world) + } + + #[test] + fn status_prints_an_open_incident_under_its_target() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + admit_incumbent(&world)?; + workload.kill(); + spend_the_window(&world)?; + world.engine.supervise_one_admitted_generation()?; + let opened = incidents_of(&world)?[0].opened_at_unix_millis; + + let mut printed = Vec::new(); + status(&mut printed, &world.state_store, &incident_path(&world), None)?; + let printed = String::from_utf8(printed)?; + let target = printed.find("target service ").context("no target line")?; + let incident = printed + .find(&format!(" incident continuity-exhausted opened-at {opened}")) + .context("status printed no incident")?; + assert!(target < incident, "{printed}"); + Ok(()) + } + + #[test] + fn serve_ticks_until_told_to_stop() -> Result<()> { + let workload = SwitchWorkload::new(); + let world = EngineFixture::with_workload(workload.clone())?; + admit_incumbent(&world)?; + workload.kill(); + spend_the_window(&world)?; + let mut options = world.engine.options.clone(); + options.poll_millis = 1; + let engine = Engine::open_with_systemd_workload(options, workload.clone())?; + + let mut asked = 0; + serve_while(&engine, || { + asked += 1; + asked <= 3 + })?; + assert_eq!(asked, 4); + assert!(incidents_of(&world)?.iter().any(|record| record.is_open()), "no tick ran"); + Ok(()) + } + + #[test] + fn run_dispatches_serve_and_status() { + let temp = TempDir::new().unwrap(); + let args = |words: &[&str]| words.iter().map(|word| (*word).to_owned()).collect::>(); + // A control store beneath a regular file: serve's boot cannot make it, + // and a serve that returned at once would say Ok instead. + let file = temp.path().join("not-a-directory"); + std::fs::write(&file, b"a file").unwrap(); + let store = file.join("control.cc"); + assert!( + run(args(&["serve", "--state-store", store.to_str().unwrap()]).into_iter()).is_err() + ); + // A control store that is not one: status reads it and refuses. + let junk = temp.path().join("junk.cc"); + std::fs::write(&junk, b"not a cultcache file").unwrap(); + assert!( + run(args(&["status", "--state-store", junk.to_str().unwrap()]).into_iter()).is_err() + ); + } + #[test] fn continuity_stops_when_the_targets_own_log_has_spent_the_window() -> Result<()> { let workload = SwitchWorkload::new(); diff --git a/src/drivers.rs b/src/drivers.rs index eb162e9..9bf4372 100644 --- a/src/drivers.rs +++ b/src/drivers.rs @@ -7659,29 +7659,34 @@ fn ensure_bundle_is_reachable_by_workload( Ok(()) } +/// One published file: `0644`, because Idunn's `UMask=027` would land it +/// `0640 root:root` and deny its readers. A chmod by hand does not hold, since +/// each publish writes a new file. +pub(crate) fn publish_file_mode(path: &Path) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if path.exists() { + fs::set_permissions(path, fs::Permissions::from_mode(0o644)) + .with_context(|| format!("publishing {}", path.display()))?; + } + } + Ok(()) +} + /// The topology store is Idunn's *published* surface: every managed target /// reads it to verify its own Expected incarnation against the Idunn anchor. /// /// Idunn runs with `UMask=027`, which is right for its private state and wrong /// for this one file -- it lands `0640 root:root`, and a `DynamicUser` workload -/// gets EACCES. A chmod by hand does not hold, because each publish writes a -/// new file. Integrity here comes from the signatures over the records, not -/// from the mode, so the published copy is readable. -pub(crate) fn publish_projection_mode(path: &Path) -> Result<()> { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - // The lock sibling too: CultCache opens it alongside the store, so a - // 0640 lock denies the read just as surely as a 0640 store, and it is - // created fresh under Idunn's umask on every publish. - for path in [path.to_path_buf(), authority_lock_path(path)] { - if path.exists() { - fs::set_permissions(&path, fs::Permissions::from_mode(0o644)) - .with_context(|| format!("publishing {}", path.display()))?; - } - } - } - Ok(()) +/// gets EACCES. Integrity here comes from the signatures over the records, not +/// from the mode, so the published copy is readable. The lock sibling too: +/// CultCache opens it alongside the store, so a 0640 lock denies the read just +/// as surely as a 0640 store, and it is created fresh under Idunn's umask on +/// every publish. +fn publish_projection_mode(path: &Path) -> Result<()> { + publish_file_mode(path)?; + publish_file_mode(&authority_lock_path(path)) } fn build_machine_id(workspace: &Path) -> Result { diff --git a/src/incident.rs b/src/incident.rs index cd56c54..7de86cf 100644 --- a/src/incident.rs +++ b/src/incident.rs @@ -12,14 +12,15 @@ use std::path::{Path, PathBuf}; -use anyhow::{Context, Result, ensure}; +use anyhow::{Context, Result, bail, ensure}; use cultcache_rs::{ - CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, + CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, + TryCompareExchangeSnapshotOutcome, }; use serde::{Deserialize, Serialize}; use crate::control_plane::{decode_record, require_id, typed_envelope}; -use crate::drivers::publish_projection_mode; +use crate::drivers::publish_file_mode; const INCIDENT_SCHEMA: &str = "idunn.operator_incident.v1"; @@ -41,6 +42,15 @@ impl IncidentCondition { Self::ContinuityExhausted => "continuity-exhausted", } } + + /// Whether the subject is an admitted target, so that the target leaving + /// admission ends the condition. A condition about anything else (a + /// transaction, a store) answers false and is closed by its own owner. + pub(crate) const fn ends_with_admission(self) -> bool { + match self { + Self::ContinuityExhausted => true, + } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -98,6 +108,14 @@ impl IncidentRecord { self.closed_at_unix_millis.is_none() } + /// Whether the record still belongs in the published file: open, or closed + /// no more than `INCIDENT_RETENTION_MILLIS` ago. The one predicate behind + /// both retirement and `idunn status`. + pub(crate) fn inside_retention(&self, now: u64) -> bool { + self.closed_at_unix_millis + .is_none_or(|closed_at| now.saturating_sub(closed_at) <= INCIDENT_RETENTION_MILLIS) + } + pub(crate) fn validate(&self) -> Result<()> { ensure!( self.schema_version == INCIDENT_SCHEMA, @@ -139,14 +157,28 @@ impl IncidentRecord { } } -struct Stored { - envelope: CultCacheEnvelope, - record: IncidentRecord, +/// One read of the incident file: its envelopes exactly as stored, and the +/// records decoded from them, in the same order. Every write expects exactly +/// these envelopes, so a write only lands on the file it was decided against. +struct Snapshot { + envelopes: Vec, + records: Vec, } -/// The incident file and its history sibling. Every write is a compare-exchange -/// against exactly what was read, and every write is followed by the -/// world-readable publication mode. +impl Snapshot { + fn open_record(&self, condition: IncidentCondition, subject: &str) -> Option { + self.records.iter().position(|record| { + record.is_open() && record.condition == condition && record.subject == subject + }) + } +} + +/// The incident file and its history sibling. Incidents are written from the +/// scheduler tick, so no write waits: each is one nonblocking compare-exchange +/// of the whole file against the snapshot it was decided on. A lost race or a +/// held lock is an error and a no-op, retried on a later pass. The lock beside +/// the file is not published: the readers of `incidents.cc` take no lock, so +/// only Idunn can ever hold it. pub(crate) struct IncidentStore { path: PathBuf, } @@ -162,57 +194,54 @@ impl IncidentStore { self.path.with_file_name("incident-history.cc") } - fn backing(&self) -> SingleFileMessagePackBackingStore { - SingleFileMessagePackBackingStore::new(&self.path) - } - /// Every record, oldest key first. An absent file is empty. The file /// refuses any document that is not an operator incident. pub(crate) fn read(&self) -> Result> { - Ok(self - .read_stored()? - .into_iter() - .map(|stored| stored.record) - .collect()) + let mut records = self.snapshot()?.records; + records.sort_by(|left, right| left.incident_key.cmp(&right.incident_key)); + Ok(records) } - fn read_stored(&self) -> Result> { - if !self.path.exists() { - return Ok(Vec::new()); - } - let mut stored = Vec::new(); - for envelope in self - .backing() + fn snapshot(&self) -> Result { + let envelopes = SingleFileMessagePackBackingStore::new(&self.path) .pull_all_read_only_snapshot() - .context("reading the incident store")? - { + .context("reading the incident store")?; + let mut records = Vec::new(); + for envelope in &envelopes { ensure!( envelope.r#type == IncidentRecord::TYPE && envelope.schema_id.as_deref() == Some(INCIDENT_SCHEMA), "the incident store holds a document that is not an operator incident" ); - let record: IncidentRecord = decode_record(&envelope)?; + let record: IncidentRecord = decode_record(envelope)?; record.validate()?; ensure!( envelope.key == record.incident_key, "incident store key differs from the incident's identity" ); - stored.push(Stored { envelope, record }); + records.push(record); } - stored.sort_by(|left, right| left.record.incident_key.cmp(&right.record.incident_key)); - Ok(stored) + Ok(Snapshot { envelopes, records }) } - fn open_record<'a>( - stored: &'a [Stored], - condition: IncidentCondition, - subject: &str, - ) -> Option<&'a Stored> { - stored.iter().find(|stored| { - stored.record.is_open() - && stored.record.condition == condition - && stored.record.subject == subject - }) + /// Replace `path`'s whole content with `replacements` if it is still + /// exactly `expected`. Never waits for the lock. + fn exchange( + path: &Path, + expected: &[CultCacheEnvelope], + replacements: &[CultCacheEnvelope], + ) -> Result<()> { + match SingleFileMessagePackBackingStore::new(path) + .try_compare_exchange_snapshot(expected, replacements)? + { + TryCompareExchangeSnapshotOutcome::Exchanged => Ok(()), + TryCompareExchangeSnapshotOutcome::Mismatch => { + bail!("the incident store changed while it was being written") + } + TryCompareExchangeSnapshotOutcome::LockContended => { + bail!("the incident store is locked by another holder") + } + } } /// Open an incident unless one is already open for `(condition, subject)`. @@ -223,23 +252,24 @@ impl IncidentStore { subject: &str, now: u64, ) -> Result { - let stored = self.read_stored()?; - if Self::open_record(&stored, condition, subject).is_some() { + self.open_on(&self.snapshot()?, condition, subject, now) + } + + fn open_on( + &self, + snapshot: &Snapshot, + condition: IncidentCondition, + subject: &str, + now: u64, + ) -> Result { + if snapshot.open_record(condition, subject).is_some() { return Ok(false); } - let record = IncidentRecord::opened(condition, subject, now); - let written = self.backing().compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: IncidentRecord::TYPE.into(), - key: record.incident_key.clone(), - current: None, - }], - &[record.envelope(now)?], - )?; - if written { - publish_projection_mode(&self.path)?; - } - Ok(written) + let mut replacements = snapshot.envelopes.clone(); + replacements.push(IncidentRecord::opened(condition, subject, now).envelope(now)?); + Self::exchange(&self.path, &snapshot.envelopes, &replacements)?; + publish_file_mode(&self.path)?; + Ok(true) } /// Close the open incident for `(condition, subject)`, if there is one. @@ -251,60 +281,56 @@ impl IncidentStore { reason: CloseReason, now: u64, ) -> Result { - let stored = self.read_stored()?; - let Some(open) = Self::open_record(&stored, condition, subject) else { + let snapshot = self.snapshot()?; + let Some(index) = snapshot.open_record(condition, subject) else { return Ok(false); }; - let mut closed = open.record.clone(); + let mut closed = snapshot.records[index].clone(); // A clock stepped back must not close an incident before it opened. closed.closed_at_unix_millis = Some(now.max(closed.opened_at_unix_millis)); closed.close_reason = Some(reason); - let written = self.backing().compare_exchange( - &[CultCacheExpectedEnvelope { - r#type: IncidentRecord::TYPE.into(), - key: closed.incident_key.clone(), - current: Some(open.envelope.clone()), - }], - &[closed.envelope(now)?], - )?; - if written { - publish_projection_mode(&self.path)?; - } - Ok(written) + let mut replacements = snapshot.envelopes.clone(); + replacements[index] = closed.envelope(now)?; + Self::exchange(&self.path, &snapshot.envelopes, &replacements)?; + publish_file_mode(&self.path)?; + Ok(true) } - /// Move every incident closed more than `INCIDENT_RETENTION_MILLIS` ago to - /// the history file, then delete it here. History first: a crash between - /// the two leaves the record in both, and `insert_entry_if_absent` makes - /// the repeat a no-op. An open incident never moves. + /// Move every incident that has left retention to the history file, then + /// drop it here. History first: a crash between the two leaves the record + /// in both, and the repeat finds it already archived. An open incident + /// never moves. pub(crate) fn retire_closed(&self, now: u64) -> Result { - let retiring = self - .read_stored()? - .into_iter() - .filter(|stored| { - stored.record.closed_at_unix_millis.is_some_and(|closed_at| { - now.saturating_sub(closed_at) > INCIDENT_RETENTION_MILLIS - }) - }) - .map(|stored| stored.envelope) - .collect::>(); + let snapshot = self.snapshot()?; + let (kept, retiring): (Vec<_>, Vec<_>) = snapshot + .envelopes + .iter() + .zip(&snapshot.records) + .partition(|(_, record)| record.inside_retention(now)); if retiring.is_empty() { return Ok(false); } - let history = SingleFileMessagePackBackingStore::new(&self.history_path()); - for envelope in &retiring { - history - .insert_entry_if_absent(envelope.clone()) - .context("archiving a closed incident")?; + let history_path = self.history_path(); + let archived = SingleFileMessagePackBackingStore::new(&history_path) + .pull_all_read_only_snapshot() + .context("reading the incident history")?; + let mut history = archived.clone(); + history.extend( + retiring + .iter() + .filter(|(envelope, _)| !archived.iter().any(|held| held.key == envelope.key)) + .map(|(envelope, _)| (*envelope).clone()), + ); + if history.len() != archived.len() { + Self::exchange(&history_path, &archived, &history)?; } - let deleted = self - .backing() - .delete_batch_if_unchanged(&retiring) - .context("retiring a closed incident")?; - if deleted { - publish_projection_mode(&self.path)?; - } - Ok(deleted) + let kept = kept + .into_iter() + .map(|(envelope, _)| envelope.clone()) + .collect::>(); + Self::exchange(&self.path, &snapshot.envelopes, &kept)?; + publish_file_mode(&self.path)?; + Ok(true) } } @@ -313,12 +339,7 @@ impl IncidentStore { pub(crate) fn render_incidents(records: &[IncidentRecord], target: &str, now: u64) -> Vec { records .iter() - .filter(|record| record.subject == target) - .filter(|record| { - record.closed_at_unix_millis.is_none_or(|closed_at| { - now.saturating_sub(closed_at) <= INCIDENT_RETENTION_MILLIS - }) - }) + .filter(|record| record.subject == target && record.inside_retention(now)) .map(|record| { let mut line = format!( " incident {} opened-at {}", @@ -336,7 +357,10 @@ pub(crate) fn render_incidents(records: &[IncidentRecord], target: &str, now: u6 } #[cfg(test)] -mod tests { +pub(crate) mod tests { + #[cfg(unix)] + use std::time::{Duration, Instant}; + use tempfile::TempDir; use super::*; @@ -592,7 +616,7 @@ mod tests { #[cfg(unix)] #[test] - fn published_incident_store_is_world_readable() { + fn published_incident_store_is_world_readable_and_its_lock_is_not() { use std::os::unix::fs::PermissionsExt; let temp = TempDir::new().unwrap(); @@ -603,19 +627,156 @@ mod tests { let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777; assert!(under_service_umask(|| store.open(condition, "service", OPENED)).unwrap()); - assert_eq!((mode(&path), mode(&lock)), (0o644, 0o644), "after open"); + assert_eq!(mode(&path), 0o644, "after open"); + assert_eq!(mode(&lock) & 0o007, 0, "the lock is open to others after open"); // Each write replaces the file, and the replacement is published too. assert!( under_service_umask(|| store.close(condition, "service", CloseReason::Recovered, CLOSED)) .unwrap() ); - assert_eq!((mode(&path), mode(&lock)), (0o644, 0o644), "after close"); + assert_eq!(mode(&path), 0o644, "after close"); + assert_eq!(mode(&lock) & 0o007, 0, "the lock is open to others after close"); assert!( under_service_umask(|| store.retire_closed(CLOSED + INCIDENT_RETENTION_MILLIS + 1)) .unwrap() ); assert_eq!(mode(&path), 0o644, "after retire"); + assert_eq!(mode(&lock) & 0o007, 0, "the lock is open to others after retire"); + } + + /// An exclusive lock on a store's lock file, held through another file + /// description. flock conflicts between descriptions, so the holder need + /// not be another process or another uid: the test does not depend on who + /// it runs as. + #[cfg(unix)] + pub(crate) struct HeldLock(#[allow(dead_code)] std::fs::File); + + #[cfg(unix)] + pub(crate) fn hold_lock_of(store: &Path) -> HeldLock { + use std::os::unix::io::AsRawFd; + + let mut name = store.file_name().unwrap().to_owned(); + name.push(".lock"); + let file = std::fs::OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .open(store.with_file_name(name)) + .unwrap(); + // SAFETY: flock on a descriptor this function owns. + assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }, 0); + HeldLock(file) + } + + /// Run `work` while `held` is held, and fail if it waited on it. The + /// holder lets go after three seconds so that work which does wait ends, + /// late, and the test fails instead of hanging. + #[cfg(unix)] + pub(crate) fn run_while_held(held: HeldLock, work: impl FnOnce() -> T) -> T { + let (release, released) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + let _ = released.recv_timeout(Duration::from_secs(3)); + drop(held); + }); + let started = Instant::now(); + let result = work(); + let waited = started.elapsed(); + let _ = release.send(()); + holder.join().unwrap(); + assert!(waited < Duration::from_secs(2), "the work waited {waited:?} on a held lock"); + result + } + + #[cfg(unix)] + #[test] + fn no_incident_write_waits_on_a_held_lock_and_each_lands_when_it_is_freed() { + let temp = TempDir::new().unwrap(); + let path = temp.path().join("incidents.cc"); + let store = IncidentStore::new(&path); + let condition = IncidentCondition::ContinuityExhausted; + assert!(store.open(condition, "closing", OPENED).unwrap()); + assert!(store.close(condition, "closing", CloseReason::Recovered, OPENED + 1).unwrap()); + assert!(store.open(condition, "open", OPENED).unwrap()); + let before = std::fs::read(&path).unwrap(); + let retired = OPENED + 1 + INCIDENT_RETENTION_MILLIS + 1; + + let outcomes = run_while_held(hold_lock_of(&path), || { + ( + store.open(condition, "new", CLOSED), + store.close(condition, "open", CloseReason::Recovered, CLOSED), + store.retire_closed(retired), + ) + }); + for outcome in [outcomes.0, outcomes.1, outcomes.2] { + assert!(outcome.is_err()); + } + assert_eq!(std::fs::read(&path).unwrap(), before, "a contended write changed the file"); + assert!(!temp.path().join("incident-history.cc").exists()); + + // Nothing was lost by the refusal: the same calls land once it is free. + assert!(store.open(condition, "new", CLOSED).unwrap()); + assert!(store.close(condition, "open", CloseReason::Recovered, CLOSED).unwrap()); + assert!(store.retire_closed(retired).unwrap()); + } + + #[cfg(unix)] + #[test] + fn a_held_history_lock_keeps_the_incident_where_it_is() { + let temp = TempDir::new().unwrap(); + let path = temp.path().join("incidents.cc"); + let history = temp.path().join("incident-history.cc"); + let store = IncidentStore::new(&path); + let condition = IncidentCondition::ContinuityExhausted; + assert!(store.open(condition, "old", OPENED).unwrap()); + assert!(store.close(condition, "old", CloseReason::Recovered, OPENED + 1).unwrap()); + let before = std::fs::read(&path).unwrap(); + let retired = OPENED + 1 + INCIDENT_RETENTION_MILLIS + 1; + + let outcome = run_while_held(hold_lock_of(&history), || store.retire_closed(retired)); + assert!(outcome.is_err()); + assert_eq!(std::fs::read(&path).unwrap(), before); + assert!(store.retire_closed(retired).unwrap()); + } + + #[test] + fn a_write_decided_on_a_stale_snapshot_does_not_land() { + let temp = TempDir::new().unwrap(); + let path = temp.path().join("incidents.cc"); + let store = IncidentStore::new(&path); + let condition = IncidentCondition::ContinuityExhausted; + + // Two writers read the file with no incident open for the subject. + let stale = store.snapshot().unwrap(); + assert!(store.open(condition, "service", OPENED).unwrap()); + + // The slower one must lose: one open incident per subject. + let error = store + .open_on(&stale, condition, "service", OPENED + 1) + .unwrap_err(); + assert!(error.to_string().contains("changed"), "{error}"); + let records = store.read().unwrap(); + assert_eq!(records.len(), 1); + assert_eq!(records[0].opened_at_unix_millis, OPENED); + } + + #[test] + fn retiring_after_a_crash_between_history_and_delete_archives_once() { + let temp = TempDir::new().unwrap(); + let path = temp.path().join("incidents.cc"); + let store = IncidentStore::new(&path); + let condition = IncidentCondition::ContinuityExhausted; + assert!(store.open(condition, "old", OPENED).unwrap()); + assert!(store.close(condition, "old", CloseReason::Recovered, OPENED + 1).unwrap()); + // History already holds the record: the delete never ran. + let envelope = store.snapshot().unwrap().envelopes[0].clone(); + let history = SingleFileMessagePackBackingStore::new(&temp.path().join("incident-history.cc")); + assert!(history.insert_entry_if_absent(envelope).unwrap()); + + assert!(store.retire_closed(OPENED + 1 + INCIDENT_RETENTION_MILLIS + 1).unwrap()); + assert!(store.read().unwrap().is_empty()); + assert_eq!(history.pull_all_read_only_snapshot().unwrap().len(), 1); } }