From 61fc830f9a018347960f3eff2656524e33a1032f Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 12:35:43 +0200 Subject: [PATCH 1/3] fix(ports): on Windows a port another process holds on 0.0.0.0 is in use On Windows a bind on 127.0.0.1 succeeds while a process of the same user listens on 0.0.0.0 (a dev server started with `--host 0.0.0.0`, Docker Desktop's published ports), so `port_in_use` took such a port to be free: the start checks, the port ranges of lanes, the forwarded ports of lanes on nodes and `devstack doctor`. - `devstack_proc::tcp_listening(port)` reads the system's tables of TCP listeners (`GetExtendedTcpTable`, IPv4 and IPv6) and says whether one listens on the port on the wildcard address or on loopback. About 0.3 ms per call for both tables (debug build), so range scans stay cheap. Nothing listens on the wildcard to ask (no firewall prompt), and there is no connect probe (seconds per closed loopback port). - `port_in_use` asks it on Windows after the binds; Linux and macOS are unchanged. - `a_port_held_on_every_address_is_in_use` runs on Windows too. Closes #226 Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 1 + crates/devstack-daemon/src/supervisor/mod.rs | 12 +-- crates/devstack-proc/src/lib.rs | 11 +++ crates/devstack-proc/src/posix.rs | 6 ++ crates/devstack-proc/src/windows.rs | 95 ++++++++++++++++++++ 5 files changed, 119 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d703e949..c6dabe2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,7 @@ windows = { version = "0.62", features = ["Data_Xml_Dom", "Foundation", "UI_Noti zbus = { version = "6", default-features = false, features = ["tokio", "proxy"] } windows-sys = { version = "0.61", features = [ "Win32_Foundation", + "Win32_NetworkManagement_IpHelper", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_ProcessStatus", diff --git a/crates/devstack-daemon/src/supervisor/mod.rs b/crates/devstack-daemon/src/supervisor/mod.rs index d57e1971..cee58dcd 100644 --- a/crates/devstack-daemon/src/supervisor/mod.rs +++ b/crates/devstack-daemon/src/supervisor/mod.rs @@ -1030,6 +1030,8 @@ fn topo(deps: BTreeMap>) -> Vec { /// Taken on IPv4 or IPv6 loopback. A dev server bound to `localhost` may hold /// only `::1` (Node on Windows); binding `127.0.0.1` would still succeed. A host /// without IPv6 fails the `::1` bind with another error, which is not "in use". +/// A port held on every address (`0.0.0.0`) is told on Windows by the table +/// of listeners, on macOS by a connect (#226). pub fn port_in_use(port: u16) -> bool { // Windows reports a port held exclusively by another process as access denied. let taken = |r: std::io::Result| { @@ -1042,6 +1044,7 @@ pub fn port_in_use(port: u16) -> bool { }; taken(std::net::TcpListener::bind(("127.0.0.1", port))) || taken(std::net::TcpListener::bind(("::1", port))) + || (cfg!(windows) && devstack_proc::tcp_listening(port)) || (cfg!(target_os = "macos") && answers_locally(port)) } @@ -1233,14 +1236,11 @@ mod port_tests { assert!(!super::port_in_use(port)); } - // Not on Windows: there a bind on 127.0.0.1 succeeds too while the same - // user listens on 0.0.0.0, and a connect probe would take seconds per - // closed port; not covered yet. - #[cfg(not(windows))] #[test] fn a_port_held_on_every_address_is_in_use() { - // Docker's published ports, a dev server on 0.0.0.0. With BSD sockets - // (macOS) a bind on 127.0.0.1 still succeeds; the connect tells. + // Docker's published ports, a dev server on 0.0.0.0. On Windows and + // with BSD sockets (macOS) a bind on 127.0.0.1 still succeeds; the + // table of listeners tells (Windows), or a connect (macOS). let l = std::net::TcpListener::bind(("0.0.0.0", 0)).unwrap(); let port = l.local_addr().unwrap().port(); assert!(super::port_in_use(port)); diff --git a/crates/devstack-proc/src/lib.rs b/crates/devstack-proc/src/lib.rs index 1207f299..e947e763 100644 --- a/crates/devstack-proc/src/lib.rs +++ b/crates/devstack-proc/src/lib.rs @@ -274,6 +274,17 @@ pub fn raise_open_files() -> Option { backend::raise_open_files() } +/// Windows: does a process listen on TCP `port` on the wildcard address +/// (`0.0.0.0`, `::`) or on loopback? Read from the system's table of +/// listeners. There a bind on `127.0.0.1` succeeds while a process of the +/// same user listens on `0.0.0.0`, and a connect to a closed loopback port +/// takes seconds of retries, so neither tells. `false` elsewhere, where a +/// bind tells (Linux) or a connect (macOS), and when the table cannot be +/// read. +pub fn tcp_listening(port: u16) -> bool { + backend::tcp_listening(port) +} + /// Windows: the long form of a path (`C:\Users\RUNNER~1` becomes /// `C:\Users\runneradmin`). Compilers report long paths; a repository known /// by its 8.3 name would not be recognised in their messages. Unlike diff --git a/crates/devstack-proc/src/posix.rs b/crates/devstack-proc/src/posix.rs index 36ae3fd6..bfe3440d 100644 --- a/crates/devstack-proc/src/posix.rs +++ b/crates/devstack-proc/src/posix.rs @@ -377,6 +377,12 @@ pub(crate) fn disk_free(path: &Path) -> Option { ok.then(|| s.f_bavail as u64 * s.f_frsize as u64) } +/// A bind on loopback tells on Linux; macOS asks with a connect. The +/// daemon's `port_in_use` does both. +pub(crate) fn tcp_listening(_port: u16) -> bool { + false +} + pub(crate) fn raise_open_files() -> Option { let mut l: libc::rlimit = unsafe { std::mem::zeroed() }; // SAFETY: `l` is an rlimit to fill. diff --git a/crates/devstack-proc/src/windows.rs b/crates/devstack-proc/src/windows.rs index 53b3976a..650dfb27 100644 --- a/crates/devstack-proc/src/windows.rs +++ b/crates/devstack-proc/src/windows.rs @@ -516,6 +516,81 @@ pub(crate) fn raise_open_files() -> Option { None } +/// A listener on `port` in the TCP tables (IPv4, then IPv6) whose address is +/// the wildcard or loopback. A listener on another address of the machine +/// (`192.168.1.5`) does not hold the port for a service on loopback. +pub(crate) fn tcp_listening(port: u16) -> bool { + use windows_sys::Win32::NetworkManagement::IpHelper::{ + MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID, + }; + // `AF_INET`, `AF_INET6` (WinSock). + const AF_INET: u32 = 2; + const AF_INET6: u32 = 23; + // Ports are in network byte order in the low 16 bits. + let port_of = |p: u32| u16::from_be(p as u16); + let listen = MIB_TCP_STATE_LISTEN as u32; + let v4 = listeners::(AF_INET).is_some_and(|rows| { + rows.iter().any(|r| { + // The address in network byte order: its bytes as they are. + let a = r.dwLocalAddr.to_ne_bytes(); + r.dwState == listen && port_of(r.dwLocalPort) == port && (a == [0; 4] || a[0] == 127) + }) + }); + v4 || listeners::(AF_INET6).is_some_and(|rows| { + rows.iter().any(|r| { + let a = std::net::Ipv6Addr::from(r.ucLocalAddr); + r.dwState == listen + && port_of(r.dwLocalPort) == port + && (a.is_unspecified() + || a.is_loopback() + || a.to_ipv4_mapped().is_some_and(|v| v.is_loopback())) + }) + }) +} + +/// The rows of `GetExtendedTcpTable(TCP_TABLE_OWNER_PID_LISTENER)` for one +/// address family; `Row` is that family's `MIB_TCP*ROW_OWNER_PID`. The table +/// is a row count followed by the rows; it is read into `u32`s, which aligns +/// both row types. +fn listeners(family: u32) -> Option> { + use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, NO_ERROR}; + use windows_sys::Win32::NetworkManagement::IpHelper::{ + GetExtendedTcpTable, TCP_TABLE_OWNER_PID_LISTENER, + }; + let mut size: u32 = 0; + let mut buf: Vec = Vec::new(); + // The table can grow between asking its size and reading it. + for _ in 0..4 { + // SAFETY: `buf` holds at least `size` bytes, as the call is told. + let r = unsafe { + GetExtendedTcpTable( + buf.as_mut_ptr().cast(), + &mut size, + 0, + family, + TCP_TABLE_OWNER_PID_LISTENER, + 0, + ) + }; + match r { + NO_ERROR => { + let n = *buf.first()? as usize; + let bytes = buf.len() * 4; + if 4 + n * mem::size_of::() > bytes || mem::align_of::() > 4 { + return None; + } + // SAFETY: `n` rows of `Row` follow the count, within `buf` + // (checked above), at an offset aligned for `Row`. + let rows = unsafe { std::slice::from_raw_parts(buf.as_ptr().add(1).cast(), n) }; + return Some(rows.to_vec()); + } + ERROR_INSUFFICIENT_BUFFER => buf = vec![0; (size as usize).div_ceil(4) + 1], + _ => return None, + } + } + None +} + fn memory_status() -> Option { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { mem::zeroed() }; @@ -606,4 +681,24 @@ mod tests { back.display() ); } + + #[test] + fn a_listener_on_the_wildcard_or_loopback_is_in_the_table() { + use std::net::TcpListener; + for addr in ["0.0.0.0", "127.0.0.1", "::", "::1"] { + let Ok(l) = TcpListener::bind((addr, 0)) else { + continue; // no IPv6 on this host + }; + let port = l.local_addr().unwrap().port(); + assert!(super::tcp_listening(port), "{addr}:{port}"); + drop(l); + assert!(!super::tcp_listening(port), "{addr}:{port} after close"); + } + // Cheap enough for a scan of a range of ports. + let t0 = std::time::Instant::now(); + for p in 0..100 { + super::tcp_listening(40000 + p); + } + eprintln!("100 reads of the table: {:?}", t0.elapsed()); + } } From 7cb659a30b54ed28cdf10e26a42bf1b17fda82d8 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 12:41:08 +0200 Subject: [PATCH 2/3] fix(pool): the hub does not report over a node agent of the same member On a machine where the hub and `devstack node agent` run for the same pool, both reported as the same member every 15 s, and the coordinator keeps only the last report. The hub's carries no API and no leases: after each, placement took the machine for one without an agent, and its leases were dropped, to come back with the agent's next report with a new `created`, a new token and without their sharing (ADR-0035). - The node agent holds `node/lock` in its membership's folder while it runs (`StateLock`); it waits a few seconds for one held by the agent it replaces, and refuses a second agent of the same member. - The hub's share loop does not report for a pool while that lock is held; the agent reports the machine then, total and GPUs included. `GET /hub/pool/share` says so (`agent`). - `StateLock::held` asks with a shared lock for a moment and creates nothing. - A test with a coordinator, the hub's round and an agent of the same member: across the hub's rounds the node keeps its API and a running, shared lease its `created` and its sharing; once the agent stops, the hub reports again. Closes #170 Co-Authored-By: Claude Opus 5.5 --- crates/devstack-hub/src/share.rs | 244 +++++++++++++++++++++++++++++-- crates/devstack-node/src/node.rs | 34 +++++ crates/devstack-proc/src/lock.rs | 14 ++ docs/dashboard-api.md | 2 +- docs/pool.md | 6 +- ui/src/api/types.ts | 2 + 6 files changed, 284 insertions(+), 18 deletions(-) diff --git a/crates/devstack-hub/src/share.rs b/crates/devstack-hub/src/share.rs index bf3e1a11..dc175b12 100644 --- a/crates/devstack-hub/src/share.rs +++ b/crates/devstack-hub/src/share.rs @@ -1,7 +1,10 @@ //! This machine in the pool (ADR-0031): the hub measures what the machine has //! and what is free and reports it to the coordinator every 15 s, which also //! tells the pool the machine is online and which devstack it runs. A machine -//! in no pool, or not approved yet, reports nothing. +//! in no pool, or not approved yet, reports nothing. Nor does the hub for a +//! pool while a node agent of the same membership runs here: the agent +//! reports the machine then, with its API and its leases, which a report of +//! the hub's would drop (#170). //! //! The hub offers nothing to the pool. A machine runs other members' lanes //! with a node agent (`devstack node agent`, granted by an admin), and the @@ -44,6 +47,9 @@ pub struct Status { pub reported_at: Option, /// Why the last report failed. pub error: Option, + /// A node agent of this membership runs here and reports the machine; + /// the hub does not (#170). + pub agent: bool, /// The devstack the coordinator runs, from its answer to the last /// report; `None` before one, or from an older coordinator. #[serde(skip_serializing_if = "Option::is_none")] @@ -131,19 +137,26 @@ fn run() { let Some(status) = STATUS.get() else { return }; let gpus = devstack_node::share::gpus(); for (pool, _) in devstack_node::member::pools(&state()) { - let result = report(&pool, total, &gpus); + let result = round(&dir(&pool), total, &gpus); let mut map = status.lock().unwrap(); let st = entry(&mut map, &pool); st.total = total; st.free = free; + st.agent = matches!(result, Ok(Round::Agent)); match result { - Ok(answer) => { - st.member = answer.is_some(); + Ok(Round::NoMember) => { + st.member = false; st.error = None; - if let Some(coordinator) = answer { - st.reported_at = Some(now_ms()); - st.coordinator = coordinator; - } + } + Ok(Round::Agent) => { + st.member = true; + st.error = None; + } + Ok(Round::Reported(coordinator)) => { + st.member = true; + st.error = None; + st.reported_at = Some(now_ms()); + st.coordinator = coordinator; } Err(e) => st.error = Some(e), } @@ -171,19 +184,36 @@ fn guests(pool: &str) -> Option> { Some(crate::guests::of(pool, &m.id, &leases, &nodes)) } -/// Report to the coordinator, offering nothing: what it says it runs; -/// `Ok(None)` when this machine is no approved member (nothing to report to). -fn report( - pool: &str, +/// What one round did for a pool. +#[derive(Debug, PartialEq)] +enum Round { + /// This machine is no approved member: nothing to report to. + NoMember, + /// A node agent of the membership runs here and reports (#170). + Agent, + /// Reported; what the coordinator says it runs. + Reported(Option), +} + +/// Report the membership in `dir` to the coordinator, offering nothing, +/// unless a node agent of it runs here. Its report carries no API and no +/// leases: sent while the agent runs, the coordinator would take the node +/// for one without an agent and drop its leases until the agent's next +/// report, which brings them back new, without their sharing. +fn round( + dir: &std::path::Path, total: Amount, gpus: &[devstack_node::share::Gpu], -) -> Result>, String> { - let local = devstack_node::member::Local::new(&dir(pool)); +) -> Result { + let local = devstack_node::member::Local::new(dir); match local.membership() { Ok(Some(m)) if m.state == State::Approved => {} - Ok(_) => return Ok(None), + Ok(_) => return Ok(Round::NoMember), Err(e) => return Err(e.to_string()), } + if devstack_node::node::agent_runs(dir) { + return Ok(Round::Agent); + } local .report(&Report { sharing: false, @@ -210,7 +240,7 @@ fn report( }) .collect(), }) - .map(|a| Some(a.coordinator)) + .map(|a| Round::Reported(a.coordinator)) .map_err(|e| e.to_string()) } @@ -241,3 +271,185 @@ pub async fn get(Query(q): Query) -> Response { .into_response(), } } + +#[cfg(test)] +mod tests { + use super::{Round, round}; + use devstack_node::coordinator::{self, LeaseRequest, SharedService, Sharing}; + use devstack_node::member::Local; + use devstack_node::node::{self, NodeConfig}; + use devstack_node::nodeclient::NodeClient; + use devstack_node::share::{Amount, Need, Settings}; + use devstack_node::store::{SHELL, Store}; + use std::path::Path; + use std::time::{Duration, Instant}; + + fn rt() -> tokio::runtime::Runtime { + tokio::runtime::Runtime::new().unwrap() + } + + fn wait_for(secs: u64, what: &str, mut f: impl FnMut() -> bool) { + let until = Instant::now() + Duration::from_secs(secs); + while !f() { + assert!(Instant::now() < until, "{what}"); + std::thread::sleep(Duration::from_millis(200)); + } + } + + /// A machine in `dir` that joined and was approved. + fn member(coord: &Path, url: &str, fp: &str, dir: &Path, name: &str) -> Local { + let l = Local::new(dir); + let m = l.join(url, fp, name).unwrap(); + Store::new(coord) + .approve(&m.id, &coordinator::ca(coord).unwrap(), None, SHELL) + .unwrap(); + l.refresh().unwrap(); + l + } + + /// A machine that runs the hub and a node agent of the same membership + /// (#170): while the agent runs, the hub does not report, so the node + /// keeps its API, and a running lease its `created` and its sharing, + /// across the hub's rounds. Once the agent is gone, the hub reports. + #[test] + fn the_hub_does_not_report_over_a_node_agent_of_the_same_member() { + let c = tempfile::tempdir().unwrap(); + let fp = coordinator::init(c.path(), &["127.0.0.1".into()]).unwrap(); + let rt_coord = rt(); + let listener = rt_coord + .block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0))) + .unwrap(); + let url = format!( + "https://127.0.0.1:{}", + listener.local_addr().unwrap().port() + ); + let cdir = c.path().to_path_buf(); + std::thread::spawn(move || { + rt_coord + .block_on(coordinator::serve(&cdir, listener, std::future::pending())) + .unwrap(); + }); + let (md, rd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let machine = member(c.path(), &url, &fp, md.path(), "dev-box"); + let requester = member(c.path(), &url, &fp, rd.path(), "laptop"); + let id = machine.membership().unwrap().unwrap().id; + Store::new(c.path()).set_node(&id, true, SHELL).unwrap(); + let total = Amount { + cpus: 8.0, + memory: 16 << 30, + }; + + // No agent yet: the hub reports the machine. + assert!(matches!( + round(md.path(), total, &[]), + Ok(Round::Reported(_)) + )); + + // The agent of the same membership, until `stop`. + let rt_node = rt(); + let listener = rt_node + .block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0))) + .unwrap(); + let api = format!( + "https://127.0.0.1:{}", + listener.local_addr().unwrap().port() + ); + let config = NodeConfig { + on_update: None, + dir: md.path().to_path_buf(), + api: api.clone(), + share: Settings { + enabled: true, + max_cpus: Some(4.0), + max_memory: Some(4 << 30), + }, + dedicated: false, + }; + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let agent = std::thread::spawn(move || { + rt_node + .block_on(node::serve(config, listener, async { + let _ = stopped.await; + })) + .unwrap(); + }); + let node_api = || { + requester + .nodes() + .unwrap() + .into_iter() + .find(|n| n.id == id) + .and_then(|n| n.report.and_then(|r| r.api)) + }; + wait_for(20, "the agent reports its API", || { + node_api().as_deref() == Some(api.as_str()) + }); + + // A running lease on it, shared. + let offer = requester + .lease(&LeaseRequest { + node: "dev-box".into(), + repo: "shop".into(), + lane: "fix".into(), + need: Need { + cpus: 0.1, + memory: 64 << 20, + ..Need::default() + }, + need_from: None, + floor: None, + profile: None, + devstack: None, + }) + .unwrap(); + let rt = rt(); + let client = NodeClient::new(&requester, offer.node.clone()).unwrap(); + rt.block_on(client.admit(&offer)).unwrap(); + let sharing = Sharing::new( + vec!["*".into()], + vec![SharedService { + name: "web".into(), + port: 5173, + scheme: "http".into(), + here: 5273, + }], + ); + requester.share_lease(&offer.id, Some(&sharing)).unwrap(); + let lease = || { + requester + .leases() + .unwrap() + .into_iter() + .find(|l| l.node == id && l.lane == "fix") + }; + wait_for(20, "the agent reports the lease running", || { + lease().is_some_and(|l| l.state == "running") + }); + let before = lease().unwrap(); + assert_eq!(before.shared.as_ref(), Some(&sharing)); + // A lease the coordinator took for new would have a later `created`. + std::thread::sleep(Duration::from_millis(1100)); + + // The hub's rounds leave the node to its agent. + for _ in 0..3 { + assert_eq!(round(md.path(), total, &[]), Ok(Round::Agent)); + assert_eq!(node_api().as_deref(), Some(api.as_str()), "the API stays"); + let now = lease().expect("the lease stays"); + assert_eq!( + (now.id.as_str(), now.created, now.shared.as_ref()), + (before.id.as_str(), before.created, Some(&sharing)) + ); + std::thread::sleep(Duration::from_millis(300)); + } + + // The agent stops: the hub reports the machine again. + let _ = stop.send(()); + agent.join().unwrap(); + assert!(!node::agent_runs(md.path())); + assert!(matches!( + round(md.path(), total, &[]), + Ok(Round::Reported(_)) + )); + assert_eq!(node_api(), None, "a hub's report has no API"); + } +} diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index bbbd8ad1..5d5ef7b6 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -3601,6 +3601,37 @@ fn restart_on(binary: &Path) -> String { } } +/// Whether a node agent runs for the membership in `dir` (`pool/` or +/// `pools//` in devstack's per-user state): it holds `node/lock` +/// while it runs. The hub on the same machine then does not report for that +/// pool; the agent reports the machine (#170). +pub fn agent_runs(dir: &Path) -> bool { + devstack_proc::StateLock::held(&dir.join("node")) +} + +/// The agent's lock in `root` (its `node/` directory). Held a moment longer +/// by the agent it replaces (a restart after an update, on Windows a new +/// process) or by a hub that looks whether it is held: tried again for a few +/// seconds. +async fn agent_lock(root: &Path) -> Result { + let t0 = Instant::now(); + loop { + match devstack_proc::StateLock::acquire(root) { + Ok(l) => return Ok(l), + Err(devstack_proc::LockError::Held(_)) if t0.elapsed() < Duration::from_secs(10) => { + tokio::time::sleep(Duration::from_millis(100)).await; + } + Err(devstack_proc::LockError::Held(p)) => { + return Err(NodeError::Other(format!( + "a node agent of this member runs already ({} is held)", + p.display() + ))); + } + Err(e) => return Err(NodeError::Other(e.to_string())), + } + } +} + /// Run the node agent of the member in `config.dir` on `listener` until /// `stop` resolves. pub async fn serve( @@ -3629,6 +3660,9 @@ pub async fn serve( ) .map_err(|e| NodeError::Other(e.to_string()))?; let root = config.dir.join("node"); + // One reporter per machine and pool (#170): while it is held, the hub + // does not report for this membership. + let _lock = agent_lock(&root).await?; std::fs::create_dir_all(root.join("lanes")).map_err(|e| NodeError::Io(root.clone(), e))?; let leases: HashMap = std::fs::read(root.join("leases.json")) .ok() diff --git a/crates/devstack-proc/src/lock.rs b/crates/devstack-proc/src/lock.rs index b4e59c8a..177ab132 100644 --- a/crates/devstack-proc/src/lock.rs +++ b/crates/devstack-proc/src/lock.rs @@ -48,6 +48,17 @@ impl StateLock { let _ = write!(file, "{}", std::process::id()); Ok(Self { _file: file, path }) } + + /// Whether a process holds the lock in `state_dir` now. Asked with a + /// shared lock for a moment, so one who acquires it meanwhile is refused + /// and tries again. Without a lock file, nobody holds it; nothing is + /// created. + pub fn held(state_dir: &Path) -> bool { + let Ok(file) = OpenOptions::new().read(true).open(state_dir.join("lock")) else { + return false; + }; + matches!(file.try_lock_shared(), Err(TryLockError::WouldBlock)) + } } #[cfg(test)] @@ -57,7 +68,10 @@ mod tests { #[test] fn second_acquire_is_refused_until_the_first_is_dropped() { let dir = tempfile::tempdir().unwrap(); + assert!(!StateLock::held(dir.path()), "no lock file"); + assert!(!dir.path().join("lock").exists()); let first = StateLock::acquire(dir.path()).unwrap(); + assert!(StateLock::held(dir.path())); assert!(matches!( StateLock::acquire(dir.path()), Err(LockError::Held(_)) diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index e80cf6f1..66c66589 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -98,7 +98,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/pool/nodes/{id}/policy` (a `NodePolicy` or `null`) | cookie + Origin | admins only: what the node lets run on it, `{allow, repos, memory_headroom?, max_cpus?, share_percent?, network: "lan"\|"internet"\|"none"}`; `null` lifts it | | `POST /hub/pool/join {"coordinator", "fingerprint", "name"?}` | cookie + Origin | ask a pool to admit this machine (`devstack join` without waiting); `GET /hub/pool` shows it pending until an admin approves. `coordinator` is `https://[:]` and nothing more (`400` otherwise). Errors of every `/hub/pool...` route pass on the coordinator's own `{"error"}` only, never the body of whatever else answered | | `POST /hub/pool/members/{id}/role {"role"}` | cookie + Origin | admins only: `member` or `admin`; `409 {"error"}` for the last admin. A member who is no admin gets `403` from all three | -| `GET /hub/pool/share?pool=` | cookie | this machine in the pool, per pool: what it has and what is free (`total`, `free`), whether it is an approved member, the last report (`reported_at`, `error`), the `PoolRelease` the coordinator answered it with (`coordinator?`), and why it offers nothing (`unavailable`: a node agent runs lanes, the dashboard does not start one yet, [#171](https://github.com/nuetzliches/devstack/issues/171)). The share switch and its `PUT` are gone (#169) | +| `GET /hub/pool/share?pool=` | cookie | this machine in the pool, per pool: what it has and what is free (`total`, `free`), whether it is an approved member, the last report (`reported_at`, `error`), whether a node agent of the same membership runs here and reports the machine instead of the hub (`agent`, [#170](https://github.com/nuetzliches/devstack/issues/170)), the `PoolRelease` the coordinator answered it with (`coordinator?`), and why it offers nothing (`unavailable`: a node agent runs lanes, the dashboard does not start one yet, [#171](https://github.com/nuetzliches/devstack/issues/171)). The share switch and its `PUT` are gone (#169) | | `POST /hub/shutdown` | `Authorization: Bearer ` | `202`; the hub exits (`devstack hub stop`) | | `POST /hub/pair` | `Authorization: Bearer ` | `{"code": "...", "url": "http://127.0.0.1:4250/auth?code=..."}` (CLI only) | diff --git a/docs/pool.md b/docs/pool.md index baebb57c..edad44eb 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -71,7 +71,11 @@ and is gone until it does ([#171](https://github.com/nuetzliches/devstack/issues/171); on Windows, which cannot run the Linux lanes yet, [#168](https://github.com/nuetzliches/devstack/issues/168)). The hub reports -the machine (online, what it has, its devstack) and offers nothing. +the machine (online, what it has, its devstack) and offers nothing. While a +node agent of the same membership runs on the machine, the hub does not +report for that pool and the agent reports the machine: the agent holds +`node/lock` in the membership's folder while it runs +([#170](https://github.com/nuetzliches/devstack/issues/170)). Lanes of other members on your machine always show: a banner below the dashboard's top bar (it can be hidden until a lane comes or goes), a tile in diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 422c9a46..03097d76 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -486,6 +486,8 @@ export type ShareStatus = { /** Unix ms of the last report that reached the coordinator. */ reported_at: number | null; error: string | null; + /** A node agent of the same membership runs here and reports the machine, not the hub (#170); absent from an older hub. */ + agent?: boolean; /** The devstack the coordinator runs, from its answer to the last report; absent from an older one. */ coordinator?: PoolRelease; /** Why this machine offers the pool nothing (a node agent runs lanes; #171, on Windows #168). */ From e5c237750e745786eefd019f2f043c294ef78140 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 12:43:32 +0200 Subject: [PATCH 3/3] fix(status): Compose containers get their own table, not the SERVICE column `devstack status` printed its `SERVICE` header for every stack and the Compose groups below it, so a stack of containers only showed them under `SERVICE`, while a service in the stack file and in "main ports" is a `[services.*]` entry only. - The service table shows when the stack has services (or nothing else). - The containers follow in a table of their own, `CONTAINER`, `STATE`, `PORTS`, by group (`compose. ()`), as `devstack top` lists them apart already. - The devstack skill says which is which. Closes #184 Co-Authored-By: Claude Opus 5.5 --- crates/devstack/src/client.rs | 65 ++++++++++++++++++++++++++++------- skills/devstack/SKILL.md | 2 +- 2 files changed, 54 insertions(+), 13 deletions(-) diff --git a/crates/devstack/src/client.rs b/crates/devstack/src/client.rs index 7563df6a..fd4dea1b 100644 --- a/crates/devstack/src/client.rs +++ b/crates/devstack/src/client.rs @@ -705,6 +705,8 @@ pub fn print_status_for(stack: &Value, stack_file: &Path) { } /// The service table and the infrastructure, as `devstack status` shows them. +/// `SERVICE` is a `[services.*]` entry only, as in the stack file and in +/// "main ports"; Compose containers have their own table, by group (#184). pub fn status_text(stack: &Value) -> String { use std::fmt::Write; let mut out = String::new(); @@ -726,12 +728,17 @@ pub fn status_text(stack: &Value) -> String { let _ = writeln!(out, "! {t}\n"); } } - let _ = writeln!( - out, - "{:<22} {:<38} {:<17} {:>6} {:>7}", - "SERVICE", "STATE", "BUILD", "PORT", "PID" - ); - for s in stack["services"].as_array().into_iter().flatten() { + let services = stack["services"].as_array().filter(|s| !s.is_empty()); + let groups = stack["infra"].as_array().filter(|g| !g.is_empty()); + // A stack of containers only has no service table. + if services.is_some() || groups.is_none() { + let _ = writeln!( + out, + "{:<22} {:<38} {:<17} {:>6} {:>7}", + "SERVICE", "STATE", "BUILD", "PORT", "PID" + ); + } + for s in services.into_iter().flatten() { let _ = writeln!( out, "{:<22} {:<38} {:<17} {:>6} {:>7}", @@ -763,10 +770,16 @@ pub fn status_text(stack: &Value) -> String { ); } } - for g in stack["infra"].as_array().into_iter().flatten() { + if groups.is_some() { + if services.is_some() { + out.push('\n'); + } + let _ = writeln!(out, "{:<22} {:<24} PORTS", "CONTAINER", "STATE"); + } + for g in groups.into_iter().flatten() { let _ = writeln!( out, - "\ncompose.{} ({})", + "compose.{} ({})", g["group"].as_str().unwrap_or(""), g["project"].as_str().unwrap_or("") ); @@ -785,13 +798,13 @@ pub fn status_text(stack: &Value) -> String { .flatten() .filter_map(|p| p.as_str()) .collect(); - let _ = writeln!( - out, - " {:<20} {}{health} {}", + let state = format!("{}{health}", c["state"].as_str().unwrap_or("")); + let row = format!( + " {:<20} {state:<24} {}", c["service"].as_str().unwrap_or(""), - c["state"].as_str().unwrap_or(""), ports.join(", ") ); + let _ = writeln!(out, "{}", row.trim_end()); let lost: Vec<&str> = c["unreachable"] .as_array() .into_iter() @@ -2316,6 +2329,34 @@ data: {\"type\":\"line\",\"text\":\"c\"}\n\n"; assert!(!status_text(&serde_json::json!({ "services": [] })).contains('!')); } + #[test] + fn containers_are_listed_apart_from_services() { + let container = serde_json::json!({ "group": "app", "project": "shop", "containers": [ + { "service": "db", "state": "running", "health": "healthy", "ports": ["127.0.0.1:3306"] }, + { "service": "migrate", "state": "exited", "ports": [] } + ] }); + // Containers only: no service table, nothing under `SERVICE`. + let only = status_text(&serde_json::json!({ "services": [], "infra": [container] })); + assert_eq!( + only, + "CONTAINER STATE PORTS\n\ + compose.app (shop)\n \ + db running (healthy) 127.0.0.1:3306\n \ + migrate exited\n" + ); + // Both: the service table, then the containers'. + let both = status_text(&serde_json::json!({ + "services": [{ "name": "api", "status": { "state": "stopped" } }], + "infra": [container] + })); + let s = both.find("SERVICE ").unwrap(); + let api = both.find("\napi ").unwrap(); + let c = both.find("\n\nCONTAINER ").unwrap(); + assert!(s < api && api < c, "{both}"); + // Neither: the empty service table. + assert!(status_text(&serde_json::json!({ "services": [] })).starts_with("SERVICE ")); + } + #[test] fn the_status_lists_the_trees_notices() { let stack = serde_json::json!({ "services": [], "notices": [ diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index c0caa9d9..a0edfa52 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -48,7 +48,7 @@ Run from the repository root (devstack looks for `{{devstack:stack_file}}` there | Command | Effect | | --- | --- | | `devstack up` | Docker check, infrastructure, jobs, every autostart service; starts the dashboard hub. First run takes minutes (images, builds), later ones well under a minute | -| `devstack status` | state per service and container; `-> not yet active: …` means the latest change is not running yet | +| `devstack status` | state per service (`SERVICE`: the `[services.*]` entries) and per Compose container (`CONTAINER`, by group); `-> not yet active: …` means the latest change is not running yet | | `devstack logs --follow` | console output, then every new line (`-n 500` for more history, `--grep X` for matching lines only) | | `devstack logs --grep ` | matching lines of every service's log ("where did this error come from"); with a service only its log | | `devstack logs --since 2h` | every instance of that time, not only the current one: what a crashed or replaced instance printed (`--build `: that build's log and its instances; `--list`, `--log `) |