Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions src/cli/service_supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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());
Expand All @@ -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
Expand All @@ -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) => {}
Expand All @@ -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(());
Expand Down Expand Up @@ -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);
Expand Down
77 changes: 71 additions & 6 deletions src/cli/services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1270,6 +1271,7 @@ pub(crate) fn admit(
_ => None,
};
let mut stopped_at: Option<Instant> = None;
let mut ended_at: Option<Instant> = None;
loop {
let running = match store.lock(key)? {
Admission::Admitted(lock) => {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
Expand Down
51 changes: 44 additions & 7 deletions src/daemon/dns_server.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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<BoundDns> {
let (ipv4_ip, ipv6_ip) = if self.lan_access {
(Ipv4Addr::UNSPECIFIED, Ipv6Addr::UNSPECIFIED)
} else {
Expand All @@ -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.
Expand All @@ -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<UdpSocket>,
tcp_v6: Option<TcpListener>,
ttl: u32,
resolver: Arc<IpResolver>,
}

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,
Expand Down
13 changes: 9 additions & 4 deletions src/daemon/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -220,9 +222,12 @@ impl Server {
}
}

fn spawn_dns_server(port: u16, lan_access: bool) -> tokio::task::JoinHandle<Result<()>> {
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<tokio::task::JoinHandle<Result<()>>> {
let dns = DnsServer::new(port, lan_access).bind().await?;
Ok(tokio::spawn(dns.serve()))
}

fn spawn_reload_listener(
Expand Down
30 changes: 25 additions & 5 deletions src/infrastructure/running_services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<bool> {
Expand Down Expand Up @@ -1122,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.
Expand Down
4 changes: 3 additions & 1 deletion src/infrastructure/runs/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(_)
));

Expand Down
17 changes: 15 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<epoch>:<rev>`: an unchanged snapshot is not sent again
#[arg(long, value_name = "EPOCH:REV")]
/// The revision already held, `<epoch>:<rev>`: 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<String>,
},

Expand Down Expand Up @@ -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"));
}
}
3 changes: 2 additions & 1 deletion tests/runs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading