From c8efc6ce4ec3009cc7b5d41a97a0dd2fb260131a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Tue, 24 Nov 2026 10:05:22 +0100 Subject: [PATCH 1/5] fix(cli): read an inventory revision whose epoch starts with a hyphen An epoch is base64url, so one in 64 starts with '-'. clap then took '--have -1aB:3' for an unknown option, and 'localify inventory --have' failed. This is what made the_daemon_reports_each_state_and_revision_of_a_service fail now and then at tests/inventory.rs:309. --- src/main.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index fd53ab6..0e5c2c9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -374,8 +374,9 @@ enum Commands { /// This machine's inventory, as JSON, from the daemon (docs/remote-machines.md) #[command(hide = true)] Inventory { - /// The revision already held, `:`: an unchanged snapshot is not sent again - #[arg(long, value_name = "EPOCH:REV")] + /// The revision already held, `:`: an unchanged snapshot is not sent again. + /// An epoch is base64url, so it may start with `-` + #[arg(long, value_name = "EPOCH:REV", allow_hyphen_values = true)] have: Option, }, @@ -1896,4 +1897,16 @@ mod tests { let error = subscribe(&["--machines", "21"]).err().unwrap().to_string(); assert!(error.contains("1 to 20"), "{error}"); } + + /// One epoch in 64 starts with `-`, as base64url may: it is still the + /// revision held, not an option. + #[test] + fn inventory_reads_a_revision_whose_epoch_starts_with_a_hyphen() { + let cli = Cli::try_parse_from(["localify", "inventory", "--have", "-1aB_c:3"]).unwrap(); + + let Commands::Inventory { have } = cli.command else { + panic!("not the inventory"); + }; + assert_eq!(have.as_deref(), Some("-1aB_c:3")); + } } From 3247c59ee18b8712a32669c55fbad92626e0bbaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Tue, 24 Nov 2026 10:05:32 +0100 Subject: [PATCH 2/5] fix(daemon): bind the DNS port before answering on the management socket The DNS server bound its sockets in a task of its own, while the management socket already answered. When another program took the DNS port in between, the daemon answered status and inventory requests and then exited. The sockets are now bound first, so such a start fails before anything sees the daemon up, with a message naming the port. --- src/daemon/dns_server.rs | 51 ++++++++++++++++++++++++++++++++++------ src/daemon/server.rs | 13 ++++++---- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/daemon/dns_server.rs b/src/daemon/dns_server.rs index 4069bdd..1c3671e 100644 --- a/src/daemon/dns_server.rs +++ b/src/daemon/dns_server.rs @@ -1,7 +1,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; -use anyhow::Result; +use anyhow::{Context, Result}; use simple_dns::rdata::{A, AAAA, RData}; use simple_dns::{CLASS, Name, Packet, PacketFlag, QTYPE, Question, RCODE, ResourceRecord, TYPE}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -86,7 +86,10 @@ impl DnsServer { } } - pub async fn run(&self) -> Result<()> { + /// Binds the DNS sockets. The daemon does this before it answers on its + /// management socket, so a port another program took fails its start + /// instead of ending a daemon that already answered. + pub async fn bind(self) -> Result { let (ipv4_ip, ipv6_ip) = if self.lan_access { (Ipv4Addr::UNSPECIFIED, Ipv6Addr::UNSPECIFIED) } else { @@ -95,9 +98,14 @@ impl DnsServer { let ipv4_addr = SocketAddr::from((ipv4_ip, self.port)); let ipv6_addr = SocketAddr::from((ipv6_ip, self.port)); - // Bind UDP sockets - let udp_v4 = UdpSocket::bind(ipv4_addr).await?; - let tcp_v4 = TcpListener::bind(ipv4_addr).await?; + let in_use = || { + format!( + "Failed to open the DNS port {ipv4_addr}. Another program may hold it: check with lsof -nP -i :{}", + self.port + ) + }; + let udp_v4 = UdpSocket::bind(ipv4_addr).await.with_context(in_use)?; + let tcp_v4 = TcpListener::bind(ipv4_addr).await.with_context(in_use)?; // IPv6 binds may fail on Linux where the IPv4 dual-stack socket already // covers both protocols. This is fine — we just skip IPv6-specific listeners. @@ -119,8 +127,37 @@ impl DnsServer { ); } - let ttl = self.ttl; - let resolver = self.ip_resolver.clone(); + Ok(BoundDns { + udp_v4, + tcp_v4, + udp_v6, + tcp_v6, + ttl: self.ttl, + resolver: self.ip_resolver, + }) + } +} + +/// The DNS server with its sockets bound, ready to serve. +pub struct BoundDns { + udp_v4: UdpSocket, + tcp_v4: TcpListener, + udp_v6: Option, + tcp_v6: Option, + ttl: u32, + resolver: Arc, +} + +impl BoundDns { + pub async fn serve(self) -> Result<()> { + let Self { + udp_v4, + tcp_v4, + udp_v6, + tcp_v6, + ttl, + resolver, + } = self; tokio::select! { r = serve_udp(udp_v4, ttl, resolver.clone()) => r, diff --git a/src/daemon/server.rs b/src/daemon/server.rs index ff7eacc..8781869 100644 --- a/src/daemon/server.rs +++ b/src/daemon/server.rs @@ -138,7 +138,9 @@ impl Server { "Localify daemon starting" ); - let dns_handle = spawn_dns_server(self.dns_port, self.listeners.lan_access); + // Bound before the management socket answers: a daemon that answered + // there never exits next because another program took the DNS port. + let dns_handle = spawn_dns_server(self.dns_port, self.listeners.lan_access).await?; let domain_accesses = self.state.load().domain_access_log(); let launch_sessions = self.state.load().launch_sessions(); let inventory = Arc::new(LocalInventory::new( @@ -220,9 +222,12 @@ impl Server { } } -fn spawn_dns_server(port: u16, lan_access: bool) -> tokio::task::JoinHandle> { - let dns_server = DnsServer::new(port, lan_access); - tokio::spawn(async move { dns_server.run().await }) +async fn spawn_dns_server( + port: u16, + lan_access: bool, +) -> Result>> { + let dns = DnsServer::new(port, lan_access).bind().await?; + Ok(tokio::spawn(dns.serve())) } fn spawn_reload_listener( From 4cbd1539ff316675bac130628d6aaaa0e05b2bba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Tue, 24 Nov 2026 10:05:32 +0100 Subject: [PATCH 3/5] fix(dev): scan the service's processes again on the first Ctrl+C The loop decides whether to scan before it reads the Ctrl+C count. A press that came in between was handled with the last scan, which could predate a worker the service had just started. That worker got no SIGINT, was orphaned when the launcher exited, and was never stopped. The interrupt now scans the tree itself. --- src/cli/service_supervisor.rs | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/cli/service_supervisor.rs b/src/cli/service_supervisor.rs index 8a6d90c..8906b55 100644 --- a/src/cli/service_supervisor.rs +++ b/src/cli/service_supervisor.rs @@ -495,10 +495,14 @@ impl<'a> Stopping<'a> { } /// The first Ctrl+C: SIGINT to whoever no terminal reached (see - /// [`interrupt_targets`]). - fn interrupt(&mut self, now: Instant, scan: &[ProcessInfo]) { + /// [`interrupt_targets`]). The tree is scanned again first: a Ctrl+C can + /// come in after the loop decided not to scan, and a process the service + /// started since the last scan, left out of the SIGINT, would be orphaned + /// by the service's exit, out of reach of the stop. + fn interrupt(&mut self, now: Instant) { + let scan = self.track(); let terminal_group = terminal_foreground_group(); - let targets = interrupt_targets(&self.targets_on_interrupt(), scan, terminal_group); + let targets = interrupt_targets(&self.targets_on_interrupt(), &scan, terminal_group); self.signal(&targets, Signal::Interrupt); self.interrupted_since = Some(now); } @@ -619,7 +623,6 @@ fn supervise( }; let mut stopping = Stopping::new(launch, root); let mut next_scan = started; - let mut scan = Vec::new(); let status = loop { #[cfg(test)] drop(stops.poll_gate.lock()); @@ -630,7 +633,7 @@ fn supervise( // Every process is scanned only as often as the run's state needs. let busy = stopping.stopping() || expiring || stops.stopping(); if busy || now >= next_scan { - scan = stopping.track(); + stopping.track(); next_scan = now + if busy { SCAN_WHILE_STOPPING @@ -654,7 +657,7 @@ fn supervise( stops.lose_terminal(&stopping); } // Before the exit: a service a Ctrl+C just ended leaves its stop to run. - respond_to_stop_requests(&mut stopping, stops, now, &scan); + respond_to_stop_requests(&mut stopping, stops, now); match child.try_wait() { Ok(Some(status)) => break status, Ok(None) => {} @@ -671,9 +674,9 @@ fn supervise( } // The rest is a stop or a cleanup: every SCAN_WHILE_STOPPING. let cleanup = loop { - let scan = stopping.track(); + stopping.track(); let now = Instant::now(); - respond_to_stop_requests(&mut stopping, stops, now, &scan); + respond_to_stop_requests(&mut stopping, stops, now); let left = stopping.targets(); if left.is_empty() { break Ok(()); @@ -703,15 +706,10 @@ fn supervise( /// Turns pending stop requests into a stop: a Ctrl+C, or a SIGTERM already /// forwarded to the service, whose survivors get SIGKILL after the grace /// period. A SIGHUP is only forwarded. -fn respond_to_stop_requests( - stopping: &mut Stopping<'_>, - stops: &StopRequests, - now: Instant, - scan: &[ProcessInfo], -) { +fn respond_to_stop_requests(stopping: &mut Stopping<'_>, stops: &StopRequests, now: Instant) { let presses = stops.presses(); if presses > 0 && stopping.interrupted_since.is_none() { - stopping.interrupt(now, scan); + stopping.interrupt(now); } if stops.terminated.load(Ordering::SeqCst) && stopping.terminated_since.is_none() { stopping.terminated_since = Some(now); From 6b0ef038d3c7b97cc318784922ef43a1d7eea269 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Tue, 24 Nov 2026 10:05:43 +0100 Subject: [PATCH 4/5] fix(dev): wait for a run that ended to let go of the service's lock An executor records its exit, then releases the service's lock. A launch in between found the lock held and refused with "'web' is already running", though the run had ended. It now waits for the lock while the record (or the launch record) holds the run's exit and its executor still runs, up to the same 10 s as after a stop. This is what made a_lost_acknowledgement_is_reported_exactly time out waiting for B. --- src/cli/services.rs | 77 ++++++++++++++++++++++++-- src/infrastructure/running_services.rs | 19 ++++++- 2 files changed, 89 insertions(+), 7 deletions(-) diff --git a/src/cli/services.rs b/src/cli/services.rs index a29fa8d..aaa3b15 100644 --- a/src/cli/services.rs +++ b/src/cli/services.rs @@ -1247,12 +1247,13 @@ pub(crate) struct Admitted { /// service's lock. const RELEASE_TIMEOUT: Duration = Duration::from_secs(10); -/// Takes the service's lock for this launch. A run that is already going is -/// stopped, as `stop` would, and finalized first when `replace` says so. Only -/// the run chosen is replaced, the one a person agreed to stop or else the -/// one seen first: when the service holds another run once the lock is -/// free, someone else restarted it, and this launch starts nothing, so two -/// replacing launches never both start. A run of an older version is never +/// Takes the service's lock for this launch. A run that already ended is +/// waited for while its executor lets go of the lock. A run that is already +/// going is stopped, as `stop` would, and finalized first when `replace` +/// says so. Only the run chosen is replaced, the one a person agreed to stop +/// or else the one seen first: when the service holds another run once the +/// lock is free, someone else restarted it, and this launch starts nothing, +/// so two replacing launches never both start. A run of an older version is never /// stopped here. Returns, with the lock, the run this launch takes over: the /// one it stopped or was approved to replace, which the record still names. /// Only the launch that wins the lock gets it, so only the winner records @@ -1270,6 +1271,7 @@ pub(crate) fn admit( _ => None, }; let mut stopped_at: Option = None; + let mut ended_at: Option = None; loop { let running = match store.lock(key)? { Admission::Admitted(lock) => { @@ -1318,6 +1320,20 @@ pub(crate) fn admit( { bail!("{}", restarted_by_someone_else(key, &stopped)); } + if stopped_at.is_none() && store.is_letting_go(&running) { + // The run already ended on its own: its executor is letting go of + // the lock, and the service is not running any more. + let since = *ended_at.get_or_insert_with(Instant::now); + if since.elapsed() >= RELEASE_TIMEOUT { + bail!( + "'{}' has ended, but its launcher (PID {}) still holds the service's lock. Try again in a moment.", + key.service_id, + running.pid + ); + } + thread::sleep(Duration::from_millis(100)); + continue; + } if let Some(since) = stopped_at { // The run just stopped is letting go of the lock. if since.elapsed() >= RELEASE_TIMEOUT { @@ -2803,6 +2819,55 @@ mod tests { assert!(!answer("").0); } + /// A run that ended on its own, whose executor has yet to let go of the + /// service's lock, is not running any more: the next launch waits for the + /// lock, starts, and replaces nothing. + #[test] + fn a_launch_waits_for_a_run_that_ended_to_let_go_of_the_lock() { + let dir = tempfile::tempdir().unwrap(); + let store = RunningServiceStore::new(dir.path().to_path_buf()); + let key = ServiceKey { + project_id: "app".into(), + environment: None, + service_id: "web".into(), + }; + // This test process is the executor. + let lock = store.lock(&key).unwrap().admitted(); + let run_id = RunId::generate().unwrap(); + store + .register( + &lock, + NewRun { + key: key.clone(), + run_id: run_id.clone(), + url: "https://web.localify".into(), + port: 3000, + origin: ServiceOrigin::Background, + profile: None, + output: Some(RunOutput::Pipe), + }, + ) + .unwrap(); + let error = admit(&store, &key, Replace::No, &|| Ok(())).err().unwrap(); + assert!(error.to_string().contains("is already running"), "{error}"); + + // Its end, as the executor records it right before it lets go. + run_output::publish_end( + &store.run_dir(&run_id), + &RunEnd::now(EndReason::Complete, 0), + ) + .unwrap(); + store.mark_exited(&key, &run_id, Some(3)).unwrap(); + let letting_go = thread::spawn(move || { + thread::sleep(Duration::from_millis(300)); + drop(lock); + }); + let admitted = admit(&store, &key, Replace::No, &|| Ok(())).unwrap(); + letting_go.join().unwrap(); + + assert_eq!(admitted.replaces, None); + } + fn test_service(id: &str, root_path: &str, service_path: Option<&str>) -> ConfiguredService { ConfiguredService { id: id.into(), diff --git a/src/infrastructure/running_services.rs b/src/infrastructure/running_services.rs index 7ac3ab6..adbbb9d 100644 --- a/src/infrastructure/running_services.rs +++ b/src/infrastructure/running_services.rs @@ -28,7 +28,7 @@ use crate::infrastructure::runs::finish::{ CLEANUP_WAIT, Finish, Finisher, Membership, RunSession, membership, }; use crate::infrastructure::runs::launches::{ - ExitReason, LaunchExit, LaunchRecords, TEMPORARY_MAX_AGE, reconcile_unresolved, + ExitReason, LaunchExit, LaunchRecord, LaunchRecords, TEMPORARY_MAX_AGE, reconcile_unresolved, sweep_temporaries, }; use crate::infrastructure::runs::output::{self, plain_lines}; @@ -435,6 +435,23 @@ impl RunningServiceStore { })) } + /// Whether `record`'s run is over and only its executor has yet to let go + /// of the service's lock: the executor still runs, and its exit is + /// recorded, in the service's record or, a moment before that, in its + /// launch record. A launch then waits for the lock instead of reporting + /// a run that already ended as running. + pub fn is_letting_go(&self, record: &RunningService) -> bool { + let Some(run_id) = record.run_id() else { + return false; + }; + let ended = record.exit.is_some() + || matches!( + self.launches().read(run_id), + Ok(Some(LaunchRecord::Admitted(launch))) if launch.exit.is_some() + ); + ended && record.executor_runs() + } + /// The next launcher's part in ending the previous run, through the same /// finisher as `stop` and the daemon. Returns whether it still runs. fn end_previous(&self, previous: &RunningService) -> Result { From 563d3a60f36d03daa6dcea4fe3f62984278b13f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Tue, 24 Nov 2026 10:05:43 +0100 Subject: [PATCH 5/5] fix(test): wait for a lock to be released instead of asserting it at once On macOS a flock belongs to the open file description, which a child another test forks keeps until it execs: right after a drop, the lock may still be held for a moment. the_finalize_lock_is_exclusive_and_never_recreates_a_folder failed this way on main; the_lock_admits_one_executor_at_a_time relies on the same thing. Both now wait for the release. a_stop_whose_executor_dies_goes_on_only_under_the_lock waited 5 s for a SIGTERM sent after a journal write; under heavy disk load that write alone took longer. Its hang guard is now 30 s, as for the other waits of that file. --- src/infrastructure/running_services.rs | 11 +++++++---- src/infrastructure/runs/output.rs | 4 +++- tests/runs.rs | 3 ++- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/infrastructure/running_services.rs b/src/infrastructure/running_services.rs index adbbb9d..9fc38f5 100644 --- a/src/infrastructure/running_services.rs +++ b/src/infrastructure/running_services.rs @@ -1139,10 +1139,13 @@ mod tests { assert!(matches!(second, Admission::Running(None))); drop(lock); - assert!(matches!( - store.lock(&key("web")).unwrap(), - Admission::Admitted(_) - )); + // Free once every copy of its descriptor is closed: a child another + // test forks meanwhile keeps one until it execs. + let deadline = Instant::now() + Duration::from_secs(10); + while !matches!(store.lock(&key("web")).unwrap(), Admission::Admitted(_)) { + assert!(Instant::now() < deadline, "the lock was never released"); + thread::sleep(Duration::from_millis(10)); + } } /// What an older version recorded for `pid`: the start `ps` printed. diff --git a/src/infrastructure/runs/output.rs b/src/infrastructure/runs/output.rs index 1e2af0c..db3fd0e 100644 --- a/src/infrastructure/runs/output.rs +++ b/src/infrastructure/runs/output.rs @@ -954,8 +954,10 @@ mod tests { Acquired::Busy )); drop(held); + // Free once every copy of its descriptor is closed: a child another + // test forks meanwhile keeps one until it execs. assert!(matches!( - FinalizeLock::acquire_within(&run, Duration::ZERO).unwrap(), + FinalizeLock::acquire_within(&run, Duration::from_secs(10)).unwrap(), Acquired::Locked(_) )); diff --git a/tests/runs.rs b/tests/runs.rs index 33bbc6f..31c0566 100644 --- a/tests/runs.rs +++ b/tests/runs.rs @@ -1160,7 +1160,8 @@ fn a_stop_whose_executor_dies_goes_on_only_under_the_lock() { finisher.stop(dir.path(), &recorded_session("boot-a"), true) }); // The executor dies of its SIGTERM; another finisher then takes the lock. - let died = wait_until(Duration::from_secs(5), || { + // Its journal is written before the signal, which a busy disk delays. + let died = wait_until(Duration::from_secs(30), || { let signals = table.signals.lock().unwrap(); signals .iter()