From 4d70e96b0efcc50a80127bace72c2aef3167cd70 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 12:56:09 +0200 Subject: [PATCH 1/3] docs(adr): ADR-0056, a lane on a node relays its UDP ports (Proposed) A UDP session is its own tunnel (`Upgrade: devstack-udp` on the lane daemon's `/v1/tunnel/{port}`), each datagram a length-prefixed frame; the requester keys sessions by the client's address with a 60 s idle timeout, the lane daemon opens a socket per session towards the container. The requester asks for it at the start, so an older peer leaves UDP ports marked as not forwarded, with the reason. Linked from ADR-0029. Co-Authored-By: Claude Opus 5.5 --- ...nc-and-port-forwarding-for-remote-lanes.md | 2 +- ...-udp-ports-through-a-tunnel-per-session.md | 138 ++++++++++++++++++ docs/adr/README.md | 3 +- 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md diff --git a/docs/adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md b/docs/adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md index e5b358c7..fde10512 100644 --- a/docs/adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md +++ b/docs/adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md @@ -3,7 +3,7 @@ - **Status:** Accepted (2026-10-16); point 2 amended (2026-10-16); its Consequences (a mirror kept, and removed with the member) built by [ADR-0038](0038-a-lanes-data-outlives-its-lease.md) (2026-10-19) - **Date:** 2026-10-15 - **Deciders:** project owner -- **Related:** plan §3.2, §3.4, [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0011](0011-platform-windows-native-first.md), [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0027](0027-trust-between-nodes.md), [ADR-0035](0035-lanes-can-be-shared-with-the-pool.md) (point 4 used there: forwards to others in the pool) +- **Related:** plan §3.2, §3.4, [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0011](0011-platform-windows-native-first.md), [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0027](0027-trust-between-nodes.md), [ADR-0035](0035-lanes-can-be-shared-with-the-pool.md) (point 4 used there: forwards to others in the pool), [ADR-0056](0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md) (point 4 extended: UDP ports, relayed; Proposed) ## Context diff --git a/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md b/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md new file mode 100644 index 00000000..3011c179 --- /dev/null +++ b/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md @@ -0,0 +1,138 @@ +# ADR-0056: A lane on a node relays its UDP ports, a tunnel per client, a datagram per frame + +- **Status:** Proposed +- **Date:** 2026-10-23 +- **Deciders:** project owner +- **Related:** [ADR-0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) (point 4 extended to UDP here), [ADR-0025](0025-a-lane-can-run-on-another-node.md), [ADR-0048](0048-a-containers-main-port-can-move-with-the-main-slot.md) (point 6: the main slot moves TCP only), [ADR-0052](0052-a-restart-carries-the-lanes-over.md), [ADR-0053](0053-whoever-a-lane-is-shared-with-connects-to-it.md), [#192](https://github.com/nuetzliches/devstack/issues/192), [#219](https://github.com/nuetzliches/devstack/issues/219) + +## Context + +A lane on a node forwards its services' and containers' TCP ports to the +requester's loopback (ADR-0029 point 4). Since 0.19.0 (#192) a container +port published as UDP (`53/udp`, a game's voice port, a SIP proxy) runs on +the node, is not forwarded, and the lane's page and `devstack lane list` say +so. A stack that needs such a port has to stay local. + +The tunnel has no multiplexing to put datagrams in. As built (ADR-0029, +*Paths as built*), every forwarded connection is its own request over the +pool's mutual TLS: an HTTP upgrade (`devstack-tcp`) that the node agent +splices to the lane daemon's `/v1/tunnel/{port}`, which connects to the +container on the lane's network. A new one costs 5 to 30 ms (its TLS +handshake), a kept one 0.5 ms per round trip. The agent passes an upgrade +on without reading its protocol. + +## Decision + +1. **A tunnel per session, a frame per datagram.** A UDP session is its + own HTTP upgrade, `Upgrade: devstack-udp`, on the same + `/v1/tunnel/{port}` of the lane daemon, through the node agent as a TCP + tunnel goes. On it each datagram is a frame: its length as two bytes, + big-endian, then the datagram. Nothing else travels; no session id is + needed, as the tunnel is the session. +2. **The relay on the requester.** It binds each of the lane's UDP ports on + loopback (IPv4, and IPv6 where there is one), at the lane's port, as for + TCP. A session is keyed by the client's address (IP and port). The first + datagram of a client opens its tunnel; up to 64 datagrams wait while it + opens, more are dropped. A tunnel that cannot be opened (the container + does not run yet, the node does not answer) drops what waited, ends the + session, and the next datagram of that client tries again, at most once + a second. There is no hold while a container starts: what arrives + before it answers is lost, as on a network. At most 256 sessions per + port; a further client's datagrams are dropped until one ends. +3. **The idle timeout is 60 s** without a datagram either way. Protocols + that keep a session send keepalives well inside that (NAT keepalives, + SIP, WireGuard, QUIC every 15 to 30 s); a one-off exchange (a DNS query + from a fresh source port) holds a tunnel to the node for no more than a + minute. Docker's own UDP proxy keeps 90 s; shorter here, because each + session holds a TLS connection on the node, whose server takes 1024 at + once. +4. **The relay on the node.** The lane daemon answers the upgrade with a + UDP socket of its own for the session, connected to the container's + address on the lane's network (`dns:53`); what comes back from there + goes back as frames. The session ends with its tunnel, or after twice + the idle timeout without traffic, a backstop for a requester gone + without closing. A port-unreachable error (the container restarts) is + not an end: that datagram is lost, the next one is sent. +5. **Size.** A frame carries up to 65,535 bytes and both relays read with + a 64 KiB buffer, so every datagram the operating system delivers + (65,507 bytes at most over IPv4) arrives whole and leaves as one + datagram of the same size. The tunnel is a TCP stream with no MTU of + its own; on each end the operating system fragments a datagram larger + than its link (loopback, the lane's Docker bridge), as it would for a + local lane. A stream that ends inside a frame ends the session. +6. **A lost tunnel** ends its session only: its datagrams in flight are + lost, and the client's next datagram opens a new session, with a new + socket on the node, so the container sees a new source port, as after + a NAT rebinding. Nothing is buffered or replayed across it. A lease that + is over, a lane that stops or moves away closes the listeners and every + session with them, as for TCP. +7. **Compatibility is asked for, not assumed.** The requester asks for UDP + when it starts the lane (`relay_udp` in the start request). A node that + relays writes that into the lane daemon's file (`udp`), and answers with + the lane's UDP ports (`infra_udp_ports`) beside its TCP ones; only then + does the lane daemon stop listing UDP ports as `not_forwarded`. An older + requester does not ask: the ports stay `not_forwarded`, as it shows them + today. An older node does not answer with them: the requester relays + none, and the lane's `not_forwarded` ports come with the reason + (`not_forwarded_reason`: the node's devstack forwards TCP only, with its + release). A lane carried over a restart (ADR-0052) keeps its UDP ports. + +## Alternatives considered + +- **One tunnel per port, sessions multiplexed by an id in each frame.** One + handshake per port instead of per client, but it needs a session protocol + inside (open, close, flow control), and a slow session stalls every other + one behind it on the same stream. The handshake is paid once per client + and session, which a development client does not notice. +- **Datagrams over UDP to the node** (DTLS, QUIC, WireGuard). No + head-of-line blocking, but a second listener and a second trust path + beside the pool's mutual TLS, a UDP port to open in every node's firewall, + and a connection through restrictive networks that TCP gets through. +- **The one multiplexed connection ADR-0029 point 3 decided.** It would + carry datagrams as one more stream type, but it is not built, and + rebuilding every tunnel for UDP is out of proportion. +- **Holding datagrams until the container answers.** UDP clients retry by + themselves; a held datagram arrives late and out of order with the + retries, which is worse than none. + +## Consequences + +- A TCP stream carries the datagrams: one lost packet on the way to the + node delays the datagrams behind it of that session (head-of-line + blocking) instead of dropping one. For development traffic on a pool + link that is the better trade; a real-time media stream over a lossy + link can stutter where it would have skipped. +- A client's first datagram waits for a TLS handshake to the node (5 to + 30 ms); each session holds a connection on the node until its timeout. +- The container sees the lane daemon's address, one source port per + session, never the client's. +- Each session counts as a tunnel in the telemetry (`devstack.tunnels`). + +## Enforced by + +Will live in: + +- `crates/devstack-daemon/src/udprelay.rs`: the framing, the requester's + relay (sessions, idle timeout, limits), the lane daemon's session. +- `crates/devstack-daemon/src/api.rs`: `/v1/tunnel/{port}` with + `devstack-udp`. `crates/devstack-daemon/src/supervisor/infra.rs` + (`infra_udp`), `crates/devstack-daemon/src/external.rs` (`udp`, what is + `not_forwarded`). +- `crates/devstack-daemon/src/remote.rs`: the listeners, `relay_udp`, the + reason, `Carried`. +- `crates/devstack-node/src/node.rs` (`Start.relay_udp`, + `LaneState.infra_udp_ports`), `crates/devstack-node/src/lanerun.rs` (the + lane daemon's file). +- `docs/pool.md`, `docs/dashboard-api.md`, the `devstack` skill, the + dashboard's texts, `devstack lane list`. + +## What this ADR does not say + +- That the main slot moves UDP ports. ADR-0048 point 6 stays: a UDP port of + a named service stays Docker's in the main tree. Moving it needs a UDP + front on the fixed port, which is a decision of its own. +- That a lane shared with others (ADR-0035, ADR-0053) relays UDP to them. + A lane shares `http` and `https` services only; there is no UDP port to + connect to. +- That other protocols are forwarded. An SCTP port stays `not_forwarded`. +- Anything about local lanes: Docker publishes their UDP ports itself. diff --git a/docs/adr/README.md b/docs/adr/README.md index 9fde750f..d12429e9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -77,7 +77,7 @@ stay. | [0026](0026-placement-by-the-requester-admission-by-the-node.md) | The requester places a lane; the node admits it, under a lease | Accepted; points 1, 3 replaced by ADR-0031 | | [0027](0027-trust-between-nodes.md) | Nodes and requesters trust each other by pinned keys, never by network location | Accepted; points 1, 2 replaced by ADR-0031; point 5 amended | | [0028](0028-lane-images.md) | A remote lane runs in a stack-provided toolchain image; the node supplies devstack | Accepted, amended (a Dockerfile the node builds) | -| [0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) | A remote lane works on a mirror of the requester's tree; ports and API come back over one connection | Accepted; point 2 amended (`[lanes] sync`); Consequences built by ADR-0038 | +| [0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) | A remote lane works on a mirror of the requester's tree; ports and API come back over one connection | Accepted; point 2 amended (`[lanes] sync`); Consequences built by ADR-0038; point 4 extended to UDP by ADR-0056 (Proposed) | | [0030](0030-each-lane-has-its-own-infrastructure.md) | Each lane has its own infrastructure | Accepted | | [0031](0031-a-coordinator-places-lanes.md) | A coordinator places lanes and admits members; nodes admit leases; data goes directly | Accepted, amended (one binary: `devstack node`), amended 2026-10-19 (versions in the pool), amended 2026-10-21 (no share switch) | | [0032](0032-the-pool-is-administered-in-the-dashboard.md) | The pool is administered in the dashboard, by members with the admin role | Accepted, amended (admins grant nodes); extended by ADR-0039 (updating a server) | @@ -104,3 +104,4 @@ stay. | [0053](0053-whoever-a-lane-is-shared-with-connects-to-it.md) | Whoever a lane is shared with connects to it, and disconnects again | Accepted | | [0054](0054-macos-is-a-developer-platform-in-preview.md) | macOS is a developer platform in preview, installed by Homebrew, checked by CI and by its testers | Accepted | | [0055](0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md) | A lane whose branch has no stack file runs with the main tree's, says so, and can be given one | Accepted | +| [0056](0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md) | A lane on a node relays its UDP ports, a tunnel per client, a datagram per frame | Proposed | From 6d35d7a546a53aa42c39b3ff51fc3de0c6d3e918 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 13:09:48 +0200 Subject: [PATCH 2/3] feat(lanes): a lane on a node relays its UDP ports through its tunnel (ADR-0056) A container port published as UDP on a lane on a node is no longer only named as not forwarded: the requester binds it on loopback at the lane's port and relays it, a tunnel per client address (`Upgrade: devstack-udp` on the lane daemon's `/v1/tunnel/{port}`), each datagram a frame of its length (two bytes, big-endian) and its bytes. A session ends after 60 s without a datagram either way; nothing is held while a container starts. The lane daemon sends a session's datagrams from a socket of its own to the container on the lane's network. - `udprelay`: framing, the requester's session table (limits, retry after a tunnel that did not open), the lane daemon's session. - The requester asks for UDP when it starts the lane (`relay_udp`); a node that relays tells the lane daemon (`udp` in its file) and answers with `infra_udp_ports`. An older requester or node leaves the ports `not_forwarded`; the lane then says why (`not_forwarded_reason` in `GET /v1/lanes`, `devstack lane list`, the dashboard's lane header). - A lane carried over a restart (ADR-0052) keeps its UDP ports. - Docs: pool.md, dashboard-api.md, the devstack skill. - Tests: framing, session table, idle timeout, a refused tunnel; an end to end test through a real lane daemon's tunnel to an echo socket, without Docker. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 + crates/devstack-daemon/src/api.rs | 57 +- crates/devstack-daemon/src/external.rs | 44 +- crates/devstack-daemon/src/lanes.rs | 9 +- crates/devstack-daemon/src/lib.rs | 1 + crates/devstack-daemon/src/remote.rs | 252 ++++++- crates/devstack-daemon/src/state.rs | 6 +- .../devstack-daemon/src/supervisor/infra.rs | 17 +- crates/devstack-daemon/src/udprelay.rs | 677 ++++++++++++++++++ crates/devstack-node/src/lanerun.rs | 56 +- crates/devstack-node/src/node.rs | 33 +- crates/devstack-node/src/nodeclient.rs | 6 +- crates/devstack-node/tests/lanerun.rs | 1 + crates/devstack/Cargo.toml | 4 + crates/devstack/src/client.rs | 36 +- crates/devstack/src/poolcmd.rs | 1 + crates/devstack/tests/udp_relay.rs | 203 ++++++ docs/dashboard-api.md | 8 +- docs/pool.md | 16 +- skills/devstack/SKILL.md | 2 +- ui/src/api/types.ts | 6 +- ui/src/components/StackHeader.vue | 2 +- ui/src/lib/lanes.test.ts | 9 +- ui/src/lib/lanes.ts | 8 +- 24 files changed, 1367 insertions(+), 91 deletions(-) create mode 100644 crates/devstack-daemon/src/udprelay.rs create mode 100644 crates/devstack/tests/udp_relay.rs diff --git a/Cargo.lock b/Cargo.lock index d8a75e80..efb7b19b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,6 +541,7 @@ name = "devstack" version = "0.19.0" dependencies = [ "anyhow", + "bytes", "clap", "devstack-build", "devstack-compose", @@ -553,6 +554,9 @@ dependencies = [ "devstack-proc", "devstack-skills", "flate2", + "http-body-util", + "hyper", + "hyper-util", "jiff", "libc", "serde", diff --git a/crates/devstack-daemon/src/api.rs b/crates/devstack-daemon/src/api.rs index 43edca5e..01472599 100644 --- a/crates/devstack-daemon/src/api.rs +++ b/crates/devstack-daemon/src/api.rs @@ -597,7 +597,62 @@ fn memory_fits( /// listen on its container's loopback, and the requester forwards its /// local ports through the node agent to here. Only the ports of the stack's /// services, behind the API's token like every route. -async fn tunnel(State(s): State, Path(port): Path, mut req: Request) -> Response { +/// +/// With `Upgrade: devstack-udp` the connection is a UDP session to the +/// container published on `port` as UDP (ADR-0056): datagrams as frames, +/// sent from a socket of the session's own. +async fn tunnel(State(s): State, Path(port): Path, req: Request) -> Response { + let udp = req + .headers() + .get(header::UPGRADE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.eq_ignore_ascii_case(crate::udprelay::PROTOCOL)); + if udp { + udp_tunnel(&s, port, req).await + } else { + tcp_tunnel(&s, port, req).await + } +} + +/// [`tunnel`] for a UDP session (ADR-0056 point 4). +async fn udp_tunnel(s: &AppState, port: u16, mut req: Request) -> Response { + let Some(addr) = s.sup.infra_udp(port) else { + return err( + StatusCode::FORBIDDEN, + format!( + "port {port} is no container's UDP port in this stack (devstack {} here)", + env!("CARGO_PKG_VERSION") + ), + ); + }; + // The container's name resolves once it runs: before, the datagram is + // dropped on the requester, and the next one tries again (no hold). + let socket = match crate::udprelay::connect(&addr).await { + Ok(x) => x, + Err(e) => { + return err( + StatusCode::BAD_GATEWAY, + format!("nothing answers at {addr}/udp: {e}"), + ); + } + }; + let upgrade = hyper::upgrade::on(&mut req); + tokio::spawn(async move { + let Ok(up) = upgrade.await else { return }; + // A backstop: the requester ends an idle session first. + let idle = crate::udprelay::Limits::default().idle * 2; + crate::udprelay::serve(hyper_util::rt::TokioIo::new(up), socket, idle).await; + }); + Response::builder() + .status(StatusCode::SWITCHING_PROTOCOLS) + .header(header::CONNECTION, "upgrade") + .header(header::UPGRADE, crate::udprelay::PROTOCOL) + .body(axum::body::Body::empty()) + .expect("a valid response") +} + +/// [`tunnel`] for a TCP connection. +async fn tcp_tunnel(s: &AppState, port: u16, mut req: Request) -> Response { // A service's port on this machine's loopback, or (a lane on a node) a // container's, at its address on the lane's network. let container = s.sup.infra_tunnel(port); diff --git a/crates/devstack-daemon/src/external.rs b/crates/devstack-daemon/src/external.rs index 7db117de..d47c04ed 100644 --- a/crates/devstack-daemon/src/external.rs +++ b/crates/devstack-daemon/src/external.rs @@ -21,6 +21,11 @@ pub struct ExternalInfra { /// agent from before #101 writes the file once, without it. #[serde(default)] pub at: Option, + /// The lane's requester relays its UDP ports (ADR-0056): it asked for + /// it at the start, and this node's agent passes them on. An older + /// requester or agent leaves it out, and the ports stay not forwarded. + #[serde(default)] + pub udp: bool, } #[derive(Debug, Clone, Deserialize, Default)] @@ -81,10 +86,13 @@ pub struct PortKey { } impl PortKey { - /// devstack forwards TCP only (#192). pub fn is_tcp(&self) -> bool { self.protocol == "tcp" } + + pub fn is_udp(&self) -> bool { + self.protocol == "udp" + } } impl std::str::FromStr for PortKey { @@ -122,7 +130,8 @@ pub struct ExternalService { /// Container port -> the port it is on at the lane's developer's machine /// (what a local lane would publish it on): its links point there, and /// the developer's tunnels to it come in on that port (ADR-0029 point 4). - /// A port of another protocol than TCP is listed, but not forwarded. + /// A UDP port is relayed when the requester asked for it (ADR-0056); a + /// port of another protocol is listed, but not forwarded. #[serde(default)] pub published: BTreeMap, /// Empty: not started (a parked service that is only an environment source). @@ -148,13 +157,13 @@ impl ExternalService { .map(|(k, h)| (k.port, *h)) } - /// Its published ports of another protocol, as the developer would - /// reach them (`5353/udp`): not forwarded, devstack forwards TCP only - /// (#192). - pub fn not_forwarded(&self) -> Vec { + /// Its published ports the developer does not reach, as they would + /// (`5353/udp`): those of another protocol than TCP (#192), UDP ones + /// too unless the requester relays them (`udp`, ADR-0056). + pub fn not_forwarded(&self, udp: bool) -> Vec { self.published .iter() - .filter(|(k, _)| !k.is_tcp()) + .filter(|(k, _)| !k.is_tcp() && !(udp && k.is_udp())) .map(|(k, h)| format!("{h}/{}", k.protocol)) .collect() } @@ -262,12 +271,31 @@ mod tests { dns.forwarded().collect::>(), [(53, 5453), (8080, 8180)] ); - assert_eq!(dns.not_forwarded(), ["5453/udp"]); + assert_eq!(dns.not_forwarded(false), ["5453/udp"]); + assert!(dns.not_forwarded(true).is_empty(), "relayed (ADR-0056)"); assert_eq!( dns.shown_ports(), ["5453->dns:53", "5453/udp->dns:53", "8180->dns:8080"] ); assert!("x/udp".parse::().is_err()); assert_eq!("53/UDP".parse::().unwrap().protocol, "udp"); + assert!( + !x.udp, + "an older agent's file, or an older requester's lane" + ); + } + + #[test] + fn a_relayed_lane_still_names_a_port_of_a_third_protocol() { + let x: super::ExternalInfra = serde_json::from_str( + r#"{"udp":true,"groups":{"app":{"services":{"voice":{ + "ports":{"5060/udp":"voice:5060","9000/sctp":"voice:9000"}, + "published":{"5060/udp":5160,"9000/sctp":9100}, + "state":"running"}}}}}"#, + ) + .unwrap(); + assert!(x.udp); + let voice = &x.groups["app"].services["voice"]; + assert_eq!(voice.not_forwarded(x.udp), ["9100/sctp"]); } } diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index 689e338c..d7af8ace 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -91,9 +91,13 @@ pub struct LaneView { #[serde(skip_serializing_if = "Option::is_none")] pub node_warning: Option, /// Of a lane on a node, its containers' published ports this machine - /// does not forward (`5353/udp`): devstack forwards TCP only (#192). + /// does not forward (`5353/udp`): another protocol than TCP and UDP + /// (#192), or UDP the node does not relay (ADR-0056). #[serde(skip_serializing_if = "Vec::is_empty")] pub not_forwarded: Vec, + /// Why they are not, when there are such ports. + #[serde(skip_serializing_if = "Option::is_none")] + pub not_forwarded_reason: Option, /// A start on a node or a move under way, or one that failed lately. #[serde(skip_serializing_if = "Option::is_none")] pub moving: Option, @@ -1698,6 +1702,9 @@ impl Lanes { .as_ref() .map(|st| st.not_forwarded.clone()) .unwrap_or_default(), + not_forwarded_reason: node_state + .as_ref() + .and_then(|st| st.not_forwarded_reason.clone()), node_warning: on_node .and_then(|r| r.warning.clone()) .or_else(|| moves.get(&k.entry.name).and_then(|m| m.warning.clone())), diff --git a/crates/devstack-daemon/src/lib.rs b/crates/devstack-daemon/src/lib.rs index fe33474f..bc869efc 100644 --- a/crates/devstack-daemon/src/lib.rs +++ b/crates/devstack-daemon/src/lib.rs @@ -21,6 +21,7 @@ pub mod tcpfwd; pub mod telemetry; pub mod timeline; pub mod token; +pub mod udprelay; pub mod usage; pub mod watch; diff --git a/crates/devstack-daemon/src/remote.rs b/crates/devstack-daemon/src/remote.rs index 3a2c51d6..f6dbf4ff 100644 --- a/crates/devstack-daemon/src/remote.rs +++ b/crates/devstack-daemon/src/remote.rs @@ -43,8 +43,12 @@ pub struct RemoteState { /// Its services that run now (healthy or running), by name. pub active: Vec, /// Its containers' published ports this machine does not forward - /// (`5353/udp`): devstack forwards TCP only (#192). + /// (`5353/udp`): another protocol than TCP and UDP (#192), or UDP where + /// the node, or the daemon that started the lane, does not relay it + /// (ADR-0056). pub not_forwarded: Vec, + /// Why, when there are such ports. + pub not_forwarded_reason: Option, } impl RemoteState { @@ -82,6 +86,8 @@ pub struct RemoteLane { stopped: tokio::sync::watch::Sender, /// The lane's ports, `(on the node, here)`. ports: Vec<(u16, u16)>, + /// Its containers' UDP ports, `(on the node, here)`, relayed (ADR-0056). + udp_ports: Vec<(u16, u16)>, /// Whether this machine listens on them for the lane now: a lane that /// moves here takes them over before its old placement goes. listening: tokio::sync::watch::Sender, @@ -427,6 +433,7 @@ struct Parts<'a> { extra: &'a [String], client: NodeClient, ports: Vec<(u16, u16)>, + udp_ports: Vec<(u16, u16)>, hashes: HashCache, } @@ -439,6 +446,10 @@ pub struct Carried { pub lease: String, /// Its ports, `(on the node, here)`, its containers' included. pub ports: Vec<(u16, u16)>, + /// Its containers' UDP ports, relayed (ADR-0056); absent from a daemon + /// before that, whose lane relays none. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub udp_ports: Vec<(u16, u16)>, #[serde(default, skip_serializing_if = "Option::is_none")] pub warning: Option, } @@ -704,6 +715,9 @@ impl RemoteLane { Some(&display), port_offset, profile, + // This machine relays UDP (ADR-0056); an older node + // does not read it, and its lane names none. + true, Duration::from_secs(1800), &|p| { step(3, &format!("on {node}: {p}")); @@ -731,6 +745,7 @@ impl RemoteLane { ports.push((p, p)); } } + let udp_ports = started.infra_udp_ports.iter().map(|p| (*p, *p)).collect(); crate::diag::info( "remote_lane_started", serde_json::json!({ "lane": name, "node": offer.node.name, "lease": offer.id, @@ -749,6 +764,7 @@ impl RemoteLane { extra, client, ports, + udp_ports, hashes, }, ); @@ -782,6 +798,7 @@ impl RemoteLane { state: Mutex::new(RemoteState::default()), stopped: tokio::sync::watch::channel(false).0, ports: p.ports, + udp_ports: p.udp_ports, listening: tokio::sync::watch::channel(false).0, gone: tokio::sync::watch::channel(false).0, dirty: dirty.clone(), @@ -832,6 +849,7 @@ impl RemoteLane { node: self.node.clone(), lease: self.lease.clone(), ports: self.ports.clone(), + udp_ports: self.udp_ports.clone(), warning: self.warning.clone(), } } @@ -887,6 +905,7 @@ impl RemoteLane { extra, client, ports: c.ports, + udp_ports: c.udp_ports, hashes: HashCache::default(), }, ); @@ -1223,6 +1242,7 @@ impl RemoteLane { st.containers = all.len(); st.active = active; st.not_forwarded = not_forwarded(&all); + st.not_forwarded_reason = self.not_forwarded_reason(&st.not_forwarded); } if !self.tick(STATE_EVERY).await { return; @@ -1233,7 +1253,8 @@ impl RemoteLane { /// Listen on the lane's ports here (again): each on loopback, IPv4 and, /// where there is one, IPv6, every connection carried to its port of the /// lane on its node, bytes unchanged, so WebSockets, hot module - /// replacement and TLS dev servers work as they do locally. + /// replacement and TLS dev servers work as they do locally. Its UDP + /// ports are relayed alike, a tunnel per client (ADR-0056). pub fn start_forwarding(self: &Arc, rt: &tokio::runtime::Handle) { if self.listening.send_replace(true) { return; @@ -1242,6 +1263,10 @@ impl RemoteLane { let l = self.clone(); rt.spawn(async move { l.forward_port(there, here).await }); } + for &(there, here) in &self.udp_ports { + let l = self.clone(); + rt.spawn(async move { l.forward_udp(there, here).await }); + } } /// Stop listening on the lane's ports here; open connections stay. @@ -1250,10 +1275,14 @@ impl RemoteLane { self.listening.send_replace(false); let until = Instant::now() + Duration::from_secs(2); while Instant::now() < until - && self + && (self .ports .iter() .any(|(_, here)| crate::supervisor::port_in_use(*here)) + || self + .udp_ports + .iter() + .any(|(_, here)| std::net::UdpSocket::bind(("127.0.0.1", *here)).is_err())) { std::thread::sleep(Duration::from_millis(50)); } @@ -1293,26 +1322,29 @@ impl RemoteLane { } } - async fn forward_port(self: Arc, there: u16, here: u16) { - let mut listeners = Vec::new(); - // A port something else still holds (a container on its way out) is - // tried again: every second for half a minute, then every 15 s, as - // long as the lane forwards. The lane says so meanwhile. + /// Bind with `bind`, tried again while something else holds the port + /// (a container on its way out): every second for half a minute, then + /// every 15 s, as long as the lane forwards. The lane says so meanwhile, + /// under `about` (`port 3000`). `None`: it no longer forwards. + async fn bind_retrying(&self, about: &str, bind: F) -> Option + where + F: Fn() -> Fut, + Fut: std::future::Future>, + { let t0 = Instant::now(); let mut stopped = self.stopped.subscribe(); let mut listening = self.listening.subscribe(); loop { - match tokio::net::TcpListener::bind(("127.0.0.1", here)).await { + match bind().await { Ok(l) => { - listeners.push(l); - self.trouble(&format!("port {here}"), None); - break; + self.trouble(about, None); + return Some(l); } Err(e) => { self.trouble( - &format!("port {here}"), + about, Some(format!( - "port {here} here: {e} (something else holds it; tried again until it is free)" + "{about} here: {e} (something else holds it; tried again until it is free)" )), ); let wait = if t0.elapsed() < Duration::from_secs(30) { @@ -1322,12 +1354,24 @@ impl RemoteLane { }; tokio::select! { _ = tokio::time::sleep(wait) => {} - _ = stopped.wait_for(|s| *s) => return, - _ = listening.wait_for(|l| !*l) => return, + _ = stopped.wait_for(|s| *s) => return None, + _ = listening.wait_for(|l| !*l) => return None, } } } } + } + + async fn forward_port(self: Arc, there: u16, here: u16) { + let Some(l) = self + .bind_retrying(&format!("port {here}"), || { + tokio::net::TcpListener::bind(("127.0.0.1", here)) + }) + .await + else { + return; + }; + let mut listeners = vec![l]; if let Ok(l) = tokio::net::TcpListener::bind(("::1", here)).await { listeners.push(l); } @@ -1368,14 +1412,99 @@ impl RemoteLane { } } + /// Relay a UDP port of the lane's containers here (ADR-0056): each + /// client's datagrams through a tunnel of its own to the lane daemon, + /// which sends them on to the container, until the lane no longer + /// forwards. + async fn forward_udp(self: Arc, there: u16, here: u16) { + let Some(s) = self + .bind_retrying(&format!("port {here}/udp"), || { + tokio::net::UdpSocket::bind(("127.0.0.1", here)) + }) + .await + else { + return; + }; + let mut sockets = vec![s]; + if let Ok(s) = tokio::net::UdpSocket::bind(("::1", here)).await { + sockets.push(s); + } + for socket in sockets { + let me = self.clone(); + tokio::spawn(async move { + let mut stopped = me.stopped.subscribe(); + let mut listening = me.listening.subscribe(); + let opener = me.clone(); + let open = move || { + let me = opener.clone(); + async move { me.open_udp(there).await } + }; + let (name, key) = ( + me.name.clone(), + format!("remote_lane_udp:{}:{there}", me.name), + ); + let report = Arc::new(move |e: String| { + crate::diag::warn_limited( + &key, + "remote_lane_udp", + serde_json::json!({ "lane": name, "port": there, "error": e }), + ); + }); + let limits = crate::udprelay::Limits::default(); + // Dropped, the relay ends its sessions and lets the port go. + tokio::select! { + _ = crate::udprelay::relay(socket, open, limits, report) => {} + _ = stopped.wait_for(|s| *s) => {} + _ = listening.wait_for(|l| !*l) => {} + _ = me.over() => {} + } + }); + } + } + + /// A UDP session's tunnel, through the node agent to the lane daemon. + async fn open_udp( + &self, + port: u16, + ) -> Result>, String> + { + let stream = self.open_tunnel(port, crate::udprelay::PROTOCOL).await?; + let open = crate::telemetry::Tunnel::open(&self.name, &self.node.name); + Ok(crate::udprelay::Opened { + stream, + closed: Some(Box::new(move |bytes| open.closed(bytes))), + }) + } + /// One connection, through the node agent to the lane daemon's tunnel. async fn tunnel(&self, mut tcp: tokio::net::TcpStream, port: u16) -> Result<(), String> { let _ = tcp.set_nodelay(true); + let mut up = self.open_tunnel(port, crate::api::TUNNEL_PROTOCOL).await?; + let open = crate::telemetry::Tunnel::open(&self.name, &self.node.name); + match tokio::io::copy_bidirectional(&mut up, &mut tcp).await { + Ok((a, b)) => { + open.closed(a + b); + Ok(()) + } + // One end hung up without a goodbye (a browser closing a tab or + // a dev server's WebSocket): how connections end, not a fault. + Err(e) if closed_by_a_peer(&e) => Ok(()), + Err(e) => Err(e.to_string()), + } + } + + /// A tunnel to `port` of the lane, through the node agent to the lane + /// daemon's `/v1/tunnel/{port}`, upgraded to `protocol`. + async fn open_tunnel( + &self, + port: u16, + protocol: &str, + ) -> Result, String> { let req = axum::http::Request::builder() .method("GET") .uri(format!("/v1/tunnel/{port}")) .header(axum::http::header::CONNECTION, "upgrade") - .header(axum::http::header::UPGRADE, crate::api::TUNNEL_PROTOCOL) + .header(axum::http::header::UPGRADE, protocol) .body(http_body_util::Empty::::new()) .map_err(|e| e.to_string())?; let mut res = self @@ -1401,18 +1530,12 @@ impl RemoteLane { let up = hyper::upgrade::on(&mut res) .await .map_err(|e| e.to_string())?; - let mut up = hyper_util::rt::TokioIo::new(up); - let open = crate::telemetry::Tunnel::open(&self.name, &self.node.name); - match tokio::io::copy_bidirectional(&mut up, &mut tcp).await { - Ok((a, b)) => { - open.closed(a + b); - Ok(()) - } - // One end hung up without a goodbye (a browser closing a tab or - // a dev server's WebSocket): how connections end, not a fault. - Err(e) if closed_by_a_peer(&e) => Ok(()), - Err(e) => Err(e.to_string()), - } + Ok(hyper_util::rt::TokioIo::new(up)) + } + + /// Why its `not_forwarded` ports are not (ADR-0056 point 7). + fn not_forwarded_reason(&self, ports: &[String]) -> Option { + not_forwarded_reason(ports, &self.node.name, self.node_release.as_ref()) } /// Why the node cannot do what `method` on the lane daemon's `path` @@ -1527,6 +1650,31 @@ fn not_forwarded(containers: &[serde_json::Value]) -> Vec { out } +/// The release from which a node relays a lane's UDP ports (ADR-0056). +const RELAYS_UDP: &str = "0.20.0"; + +/// Why a lane's ports `not_forwarded` (`5353/udp`) are not: `None` when +/// there are none. A UDP port is relayed unless the node is older than +/// [`RELAYS_UDP`], or the lane was started by a daemon that was. +fn not_forwarded_reason(ports: &[String], node: &str, release: Option<&Release>) -> Option { + if ports.is_empty() { + return None; + } + if !ports.iter().any(|p| p.ends_with("/udp")) { + return Some("devstack forwards TCP and UDP only".into()); + } + if !version::at_least(release, RELAYS_UDP) { + return Some(format!( + "the node {node} runs {}, which forwards TCP only: devstack {RELAYS_UDP} or later there relays UDP", + version::describe(release) + )); + } + Some( + "the lane was started by an earlier devstack here, which forwards TCP only: start it again to relay UDP" + .into(), + ) +} + /// What a lease offer says of the node's and the coordinator's devstack: /// `Err` for a node with another pool protocol, a warning for another /// release or one that does not say. @@ -1892,4 +2040,50 @@ members = ["api"] "an older lane daemon's" ); } + + #[test] + fn a_udp_port_not_relayed_says_which_side_is_too_old() { + use super::not_forwarded_reason as why; + let at = |v: &str| Release { + version: v.into(), + protocol: version::PROTOCOL, + }; + let udp = ["5453/udp".to_string()]; + assert_eq!(why(&[], "build-1", None), None, "nothing to say"); + let old = why(&udp, "build-1", Some(&at("0.18.2"))).unwrap(); + assert!( + old.contains("the node build-1 runs devstack 0.18.2") + && old.contains("0.20.0 or later there relays UDP"), + "{old}" + ); + let unknown = why(&udp, "build-1", None).unwrap(); + assert!(unknown.contains("does not say its version"), "{unknown}"); + // The node relays: the lane was started before this machine did. + let here = why(&udp, "build-1", Some(&at("0.20.1"))).unwrap(); + assert!(here.contains("start it again"), "{here}"); + assert_eq!( + why(&["9100/sctp".to_string()], "build-1", Some(&at("0.20.0"))).as_deref(), + Some("devstack forwards TCP and UDP only") + ); + } + + #[test] + fn a_lane_carried_over_keeps_its_udp_ports() { + let c: super::Carried = serde_json::from_str( + r#"{"pool":"default","node":{"id":"n1","name":"build-1","api":"https://n"}, + "lease":"l1","ports":[[3000,3100]]}"#, + ) + .unwrap(); + assert!( + c.udp_ports.is_empty(), + "a daemon before ADR-0056 relays none" + ); + let c = super::Carried { + udp_ports: vec![(5453, 5453)], + ..c + }; + let again: super::Carried = + serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap(); + assert_eq!(again.udp_ports, [(5453, 5453)]); + } } diff --git a/crates/devstack-daemon/src/state.rs b/crates/devstack-daemon/src/state.rs index 8a16ae13..daae07ef 100644 --- a/crates/devstack-daemon/src/state.rs +++ b/crates/devstack-daemon/src/state.rs @@ -138,9 +138,9 @@ pub struct ContainerView { /// container may look healthy. A restart of the container fixes it. #[serde(skip_serializing_if = "Vec::is_empty", default)] pub unreachable: Vec, - /// Of a lane on a node, its published ports of another protocol than - /// TCP (`5353/udp`): devstack forwards TCP only, so the developer's - /// machine does not reach them (#192). + /// Of a lane on a node, its published ports the developer's machine + /// does not reach (`5353/udp`): another protocol than TCP (#192), UDP + /// too unless the requester relays it (ADR-0056). #[serde(skip_serializing_if = "Vec::is_empty", default)] pub not_forwarded: Vec, /// Its fixed ports devstack holds (`main_ports`, ADR-0048): `port` the diff --git a/crates/devstack-daemon/src/supervisor/infra.rs b/crates/devstack-daemon/src/supervisor/infra.rs index 6b0dba4f..f1a28820 100644 --- a/crates/devstack-daemon/src/supervisor/infra.rs +++ b/crates/devstack-daemon/src/supervisor/infra.rs @@ -64,7 +64,8 @@ impl Supervisor { } let g = self.compose_group(group); let model = self.docker.config(&g).map_err(|e| e.to_string())?; - // devstack forwards TCP only (#192): a UDP port stays Docker's. + // The main slot moves TCP only (ADR-0048 point 6; a lane on a node + // relays UDP, ADR-0056): a UDP port stays Docker's. for name in names { for p in model.services.get(name).map_or(&[][..], |s| &s.ports[..]) { let proto = p.protocol.as_deref().unwrap_or("tcp"); @@ -1035,6 +1036,16 @@ impl Supervisor { /// to, when `port` is where a container of the lane is published for its /// developer (ADR-0029 point 4). A tunnel carries TCP (#192). pub fn infra_tunnel(&self, port: u16) -> Option { + self.infra_target(port, "tcp") + } + + /// [`Self::infra_tunnel`] for a UDP port: where a UDP session on `port` + /// sends its datagrams (ADR-0056). + pub fn infra_udp(&self, port: u16) -> Option { + self.infra_target(port, "udp") + } + + fn infra_target(&self, port: u16, protocol: &str) -> Option { let ext = crate::external::read(&self.external_infra()?).ok()?; ext.groups .values() @@ -1042,7 +1053,7 @@ impl Supervisor { .find_map(|s| { s.published .iter() - .find(|(k, h)| k.is_tcp() && **h == port) + .find(|(k, h)| k.protocol == protocol && **h == port) .and_then(|(target, _)| s.ports.get(target).cloned()) }) } @@ -1114,7 +1125,7 @@ impl Supervisor { urls: self.container_urls(&g, &svc, &here), ports, unreachable: Vec::new(), - not_forwarded: s.not_forwarded(), + not_forwarded: s.not_forwarded(ext.udp), held: Vec::new(), managed: true, }); diff --git a/crates/devstack-daemon/src/udprelay.rs b/crates/devstack-daemon/src/udprelay.rs new file mode 100644 index 00000000..d49c6202 --- /dev/null +++ b/crates/devstack-daemon/src/udprelay.rs @@ -0,0 +1,677 @@ +//! UDP ports of a lane on a node, relayed through its tunnel (ADR-0056). +//! +//! A UDP session is a tunnel of its own: an HTTP upgrade +//! ([`PROTOCOL`]) on the lane daemon's `/v1/tunnel/{port}`, through the node +//! agent as a TCP tunnel goes. On it each datagram is a frame, its length as +//! two bytes, big-endian, then the datagram. +//! +//! - [`relay`], on the requester: a socket on the lane's port, a session per +//! client address, each opening its tunnel with the first datagram and +//! ending after [`Limits::idle`] without traffic. +//! - [`serve`], in the lane daemon: a session's socket towards the +//! container's port. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::UdpSocket; +use tokio::sync::{mpsc, watch}; + +/// The `Upgrade` protocol of a UDP session's tunnel. +pub const PROTOCOL: &str = "devstack-udp"; + +/// The largest datagram a frame carries: its length is two bytes. Every +/// UDP datagram fits (65,507 bytes over IPv4, 65,527 over IPv6). +pub const MAX_DATAGRAM: usize = u16::MAX as usize; + +/// What a socket is read with: any datagram the system delivers, whole. +const BUFFER: usize = 1 << 16; + +/// A datagram longer than a frame carries. +#[derive(Debug, PartialEq, Eq)] +pub struct TooLarge(pub usize); + +impl std::fmt::Display for TooLarge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "a datagram of {} bytes is larger than {MAX_DATAGRAM}", + self.0 + ) + } +} + +/// `datagram` as a frame, appended to `out`. +pub fn encode(datagram: &[u8], out: &mut Vec) -> Result<(), TooLarge> { + let len = u16::try_from(datagram.len()).map_err(|_| TooLarge(datagram.len()))?; + out.reserve(2 + datagram.len()); + out.extend_from_slice(&len.to_be_bytes()); + out.extend_from_slice(datagram); + Ok(()) +} + +/// Write `datagram` as one frame, in one write, and flush it: a datagram +/// waits for nothing after it. +pub async fn write_frame(w: &mut W, datagram: &[u8]) -> std::io::Result<()> { + let mut frame = Vec::new(); + encode(datagram, &mut frame).map_err(|e| std::io::Error::other(e.to_string()))?; + w.write_all(&frame).await?; + w.flush().await +} + +/// Read the next frame's datagram into `buf`. `false`: the stream ended +/// between frames; a stream that ends inside one is an error. +pub async fn read_frame( + r: &mut R, + buf: &mut Vec, +) -> std::io::Result { + let mut len = [0u8; 2]; + match r.read(&mut len[..1]).await? { + 0 => return Ok(false), + _ => r.read_exact(&mut len[1..]).await?, + }; + buf.resize(u16::from_be_bytes(len) as usize, 0); + r.read_exact(buf).await?; + Ok(true) +} + +/// How a relay on the requester holds its sessions (ADR-0056 points 2, 3). +#[derive(Debug, Clone, Copy)] +pub struct Limits { + /// A session ends after this long without a datagram either way. + pub idle: Duration, + /// Datagrams of a session that wait while its tunnel opens, or the + /// node is slower than its client; more are dropped. + pub queued: usize, + /// Sessions per socket; a further client's datagrams are dropped. + pub sessions: usize, + /// A client whose tunnel could not be opened is tried again after this. + pub retry: Duration, +} + +impl Default for Limits { + fn default() -> Self { + Self { + idle: Duration::from_secs(60), + queued: 64, + sessions: 256, + retry: Duration::from_secs(1), + } + } +} + +/// What becomes of a datagram from a client, by [`Table::route`]. +#[derive(Debug)] +enum Route { + /// Its session runs: into its queue. + Session(mpsc::Sender>), + /// A new session, for the caller to open. + Open, + /// Dropped: the client's tunnel failed a moment ago. + Backoff, + /// Dropped: the socket has as many sessions as it takes. + Full, +} + +/// A relay's sessions, by the client's address. +#[derive(Debug)] +struct Table { + sessions: HashMap>)>, + /// Clients whose tunnel could not be opened, and when. + refused: HashMap, + next: u64, + limits: Limits, +} + +impl Table { + fn new(limits: Limits) -> Self { + Self { + sessions: HashMap::new(), + refused: HashMap::new(), + next: 0, + limits, + } + } + + fn route(&mut self, from: SocketAddr, now: Instant) -> Route { + if let Some((_, tx)) = self.sessions.get(&from) { + if !tx.is_closed() { + return Route::Session(tx.clone()); + } + // Ended a moment ago, not removed yet: a new one. + self.sessions.remove(&from); + } + if let Some(at) = self.refused.get(&from) { + if now.duration_since(*at) < self.limits.retry { + return Route::Backoff; + } + self.refused.remove(&from); + } + if self.sessions.len() >= self.limits.sessions { + self.sessions.retain(|_, (_, tx)| !tx.is_closed()); + if self.sessions.len() >= self.limits.sessions { + return Route::Full; + } + } + Route::Open + } + + /// A session for `from`: its id, and where its datagrams go. + fn open(&mut self, from: SocketAddr) -> (u64, mpsc::Sender>, mpsc::Receiver>) { + self.next += 1; + let (tx, rx) = mpsc::channel(self.limits.queued.max(1)); + self.sessions.insert(from, (self.next, tx.clone())); + (self.next, tx, rx) + } + + /// Session `id` of `from` is over; `refused`: its tunnel did not open. + fn ended(&mut self, from: SocketAddr, id: u64, refused: Option) { + if self.sessions.get(&from).is_some_and(|(i, _)| *i == id) { + self.sessions.remove(&from); + } + if let Some(at) = refused { + // Forget the old ones, so a scan does not keep them all. + let retry = self.limits.retry; + self.refused.retain(|_, t| at.duration_since(*t) < retry); + self.refused.insert(from, at); + } + } + + #[cfg(test)] + fn len(&self) -> usize { + self.sessions.len() + } +} + +/// A session's tunnel, as the requester opened it. +pub struct Opened { + pub stream: S, + /// Told the bytes the session carried when it ends (telemetry). + pub closed: Option>, +} + +/// Relay `socket` (a lane's UDP port on the requester) until this future +/// is dropped: each client's datagrams go through a tunnel `open` opens +/// for it, what comes back goes to that client. Dropped, every session +/// ends and the socket is let go. `report` hears what goes wrong, a tunnel +/// that does not open. +pub async fn relay( + socket: UdpSocket, + open: O, + limits: Limits, + report: Arc, +) where + O: Fn() -> F + Send + Sync + 'static, + F: std::future::Future, String>> + Send + 'static, + S: AsyncRead + AsyncWrite + Send + Unpin + 'static, +{ + let socket = Arc::new(socket); + let open = Arc::new(open); + let table = Arc::new(Mutex::new(Table::new(limits))); + // Its sessions end with it. + let (stop, _) = watch::channel(false); + let _stop = StopOnDrop(stop.clone()); + let mut buf = vec![0u8; BUFFER]; + loop { + let (n, from) = match socket.recv_from(&mut buf).await { + Ok(x) => x, + // Windows reports a reply that found no client (ICMP port + // unreachable) on the next read: not this socket's end. + Err(e) if refused(&e) => continue, + Err(_) => { + tokio::time::sleep(Duration::from_millis(50)).await; + continue; + } + }; + let datagram = buf[..n].to_vec(); + let route = table.lock().unwrap().route(from, Instant::now()); + match route { + Route::Session(tx) => { + // Full: the tunnel lags; dropped, as a network would. + let _ = tx.try_send(datagram); + } + Route::Backoff | Route::Full => {} + Route::Open => { + let (id, tx, rx) = table.lock().unwrap().open(from); + let _ = tx.try_send(datagram); + drop(tx); + let (socket, open, table, report) = + (socket.clone(), open.clone(), table.clone(), report.clone()); + let mut stopped = stop.subscribe(); + tokio::spawn(async move { + let session = async { + let opened = match open().await { + Ok(o) => o, + Err(e) => { + report(e); + return Some(Instant::now()); + } + }; + let bytes = carry(opened.stream, rx, &socket, from, limits.idle).await; + if let Some(closed) = opened.closed { + closed(bytes); + } + None + }; + let refused = tokio::select! { + r = session => r, + _ = stopped.wait_for(|s| *s) => None, + }; + table.lock().unwrap().ended(from, id, refused); + }); + } + } + } +} + +struct StopOnDrop(watch::Sender); + +impl Drop for StopOnDrop { + fn drop(&mut self) { + self.0.send_replace(true); + } +} + +/// A port-unreachable error a UDP socket reports after a datagram it sent: +/// that datagram is lost, the socket goes on. +fn refused(e: &std::io::Error) -> bool { + matches!( + e.kind(), + std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::ConnectionReset + ) +} + +/// The time of the last datagram either way, shared by both directions. +struct Activity(Mutex); + +impl Activity { + fn new() -> Self { + Self(Mutex::new(Instant::now())) + } + + fn touch(&self) { + *self.0.lock().unwrap() = Instant::now(); + } + + /// Returns once nothing went either way for `idle`. + async fn idle(&self, idle: Duration) { + loop { + let until = *self.0.lock().unwrap() + idle; + if Instant::now() >= until { + return; + } + tokio::time::sleep_until(until.into()).await; + } + } +} + +/// One session on the requester: `rx`'s datagrams into `stream` as frames, +/// its frames to `client`, until the tunnel ends or nothing went either +/// way for `idle`. Returns the bytes carried. +async fn carry( + stream: S, + mut rx: mpsc::Receiver>, + socket: &UdpSocket, + client: SocketAddr, + idle: Duration, +) -> u64 +where + S: AsyncRead + AsyncWrite + Send + Unpin, +{ + let (mut rd, mut wr) = tokio::io::split(stream); + let activity = Activity::new(); + let bytes = std::sync::atomic::AtomicU64::new(0); + let count = |n: usize| bytes.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); + let up = async { + while let Some(d) = rx.recv().await { + if write_frame(&mut wr, &d).await.is_err() { + return; + } + count(d.len()); + activity.touch(); + } + }; + let down = async { + let mut buf = Vec::new(); + while let Ok(true) = read_frame(&mut rd, &mut buf).await { + activity.touch(); + count(buf.len()); + let _ = socket.send_to(&buf, client).await; + } + }; + tokio::select! { + _ = up => {} + _ = down => {} + _ = activity.idle(idle) => {} + } + bytes.load(std::sync::atomic::Ordering::Relaxed) +} + +/// One session in the lane daemon: `stream`'s frames to `target` (a socket +/// connected to the container's port), what comes back as frames, until +/// the tunnel ends or nothing went either way for `idle` (a backstop: the +/// requester ends a session first). A port-unreachable error (the +/// container restarts) loses that datagram, not the session. +pub async fn serve(stream: S, target: UdpSocket, idle: Duration) +where + S: AsyncRead + AsyncWrite + Send + Unpin, +{ + let (mut rd, mut wr) = tokio::io::split(stream); + let activity = Activity::new(); + let up = async { + let mut buf = Vec::new(); + while let Ok(true) = read_frame(&mut rd, &mut buf).await { + activity.touch(); + let _ = target.send(&buf).await; + } + }; + let down = async { + let mut buf = vec![0u8; BUFFER]; + loop { + match target.recv(&mut buf).await { + Ok(n) => { + activity.touch(); + if write_frame(&mut wr, &buf[..n]).await.is_err() { + return; + } + } + Err(e) if refused(&e) => continue, + Err(_) => return, + } + } + }; + tokio::select! { + _ = up => {} + _ = down => {} + _ = activity.idle(idle) => {} + } +} + +/// A UDP socket for a session towards `addr` (`dns:53`, a container on the +/// lane's network): bound to any port of the address's family, connected, +/// so only `addr` is heard. +pub async fn connect(addr: &str) -> std::io::Result { + let to = tokio::net::lookup_host(addr) + .await? + .next() + .ok_or_else(|| std::io::Error::other(format!("{addr} has no address")))?; + let any: SocketAddr = if to.is_ipv4() { + (std::net::Ipv4Addr::UNSPECIFIED, 0).into() + } else { + (std::net::Ipv6Addr::UNSPECIFIED, 0).into() + }; + let socket = UdpSocket::bind(any).await?; + socket.connect(to).await?; + Ok(socket) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_datagram_is_its_length_and_its_bytes() { + let mut out = Vec::new(); + encode(b"dns?", &mut out).unwrap(); + encode(b"", &mut out).unwrap(); + assert_eq!(out, [0, 4, b'd', b'n', b's', b'?', 0, 0]); + let big = vec![7u8; MAX_DATAGRAM]; + let mut out = Vec::new(); + encode(&big, &mut out).unwrap(); + assert_eq!(&out[..2], &[0xff, 0xff]); + assert_eq!(out.len(), 2 + MAX_DATAGRAM); + assert_eq!( + encode(&vec![0u8; MAX_DATAGRAM + 1], &mut Vec::new()), + Err(TooLarge(MAX_DATAGRAM + 1)) + ); + } + + #[tokio::test] + async fn frames_read_back_as_the_datagrams_written() { + let (mut a, mut b) = tokio::io::duplex(1 << 18); + let sent: Vec> = vec![b"one".to_vec(), Vec::new(), vec![9u8; 65_507]]; + for d in &sent { + write_frame(&mut a, d).await.unwrap(); + } + drop(a); + let mut buf = Vec::new(); + for d in &sent { + assert!(read_frame(&mut b, &mut buf).await.unwrap()); + assert_eq!(&buf, d); + } + assert!( + !read_frame(&mut b, &mut buf).await.unwrap(), + "ends between frames" + ); + } + + #[tokio::test] + async fn a_stream_that_ends_inside_a_frame_is_an_error() { + for cut in [&[0u8][..], &[0, 5, b'a', b'b'][..]] { + let mut r = cut; + let e = read_frame(&mut r, &mut Vec::new()).await.unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof, "{cut:?}"); + } + } + + fn addr(port: u16) -> SocketAddr { + ([127, 0, 0, 1], port).into() + } + + #[test] + fn sessions_are_keyed_by_the_clients_address() { + let mut t = Table::new(Limits::default()); + let now = Instant::now(); + assert!(matches!(t.route(addr(1000), now), Route::Open)); + let (id, _tx, _rx) = t.open(addr(1000)); + // The same client: its session; another port is another client. + assert!(matches!(t.route(addr(1000), now), Route::Session(_))); + assert!(matches!(t.route(addr(1001), now), Route::Open)); + let (other, _tx2, _rx2) = t.open(addr(1001)); + assert_eq!(t.len(), 2); + // An old session's end does not remove a newer one of the client. + t.ended(addr(1000), id + 100, None); + assert_eq!(t.len(), 2); + t.ended(addr(1001), other, None); + assert_eq!(t.len(), 1); + assert!(matches!(t.route(addr(1001), now), Route::Open)); + } + + #[test] + fn a_session_whose_queue_closed_is_opened_again() { + let mut t = Table::new(Limits::default()); + let (_, tx, rx) = t.open(addr(1000)); + drop((tx, rx)); + assert!(matches!(t.route(addr(1000), Instant::now()), Route::Open)); + assert_eq!(t.len(), 0); + } + + #[test] + fn a_refused_client_waits_and_a_full_table_drops() { + let limits = Limits { + sessions: 2, + retry: Duration::from_secs(1), + ..Limits::default() + }; + let mut t = Table::new(limits); + let now = Instant::now(); + let (id, _, _) = t.open(addr(1)); + t.ended(addr(1), id, Some(now)); + assert!(matches!(t.route(addr(1), now), Route::Backoff)); + assert!(matches!( + t.route(addr(1), now + Duration::from_millis(999)), + Route::Backoff + )); + assert!(matches!( + t.route(addr(1), now + Duration::from_secs(1)), + Route::Open + )); + let (_, _a, _ra) = t.open(addr(2)); + let (_, _b, _rb) = t.open(addr(3)); + assert!(matches!(t.route(addr(4), now), Route::Full)); + // One that ended frees its place. + drop((_b, _rb)); + assert!(matches!(t.route(addr(4), now), Route::Open)); + } + + async fn echo() -> (SocketAddr, tokio::task::JoinHandle<()>) { + let s = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let at = s.local_addr().unwrap(); + let h = tokio::spawn(async move { + let mut buf = vec![0u8; BUFFER]; + while let Ok((n, from)) = s.recv_from(&mut buf).await { + let mut reply = b"echo:".to_vec(); + reply.extend_from_slice(&buf[..n]); + let _ = s.send_to(&reply, from).await; + } + }); + (at, h) + } + + /// A relay whose tunnels are in-process pipes to [`serve`] towards + /// `target`: both ends of a session without HTTP between. + async fn relay_to( + target: SocketAddr, + limits: Limits, + node_idle: Duration, + ) -> ( + SocketAddr, + Arc, + tokio::task::JoinHandle<()>, + ) { + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let at = socket.local_addr().unwrap(); + let opened = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = opened.clone(); + let open = move || { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + async move { + let (a, b) = tokio::io::duplex(1 << 17); + let to = connect(&target.to_string()) + .await + .map_err(|e| e.to_string())?; + tokio::spawn(serve(b, to, node_idle)); + Ok(Opened { + stream: a, + closed: None, + }) + } + }; + let h = tokio::spawn(relay(socket, open, limits, Arc::new(|_| {}))); + (at, opened, h) + } + + async fn ask(client: &UdpSocket, to: SocketAddr, what: &[u8]) -> Vec { + client.send_to(what, to).await.unwrap(); + let mut buf = vec![0u8; BUFFER]; + let (n, _) = tokio::time::timeout(Duration::from_secs(5), client.recv_from(&mut buf)) + .await + .expect("an answer") + .unwrap(); + buf.truncate(n); + buf + } + + #[tokio::test] + async fn a_session_carries_datagrams_both_ways_and_ends_when_idle() { + let (target, _echo) = echo().await; + let limits = Limits { + idle: Duration::from_millis(300), + ..Limits::default() + }; + let (relay_at, opened, relay) = relay_to(target, limits, Duration::from_secs(60)).await; + let a = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let b = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + assert_eq!(ask(&a, relay_at, b"one").await, b"echo:one"); + assert_eq!(ask(&a, relay_at, b"two").await, b"echo:two"); + let big = vec![b'x'; 60_000]; + assert_eq!(ask(&a, relay_at, &big).await.len(), 60_005, "whole"); + assert_eq!( + opened.load(std::sync::atomic::Ordering::SeqCst), + 1, + "one session" + ); + assert_eq!(ask(&b, relay_at, b"three").await, b"echo:three"); + assert_eq!( + opened.load(std::sync::atomic::Ordering::SeqCst), + 2, + "a client each" + ); + // Idle for longer than the timeout: the next datagram opens anew. + tokio::time::sleep(Duration::from_millis(600)).await; + assert_eq!(ask(&a, relay_at, b"four").await, b"echo:four"); + assert_eq!(opened.load(std::sync::atomic::Ordering::SeqCst), 3); + relay.abort(); + } + + #[tokio::test] + async fn the_node_side_ends_an_idle_session_and_the_next_datagram_reopens() { + let (target, _echo) = echo().await; + let (relay_at, opened, relay) = + relay_to(target, Limits::default(), Duration::from_millis(200)).await; + let a = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + assert_eq!(ask(&a, relay_at, b"one").await, b"echo:one"); + // The tunnel ends from the other side (a lost tunnel looks alike). + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(ask(&a, relay_at, b"two").await, b"echo:two"); + assert_eq!(opened.load(std::sync::atomic::Ordering::SeqCst), 2); + relay.abort(); + } + + #[tokio::test] + async fn a_tunnel_that_does_not_open_drops_and_is_tried_again_later() { + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let at = socket.local_addr().unwrap(); + let tries = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = tries.clone(); + let open = move || { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + async { Err::, _>("the container does not run".into()) } + }; + let said = Arc::new(Mutex::new(Vec::new())); + let s2 = said.clone(); + let limits = Limits { + retry: Duration::from_millis(400), + ..Limits::default() + }; + let relay = tokio::spawn(relay( + socket, + open, + limits, + Arc::new(move |e| s2.lock().unwrap().push(e)), + )); + let c = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + for _ in 0..5 { + c.send_to(b"x", at).await.unwrap(); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!( + tries.load(std::sync::atomic::Ordering::SeqCst), + 1, + "no hold, no storm" + ); + tokio::time::sleep(Duration::from_millis(500)).await; + c.send_to(b"x", at).await.unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(tries.load(std::sync::atomic::Ordering::SeqCst), 2); + assert_eq!(said.lock().unwrap()[0], "the container does not run"); + relay.abort(); + } + + #[tokio::test] + async fn a_relay_dropped_lets_its_port_go() { + let (target, _echo) = echo().await; + let (relay_at, _, relay) = + relay_to(target, Limits::default(), Duration::from_secs(60)).await; + let a = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + assert_eq!(ask(&a, relay_at, b"one").await, b"echo:one"); + relay.abort(); + let until = Instant::now() + Duration::from_secs(5); + while UdpSocket::bind(relay_at).await.is_err() { + assert!(Instant::now() < until, "the port stays held by a session"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + } +} diff --git a/crates/devstack-node/src/lanerun.rs b/crates/devstack-node/src/lanerun.rs index 02746f2f..04223a97 100644 --- a/crates/devstack-node/src/lanerun.rs +++ b/crates/devstack-node/src/lanerun.rs @@ -67,6 +67,9 @@ pub struct LaneRun { pub port_offset: u16, /// The profile it runs with (ADR-0041, `DEVSTACK_PROFILE`). pub profile: Option, + /// Its requester relays UDP ports (ADR-0056): the lane's daemon is told, + /// and the start answers with them. + pub relay_udp: bool, /// The memory limit of each of its containers (ADR-0033), bytes. pub memory_limit: Option, /// Their CPU limit, cores. @@ -88,6 +91,8 @@ pub struct DaemonAddr { /// (the Compose files' host ports moved by the lane's offset): the /// requester forwards them like the services' (ADR-0029 point 4). pub infra_ports: Vec, + /// Those published as UDP, when the requester relays them (ADR-0056). + pub infra_udp_ports: Vec, } /// A lane whose daemon answers: where it is, and what is left of its start. @@ -169,13 +174,16 @@ impl InfraUp { /// addresses of its ports as the stack file's Compose files have them /// (`model`, read before the overlay that publishes nothing): the lane /// container reaches every target port by the service's name. And the ports -/// the requester forwards: where a local lane would publish them. +/// the requester forwards, TCP and (`relay_udp`, ADR-0056) UDP: where a +/// local lane would publish them. fn initial_infra( groups: &[(String, Group, Model)], port_offset: u16, -) -> (serde_json::Value, Vec) { + relay_udp: bool, +) -> (serde_json::Value, Vec, Vec) { let mut infra = BTreeMap::new(); let mut infra_ports = Vec::new(); + let mut udp_ports = Vec::new(); for (name, g, model) in groups { let services: BTreeMap = model .services @@ -199,15 +207,17 @@ fn initial_infra( Some((port_key(p), host.checked_add(port_offset)?)) }) .collect(); - // The requester forwards TCP only (#192): a UDP port stays - // listed, for the daemon to say it is not forwarded. + // TCP is forwarded, UDP relayed when the requester asked + // (ADR-0056); every port stays listed, for the daemon to + // say which are not forwarded (#192). if starts { - infra_ports.extend( - published - .iter() - .filter(|(key, _)| !key.contains('/')) - .map(|(_, host)| *host), - ); + for (key, host) in &published { + match key.split_once('/') { + None => infra_ports.push(*host), + Some((_, "udp")) if relay_udp => udp_ports.push(*host), + Some(_) => {} + } + } } ( svc.clone(), @@ -232,7 +242,13 @@ fn initial_infra( } infra_ports.sort_unstable(); infra_ports.dedup(); - (serde_json::json!({ "groups": infra }), infra_ports) + udp_ports.sort_unstable(); + udp_ports.dedup(); + let mut file = serde_json::json!({ "groups": infra }); + if relay_udp { + file["udp"] = true.into(); + } + (file, infra_ports, udp_ports) } /// A Compose port without a protocol, or `tcp`, is TCP. @@ -755,7 +771,8 @@ impl LaneRun { // The lane's daemon starts before its containers do (#164): it // reads them as created, and waits for each group as the agent // brings it up after answering ([`InfraUp::run`]). - let (infra, infra_ports) = initial_infra(&groups, self.port_offset); + let (infra, infra_ports, infra_udp_ports) = + initial_infra(&groups, self.port_offset, self.relay_udp); let io = |p: &str| { let p = src.join(p); move |e| RunError::Io(p, e) @@ -883,6 +900,7 @@ impl LaneRun { addr, token, infra_ports, + infra_udp_ports, }, infra: InfraUp { groups: groups.into_iter().map(|(n, g, _)| (n, g)).collect(), @@ -943,6 +961,7 @@ impl LaneRun { addr: self.address(&networks, agent)?, token: self.wait_token(Duration::from_secs(5))?, infra_ports: Vec::new(), + infra_udp_ports: Vec::new(), }) } @@ -1140,7 +1159,8 @@ mod tests { services: vec!["db".into(), "cache".into()], dir: PathBuf::from("/compose"), }; - let (infra, ports) = initial_infra(&[("app".into(), g, model)], 100); + let (infra, ports, udp) = initial_infra(&[("app".into(), g, model)], 100, true); + assert!(udp.is_empty()); let app = &infra["groups"]["app"]; assert_eq!(app["state"], crate::laneinfra::CREATED); assert_eq!(app["project"], "shop-ab12"); @@ -1176,7 +1196,10 @@ mod tests { services: Vec::new(), dir: PathBuf::from("/compose"), }; - let (infra, ports) = initial_infra(&[("app".into(), g, model)], 100); + let groups = [("app".to_string(), g, model)]; + let (infra, ports, udp) = initial_infra(&groups, 100, false); + assert!(udp.is_empty(), "an older requester did not ask"); + assert!(infra.get("udp").is_none()); let dns = &infra["groups"]["app"]["services"]["dns"]; assert_eq!(dns["ports"]["53"], "dns:53"); assert_eq!(dns["ports"]["53/udp"], "dns:53", "not folded into 53/tcp"); @@ -1186,6 +1209,11 @@ mod tests { let voice = &infra["groups"]["app"]["services"]["voice"]; assert_eq!(voice["published"]["5060/udp"], 5160); assert_eq!(ports, [5453, 8180], "TCP only, each once"); + // Asked for (ADR-0056): the UDP ones beside, and the daemon told. + let (infra, ports, udp) = initial_infra(&groups, 100, true); + assert_eq!(ports, [5453, 8180]); + assert_eq!(udp, [5160, 5453]); + assert_eq!(infra["udp"], true); } #[test] diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index bbbd8ad1..1c9b2e20 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -1013,6 +1013,7 @@ impl Inner { display_root: None, port_offset: 0, profile: None, + relay_udp: false, memory_limit: None, cpu_limit: None, network: crate::policy::Network::Lan, @@ -1928,6 +1929,11 @@ pub struct Start { /// The profile it runs with (ADR-0041); absent: none. #[serde(default, skip_serializing_if = "Option::is_none")] pub profile: Option, + /// The requester relays the lane's UDP ports (ADR-0056): the lane's + /// daemon is told, and the lane's state names them. An older requester + /// does not send it, an older agent does not read it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub relay_udp: bool, } fn default_stack_file() -> String { @@ -1952,6 +1958,10 @@ pub struct LaneState { /// requester's machine. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub infra_ports: Vec, + /// Those published as UDP, when the start asked for them (`relay_udp`, + /// ADR-0056). An older agent does not send it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub infra_udp_ports: Vec, /// The phases of its last start that are over, in order, each with how /// long it took, measured here (the requester polls, so it would see a /// phase only to within its polling interval, or not at all). A failed @@ -1984,9 +1994,17 @@ async fn start( format!("{} cannot run lanes: its agent is no Linux build", s.name), )); }; - let (stack_file, display_root, port_offset, profile) = body.map_or_else( - || (default_stack_file(), None, 0, None), - |Json(b)| (b.stack_file, b.display_root, b.port_offset, b.profile), + let (stack_file, display_root, port_offset, profile, relay_udp) = body.map_or_else( + || (default_stack_file(), None, 0, None, false), + |Json(b)| { + ( + b.stack_file, + b.display_root, + b.port_offset, + b.profile, + b.relay_udp, + ) + }, ); if let Some(p) = &profile && !p @@ -2068,6 +2086,7 @@ async fn start( run.display_root = display_root; run.port_offset = port_offset; run.profile = profile; + run.relay_udp = relay_udp; let policies = s2.policies(); let all: Vec<&crate::policy::NodePolicy> = policies.iter().collect(); if let Some(p) = crate::policy::NodePolicy::strictest(&all) { @@ -2248,7 +2267,7 @@ async fn lane_state( .lock() .unwrap() .get(&id) - .map(|d| d.infra_ports.clone()); + .map(|d| (d.infra_ports.clone(), d.infra_udp_ports.clone())); let s2 = s.clone(); let running = tokio::task::spawn_blocking(move || s2.run(&l).running()) .await @@ -2257,7 +2276,11 @@ async fn lane_state( started: true, running, ready: running && infra_ports.is_some(), - infra_ports: infra_ports.unwrap_or_default(), + infra_udp_ports: infra_ports + .as_ref() + .map(|p| p.1.clone()) + .unwrap_or_default(), + infra_ports: infra_ports.map(|p| p.0).unwrap_or_default(), phases, ..LaneState::default() })) diff --git a/crates/devstack-node/src/nodeclient.rs b/crates/devstack-node/src/nodeclient.rs index 0abb0adb..c9cc322c 100644 --- a/crates/devstack-node/src/nodeclient.rs +++ b/crates/devstack-node/src/nodeclient.rs @@ -174,7 +174,9 @@ impl NodeClient { /// images); this waits until the lane is ready or its start failed, at /// most `within`, and tells `phase` every new step and `over` every step /// that is over, with how long it took as the node measured it (an - /// older agent tells no times). + /// older agent tells no times). `relay_udp`: this machine relays the + /// lane's UDP ports (ADR-0056); the state names them, unless the node + /// is older. #[allow(clippy::too_many_arguments)] pub async fn start( &self, @@ -183,6 +185,7 @@ impl NodeClient { display_root: Option<&str>, port_offset: u16, profile: Option<&str>, + relay_udp: bool, within: std::time::Duration, phase: &(dyn Fn(&str) + Send + Sync), over: &(dyn Fn(&str, u64) + Send + Sync), @@ -196,6 +199,7 @@ impl NodeClient { display_root: display_root.map(str::to_string), port_offset, profile: profile.map(str::to_string), + relay_udp, }), ) .await?; diff --git a/crates/devstack-node/tests/lanerun.rs b/crates/devstack-node/tests/lanerun.rs index 7d46fcba..2724b8f8 100644 --- a/crates/devstack-node/tests/lanerun.rs +++ b/crates/devstack-node/tests/lanerun.rs @@ -79,6 +79,7 @@ volumes: display_root: None, port_offset: 0, profile: None, + relay_udp: false, memory_limit: Some(256 << 20), cpu_limit: None, network: Network::Lan, diff --git a/crates/devstack/Cargo.toml b/crates/devstack/Cargo.toml index 1136a688..f5c5a08f 100644 --- a/crates/devstack/Cargo.toml +++ b/crates/devstack/Cargo.toml @@ -28,6 +28,10 @@ sha2.workspace = true tokio.workspace = true [dev-dependencies] +bytes.workspace = true +http-body-util.workspace = true +hyper.workspace = true +hyper-util.workspace = true serde_json.workspace = true tempfile.workspace = true ureq.workspace = true diff --git a/crates/devstack/src/client.rs b/crates/devstack/src/client.rs index 7563df6a..91a68c79 100644 --- a/crates/devstack/src/client.rs +++ b/crates/devstack/src/client.rs @@ -1362,7 +1362,8 @@ pub fn lane_list(stack_file: &Path) -> Result<()> { if let Some(w) = l["node_warning"].as_str() { troubles.push(format!("{name}: {w}")); } - if let Some(t) = not_forwarded_line(&l["not_forwarded"]) { + if let Some(t) = not_forwarded_line(&l["not_forwarded"], l["not_forwarded_reason"].as_str()) + { troubles.push(format!("{name}: {t}")); } println!( @@ -1387,8 +1388,9 @@ pub fn lane_list(stack_file: &Path) -> Result<()> { } /// A lane's `not_forwarded` (`["5353/udp"]`) as a line: `UDP port 5353 is -/// not forwarded ...`; `None` when there is none (#192). -fn not_forwarded_line(ports: &Value) -> Option { +/// not forwarded ...`, with the daemon's reason (ADR-0056); `None` when +/// there is none (#192). +fn not_forwarded_line(ports: &Value, reason: Option<&str>) -> Option { let ports: Vec<(String, String)> = ports .as_array()? .iter() @@ -1408,8 +1410,14 @@ fn not_forwarded_line(ports: &Value) -> Option { format!("ports {}", each.join(", ")) }; let are = if ports.len() == 1 { "is" } else { "are" }; + // A daemon before ADR-0056 gives no reason: it relays no UDP. + let reason = reason.unwrap_or(if ports.iter().any(|(p, _)| p == "UDP") { + "an older devstack forwards TCP only" + } else { + "devstack forwards TCP and UDP only" + }); Some(format!( - "{listed} {are} not forwarded to this machine (devstack forwards TCP only)" + "{listed} {are} not forwarded to this machine ({reason})" )) } @@ -2349,24 +2357,34 @@ data: {\"type\":\"line\",\"text\":\"c\"}\n\n"; #[test] fn a_lanes_ports_not_forwarded_are_said() { - let line = |v: Value| not_forwarded_line(&v); + let line = |v: Value| not_forwarded_line(&v, None); assert_eq!(line(serde_json::json!(null)), None, "an older daemon"); assert_eq!(line(serde_json::json!([])), None); assert_eq!( line(serde_json::json!(["5353/udp"])).as_deref(), - Some("UDP port 5353 is not forwarded to this machine (devstack forwards TCP only)") + Some( + "UDP port 5353 is not forwarded to this machine (an older devstack forwards TCP only)" + ) ); assert_eq!( line(serde_json::json!(["5060/udp", "5353/udp"])).as_deref(), Some( - "UDP ports 5060, 5353 are not forwarded to this machine (devstack forwards TCP only)" + "UDP ports 5060, 5353 are not forwarded to this machine (an older devstack forwards TCP only)" ) ); assert_eq!( - line(serde_json::json!(["5353/udp", "9000/sctp"])).as_deref(), + line(serde_json::json!(["9000/sctp"])).as_deref(), Some( - "ports UDP 5353, SCTP 9000 are not forwarded to this machine (devstack forwards TCP only)" + "SCTP port 9000 is not forwarded to this machine (devstack forwards TCP and UDP only)" ) ); + // The daemon's reason (ADR-0056): the node is too old to relay. + let why = "the node build-1 runs devstack 0.19.0, which forwards TCP only: devstack 0.20.0 or later there relays UDP"; + assert_eq!( + not_forwarded_line(&serde_json::json!(["5353/udp", "9000/sctp"]), Some(why)), + Some(format!( + "ports UDP 5353, SCTP 9000 are not forwarded to this machine ({why})" + )) + ); } } diff --git a/crates/devstack/src/poolcmd.rs b/crates/devstack/src/poolcmd.rs index fb54fda9..6b3f09c4 100644 --- a/crates/devstack/src/poolcmd.rs +++ b/crates/devstack/src/poolcmd.rs @@ -754,6 +754,7 @@ pub fn run_lane(file: &Path, on: &str, lane: &str, keep: bool) -> Result<()> { None, 0, None, + false, Duration::from_secs(1800), &|p| println!(" {p}"), &|p, ms| println!(" ({p}: {:.1} s)", ms as f64 / 1000.0), diff --git a/crates/devstack/tests/udp_relay.rs b/crates/devstack/tests/udp_relay.rs new file mode 100644 index 00000000..46b25160 --- /dev/null +++ b/crates/devstack/tests/udp_relay.rs @@ -0,0 +1,203 @@ +//! A UDP port of a lane on a node, relayed (ADR-0056), end to end at the +//! tunnel: this machine's relay ([`devstack_daemon::udprelay::relay`]) opens +//! a session as an HTTP upgrade (`devstack-udp`) on a real lane daemon's +//! `/v1/tunnel/{port}`, which sends the datagrams to the container's port +//! and the answers back. The lane daemon reads its containers from the +//! node agent's file (`DEVSTACK_EXTERNAL_INFRA`), here naming an echo +//! socket of this test instead of a container: no Docker and no node, so it +//! runs on every OS. Between the two the node agent splices any upgrade +//! without reading it (`pass` in `devstack-node`), as for TCP tunnels. + +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::net::UdpSocket; + +const BIN: &str = env!("CARGO_BIN_EXE_devstack"); + +struct Kill(Child); + +impl Drop for Kill { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +/// The lane daemon's API port and token, once it answers. +fn daemon(repo: &Path, home: &Path) -> (u16, String) { + let until = Instant::now() + Duration::from_secs(60); + loop { + let info = std::fs::read_to_string(repo.join(".devstack/daemon.json")).ok(); + let token = std::fs::read_to_string(home.join("devstack/token")).ok(); + if let (Some(info), Some(token)) = (info, token) { + let v: serde_json::Value = serde_json::from_str(&info).unwrap_or_default(); + if let Some(port) = v["port"].as_u64() + && std::net::TcpStream::connect(("127.0.0.1", port as u16)).is_ok() + { + return (port as u16, token.trim().to_string()); + } + } + assert!(Instant::now() < until, "the lane daemon does not answer"); + std::thread::sleep(Duration::from_millis(100)); + } +} + +/// `GET /v1/tunnel/{port}` with `Upgrade: protocol` on the daemon: the +/// upgraded stream, or the status and body it answered instead. +async fn open( + api: u16, + token: &str, + port: u16, + protocol: &str, +) -> Result, String> { + let tcp = tokio::net::TcpStream::connect(("127.0.0.1", api)) + .await + .map_err(|e| e.to_string())?; + let (mut send, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(tcp)) + .await + .map_err(|e| e.to_string())?; + tokio::spawn(conn.with_upgrades()); + let req = hyper::Request::get(format!("/v1/tunnel/{port}")) + .header(hyper::header::HOST, format!("127.0.0.1:{api}")) + .header(hyper::header::AUTHORIZATION, format!("Bearer {token}")) + .header(hyper::header::CONNECTION, "upgrade") + .header(hyper::header::UPGRADE, protocol) + .body(http_body_util::Empty::::new()) + .unwrap(); + let mut res = send.send_request(req).await.map_err(|e| e.to_string())?; + if res.status() != hyper::StatusCode::SWITCHING_PROTOCOLS { + use http_body_util::BodyExt; + let status = res.status(); + let body = res.into_body().collect().await.unwrap().to_bytes(); + return Err(format!("{status} {}", String::from_utf8_lossy(&body))); + } + let up = hyper::upgrade::on(&mut res) + .await + .map_err(|e| e.to_string())?; + Ok(hyper_util::rt::TokioIo::new(up)) +} + +async fn ask(client: &UdpSocket, to: std::net::SocketAddr, what: &[u8]) -> Vec { + client.send_to(what, to).await.unwrap(); + let mut buf = vec![0u8; 1 << 16]; + let (n, _) = tokio::time::timeout(Duration::from_secs(10), client.recv_from(&mut buf)) + .await + .expect("an answer through the tunnel") + .unwrap(); + buf.truncate(n); + buf +} + +#[test] +fn a_datagram_goes_through_a_lanes_tunnel_and_its_answer_comes_back() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let (repo, home) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + + // The "container": an echo socket, at the address the lane's network + // would give it. + let echo = rt.block_on(UdpSocket::bind("127.0.0.1:0")).unwrap(); + let echo_at = echo.local_addr().unwrap(); + rt.spawn(async move { + let mut buf = vec![0u8; 1 << 16]; + while let Ok((n, from)) = echo.recv_from(&mut buf).await { + let mut reply = b"echo:".to_vec(); + reply.extend_from_slice(&buf[..n]); + let _ = echo.send_to(&reply, from).await; + } + }); + + // What the node agent writes for the lane daemon: `dns` publishes 53/udp + // on 5453 for the developer, 53/tcp beside it and 8080 on 8180; the + // requester relays UDP (`udp`). + let file = repo.path().join("external-infra.json"); + std::fs::write( + &file, + serde_json::json!({ + "udp": true, + "groups": { "app": { "project": "udp-it", "state": "up", "services": { "dns": { + "ports": { "53": "127.0.0.1:9", "53/udp": echo_at.to_string(), "8080": "127.0.0.1:9" }, + "published": { "53": 5453, "53/udp": 5453, "8080": 8180 }, + "state": "running", "health": "" + }}}} + }) + .to_string(), + ) + .unwrap(); + let stack = repo.path().join("devstack.toml"); + std::fs::write(&stack, "version = 1\n[stack]\nname = \"udp-it\"\n").unwrap(); + let _daemon = Kill( + Command::new(BIN) + .args(["daemon", "-f"]) + .arg(&stack) + .current_dir(repo.path()) + .env("LOCALAPPDATA", home.path()) + .env("XDG_STATE_HOME", home.path()) + .env("DEVSTACK_EXTERNAL_INFRA", &file) + .env("DEVSTACK_NO_HUB", "1") + .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(), + ); + let (api, token) = daemon(repo.path(), home.path()); + + rt.block_on(async { + // Only a container's UDP port is a UDP tunnel: not a TCP one, not + // a port of nothing. + for port in [8180, 5454] { + match open(api, &token, port, devstack_daemon::udprelay::PROTOCOL).await { + Err(e) => assert!(e.starts_with("403"), "{port}: {e}"), + Ok(_) => panic!("{port} is no UDP port of the lane"), + } + } + + // This machine's relay, on a port of its own, its sessions opened + // on the lane daemon's tunnel. + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let relay_at = socket.local_addr().unwrap(); + let opened = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (count, token2) = (opened.clone(), token.clone()); + let opener = move || { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let token = token2.clone(); + async move { + let stream = open(api, &token, 5453, devstack_daemon::udprelay::PROTOCOL).await?; + Ok(devstack_daemon::udprelay::Opened { + stream, + closed: None, + }) + } + }; + let relay = tokio::spawn(devstack_daemon::udprelay::relay( + socket, + opener, + devstack_daemon::udprelay::Limits::default(), + Arc::new(|e| panic!("a tunnel did not open: {e}")), + )); + + let a = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let b = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + assert_eq!(ask(&a, relay_at, b"who is db?").await, b"echo:who is db?"); + assert_eq!(ask(&a, relay_at, b"again").await, b"echo:again"); + // A datagram larger than any link's MTU arrives whole. + let big = vec![b'x'; 32_000]; + let back = ask(&a, relay_at, &big).await; + assert_eq!((back.len(), &back[..5]), (32_005, &b"echo:"[..])); + assert_eq!( + opened.load(std::sync::atomic::Ordering::SeqCst), + 1, + "one client, one session" + ); + assert_eq!(ask(&b, relay_at, b"me too").await, b"echo:me too"); + assert_eq!( + opened.load(std::sync::atomic::Ordering::SeqCst), + 2, + "a session per client" + ); + relay.abort(); + }); +} diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 39f01bb6..8bb82a15 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -227,7 +227,7 @@ type InfraView = { group: string; project: string; containers: ContainerView[]; type ContainerView = { service: string; name: string; state: string; health: string; exit_code: number; ports: string[]; urls: string[]; // see below unreachable: string[]; // published ports Docker no longer forwards - not_forwarded?: string[]; // a lane on a node: its published ports of another protocol than TCP (`5353/udp`), not forwarded to the developer's machine (#192) + not_forwarded?: string[]; // a lane on a node: its published ports not forwarded to the developer's machine (`5353/udp`): another protocol than TCP and UDP (#192), UDP too unless the requester relays it (ADR-0056) held?: { port: number; upstream: number | null; active: number; served: number }[]; // its fixed ports devstack holds (`main_ports`, ADR-0048): `upstream` the container's instance port, or the lane's port while a lane serves the main ports; `ports` then names the fixed port managed: boolean }; // the group starts it (in its `services`); false: another container of the project @@ -247,7 +247,8 @@ type LaneView = { shared_with?: string[]; // ADR-0035: member ids, tags, `*` node_error?: string; // a sync or renewal that failed lately node_warning?: string; // its node or the coordinator runs another devstack, or does not say (ADR-0031 point 8) - not_forwarded?: string[]; // its containers' published ports not forwarded here (`5353/udp`): devstack forwards TCP only (#192) + not_forwarded?: string[]; // its containers' published ports not forwarded here (`5353/udp`): UDP its node does not relay (ADR-0056), another protocol than TCP and UDP (#192) + not_forwarded_reason?: string; // why: the node's devstack forwards TCP only (with its release), the lane was started by an older devstack here, or the protocol is neither TCP nor UDP moving?: { kind: "start" | "move"; to: string; step: number; steps: number; what: string; since: number; phases?: { phase: string; ms: number }[]; phase_since?: number; error?: string; failed_at?: number }; // a start on a node or a move under way, or failed lately @@ -313,7 +314,7 @@ type UsageReport = { | `POST /v1/infra/check` | probe every ready container's published ports from this machine: `[{group, service, ports}]` that accept and close at once on three probes a second apart (Docker lost the port forward, or nothing listens inside); recorded as `ContainerView.unreachable`. The daemon also judges each container once it has been ready for 20 s, and probes a port found lost again every few seconds until it answers; a restart from devstack clears the verdict. A service with `after = ["compose.."]` restarts such a container before it starts, if it has been ready for 20 s and was not restarted for this in the last 10 minutes | | `GET /v1/infra/{group}/{service}/logs?tail=200&grep=&since=` | text, a container's output (`docker compose logs`), stdout and stderr merged by Docker's timestamps, each line starting with one; `since` as Docker takes it (`30m`); `502` when Docker fails. `/v1/services/{name}/logs` answers the same for a name that is no service but exactly one Compose service | | `GET /v1/infra/{group}/{service}/logs/stream?tail=500` | SSE (`tail` at most 5000): `{"type":"line","text":"..."}` per line of `docker compose logs --follow` (timestamped), the same events as a service's log stream; in a lane its own container, the main tree's for a `shared` one | -| `GET /v1/lanes` | JSON, the lanes: the repository's other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md)), `[{name, path, branch, number, port_offset, active, owns_main, running, services, containers_running, containers, node?, pool?, shared_with?, profile?, node_error?, node_warning?, not_forwarded?}]`; `active`: started; `containers_running`/`containers`: its Compose containers devstack starts that run, and all (a stack of containers only shows by them that it runs); `node`: the node of the pool it runs on (absent: this machine), `pool`: that node's pool, `shared_with`: whom it is shared with (member ids, tags, `*`; absent: nobody), `profile`: the profile it runs with, `node_error`: what goes wrong with it now (a sync, a renewal, a port that cannot be forwarded here), each until it works again, several joined by `; `, `node_warning`: the node or the coordinator runs another devstack than this machine, or does not say which (from the lease on, so while it starts too; [ADR-0031](adr/0031-a-coordinator-places-lanes.md) point 8); `not_forwarded`: its containers' published ports of another protocol than TCP (`5353/udp`), which run on the node but are not forwarded here (devstack forwards TCP only, #192; a lane daemon of an older devstack does not say); `moving`: `{kind: start|move, to, step, steps, what, since, phases, phase_since, error?, failed_at?}` (`phases`: `[{phase, ms}]` over so far, `phase_since`: when the current one began) while a start on a node or a move runs, and for ten minutes after one failed; `removing`: `true` while the lane of a worktree that is gone is stopped and its data removed (it leaves the list after); `main_stack_file`: `true` while its worktree has no stack file at the main one's path, so it runs with the main working tree's, here and on a node ([ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md)) | +| `GET /v1/lanes` | JSON, the lanes: the repository's other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md)), `[{name, path, branch, number, port_offset, active, owns_main, running, services, containers_running, containers, node?, pool?, shared_with?, profile?, node_error?, node_warning?, not_forwarded?}]`; `active`: started; `containers_running`/`containers`: its Compose containers devstack starts that run, and all (a stack of containers only shows by them that it runs); `node`: the node of the pool it runs on (absent: this machine), `pool`: that node's pool, `shared_with`: whom it is shared with (member ids, tags, `*`; absent: nobody), `profile`: the profile it runs with, `node_error`: what goes wrong with it now (a sync, a renewal, a port that cannot be forwarded here), each until it works again, several joined by `; `, `node_warning`: the node or the coordinator runs another devstack than this machine, or does not say which (from the lease on, so while it starts too; [ADR-0031](adr/0031-a-coordinator-places-lanes.md) point 8); `not_forwarded`: its containers' published ports that run on the node but are not forwarded here (`5353/udp`): UDP ports a node older than 0.20.0 does not relay ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)), ports of another protocol than TCP and UDP (#192; a lane daemon of an older devstack does not say), `not_forwarded_reason`: why; `moving`: `{kind: start|move, to, step, steps, what, since, phases, phase_since, error?, failed_at?}` (`phases`: `[{phase, ms}]` over so far, `phase_since`: when the current one began) while a start on a node or a move runs, and for ten minutes after one failed; `removing`: `true` while the lane of a worktree that is gone is stopped and its data removed (it leaves the list after); `main_stack_file`: `true` while its worktree has no stack file at the main one's path, so it runs with the main working tree's, here and on a node ([ADR-0055](adr/0055-a-lane-without-a-stack-file-says-so-and-can-be-given-one.md)) | | `POST /v1/lanes` | `{"path", "infra"?, "workers"?, "force"?, "on"?, "profile"?}`: start the lane of that worktree, with `profile` with that profile of its stack file ([ADR-0041](adr/0041-a-profile-says-how-a-lane-runs-for-a-purpose.md); `409` when the worktree's stack file has no such profile or it does not apply); with `on` (a node's name or member id, or `pool` for the coordinator to choose; in another pool than the default one `:`, or `` for its coordinator to choose, [ADR-0034](adr/0034-a-machine-can-belong-to-several-pools.md)) on that node of the pool instead, leased, synced and started there, its API passed through under `/v1/lanes/{lane}/v1/...` ([ADR-0025](adr/0025-a-lane-can-run-on-another-node.md)) (what `devstack up` in it does; `infra` starts the main tree's `shared` Compose services if needed, the lane's own containers start with its `up`; `workers` runs its background workers; `force` skips the memory check, which otherwise answers `409` with what the lane needs and what is free, ADR-0030), then `/v1/lanes/{lane}/v1/up` starts its services and its containers. `201` with its entry. With `on`: `202` with its entry once the lane is leased and admitted by the node; its sync and its start there (minutes on a first start: images pulled and built, containers created) go on in the background, shown as the entry's `moving` (`kind: "start"`, in `lanes` events and here). It runs there once `moving` is gone and `active` is `true`, which is once the lane's daemon answers there: its containers come up after, under it (#164; a node of an earlier release answers once they are healthy), and show as `created`, then `starting` and `healthy` in its `InfraView`s (then call `/v1/up`, which starts its services once their infrastructure is up); it failed when `moving` carries `error` (for ten minutes, until the lane stops, the main tree's `/v1/down` or a start of it here). What can be told at once is refused at once: no such worktree, a lane that runs elsewhere, no lease (`409` with the reason: no node, the coordinator or the node refuses, a node with another pool protocol). The same start asked again while it goes on answers `202` too; `201` when the lane runs on that node already. Up to 0.10.1 a start on a node answered `201` only when done. Worktrees are git's: there is no route that creates or removes one | | `POST /v1/lanes/{lane}/share` | `{"with"}`: share a lane on a node with others in its pool: member ids, tags, `*` for every member; `[]` for nobody ([ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md)). They open its services and view it, read only ([ADR-0040](adr/0040-a-shared-lane-can-be-watched-like-ones-own.md)); `view`, a separate list up to 0.11.1, is ignored. Kept per lane, told the coordinator while it runs on a node. Answers with the lanes (`LaneView.shared_with`) | | `POST /v1/lanes/{lane}/reset` | a stopped lane's data goes, here and on the nodes it ran on (ADR-0038): `[Pruned]` (`{place, lane, bytes, why, removed, error}`; `removed: false` with `error` where it did not go, this machine's containers too); `409` while it runs | @@ -341,6 +342,7 @@ type UsageReport = { | `GET /v1/runs/{id}/log` | text, a command run's output so far (the last 20 000 lines) | | `POST /v1/runs/{id}/cancel` | `202`; the run stops: its `exec` step's process tree is killed, its `run` step's job stopped, no further step starts; it ends `failed` with error `cancelled`. `409` when it is not running, `404` for no such run | | `GET /v1/tunnel/{port}` with `Upgrade: devstack-tcp` | a raw TCP connection to that port on the daemon's machine (ADR-0029 point 4): a service's port on its loopback, or a lane's container port on the lane's network; other ports `403`. How the requester reaches the services of its lane on a node: each port it forwards here connects, through the node agent, to the lane daemon's tunnel there | +| `GET /v1/tunnel/{port}` with `Upgrade: devstack-udp` | a UDP session to the lane's container published on `port` as UDP ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)): each datagram a frame, its length as two bytes big-endian, then its bytes, both ways; the daemon sends them from a socket of the session's own. Other ports `403`, a container that does not resolve yet `502`. The requester opens one per client address of a UDP port it relays, and ends it after 60 s without a datagram either way | | `POST /v1/services/{name}/start` \| `stop` \| `restart` \| `rebuild` \| `promote` \| `rollback` | `200 StackView`, or `409 {"error": "..."}` (e.g. compiler errors; the running instance stays). `rebuild` is `restart` that builds even when an artifact for the same inputs exists (`devstack restart --rebuild`; the build gets the id `-`). A `stop` ends a start in progress (a build, a health wait, a job) at once. For a name that is no service but a group, `start`/`stop`/`restart` act on the group; for a name that is neither but a Compose service (`.`, the member form `compose..`, or `` when exactly one compose group lists it in `services`) they act on that container as `/v1/infra/{group}/{service}/…` does, and answer `200 StackView`. `404` for a name that is none of these. `hot-reload-on` / `hot-reload-off` switch a service with `hot_reload` in the stack file into and out of hot-reload mode (`ServiceView.hot_reload`, `hot_reload_available`) | | `POST /v1/groups/{name}/start` \| `stop` \| `restart` | every member service of the group: start in member order, stop in reverse, restart (build) at the same time; `restart` also restarts container members, commands are left out. `200 StackView`, or `409` naming each member that failed (the others ran) | | `POST /v1/infra/{group}/{service}/{start\|stop\|restart}` | `204`; one container (in a lane its own; a `shared` one: `409`). `{service}` is the Compose service name, as `ContainerView.service` gives it, never the container name (`container_name:`). The routes accept every container the view shows: one the group does not start (`managed: false`: started by hand, of a profile, left from an earlier stack file) can be stopped (`docker stop` by its name), `start` and `restart` answer `409` with the reason; a service that is neither in `services` nor a container of the project: `404` with the reason; another action: `400`. The dashboard shows each container on a page of its own (`/s//infra//`) with its log | diff --git a/docs/pool.md b/docs/pool.md index baebb57c..c48e67ec 100644 --- a/docs/pool.md +++ b/docs/pool.md @@ -199,10 +199,18 @@ devstack leases the lane, syncs the worktree to the node (by content, only what changed: a change within two seconds of saving, and everything compared every 30 s besides), starts it there and forwards its ports to your machine: `localhost:` reaches it as if it ran locally, its containers' ports too. -Forwarding carries TCP only: a container port published as UDP (`53/udp`, -a game's voice port) runs on the node but is not forwarded here. The lane's -page, its container's row and `devstack lane list` say so ("UDP port 5353 is -not forwarded to this machine"); keep such a lane local (#192). +A container port published as UDP (`53/udp`, a game's voice port) is +relayed too ([ADR-0056](adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md)): +a datagram to `localhost:` reaches it, each client through a tunnel of its own, +which ends after 60 s without a datagram. Nothing is held while the container +starts: a datagram before it answers is lost, as on a network, and the +client's next one tries again. A datagram crosses whole, up to 64 KiB; the +container sees it come from the lane daemon, one source port per client. +A node older than 0.20.0 relays no UDP: the lane's page, its container's row +and `devstack lane list` say so ("UDP port 5353 is not forwarded to this +machine (the node … runs devstack 0.19.0, which forwards TCP only …)"); update +devstack on the node, or keep such a lane local. Ports of another protocol +(SCTP) are not forwarded (#192). The dashboard shows where each lane runs, its start step by step, and offers **Start here / on a node / in the pool** for a lane that is not started. diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index c0caa9d9..980bf033 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -60,7 +60,7 @@ Run from the repository root (devstack looks for `{{devstack:stack_file}}` there | `devstack lane start [--on ]` | start a lane from the main tree (or anywhere in the repository), as `devstack up` in its worktree does; `status` in the main tree lists the lanes in one line. **To run another branch or commit beside the main stack** (an end-to-end run against a given commit, a review): `git worktree add `, `devstack lane start ` (its ports are the main ports plus its offset, `devstack lane list`), test against those, `devstack lane stop `, `git worktree remove `. A commit without a stack file of its own runs with the main tree's. **For an acceptance run** use the stack file's profile if it has one (`status` lists none; `[profiles]` in the file): `devstack lane start --profile

--run` starts the lane as the profile says (a build instead of a dev server, workers, fresh data, the suite's env) and runs its suite command. A worktree another tool or script created is a lane too: starting it gives its own ports, containers and database without building a separate environment | | `devstack lane reset ` / `devstack lane prune [--older-than 7d] [--dry-run]` | throw a stopped lane's data away (it starts fresh, seeded again); remove what lanes whose worktree is gone left behind, here and on the pool's nodes. A lane on a node keeps its data there between starts. Ask the user before either: data goes | | `devstack promote --lane ` | the lane's services, dev servers included, answer on the main ports; ask the user first, `--lane main` gives them back. A lane on a node may take them only on a dedicated node (a server) | -| `devstack up --on ` in a worktree | the lane runs on that machine of the pool (`pool`: the coordinator picks one, warm first, `:` in another pool, `local`: here): build, services, its own containers; its ports are forwarded here as if it ran locally (TCP only: a container's UDP port is not, and `devstack lane list` says so). Without `--on` it goes where this machine starts lanes by default (`devstack pool default-on`; here unless the user set it). Ask the user first before starting elsewhere than that default: the worktree's files go to that machine, untracked env files git does not ignore included | +| `devstack up --on ` in a worktree | the lane runs on that machine of the pool (`pool`: the coordinator picks one, warm first, `:` in another pool, `local`: here): build, services, its own containers; its ports are forwarded here as if it ran locally, a container's UDP ports relayed too (a node older than 0.20.0 relays no UDP, and `devstack lane list` says so). Without `--on` it goes where this machine starts lanes by default (`devstack pool default-on`; here unless the user set it). Ask the user first before starting elsewhere than that default: the worktree's files go to that machine, untracked env files git does not ignore included | | `devstack pool placement ` (MCP `placement`) | before choosing `--on`: this machine's free CPU and memory, and each node of the pools with its load, free disk, lanes and the coordinator's rank and reason (`keeps this lane's data`, `the repository ran there`, `free capacity`, or why it cannot take it); and the default. Read only | | `devstack pool default-on [pool\|\|local]` | where lanes start without `--on`; setting it is the user's consent to send worktrees there without being asked, so only on the user's word | | `devstack lane move --to ` | move a started lane: a cold start there that takes over once ready; its data comes from the seed jobs again | diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index c056f459..df8b9989 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -162,8 +162,10 @@ export type LaneView = { node_error?: string; /** Its node or the pool's coordinator runs another devstack than this machine, or does not say which. */ node_warning?: string; - /** Of a lane on a node, its containers' published ports this machine does not forward (`5353/udp`): devstack forwards TCP only. Older daemons omit it. */ + /** Of a lane on a node, its containers' published ports this machine does not forward (`5353/udp`): UDP its node does not relay (ADR-0056), another protocol than TCP and UDP. Older daemons omit it. */ not_forwarded?: string[]; + /** Why they are not (the node's devstack forwards TCP only, with its release). Older daemons omit it. */ + not_forwarded_reason?: string; /** A start on a node or a move under way (step of steps), or one that failed lately. */ moving?: LaneMove; /** Its worktree is gone: it stops and its data goes (ADR-0024 point 7); it leaves the list after. */ @@ -220,7 +222,7 @@ export type ServiceView = { export type ContainerView = { /** Published ports Docker no longer forwards (accepted, closed at once); older daemons omit it. */ unreachable?: string[]; - /** Of a lane on a node, its published ports of another protocol than TCP (`5353/udp`), which the developer's machine does not reach. Older daemons omit it. */ + /** Of a lane on a node, its published ports the developer's machine does not reach (`5353/udp`): another protocol than TCP, UDP too unless the requester relays it (ADR-0056). Older daemons omit it. */ not_forwarded?: string[]; service: string; name: string; diff --git a/ui/src/components/StackHeader.vue b/ui/src/components/StackHeader.vue index 244daab3..6889c191 100644 --- a/ui/src/components/StackHeader.vue +++ b/ui/src/components/StackHeader.vue @@ -353,7 +353,7 @@ function openWith(o: Opener) { {{ current.owns_main ? 'serves the main ports' : 'no background workers' }} · {{ current.node_error }} · {{ current.node_warning }} - · {{ notForwardedText(current.not_forwarded) }} + · {{ notForwardedText(current.not_forwarded, current.not_forwarded_reason) }} diff --git a/ui/src/lib/lanes.test.ts b/ui/src/lib/lanes.test.ts index 4a81c465..5d1be085 100644 --- a/ui/src/lib/lanes.test.ts +++ b/ui/src/lib/lanes.test.ts @@ -48,8 +48,11 @@ describe('ports a lane on a node does not forward', () => { it('are said by protocol and number', () => { expect(notForwardedText(undefined)).toBe(''); expect(notForwardedText([])).toBe(''); - expect(notForwardedText(['5353/udp'])).toBe('UDP port 5353 is not forwarded to this machine (devstack forwards TCP only)'); - expect(notForwardedText(['5060/udp', '5353/udp'])).toBe('UDP ports 5060, 5353 are not forwarded to this machine (devstack forwards TCP only)'); - expect(notForwardedText(['5353/udp', '9000/sctp'])).toBe('ports UDP 5353, SCTP 9000 are not forwarded to this machine (devstack forwards TCP only)'); + expect(notForwardedText(['5353/udp'])).toBe('UDP port 5353 is not forwarded to this machine (an older devstack forwards TCP only)'); + expect(notForwardedText(['5060/udp', '5353/udp'])).toBe('UDP ports 5060, 5353 are not forwarded to this machine (an older devstack forwards TCP only)'); + expect(notForwardedText(['9000/sctp'])).toBe('SCTP port 9000 is not forwarded to this machine (devstack forwards TCP and UDP only)'); + // The daemon's reason (ADR-0056): the node is too old to relay UDP. + const why = 'the node build-1 runs devstack 0.19.0, which forwards TCP only: devstack 0.20.0 or later there relays UDP'; + expect(notForwardedText(['5353/udp', '9000/sctp'], why)).toBe(`ports UDP 5353, SCTP 9000 are not forwarded to this machine (${why})`); }); }); diff --git a/ui/src/lib/lanes.ts b/ui/src/lib/lanes.ts index fd2a5dc2..ae33f45e 100644 --- a/ui/src/lib/lanes.ts +++ b/ui/src/lib/lanes.ts @@ -95,9 +95,10 @@ export function samePath(a: string, b: string): boolean { /** * Published ports this machine does not forward (`["5353/udp"]`, a lane on a - * node: devstack forwards TCP only, #192) as a sentence; empty for none. + * node, #192) as a sentence, with the daemon's `reason` (ADR-0056); empty for + * none. Without one, UDP is not relayed by an older devstack. */ -export function notForwardedText(ports: string[] | undefined): string { +export function notForwardedText(ports: string[] | undefined, reason?: string): string { const list = (ports ?? []).map((p) => { const [port, proto = 'udp'] = p.split('/'); return { port, proto: proto.toUpperCase() }; @@ -107,5 +108,6 @@ export function notForwardedText(ports: string[] | undefined): string { const named = one ? `${list[0].proto} port${list.length === 1 ? '' : 's'} ${list.map((p) => p.port).join(', ')}` : `ports ${list.map((p) => `${p.proto} ${p.port}`).join(', ')}`; - return `${named} ${list.length === 1 ? 'is' : 'are'} not forwarded to this machine (devstack forwards TCP only)`; + const why = reason || (list.some((p) => p.proto === 'UDP') ? 'an older devstack forwards TCP only' : 'devstack forwards TCP and UDP only'); + return `${named} ${list.length === 1 ? 'is' : 'are'} not forwarded to this machine (${why})`; } From c76f629a1aea2ef942fca00246a3ec27fcf9e15c Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Fri, 23 Oct 2026 13:20:54 +0200 Subject: [PATCH 3/3] fix(lanes): a UDP relay's sockets hold any datagram, on macOS too macOS refuses to send a UDP datagram larger than the socket's send buffer, 9 KiB by default (`net.inet.udp.maxdgram`): the relay's 60 KB test datagram failed with EMSGSIZE on the macos-14 runner. Both relays raise a socket's send and receive buffers to hold any datagram a frame carries, never lowering them; ADR-0056 point 5 says so. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 3 +++ crates/devstack-daemon/Cargo.toml | 1 + crates/devstack-daemon/src/udprelay.rs | 19 +++++++++++++++++++ crates/devstack/tests/udp_relay.rs | 3 +++ ...-udp-ports-through-a-tunnel-per-session.md | 4 +++- 6 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index efb7b19b..a4aba900 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,6 +635,7 @@ dependencies = [ "regex", "serde", "serde_json", + "socket2", "tempfile", "thiserror", "tokio", diff --git a/Cargo.toml b/Cargo.toml index d703e949..542aa84c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,9 @@ rfd = { version = "0.17", default-features = false, features = ["xdg-portal"] } schemars = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" +# A UDP socket's send buffer: macOS refuses a datagram larger than it, +# 9 KiB by default (ADR-0056). +socket2 = "0.6" tempfile = "3" thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "net", "time", "signal", "io-util"] } diff --git a/crates/devstack-daemon/Cargo.toml b/crates/devstack-daemon/Cargo.toml index 11f7df37..a13a496c 100644 --- a/crates/devstack-daemon/Cargo.toml +++ b/crates/devstack-daemon/Cargo.toml @@ -29,6 +29,7 @@ ignore.workspace = true rand.workspace = true serde.workspace = true serde_json.workspace = true +socket2.workspace = true thiserror.workspace = true tokio.workspace = true tokio-stream.workspace = true diff --git a/crates/devstack-daemon/src/udprelay.rs b/crates/devstack-daemon/src/udprelay.rs index d49c6202..cd46a07d 100644 --- a/crates/devstack-daemon/src/udprelay.rs +++ b/crates/devstack-daemon/src/udprelay.rs @@ -29,6 +29,21 @@ pub const MAX_DATAGRAM: usize = u16::MAX as usize; /// What a socket is read with: any datagram the system delivers, whole. const BUFFER: usize = 1 << 16; +/// Make `socket` able to send and receive any datagram a frame carries. +/// macOS refuses to send one larger than the socket's send buffer, 9 KiB +/// by default (the sysctl `net.inet.udp.maxdgram`), and drops one that does +/// not fit its receive buffer. A buffer is never made smaller. +pub fn room_for_any_datagram(socket: &UdpSocket) { + let s = socket2::SockRef::from(socket); + if s.send_buffer_size().is_ok_and(|n| n < BUFFER) { + let _ = s.set_send_buffer_size(BUFFER); + } + // Room for a few, with what the system counts beside their bytes. + if s.recv_buffer_size().is_ok_and(|n| n < 4 * BUFFER) { + let _ = s.set_recv_buffer_size(4 * BUFFER); + } +} + /// A datagram longer than a frame carries. #[derive(Debug, PartialEq, Eq)] pub struct TooLarge(pub usize); @@ -207,6 +222,7 @@ pub async fn relay( F: std::future::Future, String>> + Send + 'static, S: AsyncRead + AsyncWrite + Send + Unpin + 'static, { + room_for_any_datagram(&socket); let socket = Arc::new(socket); let open = Arc::new(open); let table = Arc::new(Mutex::new(Table::new(limits))); @@ -403,6 +419,7 @@ pub async fn connect(addr: &str) -> std::io::Result { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() }; let socket = UdpSocket::bind(any).await?; + room_for_any_datagram(&socket); socket.connect(to).await?; Ok(socket) } @@ -518,6 +535,7 @@ mod tests { async fn echo() -> (SocketAddr, tokio::task::JoinHandle<()>) { let s = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + room_for_any_datagram(&s); let at = s.local_addr().unwrap(); let h = tokio::spawn(async move { let mut buf = vec![0u8; BUFFER]; @@ -564,6 +582,7 @@ mod tests { } async fn ask(client: &UdpSocket, to: SocketAddr, what: &[u8]) -> Vec { + room_for_any_datagram(client); client.send_to(what, to).await.unwrap(); let mut buf = vec![0u8; BUFFER]; let (n, _) = tokio::time::timeout(Duration::from_secs(5), client.recv_from(&mut buf)) diff --git a/crates/devstack/tests/udp_relay.rs b/crates/devstack/tests/udp_relay.rs index 46b25160..875c57c2 100644 --- a/crates/devstack/tests/udp_relay.rs +++ b/crates/devstack/tests/udp_relay.rs @@ -80,6 +80,8 @@ async fn open( } async fn ask(client: &UdpSocket, to: std::net::SocketAddr, what: &[u8]) -> Vec { + // macOS sends no more than 9 KiB unless asked to. + devstack_daemon::udprelay::room_for_any_datagram(client); client.send_to(what, to).await.unwrap(); let mut buf = vec![0u8; 1 << 16]; let (n, _) = tokio::time::timeout(Duration::from_secs(10), client.recv_from(&mut buf)) @@ -98,6 +100,7 @@ fn a_datagram_goes_through_a_lanes_tunnel_and_its_answer_comes_back() { // The "container": an echo socket, at the address the lane's network // would give it. let echo = rt.block_on(UdpSocket::bind("127.0.0.1:0")).unwrap(); + devstack_daemon::udprelay::room_for_any_datagram(&echo); let echo_at = echo.local_addr().unwrap(); rt.spawn(async move { let mut buf = vec![0u8; 1 << 16]; diff --git a/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md b/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md index 3011c179..cbe71681 100644 --- a/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md +++ b/docs/adr/0056-a-lane-on-a-node-relays-its-udp-ports-through-a-tunnel-per-session.md @@ -56,7 +56,9 @@ on without reading its protocol. 5. **Size.** A frame carries up to 65,535 bytes and both relays read with a 64 KiB buffer, so every datagram the operating system delivers (65,507 bytes at most over IPv4) arrives whole and leaves as one - datagram of the same size. The tunnel is a TCP stream with no MTU of + datagram of the same size; each relay's sockets get send and receive + buffers that hold one (macOS sends at most 9 KiB by default). The + tunnel is a TCP stream with no MTU of its own; on each end the operating system fragments a datagram larger than its link (loopback, the lane's Docker bridge), as it would for a local lane. A stream that ends inside a frame ends the session.