diff --git a/crates/fctl-agent/src/link.rs b/crates/fctl-agent/src/link.rs index 4a4bbcea..c4c2e770 100644 --- a/crates/fctl-agent/src/link.rs +++ b/crates/fctl-agent/src/link.rs @@ -52,13 +52,15 @@ pub async fn accept_loop(listener: UnixListener, events: mpsc::UnboundedSender(); + if events.send(LinkEvent::Connected(id, tx)).is_err() { + return; + } let events = events.clone(); tokio::spawn(async move { let (read, mut write) = stream.into_split(); - let (tx, mut rx) = mpsc::unbounded_channel::(); - if events.send(LinkEvent::Connected(id, tx)).is_err() { - return; - } let writer = tokio::spawn(async move { while let Some(mut line) = rx.recv().await { line.push('\n'); diff --git a/crates/fctl-agent/src/supervisor.rs b/crates/fctl-agent/src/supervisor.rs index 2719c49a..d38c83a0 100644 --- a/crates/fctl-agent/src/supervisor.rs +++ b/crates/fctl-agent/src/supervisor.rs @@ -232,12 +232,22 @@ impl Supervisor { async fn on_link(&mut self, e: LinkEvent) { match e { LinkEvent::Connected(id, tx) => { + let (seq, acked) = (self.journal.last_seq(), self.journal.acked()); + match self.host.as_ref() { + Some((old, _)) => tracing::info!( + "host link {id} replaces link {old}; journal at agent_seq {seq}, {acked} acknowledged" + ), + None => tracing::info!( + "host link {id} attached; journal at agent_seq {seq}, {acked} acknowledged" + ), + } self.host = Some((id, tx)); let hello = self.hello(); self.send(&hello); } LinkEvent::Disconnected(id) => { if self.host.as_ref().is_some_and(|(cur, _)| *cur == id) { + tracing::info!("host link {id} detached"); self.host = None; } } @@ -267,6 +277,12 @@ impl Supervisor { self.outbox.clear(); match self.journal.read_after(after_agent_seq) { Ok(events) => { + if let Some((id, _)) = &self.host { + tracing::info!( + "replaying {} events after agent_seq {after_agent_seq} to host link {id}", + events.len() + ); + } for chunk in events.chunks(100) { self.send(&AgentToHost::Events { events: chunk.to_vec(), diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 2d7206cf..3f9ca996 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -3,9 +3,14 @@ //! Sessions outlive the control connection (each has its own uplink) and //! outlive the daemon itself: agents keep running in their sandboxes, and a //! restarted daemon finds and re-attaches to them. +//! +//! The control connection never waits on a driver. The hello reports what +//! the drivers said when last probed, and sweeping or cleaning up sandboxes +//! runs in tasks of their own (`Chore`), so heartbeats and pongs keep +//! flowing while a runtime hangs. use crate::config::HostConfig; -use crate::driver::{Driver, sandbox_name, session_of}; +use crate::driver::{Driver, SandboxInfo, sandbox_name, session_of, timed_out}; use crate::expiry; use crate::login::{self, LoginCmd}; use crate::session::{self, HostCtx, SessionCmd, SessionEvent, SessionHandle, Start}; @@ -13,13 +18,16 @@ use crate::sysinfo; use anyhow::Result; use fctl_client::ws; use fctl_domain::size::{self, Want}; -use fctl_proto::runner::{FleetToHost, HostHeartbeat, HostHello, HostSessionReport, HostToFleet}; +use fctl_proto::runner::{ + FleetToHost, HostHeartbeat, HostHello, HostSessionReport, HostToFleet, SessionSpec, StopReason, +}; +use fctl_proto::session::SessionStatus; use fctl_proto::{LoginJobId, PROTOCOL_VERSION, SessionId}; use futures::StreamExt; -use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, Mutex}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; use std::time::Duration; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, oneshot}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -33,39 +41,58 @@ pub struct Daemon { events_rx: mpsc::UnboundedReceiver, login_tx: mpsc::UnboundedSender, login_rx: mpsc::UnboundedReceiver, + chores_tx: mpsc::UnboundedSender, + chores_rx: mpsc::UnboundedReceiver, /// Messages waiting for the control connection. - outbox: Vec, - /// Starts that wait for the previous run of the same session to finish. - pending_starts: HashMap>, + outbox: VecDeque, + /// Starts that wait for the previous run of the same session to finish, + /// or for a chore on its sandbox. + pending_starts: HashMap>, next_request: u64, /// When to remove expired stopped sandboxes (see `expiry`). sweep: tokio::time::Interval, + /// Whether a sweep is under way. + sweeping: bool, + /// Sandboxes that chores stop or remove, with how many hold each. + /// Sessions that start in one wait for it. + busy: HashMap, +} + +/// What background work on sandboxes that no session runs in reports. +enum Chore { + /// The sweep listed this host's sandboxes. + Listed(Result>), + /// The sweep removed a sandbox, or failed to. + Removed { name: String, result: Result<()> }, + /// The sweep is over. + Swept, + /// A sandbox the control plane asked to stop is stopped (and removed, + /// when it asked for that). + Stopped { name: String, ended: HostToFleet }, } const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); +/// How often the host probes its drivers and measures what sandboxes run on. +const FACTS_EVERY: Duration = Duration::from_secs(5 * 60); +const HEARTBEAT_EVERY: Duration = Duration::from_secs(15); impl Daemon { pub async fn new(cfg: HostConfig, token: String) -> Result { let data = cfg.data_dir(); std::fs::create_dir_all(&data)?; let driver = Driver::select(&cfg.driver, &data, cfg.agent_bin.clone()).await?; - let sandbox = cfg.sandbox_limits(driver.resources().await); + let ctx = Arc::new(HostCtx::new(cfg, driver, token)); + ctx.refresh_facts().await; tracing::info!( "fctl host {VERSION} on {} using the {} driver, capacity {}, sandboxes {}", - cfg.name, - driver.name(), - cfg.capacity, - size::limits(&sandbox) + ctx.cfg.name, + ctx.driver.name(), + ctx.cfg.capacity, + size::limits(&ctx.sandbox_limits()) ); - let ctx = Arc::new(HostCtx { - cfg, - driver, - token, - runner_id: Mutex::new(None), - sandbox: Mutex::new(sandbox), - }); let (events_tx, events_rx) = mpsc::unbounded_channel(); let (login_tx, login_rx) = mpsc::unbounded_channel(); + let (chores_tx, chores_rx) = mpsc::unbounded_channel(); Ok(Self { ctx, sessions: HashMap::new(), @@ -75,16 +102,26 @@ impl Daemon { events_rx, login_tx, login_rx, - outbox: Vec::new(), + chores_tx, + chores_rx, + outbox: VecDeque::new(), pending_starts: HashMap::new(), next_request: 0, sweep: tokio::time::interval_at(tokio::time::Instant::now() + SWEEP_EVERY, SWEEP_EVERY), + sweeping: false, + busy: HashMap::new(), }) } - /// Re-attaches to sandboxes that survived a restart. - async fn recover(&mut self) { - match self.ctx.driver.list().await { + /// Re-attaches to sandboxes that survived a restart. False when the + /// runtime doesn't answer: the hello must not tell the control plane + /// that sessions are gone (it would stop them) when they may still run. + async fn recover(&mut self) -> bool { + let listed = self.ctx.driver.list().await; + if timed_out(&listed) { + return false; + } + match listed { Ok(list) => { for sb in list.into_iter().filter(|s| s.running) { if let Some(id) = session_of(&sb.name).map(SessionId) { @@ -100,19 +137,26 @@ impl Daemon { } Err(e) => tracing::warn!("listing sandboxes: {e:#}"), } + true + } + + /// Starts removing session sandboxes that have been stopped for longer + /// than `keep_stopped_hours` (0 keeps them), unless a sweep is under way. + fn start_sweep(&mut self) { + if self.sweeping { + return; + } + self.sweeping = true; + let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); + tokio::spawn(async move { + let _ = chores.send(Chore::Listed(ctx.driver.list().await)); + }); } - /// Removes session sandboxes that have been stopped for longer than - /// `keep_stopped_hours` (0 keeps them). - async fn sweep_stopped(&mut self) { + /// Picks the sandboxes the sweep removes, and removes them one after + /// another in the background. + fn sweep_listed(&mut self, list: Vec) { let hours = self.ctx.cfg.keep_stopped_hours; - let list = match self.ctx.driver.list().await { - Ok(list) => list, - Err(e) => { - tracing::warn!("listing sandboxes: {e:#}"); - return; - } - }; let in_use: HashSet = self .sessions .keys() @@ -123,20 +167,93 @@ impl Daemon { let stopped = expiry::load(&path); let now = expiry::now_ms(); let keep_ms = (hours > 0).then(|| i64::from(hours) * 3_600_000); - let (remove, mut keep) = expiry::plan(&stopped, &list, &in_use, now, keep_ms); - for name in remove { - let sb = self.ctx.driver.handle(&name); - match self.ctx.driver.remove(&sb).await { - Ok(()) => tracing::info!("removed {name}: stopped for more than {hours} hours"), - Err(e) => { - tracing::warn!("removing {name}: {e:#}"); - keep.insert(name.clone(), stopped.get(&name).copied().unwrap_or(now)); - } + let (expired, mut keep) = expiry::plan(&stopped, &list, &in_use, now, keep_ms); + // They stay on the list until they are gone, for a host that stops + // halfway; one that a chore holds waits for the next sweep. + let mut remove = Vec::new(); + for name in expired { + keep.insert(name.clone(), stopped.get(&name).copied().unwrap_or(now)); + if !self.busy.contains_key(&name) { + remove.push(name); } } if let Err(e) = expiry::save(&path, &keep) { tracing::warn!("saving {}: {e:#}", path.display()); } + if remove.is_empty() { + self.sweeping = false; + return; + } + for name in &remove { + self.hold(name); + } + let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); + tokio::spawn(async move { + for name in remove { + let result = ctx.driver.remove(&ctx.driver.handle(&name)).await; + let _ = chores.send(Chore::Removed { name, result }); + } + let _ = chores.send(Chore::Swept); + }); + } + + fn on_chore(&mut self, chore: Chore) { + match chore { + Chore::Listed(Ok(list)) => self.sweep_listed(list), + Chore::Listed(Err(e)) => { + tracing::warn!("listing sandboxes: {e:#}"); + self.sweeping = false; + } + Chore::Removed { name, result } => { + match result { + Ok(()) => { + let hours = self.ctx.cfg.keep_stopped_hours; + tracing::info!("removed {name}: stopped for more than {hours} hours"); + let path = expiry::path(&self.ctx.cfg.data_dir()); + if let Err(e) = expiry::forget(&path, &name) { + tracing::warn!("saving {}: {e:#}", path.display()); + } + } + Err(e) => tracing::warn!("removing {name}: {e:#}"), + } + self.release(&name); + } + Chore::Swept => self.sweeping = false, + Chore::Stopped { name, ended } => { + self.outbox.push_back(ended); + self.release(&name); + } + } + } + + /// Holds a sandbox for a chore: sessions that start in it wait. + fn hold(&mut self, name: &str) { + *self.busy.entry(name.to_owned()).or_default() += 1; + } + + /// Ends a chore's hold on a sandbox, and starts the session that waited + /// for it. + fn release(&mut self, name: &str) { + if let Some(n) = self.busy.get_mut(name) + && *n > 1 + { + *n -= 1; + return; + } + self.busy.remove(name); + if let Some(id) = session_of(name).map(SessionId) + && !self.sessions.contains_key(&id) + && let Some(spec) = self.pending_starts.remove(&id) + { + tracing::info!("starting {id}: {}", spec.title); + self.spawn_session(spec); + } + } + + fn spawn_session(&mut self, spec: Box) { + let id = spec.session_id.clone(); + let h = session::spawn(self.ctx.clone(), Start::New(spec), self.events_tx.clone()); + self.sessions.insert(id, h); } fn reports(&self) -> Vec { @@ -153,7 +270,7 @@ impl Daemon { .collect() } - async fn hello(&self) -> HostHello { + fn hello(&self) -> HostHello { HostHello { protocol: PROTOCOL_VERSION, version: VERSION.into(), @@ -162,32 +279,67 @@ impl Daemon { arch: sysinfo::arch().into(), cpus: sysinfo::cpus(), memory_mb: sysinfo::memory_mb(), - drivers: Driver::probe_all(&self.ctx.cfg.data_dir()).await, + drivers: self.ctx.drivers(), driver: self.ctx.driver.name().into(), capacity: self.ctx.cfg.capacity, labels: self.ctx.cfg.labels.clone(), sessions: self.reports(), image: Some(self.ctx.cfg.image.clone()), - sandbox: Some(self.ctx.refresh_sandbox_limits().await), + sandbox: Some(self.ctx.sandbox_limits()), + } + } + + fn heartbeat(&self) -> HostHeartbeat { + HostHeartbeat { + sessions: self.reports(), + load1: sysinfo::load1(), + memory_available_mb: sysinfo::memory_available_mb(), + disk_available_mb: sysinfo::disk_available_mb(&self.ctx.cfg.data_dir()), } } pub async fn run(mut self) -> Result<()> { + let mut shutdown = shutdown_signal(); keep_awake(); - self.recover().await; - self.sweep_stopped().await; + let mut wait = Duration::from_secs(5); + loop { + let recovered = tokio::select! { + r = self.recover() => r, + _ = &mut shutdown => return Ok(()), + }; + if recovered { + break; + } + tracing::warn!( + "the {} driver does not answer; connecting once it lists the sandboxes (next try in {} s)", + self.ctx.driver.name(), + wait.as_secs() + ); + tokio::select! { + _ = tokio::time::sleep(wait) => {} + _ = &mut shutdown => return Ok(()), + } + wait = (wait * 2).min(Duration::from_secs(60)); + } + self.start_sweep(); + refresh_facts_every(self.ctx.clone(), FACTS_EVERY); let url = format!( "{}/api/v1/runner/connect", self.ctx.cfg.server.trim_end_matches('/') ); let mut backoff = Duration::from_secs(1); loop { - match ws::connect(&url, Some(&self.ctx.token)).await { + let connected = tokio::select! { + c = ws::connect(&url, Some(&self.ctx.token)) => c, + _ = &mut shutdown => return Ok(()), + }; + match connected { Ok(socket) => { backoff = Duration::from_secs(1); tracing::info!("connected to {}", self.ctx.cfg.server); - if let Err(e) = self.serve(socket).await { - tracing::warn!("control connection: {e:#}"); + match self.serve(socket, &mut shutdown).await { + Ok(()) => tracing::info!("the control plane closed the connection"), + Err(e) => tracing::warn!("control connection: {e:#}"), } } Err(e) => tracing::warn!("cannot reach {}: {e:#}", self.ctx.cfg.server), @@ -198,25 +350,35 @@ impl Daemon { loop { tokio::select! { _ = &mut deadline => break, - Some(ev) = self.events_rx.recv() => { let _ = self.on_session_event(ev); } - Some(msg) = self.login_rx.recv() => self.outbox.push(msg), - _ = self.sweep.tick() => self.sweep_stopped().await, - _ = shutdown_signal() => return Ok(()), + Some(ev) = self.events_rx.recv() => self.on_session_event(ev), + Some(msg) = self.login_rx.recv() => self.outbox.push_back(msg), + Some(chore) = self.chores_rx.recv() => self.on_chore(chore), + _ = self.sweep.tick() => self.start_sweep(), + _ = &mut shutdown => return Ok(()), } } backoff = (backoff * 2).min(Duration::from_secs(30)); } } - async fn serve(&mut self, socket: ws::Socket) -> Result<()> { + async fn serve( + &mut self, + socket: ws::Socket, + shutdown: &mut oneshot::Receiver<()>, + ) -> Result<()> { let (mut sink, mut stream) = socket.split(); - ws::send_json(&mut sink, &HostToFleet::Hello(Box::new(self.hello().await))).await?; - for m in std::mem::take(&mut self.outbox) { - ws::send_json(&mut sink, &m).await?; - } - let mut heartbeat = tokio::time::interval(Duration::from_secs(15)); + ws::send_json(&mut sink, &HostToFleet::Hello(Box::new(self.hello()))).await?; + let mut heartbeat = tokio::time::interval(HEARTBEAT_EVERY); heartbeat.tick().await; loop { + // What the last step queued, and what waited for a connection. + // A message that can't be sent waits for the next one. + while let Some(m) = self.outbox.pop_front() { + if let Err(e) = ws::send_json(&mut sink, &m).await { + self.outbox.push_front(m); + return Err(e); + } + } tokio::select! { msg = ws::next_text(&mut stream) => { let text = match msg { @@ -224,34 +386,20 @@ impl Daemon { Some(Err(e)) => return Err(e), None => return Ok(()), }; - let msg: FleetToHost = match serde_json::from_str(&text) { - Ok(m) => m, - Err(e) => { tracing::warn!("unknown message from the control plane: {e}"); continue; } - }; - for reply in self.on_fleet(msg).await { - ws::send_json(&mut sink, &reply).await?; + match serde_json::from_str::(&text) { + Ok(msg) => self.on_fleet(msg), + Err(e) => tracing::warn!("unknown message from the control plane: {e}"), } } - Some(ev) = self.events_rx.recv() => { - if let Some(m) = self.on_session_event(ev) { - ws::send_json(&mut sink, &m).await?; - } - for m in std::mem::take(&mut self.outbox) { - ws::send_json(&mut sink, &m).await?; - } - } - Some(msg) = self.login_rx.recv() => ws::send_json(&mut sink, &msg).await?, - _ = self.sweep.tick() => self.sweep_stopped().await, + Some(ev) = self.events_rx.recv() => self.on_session_event(ev), + Some(msg) = self.login_rx.recv() => self.outbox.push_back(msg), + Some(chore) = self.chores_rx.recv() => self.on_chore(chore), + _ = self.sweep.tick() => self.start_sweep(), _ = heartbeat.tick() => { - let hb = HostHeartbeat { - sessions: self.reports(), - load1: sysinfo::load1(), - memory_available_mb: sysinfo::memory_available_mb(), - disk_available_mb: sysinfo::disk_available_mb(&self.ctx.cfg.data_dir()), - }; - ws::send_json(&mut sink, &HostToFleet::Heartbeat(hb)).await?; + let hb = self.heartbeat(); + self.outbox.push_back(HostToFleet::Heartbeat(hb)); } - _ = shutdown_signal() => { + _ = &mut *shutdown => { tracing::info!("shutting down; sessions keep running in their sandboxes"); std::process::exit(0); } @@ -259,8 +407,9 @@ impl Daemon { } } - /// Handles a session event; returns a message for the control plane (or queues it). - fn on_session_event(&mut self, ev: SessionEvent) -> Option { + /// Handles a session event; what it has for the control plane goes to + /// the outbox. + fn on_session_event(&mut self, ev: SessionEvent) { match ev { SessionEvent::CredentialRequest { session_id, @@ -271,13 +420,11 @@ impl Daemon { let rid = format!("h{}", self.next_request); self.pending_creds .insert(rid.clone(), (session_id.clone(), request_id)); - let m = HostToFleet::CredentialRequest { + self.outbox.push_back(HostToFleet::CredentialRequest { request_id: rid, session_id, kind, - }; - self.outbox.push(m); - None + }); } SessionEvent::Ended { session_id, @@ -296,7 +443,7 @@ impl Daemon { if let Err(e) = expiry::note_stopped(&stopped, &name, expiry::now_ms()) { tracing::warn!("saving {}: {e:#}", stopped.display()); } - self.outbox.push(HostToFleet::SessionEnded { + self.outbox.push_back(HostToFleet::SessionEnded { session_id: session_id.clone(), status, reason, @@ -304,107 +451,36 @@ impl Daemon { }); if let Some(spec) = self.pending_starts.remove(&session_id) { tracing::info!("starting the next run of {session_id}"); - let h = - session::spawn(self.ctx.clone(), Start::New(spec), self.events_tx.clone()); - self.sessions.insert(session_id, h); + self.spawn_session(spec); } - None } } } - async fn on_fleet(&mut self, msg: FleetToHost) -> Vec { + /// Handles a message from the control plane; replies go to the outbox. + fn on_fleet(&mut self, msg: FleetToHost) { match msg { FleetToHost::Welcome { runner, .. } => { tracing::info!("registered as {} ({})", runner.name, runner.id); if let Ok(mut r) = self.ctx.runner_id.lock() { *r = Some(runner.id); } - vec![] } - FleetToHost::Ping => vec![HostToFleet::Pong], + FleetToHost::Ping => self.outbox.push_back(HostToFleet::Pong), FleetToHost::StartSession { spec } => { let id = spec.session_id.clone(); - // The control plane only sends sessions that fit; an older - // one may not know this host's limits. - let limits = self.ctx.sandbox_limits(); - if !Want::of(&spec.project.settings).fits(&limits) { - return vec![HostToFleet::StartResult { - session_id: id, - accepted: false, - error: Some(format!( - "{} gives a sandbox at most {} and {} of memory", - self.ctx.cfg.name, - size::cpus(limits.max.cpus), - size::memory(limits.max.memory_mb.into()) - )), - }]; - } - if let Some(existing) = self.sessions.get(&id) { - let winding_down = existing - .report - .lock() - .map(|r| { - r.status.is_terminal() - || r.status == fctl_proto::session::SessionStatus::Stopping - }) - .unwrap_or(false); - if winding_down { - // A resume while the last run still shuts down: start it right after. - let _ = existing.tx.send(SessionCmd::Superseded); - self.pending_starts.insert(id.clone(), spec); - } - return vec![HostToFleet::StartResult { - session_id: id, - accepted: true, - error: None, - }]; - } - if self.sessions.len() as u32 >= self.ctx.cfg.capacity { - return vec![HostToFleet::StartResult { - session_id: id, - accepted: false, - error: Some("the host is at capacity".into()), - }]; - } - tracing::info!("starting {id}: {}", spec.title); - let h = session::spawn(self.ctx.clone(), Start::New(spec), self.events_tx.clone()); - self.sessions.insert(id.clone(), h); - vec![HostToFleet::StartResult { + let error = self.start_session(spec).err(); + self.outbox.push_back(HostToFleet::StartResult { session_id: id, - accepted: true, - error: None, - }] + accepted: error.is_none(), + error, + }); } FleetToHost::StopSession { session_id, reason, destroy, - } => { - match self.sessions.get(&session_id) { - Some(h) => { - let _ = h.tx.send(SessionCmd::Stop { reason, destroy }); - vec![] - } - None => { - // Not running here: clean up any leftover sandbox. - let sb = self - .ctx - .driver - .handle(&crate::driver::sandbox_name(session_id.as_str())); - let _ = self.ctx.driver.stop(&sb).await; - if destroy { - let _ = self.ctx.driver.remove(&sb).await; - } - vec![HostToFleet::SessionEnded { - session_id, - status: fctl_proto::session::SessionStatus::Stopped, - reason: Some("Stopped".into()), - run_id: None, - }] - } - } - } + } => self.stop_session(session_id, reason, destroy), FleetToHost::Credential { request_id, claude, @@ -423,7 +499,6 @@ impl Daemon { error, }); } - vec![] } FleetToHost::ClaudeLoginStart { job_id, user } => { let (tx, rx) = mpsc::unbounded_channel(); @@ -435,22 +510,110 @@ impl Daemon { rx, self.login_tx.clone(), )); - vec![] } FleetToHost::ClaudeLoginCode { job_id, code } => { if let Some(tx) = self.logins.get(&job_id) { let _ = tx.send(LoginCmd::Code(code)); } - vec![] } FleetToHost::ClaudeLoginCancel { job_id } => { if let Some(tx) = self.logins.remove(&job_id) { let _ = tx.send(LoginCmd::Cancel); } - vec![] } } } + + /// Takes on a session, or says why not. + fn start_session(&mut self, spec: Box) -> Result<(), String> { + let id = spec.session_id.clone(); + // The control plane only sends sessions that fit; an older one may + // not know this host's limits. + let limits = self.ctx.sandbox_limits(); + if !Want::of(&spec.project.settings).fits(&limits) { + return Err(format!( + "{} gives a sandbox at most {} and {} of memory", + self.ctx.cfg.name, + size::cpus(limits.max.cpus), + size::memory(limits.max.memory_mb.into()) + )); + } + if let Some(existing) = self.sessions.get(&id) { + let winding_down = existing + .report + .lock() + .map(|r| r.status.is_terminal() || r.status == SessionStatus::Stopping) + .unwrap_or(false); + if winding_down { + // A resume while the last run still shuts down: start it right after. + let _ = existing.tx.send(SessionCmd::Superseded); + self.pending_starts.insert(id, spec); + } + return Ok(()); + } + if let Some(waiting) = self.pending_starts.get_mut(&id) { + *waiting = spec; + return Ok(()); + } + let waiting = self + .pending_starts + .keys() + .filter(|id| !self.sessions.contains_key(*id)) + .count(); + if (self.sessions.len() + waiting) as u32 >= self.ctx.cfg.capacity { + return Err("the host is at capacity".into()); + } + if self.busy.contains_key(&sandbox_name(id.as_str())) { + tracing::info!("{id} starts once its sandbox is stopped or removed"); + self.pending_starts.insert(id, spec); + return Ok(()); + } + tracing::info!("starting {id}: {}", spec.title); + self.spawn_session(spec); + Ok(()) + } + + fn stop_session(&mut self, session_id: SessionId, reason: StopReason, destroy: bool) { + if let Some(h) = self.sessions.get(&session_id) { + let _ = h.tx.send(SessionCmd::Stop { reason, destroy }); + return; + } + // Not running here: a start that waits for its sandbox is called + // off, and a leftover sandbox is stopped in the background. + self.pending_starts.remove(&session_id); + let name = sandbox_name(session_id.as_str()); + self.hold(&name); + let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); + tokio::spawn(async move { + let sb = ctx.driver.handle(&name); + if let Err(e) = ctx.driver.stop(&sb).await { + tracing::warn!("stopping {name}: {e:#}"); + } + if destroy && let Err(e) = ctx.driver.remove(&sb).await { + tracing::warn!("removing {name}: {e:#}"); + } + let ended = HostToFleet::SessionEnded { + session_id, + status: SessionStatus::Stopped, + reason: Some("Stopped".into()), + run_id: None, + }; + let _ = chores.send(Chore::Stopped { name, ended }); + }); + } +} + +/// Probes the drivers and measures what sandboxes run on every `period`, in +/// the background. +fn refresh_facts_every(ctx: Arc, period: Duration) { + tokio::spawn(async move { + let mut every = tokio::time::interval_at(tokio::time::Instant::now() + period, period); + every.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + every.tick().await; + ctx.refresh_facts().await; + } + }); } fn jitter(d: Duration) -> Duration { @@ -460,7 +623,18 @@ fn jitter(d: Duration) -> Duration { Duration::from_millis((ms as i64 + spread).max(100) as u64) } -async fn shutdown_signal() { +/// Fires on SIGTERM or SIGINT. It listens from the start, so that a signal +/// that comes while the daemon is busy elsewhere is not lost. +fn shutdown_signal() -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + tokio::spawn(async move { + signalled().await; + let _ = tx.send(()); + }); + rx +} + +async fn signalled() { #[cfg(unix)] { use tokio::signal::unix::{SignalKind, signal}; diff --git a/crates/fctl-host/src/driver/container.rs b/crates/fctl-host/src/driver/container.rs index d2bcf5a0..be9b2057 100644 --- a/crates/fctl-host/src/driver/container.rs +++ b/crates/fctl-host/src/driver/container.rs @@ -8,7 +8,8 @@ //! fctl-agent attach`. use super::{ - AGENT_PATH, AgentIo, Sandbox, SandboxInfo, SandboxSpec, attach_script, run_cmd, serve_script, + AGENT_PATH, AgentIo, COMMAND_TIMEOUT, SLOW_COMMAND_TIMEOUT, Sandbox, SandboxInfo, SandboxSpec, + TimedOut, attach_script, run_cmd_within, serve_script, timed_out, }; use anyhow::{Context, Result}; use fctl_proto::runner::{DriverInfo, SandboxSize}; @@ -50,7 +51,13 @@ impl ContainerDriver { } async fn run(&self, args: &[&str]) -> Result { - run_cmd(&self.bin, args).await + // Pulling an image takes minutes, and so may `run`, which pulls one + // that is missing. + let limit = match args { + ["pull", ..] | ["image", "pull", ..] | ["run", ..] => SLOW_COMMAND_TIMEOUT, + _ => COMMAND_TIMEOUT, + }; + run_cmd_within(&self.bin, args, limit).await } pub async fn probe(&self) -> DriverInfo { @@ -82,40 +89,48 @@ impl ContainerDriver { }), }; } - let version = match self.flavor { - Flavor::Apple => self - .run(&["system", "version", "--format", "json"]) - .await - .ok() - .and_then(|s| { + // The service must be up, not just the CLI installed. + let (version, ready, hung) = match self.flavor { + Flavor::Apple => { + let version = self.run(&["system", "version", "--format", "json"]).await; + // A service that doesn't answer one command won't answer the next. + let (ready, hung) = if timed_out(&version) { + (false, true) + } else { + let status = self.run(&["system", "status"]).await; + (status.is_ok(), timed_out(&status)) + }; + let version = version.ok().and_then(|s| { let v: Value = serde_json::from_str(&s).ok()?; v.get("version") .or_else(|| v.pointer("/0/version")) .and_then(Value::as_str) .map(str::to_owned) .or(Some(s.trim().to_owned())) - }), - Flavor::Docker => self - .run(&["version", "--format", "{{.Server.Version}}"]) - .await - .ok() - .map(|s| s.trim().to_owned()), - }; - // The service must be up, not just the CLI installed. - let ready = match self.flavor { - Flavor::Apple => self.run(&["system", "status"]).await.is_ok(), - Flavor::Docker => version.is_some(), + }); + (version, ready, hung) + } + Flavor::Docker => { + let version = self + .run(&["version", "--format", "{{.Server.Version}}"]) + .await; + let hung = timed_out(&version); + let version = version.ok().map(|s| s.trim().to_owned()); + (version.clone(), version.is_some(), hung) + } }; DriverInfo { name: self.flavor_name().into(), available: ready, isolation: isolation.into(), - detail: Some(match (self.flavor, ready) { - (_, true) => "ready".into(), - (Flavor::Apple, false) => { + detail: Some(match (self.flavor, ready, hung) { + (_, true, _) => "ready".into(), + (Flavor::Apple, false, true) => "the `container` service is not answering".into(), + (Flavor::Apple, false, false) => { "the `container` service is not running (run `container system start`)".into() } - (Flavor::Docker, false) => "the docker daemon is not running".into(), + (Flavor::Docker, false, true) => "the docker daemon is not answering".into(), + (Flavor::Docker, false, false) => "the docker daemon is not running".into(), }), version, } @@ -135,25 +150,27 @@ impl ContainerDriver { docker_resources(&out) } - /// `running`, `stopped`, … or `None` when it does not exist. - async fn state(&self, name: &str) -> Option { - match self.flavor { - Flavor::Apple => { - let out = self.run(&["inspect", name]).await.ok()?; - let v: Value = serde_json::from_str(&out).ok()?; + /// `running`, `stopped`, … or `None` when it does not exist. An error + /// only when the runtime doesn't answer. + async fn state(&self, name: &str) -> Result> { + let inspect: &[&str] = match self.flavor { + Flavor::Apple => &["inspect", name], + Flavor::Docker => &["inspect", "--format", "{{.State.Status}}", name], + }; + let out = match self.run(inspect).await { + Ok(out) => out, + Err(e) if e.is::() => return Err(e), + Err(_) => return Ok(None), + }; + Ok(match self.flavor { + Flavor::Apple => serde_json::from_str::(&out).ok().and_then(|v| { v.pointer("/0/status/state") .or_else(|| v.pointer("/0/status")) .and_then(Value::as_str) .map(str::to_owned) - } - Flavor::Docker => { - let out = self - .run(&["inspect", "--format", "{{.State.Status}}", name]) - .await - .ok()?; - Some(out.trim().to_owned()) - } - } + }), + Flavor::Docker => Some(out.trim().to_owned()), + }) } pub async fn ensure( @@ -165,7 +182,7 @@ impl ContainerDriver { name: spec.name.clone(), root: None, }; - match self.state(&spec.name).await.as_deref() { + match self.state(&spec.name).await?.as_deref() { Some("running") => return Ok(sb), Some(_) => { log(format!("Starting the existing sandbox {}", spec.name)); @@ -273,7 +290,7 @@ impl ContainerDriver { } pub async fn stop(&self, sb: &Sandbox) -> Result<()> { - if self.state(&sb.name).await.as_deref() == Some("running") { + if self.state(&sb.name).await?.as_deref() == Some("running") { self.run(&["stop", "-t", "20", &sb.name]).await?; } Ok(()) @@ -284,7 +301,7 @@ impl ContainerDriver { Flavor::Apple => &["delete", "--force", &sb.name], Flavor::Docker => &["rm", "-f", &sb.name], }; - if self.state(&sb.name).await.is_some() { + if self.state(&sb.name).await?.is_some() { self.run(args).await?; } Ok(()) diff --git a/crates/fctl-host/src/driver/lima.rs b/crates/fctl-host/src/driver/lima.rs index 945f2ba6..9e74948a 100644 --- a/crates/fctl-host/src/driver/lima.rs +++ b/crates/fctl-host/src/driver/lima.rs @@ -3,7 +3,8 @@ //! Heavier than containers, but a full VM on any Mac (Intel too) or Linux host. use super::{ - AGENT_PATH, AgentIo, Sandbox, SandboxInfo, SandboxSpec, attach_script, run_cmd, serve_script, + AGENT_PATH, AgentIo, COMMAND_TIMEOUT, SLOW_COMMAND_TIMEOUT, Sandbox, SandboxInfo, SandboxSpec, + attach_script, run_cmd_within, serve_script, }; use anyhow::{Context, Result}; use fctl_proto::runner::DriverInfo; @@ -25,7 +26,12 @@ impl LimaDriver { } async fn run(&self, args: &[&str]) -> Result { - run_cmd(&self.bin, args).await + // Cloning, booting and shutting down a VM take minutes. + let limit = match args.first() { + Some(&("clone" | "start" | "stop")) => SLOW_COMMAND_TIMEOUT, + _ => COMMAND_TIMEOUT, + }; + run_cmd_within(&self.bin, args, limit).await } async fn instances(&self) -> Vec<(String, String)> { diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 5a033f16..807c621d 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -15,8 +15,19 @@ pub mod process; use anyhow::Result; use fctl_proto::runner::{DriverInfo, SandboxSize}; use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; use tokio::io::{AsyncRead, AsyncWrite}; +/// How long a driver command may run before the host kills it. Runtimes +/// answer in seconds; one that takes longer is stuck (an overloaded Docker +/// VM, say), and nothing that waits on it may hang with it. +pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); + +/// How long pulling an image, or cloning, booting or shutting down a VM, +/// may take. +pub const SLOW_COMMAND_TIMEOUT: Duration = Duration::from_secs(30 * 60); + /// What to create. #[derive(Clone, Debug)] pub struct SandboxSpec { @@ -116,13 +127,15 @@ impl Driver { /// Every driver this host could use, for the runner's hello. pub async fn probe_all(data_dir: &Path) -> Vec { - let mut out = vec![ - container::ContainerDriver::apple().probe().await, - container::ContainerDriver::docker().probe().await, - lima::LimaDriver::new().probe().await, - ]; - out.push(process::ProcessDriver::new(data_dir, None).probe().await); - out + let (apple, docker, lima, process) = ( + container::ContainerDriver::apple(), + container::ContainerDriver::docker(), + lima::LimaDriver::new(), + process::ProcessDriver::new(data_dir, None), + ); + let (apple, docker, lima, process) = + tokio::join!(apple.probe(), docker.probe(), lima.probe(), process.probe()); + vec![apple, docker, lima, process] } pub fn name(&self) -> &'static str { @@ -150,14 +163,15 @@ impl Driver { /// the VM of OrbStack, Docker Desktop or Colima), otherwise this /// machine's. Memory is 0 when unknown. pub async fn resources(&self) -> SandboxSize { - if let Self::Container(d) = self - && let Some(size) = d.resources().await - { - return size; - } - SandboxSize { - cpus: crate::sysinfo::cpus(), - memory_mb: u32::try_from(crate::sysinfo::memory_mb()).unwrap_or(u32::MAX), + self.measure().await.unwrap_or_else(machine) + } + + /// [`resources`](Self::resources), or `None` when the Docker daemon + /// doesn't say. + pub async fn measure(&self) -> Option { + match self { + Self::Container(d) if d.flavor_name() == "docker" => d.resources().await, + _ => Some(machine()), } } @@ -284,14 +298,25 @@ impl Driver { } } -/// Runs a host command, capturing output; errors carry stderr. +/// This machine's CPUs and memory. +pub fn machine() -> SandboxSize { + SandboxSize { + cpus: crate::sysinfo::cpus(), + memory_mb: u32::try_from(crate::sysinfo::memory_mb()).unwrap_or(u32::MAX), + } +} + +/// Runs a host command, capturing output; errors carry stderr. One still +/// running after [`COMMAND_TIMEOUT`] is killed. pub async fn run_cmd(program: &str, args: &[&str]) -> Result { - let out = tokio::process::Command::new(program) - .args(args) - .stdin(std::process::Stdio::null()) - .output() - .await - .map_err(|e| spawn_error(program, e))?; + run_cmd_within(program, args, COMMAND_TIMEOUT).await +} + +/// [`run_cmd`] with a time limit of its own. +pub async fn run_cmd_within(program: &str, args: &[&str], limit: Duration) -> Result { + let mut cmd = tokio::process::Command::new(program); + cmd.args(args).stdin(Stdio::null()); + let out = output_within(&mut cmd, program, || command_line(program, args), limit).await?; if !out.status.success() { anyhow::bail!( "{program} {} failed: {}", @@ -302,6 +327,76 @@ pub async fn run_cmd(program: &str, args: &[&str]) -> Result { Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } +/// Runs `cmd` to its end and captures its output. One still running after +/// `limit` is killed, and the host logs which (`what`). +pub async fn output_within( + cmd: &mut tokio::process::Command, + program: &str, + what: impl FnOnce() -> String, + limit: Duration, +) -> Result { + // Dropping the unfinished `output()` kills the process. + let run = cmd.kill_on_drop(true).output(); + match tokio::time::timeout(limit, run).await { + Ok(out) => out.map_err(|e| spawn_error(program, e)), + Err(_) => { + let e = TimedOut { + command: what(), + after: limit, + }; + tracing::warn!("{e}"); + Err(e.into()) + } + } +} + +/// A driver command that ran past its time limit, and was killed. +#[derive(Debug)] +pub struct TimedOut { + pub command: String, + pub after: Duration, +} + +impl std::fmt::Display for TimedOut { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let after = match self.after.as_secs() { + 0 => format!("{} ms", self.after.as_millis()), + s if s >= 120 && s % 60 == 0 => format!("{} minutes", s / 60), + s => format!("{s} seconds"), + }; + write!( + f, + "`{}` did not finish within {after}, so the host stopped it", + self.command + ) + } +} + +impl std::error::Error for TimedOut {} + +/// Whether `r` failed because its command ran out of time. +pub fn timed_out(r: &Result) -> bool { + r.as_ref().is_err_and(|e| e.is::()) +} + +/// A command as the log shows it: arguments with spaces quoted, and long +/// ones (scripts) cut short. +pub(crate) fn command_line(program: &str, args: &[&str]) -> String { + let mut line = program.to_owned(); + for a in args { + line.push(' '); + if a.is_empty() || a.contains(char::is_whitespace) { + line.push_str(&format!("'{a}'")); + } else { + line.push_str(a); + } + } + match line.char_indices().nth(160) { + Some((cut, _)) => format!("{}…", &line[..cut]), + None => line, + } +} + /// Why `program` could not be started, naming a missing program plainly. pub fn spawn_error(program: &str, e: std::io::Error) -> anyhow::Error { if e.kind() == std::io::ErrorKind::NotFound { @@ -327,6 +422,70 @@ mod tests { ); } + #[tokio::test] + async fn a_command_that_hangs_is_killed() -> Result<()> { + let dir = tempfile::tempdir()?; + let pid = dir.path().join("pid"); + let script = format!("echo $$ > '{}'; exec sleep 30", pid.display()); + let started = std::time::Instant::now(); + let r = run_cmd_within("sh", &["-c", &script], Duration::from_millis(500)).await; + assert!(started.elapsed() < Duration::from_secs(5)); + assert!(timed_out(&r)); + let e = r.err().map(|e| e.to_string()).unwrap_or_default(); + assert!( + e.starts_with(&format!("`sh -c 'echo $$ > '{}'", pid.display())), + "{e}" + ); + assert!( + e.ends_with("did not finish within 500 ms, so the host stopped it"), + "{e}" + ); + // Gone, or a zombie until the runtime reaps it. + let pid = std::fs::read_to_string(&pid)?; + let mut stat = String::new(); + for _ in 0..20 { + let ps = std::process::Command::new("ps") + .args(["-o", "stat=", "-p", pid.trim()]) + .output()?; + stat = String::from_utf8_lossy(&ps.stdout).trim().to_owned(); + if stat.is_empty() || stat.starts_with('Z') { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + anyhow::bail!("sleep {} still runs: {stat}", pid.trim()) + } + + #[tokio::test] + async fn quick_commands_keep_their_output_and_errors() { + let ok = run_cmd("sh", &["-c", "echo hi"]).await.ok(); + assert_eq!(ok.as_deref(), Some("hi\n")); + let failed = run_cmd("sh", &["-c", "echo nope >&2; exit 3"]).await; + assert!(!timed_out(&failed)); + let e = failed.err().map(|e| e.to_string()); + assert_eq!(e.as_deref(), Some("sh -c failed: nope")); + } + + #[test] + fn long_commands_are_cut_short_in_the_log() { + assert_eq!( + command_line("docker", &["ps", "--format", "{{.Names}}\t{{.State}}"]), + "docker ps --format '{{.Names}}\t{{.State}}'" + ); + let script = "x".repeat(300); + let line = command_line("sh", &["-c", &script]); + assert_eq!(line.chars().count(), 161); + assert!(line.ends_with('…')); + let e = TimedOut { + command: "docker pull x".into(), + after: SLOW_COMMAND_TIMEOUT, + }; + assert_eq!( + e.to_string(), + "`docker pull x` did not finish within 30 minutes, so the host stopped it" + ); + } + #[test] fn names_roundtrip() { let n = sandbox_name("ses_01M553XWYGXA3FE9YKD72G5Y8T"); diff --git a/crates/fctl-host/src/driver/process.rs b/crates/fctl-host/src/driver/process.rs index 6e95ac4d..3416ae4e 100644 --- a/crates/fctl-host/src/driver/process.rs +++ b/crates/fctl-host/src/driver/process.rs @@ -158,12 +158,12 @@ impl ProcessDriver { pub async fn exec(&self, sb: &Sandbox, script: &str) -> Result { let (home, _) = Self::paths(sb)?; - let out = tokio::process::Command::new("sh") - .args(["-c", script]) + let mut cmd = tokio::process::Command::new("sh"); + cmd.args(["-c", script]) .env("HOME", &home) - .current_dir(&home) - .output() - .await?; + .current_dir(&home); + let what = || super::command_line("sh", &["-c", script]); + let out = super::output_within(&mut cmd, "sh", what, super::COMMAND_TIMEOUT).await?; if !out.status.success() { anyhow::bail!("{}", String::from_utf8_lossy(&out.stderr).trim()); } @@ -189,7 +189,7 @@ impl ProcessDriver { if let Ok(pid) = std::fs::read_to_string(home.join(".fctl/agent.pid")) { let pid = pid.trim(); if !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()) { - let _ = tokio::process::Command::new("kill").arg(pid).status().await; + let _ = super::run_cmd("kill", &[pid]).await; } } Ok(()) diff --git a/crates/fctl-host/src/expiry.rs b/crates/fctl-host/src/expiry.rs index 975be8f5..25063d1b 100644 --- a/crates/fctl-host/src/expiry.rs +++ b/crates/fctl-host/src/expiry.rs @@ -39,6 +39,15 @@ pub fn note_stopped(path: &Path, sandbox: &str, now: i64) -> Result<()> { save(path, &stopped) } +/// Forgets `sandbox`, once it is removed. +pub fn forget(path: &Path, sandbox: &str) -> Result<()> { + let mut stopped = load(path); + if stopped.remove(sandbox).is_some() { + save(path, &stopped)?; + } + Ok(()) +} + /// What to remove now, and what to remember: session sandboxes that are /// stopped and not in use, stopped since the recorded time (or since now). /// `keep_ms` of `None` keeps them all. diff --git a/crates/fctl-host/src/lib.rs b/crates/fctl-host/src/lib.rs index eff3a242..9d07afa3 100644 --- a/crates/fctl-host/src/lib.rs +++ b/crates/fctl-host/src/lib.rs @@ -10,6 +10,7 @@ pub mod driver; pub mod expiry; pub mod files; pub mod image; +pub mod liveness; pub mod login; pub mod service; pub mod session; diff --git a/crates/fctl-host/src/liveness.rs b/crates/fctl-host/src/liveness.rs new file mode 100644 index 00000000..0e9f1de9 --- /dev/null +++ b/crates/fctl-host/src/liveness.rs @@ -0,0 +1,192 @@ +//! Whether a link to fctl-agent is alive, and when to attach again. +//! +//! fctl-agent says hello the moment the host attaches, and answers every +//! ping, so a link that stays quiet is dead: a `docker exec` stuck in an +//! overloaded runtime, or one that never reached the sandbox. The host drops +//! it, which kills the exec, and attaches again, waiting longer after each +//! attempt that fails. A runtime that hangs may come back, so the host keeps +//! trying; one that answers that the agent can't be reached gets two minutes. + +use std::time::{Duration, Instant}; + +/// How long fctl-agent has to say hello after the host attaches. +pub const HELLO_WITHIN: Duration = Duration::from_secs(30); +/// How often the host pings an attached agent. +pub const PING_EVERY: Duration = Duration::from_secs(15); +/// A link that carries nothing for this long is dead. +pub const SILENT_FOR: Duration = Duration::from_secs(60); + +/// The waits between attempts: they double from the first to the longest. +pub const FIRST_WAIT: Duration = Duration::from_secs(1); +pub const LONGEST_WAIT: Duration = Duration::from_secs(30); +/// Attaching that fails outright for this long gives up on the sandbox. +pub const GIVE_UP_AFTER: Duration = Duration::from_secs(120); + +/// One attached link, as the host hears it. +pub struct Health { + opened: Instant, + heard: Option, + pinged: Instant, +} + +/// What to do about a link now. +#[derive(Debug, PartialEq, Eq)] +pub enum Check { + Fine, + Ping, + /// Drop it, for this reason. + Dead(&'static str), +} + +impl Health { + pub fn new(now: Instant) -> Self { + Self { + opened: now, + heard: None, + pinged: now, + } + } + + /// A frame came from the agent. + pub fn heard(&mut self, now: Instant) { + self.heard = Some(now); + } + + /// Whether the agent has spoken on this link. + pub fn answered(&self) -> bool { + self.heard.is_some() + } + + pub fn check(&mut self, now: Instant) -> Check { + match self.heard { + None if now.duration_since(self.opened) >= HELLO_WITHIN => { + return Check::Dead("fctl-agent did not say hello within 30 seconds"); + } + Some(at) if now.duration_since(at) >= SILENT_FOR => { + return Check::Dead("nothing came from fctl-agent for a minute"); + } + _ => {} + } + if now.duration_since(self.pinged) >= PING_EVERY { + self.pinged = now; + return Check::Ping; + } + Check::Fine + } +} + +/// When to attach again after a link failed. +pub struct Retry { + wait: Duration, + /// Since when attaching has failed outright. + failing_since: Option, +} + +impl Default for Retry { + fn default() -> Self { + Self { + wait: FIRST_WAIT, + failing_since: None, + } + } +} + +impl Retry { + /// The agent said hello: the next failure starts over. + pub fn reset(&mut self) { + *self = Self::default(); + } + + /// A link went quiet, or the agent never answered on it. The runtime + /// may only be slow, so this never gives up. + pub fn stalled(&mut self) -> Duration { + self.next_wait() + } + + /// Attaching failed outright: the exec could not start, or ended before + /// the agent said hello. `None` once that has gone on for + /// [`GIVE_UP_AFTER`]. + pub fn failed(&mut self, now: Instant) -> Option { + let since = *self.failing_since.get_or_insert(now); + (now.duration_since(since) < GIVE_UP_AFTER).then(|| self.next_wait()) + } + + fn next_wait(&mut self) -> Duration { + let wait = self.wait; + self.wait = (self.wait * 2).min(LONGEST_WAIT); + wait + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn secs(n: u64) -> Duration { + Duration::from_secs(n) + } + + #[test] + fn an_agent_that_answers_is_pinged_and_kept() { + let t0 = Instant::now(); + let mut h = Health::new(t0); + h.heard(t0 + secs(1)); + assert_eq!(h.check(t0 + secs(14)), Check::Fine); + assert_eq!(h.check(t0 + secs(15)), Check::Ping); + assert_eq!(h.check(t0 + secs(16)), Check::Fine); + // Its pong. + h.heard(t0 + secs(16)); + assert_eq!(h.check(t0 + secs(30)), Check::Ping); + h.heard(t0 + secs(30)); + assert_eq!(h.check(t0 + secs(89)), Check::Ping); + assert!(h.answered()); + } + + #[test] + fn a_link_that_never_answers_or_goes_quiet_is_dead() { + let t0 = Instant::now(); + let mut silent = Health::new(t0); + assert_eq!(silent.check(t0 + secs(15)), Check::Ping); + assert_eq!(silent.check(t0 + secs(29)), Check::Fine); + assert_eq!( + silent.check(t0 + secs(30)), + Check::Dead("fctl-agent did not say hello within 30 seconds") + ); + assert!(!silent.answered()); + + let mut quiet = Health::new(t0); + quiet.heard(t0 + secs(1)); + for t in [15, 30, 45, 60] { + assert_eq!(quiet.check(t0 + secs(t)), Check::Ping, "{t}"); + } + assert_eq!( + quiet.check(t0 + secs(61)), + Check::Dead("nothing came from fctl-agent for a minute") + ); + } + + #[test] + fn stalls_wait_longer_each_time_and_never_give_up() { + let mut r = Retry::default(); + let waits: Vec = (0..8).map(|_| r.stalled().as_secs()).collect(); + assert_eq!(waits, [1, 2, 4, 8, 16, 30, 30, 30]); + r.reset(); + assert_eq!(r.stalled(), secs(1)); + } + + #[test] + fn failing_outright_gives_up_after_two_minutes() { + let t0 = Instant::now(); + let mut r = Retry::default(); + assert_eq!(r.failed(t0), Some(secs(1))); + assert_eq!(r.failed(t0 + secs(5)), Some(secs(2))); + assert_eq!(r.failed(t0 + secs(119)), Some(secs(4))); + assert_eq!(r.failed(t0 + secs(120)), None); + // A hello in between starts over. + let mut r = Retry::default(); + assert_eq!(r.failed(t0), Some(secs(1))); + r.reset(); + assert_eq!(r.failed(t0 + secs(130)), Some(secs(1))); + assert_eq!(r.failed(t0 + secs(200)), Some(secs(2))); + } +} diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index dedd39d8..20329f35 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -2,16 +2,17 @@ //! agent and the session's uplink. use crate::config::HostConfig; -use crate::driver::{Driver, Sandbox, SandboxSpec, sandbox_name}; +use crate::driver::{AgentIo, Driver, Sandbox, SandboxSpec, sandbox_name}; use crate::files; +use crate::liveness::{Check, Health, Retry}; use crate::uplink::Uplink; use anyhow::{Context, Result}; use fctl_domain::size::Want; use fctl_proto::agent::{AgentConfig, AgentToHost, HostToAgent, MAX_FRAME_BYTES}; use fctl_proto::event::{LogLevel, LogLine, LogSource}; use fctl_proto::runner::{ - ClaudeCredential, CredentialKind, GithubCredential, SandboxLimits, SandboxSize, SessionSpec, - StopReason, + ClaudeCredential, CredentialKind, DriverInfo, GithubCredential, SandboxLimits, SandboxSize, + SessionSpec, StopReason, }; use fctl_proto::session::SessionStatus; use fctl_proto::uplink::{Delivery, DeliveryKind, FEATURE_ATTACHMENTS, SessionState, UplinkDown}; @@ -27,11 +28,27 @@ pub struct HostCtx { pub driver: Driver, pub token: String, pub runner_id: Mutex>, - /// What this host gives each sandbox, as of the last hello. + /// What this host gives each sandbox, as last measured. pub sandbox: Mutex, + /// The drivers this host could use, as last probed. + pub drivers: Mutex>, } impl HostCtx { + /// Before [`refresh_facts`](Self::refresh_facts): sandboxes sized by + /// this machine, and no drivers probed. + pub fn new(cfg: HostConfig, driver: Driver, token: String) -> Self { + let sandbox = cfg.sandbox_limits(crate::driver::machine()); + Self { + cfg, + driver, + token, + runner_id: Mutex::new(None), + sandbox: Mutex::new(sandbox), + drivers: Mutex::new(Vec::new()), + } + } + pub fn runner_id(&self) -> RunnerId { self.runner_id .lock() @@ -44,12 +61,25 @@ impl HostCtx { *self.sandbox.lock().unwrap_or_else(PoisonError::into_inner) } - /// Measures what the sandboxes run on again (the Docker VM may have - /// been resized) and returns the limits that follow. - pub async fn refresh_sandbox_limits(&self) -> SandboxLimits { - let limits = self.cfg.sandbox_limits(self.driver.resources().await); - *self.sandbox.lock().unwrap_or_else(PoisonError::into_inner) = limits; - limits + pub fn drivers(&self) -> Vec { + self.drivers + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Probes the drivers and measures what sandboxes run on again (Docker's + /// VM may have been resized). The runner's hello reports what this + /// found last, so the control connection never waits on a runtime; a + /// Docker daemon that doesn't answer leaves the limits as they were. + pub async fn refresh_facts(&self) { + let data_dir = self.cfg.data_dir(); + let (drivers, size) = tokio::join!(Driver::probe_all(&data_dir), self.driver.measure()); + *self.drivers.lock().unwrap_or_else(PoisonError::into_inner) = drivers; + if let Some(size) = size { + *self.sandbox.lock().unwrap_or_else(PoisonError::into_inner) = + self.cfg.sandbox_limits(size); + } } /// The CPUs and memory a session's sandbox gets on this host. @@ -140,19 +170,44 @@ pub fn spawn( SessionHandle { tx, report } } -/// A framed connection to fctl-agent. +/// A framed connection to fctl-agent. Dropping it kills the exec that +/// carries it. struct AgentLink { tx: mpsc::UnboundedSender, rx: mpsc::UnboundedReceiver, + health: Health, + tasks: Vec>, _child: Option, } +impl Drop for AgentLink { + fn drop(&mut self) { + for t in &self.tasks { + t.abort(); + } + } +} + impl AgentLink { - fn open(io: crate::driver::AgentIo) -> Self { + fn open(io: AgentIo, sandbox: &str) -> Self { let (tx, mut out_rx) = mpsc::unbounded_channel::(); let (in_tx, rx) = mpsc::unbounded_channel::(); + let mut tasks = Vec::new(); + let mut child = io.child; + // Why an exec failed: the runtime's errors, or fctl-agent's. + if let Some(stderr) = child.as_mut().and_then(|c| c.stderr.take()) { + let sandbox = sandbox.to_owned(); + tasks.push(tokio::spawn(async move { + let mut lines = BufReader::new(stderr).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if !line.trim().is_empty() { + tracing::warn!("attaching to {sandbox}: {}", line.trim()); + } + } + })); + } let mut writer = io.writer; - tokio::spawn(async move { + tasks.push(tokio::spawn(async move { while let Some(msg) = out_rx.recv().await { let Ok(mut line) = serde_json::to_string(&msg) else { continue; @@ -163,9 +218,9 @@ impl AgentLink { break; } } - }); + })); let reader = io.reader; - tokio::spawn(async move { + tasks.push(tokio::spawn(async move { let mut reader = BufReader::with_capacity(256 * 1024, reader); let mut line = String::new(); loop { @@ -187,11 +242,13 @@ impl AgentLink { Err(e) => tracing::warn!("malformed frame from fctl-agent: {e}"), } } - }); + })); Self { tx, rx, - _child: io.child, + health: Health::new(Instant::now()), + tasks, + _child: child, } } @@ -233,6 +290,37 @@ fn route( } } +/// Sends the deliveries the agent hasn't confirmed over a new link, but +/// not those already waiting for one. +fn resend( + unconfirmed: &[Delivery], + jobs: &mpsc::UnboundedSender, + link: &AgentLink, + queued: &mut Vec, +) { + let waiting = |d: &Delivery| { + queued + .iter() + .any(|f| matches!(f, HostToAgent::Deliver { delivery } if delivery.id == d.id)) + }; + let again: Vec = unconfirmed + .iter() + .filter(|d| !waiting(d)) + .cloned() + .collect(); + for d in again { + route(d, jobs, Some(link), queued); + } +} + +/// Keeps `delivery` until the agent confirms it (the latest copy of each). +fn remember(unconfirmed: &mut Vec, delivery: &Delivery) { + match unconfirmed.iter_mut().find(|d| d.id == delivery.id) { + Some(d) => *d = delivery.clone(), + None => unconfirmed.push(delivery.clone()), + } +} + /// Sends a frame to the agent. An agent older than attachments gets its /// messages without their files, and the transcript says so. fn to_agent(l: &AgentLink, frame: HostToAgent, agent_files: bool, uplink: &Uplink) { @@ -324,15 +412,44 @@ async fn run( SessionStatus::Provisioning, &format!("Creating the sandbox on {}", ctx.cfg.name), )); - match prepare(&ctx, spec, &uplink).await { - Ok(sb) => sb, - Err(e) => { + // A stop calls off the preparation: a runtime that hangs may + // keep it waiting until its commands time out. + let preparing = prepare(&ctx, spec, &uplink); + tokio::pin!(preparing); + let mut listening = true; + let prepared = loop { + tokio::select! { + r = &mut preparing => break Ok(r), + c = cmds.recv(), if listening => match c { + Some(SessionCmd::Stop { destroy, .. }) => break Err(destroy), + // Nothing else is for an agent that isn't there yet. + Some(_) => {} + None => listening = false, + }, + } + }; + match prepared { + Ok(Ok(sb)) => sb, + Ok(Err(e)) => { let msg = format!("{e:#}"); host_log(&uplink, LogLevel::Error, msg.clone()); uplink.state(state(SessionStatus::Failed, &msg)); tokio::time::sleep(Duration::from_secs(2)).await; return (SessionStatus::Failed, Some(msg)); } + Err(destroy) => { + let sb = ctx.driver.handle(&sandbox_name(session_id.as_str())); + if let Err(e) = ctx.driver.stop(&sb).await { + tracing::warn!("stopping {}: {e:#}", sb.name); + } + if destroy && let Err(e) = ctx.driver.remove(&sb).await { + tracing::warn!("removing {}: {e:#}", sb.name); + } + let msg = "Stopped before it started".to_owned(); + uplink.state(state(SessionStatus::Stopped, &msg)); + tokio::time::sleep(Duration::from_millis(500)).await; + return (SessionStatus::Stopped, Some(msg)); + } } } None => { @@ -353,50 +470,90 @@ async fn run( let mut agent_files = false; let mut exited: Option<(SessionStatus, Option)> = None; let mut stop: Option<(bool, Instant)> = None; - let mut attach_failures = 0u32; let mut superseded = false; // A fresh agent for a resumed session numbers its events after the ones // the control plane has, so it waits for the uplink's Welcome. let mut configure_when_welcomed = false; let mut tick = tokio::time::interval(Duration::from_secs(1)); + // Attaching runs in a task of its own, so that a runtime that hangs + // doesn't hold up the session; after a failure it waits, and starts + // fctl-agent again first in case it is gone (harmless when it isn't). + let mut attaching: Option>> = None; + let mut attach_at = Some(Instant::now()); + let mut restart_agent = false; + let mut retry = Retry::default(); + // Deliveries the agent hasn't confirmed. Frames sent over a link that + // died may have died with it, so a new link gets these again (the agent + // ignores the ones it has). + let mut unconfirmed: Vec = Vec::new(); + let mut said_hello = false; + let gave_up = || { + let msg = "fctl-agent stopped responding in the sandbox".to_owned(); + uplink.state(state(SessionStatus::Failed, &msg)); + (SessionStatus::Failed, Some(msg)) + }; let outcome = loop { - if link.is_none() && exited.is_none() { - match ctx.driver.attach(&sb).await { - Ok(io) => { - attach_failures = 0; - link = Some(AgentLink::open(io)); + if link.is_none() + && attaching.is_none() + && exited.is_none() + && attach_at.is_some_and(|at| Instant::now() >= at) + { + attach_at = None; + let (ctx, sb) = (ctx.clone(), sb.clone()); + let restart = std::mem::take(&mut restart_agent); + attaching = Some(tokio::spawn(async move { + if restart && let Err(e) = ctx.driver.start_agent(&sb).await { + tracing::warn!("starting fctl-agent in {}: {e:#}", sb.name); } - Err(e) => { - attach_failures += 1; - tracing::warn!("attaching to {}: {e:#}", sb.name); - if attach_failures >= 5 { - let msg = "fctl-agent stopped responding in the sandbox".to_owned(); - uplink.state(state(SessionStatus::Failed, &msg)); - break (SessionStatus::Failed, Some(msg)); + ctx.driver.attach(&sb).await + })); + } + tokio::select! { + r = async { match attaching.as_mut() { Some(a) => a.await, None => std::future::pending().await } } => { + attaching = None; + match r.map_err(anyhow::Error::from).and_then(|r| r) { + Ok(io) => link = Some(AgentLink::open(io, &sb.name)), + Err(e) => { + tracing::warn!("attaching to {}: {e:#}", sb.name); + let Some(wait) = retry.failed(Instant::now()) else { break gave_up() }; + attach_at = Some(Instant::now() + wait); + restart_agent = true; } - let _ = ctx.driver.start_agent(&sb).await; - tokio::time::sleep(Duration::from_secs(2)).await; - continue; } } - } - tokio::select! { msg = async { match link.as_mut() { Some(l) => l.rx.recv().await, None => std::future::pending().await } } => { let Some(msg) = msg else { - link = None; + let answered = link.take().is_some_and(|l| l.health.answered()); if let Some(done) = exited.clone() { break done; } if stop.is_some() { break (SessionStatus::Stopped, Some("Stopped".into())); } - tokio::time::sleep(Duration::from_millis(500)).await; + if answered { + tracing::info!("the link to fctl-agent in {} closed; attaching again", sb.name); + attach_at = Some(Instant::now() + Duration::from_millis(500)); + } else { + tracing::warn!("attaching to {}: the link closed before fctl-agent said hello", sb.name); + let Some(wait) = retry.failed(Instant::now()) else { break gave_up() }; + attach_at = Some(Instant::now() + wait); + restart_agent = true; + } continue; }; - let Some(l) = link.as_ref() else { continue }; + let Some(l) = link.as_mut() else { continue }; + l.health.heard(Instant::now()); + let l = &*l; match msg { AgentToHost::Hello(h) => { + retry.reset(); + tracing::info!( + "attached to fctl-agent {} in {} (journal at agent_seq {})", + h.version, + sb.name, + h.agent_seq + ); set_report(h.status, Some(h.agent_seq)); agent_files = h.features.iter().any(|f| f == FEATURE_ATTACHMENTS); if !h.configured { @@ -414,10 +571,14 @@ async fn run( } if welcomed { l.send(HostToAgent::Replay { after_agent_seq: acked }); + if said_hello { + resend(&unconfirmed, &jobs, l, &mut queued); + } for frame in queued.drain(..) { to_agent(l, frame, agent_files, &uplink); } } + said_hello = true; } AgentToHost::Events { events: evs } => { set_report(report.lock().map(|r| r.status).unwrap_or(SessionStatus::Running), evs.last().map(|e| e.agent_seq)); @@ -430,6 +591,7 @@ async fn run( } AgentToHost::Log { line } => uplink.log(line), AgentToHost::Delivered { delivery_id, ok, error } => { + unconfirmed.retain(|d| d.id != delivery_id); uplink.send(fctl_proto::uplink::UplinkUp::Delivered { delivery_id, ok, error }); } AgentToHost::CredentialRequest { request_id, kind } => { @@ -458,6 +620,7 @@ async fn run( l.send(HostToAgent::Replay { after_agent_seq: acked }); } for p in pending { + remember(&mut unconfirmed, &p); route(p, &jobs, link.as_ref(), &mut queued); } } @@ -467,7 +630,10 @@ async fn run( l.send(HostToAgent::Ack { agent_seq }); } } - UplinkDown::Deliver { delivery } => route(delivery, &jobs, link.as_ref(), &mut queued), + UplinkDown::Deliver { delivery } => { + remember(&mut unconfirmed, &delivery); + route(delivery, &jobs, link.as_ref(), &mut queued); + } UplinkDown::Pong => {} } } @@ -495,10 +661,13 @@ async fn run( c = cmds.recv() => match c { Some(SessionCmd::Stop { reason, destroy }) => { if stop.is_none() { + // Without a link, the agent gets it once the host + // attaches again, or its sandbox stops at the deadline. stop = Some((destroy, Instant::now() + Duration::from_secs(60))); + let frame = HostToAgent::Stop { reason, grace_ms: 30_000 }; match &link { - Some(l) => l.send(HostToAgent::Stop { reason, grace_ms: 30_000 }), - None => break (SessionStatus::Stopped, Some("Stopped".into())), + Some(l) => l.send(frame), + None => queued.push(frame), } } } @@ -519,9 +688,30 @@ async fn run( && let Some(done) = exited.clone() { break done; } + // A link that goes quiet is replaced. + if let Some(l) = link.as_mut() { + match l.health.check(Instant::now()) { + Check::Fine => {} + Check::Ping => l.send(HostToAgent::Ping), + Check::Dead(why) => { + let wait = retry.stalled(); + tracing::warn!( + "{}: {why}; attaching again in {} s", + sb.name, + wait.as_secs() + ); + link = None; + attach_at = Some(Instant::now() + wait); + restart_agent = true; + } + } + } } } }; + if let Some(a) = attaching.take() { + a.abort(); + } // Give the uplink a moment to deliver the agent's last events. tokio::time::sleep(Duration::from_millis(1500)).await; diff --git a/docs/architecture.md b/docs/architecture.md index 8cc2c26d..bfda2b61 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -205,7 +205,9 @@ imports so it loads in every repository - Host status (`provisioning`, `preparing`) is sent as idempotent state, not as sequenced events. - Deliveries (messages, interrupts, stops) wait in SessionDO's outbox until - the agent confirms them; the agent remembers delivered ids. + the agent confirms them; the agent remembers delivered ids. The host keeps + them too, and sends the unconfirmed ones again over a new link to the + agent. ### Viewers @@ -301,7 +303,22 @@ process driver limits nothing. fctl-agent runs detached inside the sandbox and listens on a unix socket; the host talks to it through `fctl-agent attach` over the driver's exec channel. -Restarting or upgrading the host does not stop agents. A second socket beside +Restarting or upgrading the host does not stop agents. The host pings the +agent every 15 seconds and replaces a link that carries nothing for a +minute, or gets no hello within 30 seconds of attaching: it kills the exec, +starts fctl-agent again if it is gone, and attaches again, waiting longer +after each failure (`crates/fctl-host/src/liveness.rs`). + +Driver commands that hang, as they do in an overloaded Docker VM, are +killed after a minute (image pulls and VM boots after 30), and the control +connection never waits on one: the hello reports what the drivers said +when the host last probed them (at start and every five minutes), and +sweeps and cleanups of sandboxes run in tasks of their own, so heartbeats +keep flowing. A host that starts while its driver doesn't answer waits to +connect until it can list its sandboxes, rather than report sessions as +gone that may still run. + +A second socket beside it, the session socket (`FCTL_SESSION_SOCKET` in Claude's environment), serves programs in the sandbox: `fctl edit` names and describes the session there, with no fctl credentials in the sandbox. diff --git a/docs/cli.md b/docs/cli.md index b594e246..ab67a2ef 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -151,8 +151,9 @@ session 32 GiB of memory (the most is 15.6 GiB)"). Without `max_cpus` and Docker daemon's: on macOS that is the VM of OrbStack, Docker Desktop or Colima, which is usually smaller than the Mac. A default above the maximum is lowered to it. `fctl host status` shows the sizes the host gives. The -host measures them when it starts and when it reconnects, so run `fctl host -restart` after changing `host.toml` or resizing the Docker VM. +host measures them when it starts and every five minutes, and the control +plane learns them when the host connects, so run `fctl host restart` after +changing `host.toml` or resizing the Docker VM. Agents are told their sandbox's size in their instructions and in `FCTL_SANDBOX_CPUS` and `FCTL_SANDBOX_MEMORY_MB`: with Docker, `nproc` and