From 62179f9231ea064f7c1ae58d6aa1c696f326fa10 Mon Sep 17 00:00:00 2001 From: divesh Date: Sun, 22 Nov 2026 19:13:08 -0800 Subject: [PATCH] perf(supervisor): look up route owners on demand instead of sending the pool route directory A pool member's assignment snapshot no longer carries every route in the pool. A member asks the gateway for the owner of a route it does not own (RouteLookup/RouteOwner on the existing Attach stream) only when a sandbox runtime reaches it for that route, so a member's messages scale with its own sandboxes rather than with the pool. Closes #5783 Signed-off-by: divesh --- Cargo.lock | 1 + crates/openshell-sandbox-backend/README.md | 15 +- .../src/runtime_routed.rs | 253 +++++++++++++----- .../openshell-sandbox/src/boundary_server.rs | 2 +- crates/openshell-supervisor-control/README.md | 2 +- .../src/controller.rs | 96 ++++--- .../src/pool_limits.rs | 45 +--- crates/openshell-supervisor/Cargo.toml | 1 + crates/openshell-supervisor/README.md | 5 +- .../openshell-supervisor/src/shared_host.rs | 193 +++++++++++-- proto/supervisor_host.proto | 18 +- 11 files changed, 467 insertions(+), 164 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9260c5bc89..2ec82ec555 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5330,6 +5330,7 @@ dependencies = [ name = "openshell-supervisor" version = "0.0.0" dependencies = [ + "async-trait", "axum", "bytes", "clap", diff --git a/crates/openshell-sandbox-backend/README.md b/crates/openshell-sandbox-backend/README.md index b64aac2df3..f64330c8da 100644 --- a/crates/openshell-sandbox-backend/README.md +++ b/crates/openshell-sandbox-backend/README.md @@ -211,13 +211,16 @@ In a supervisor pool, one member hosts each route, but a runtime reaches an arbitrary member. A routed runtime therefore sends preface version `2` on every dial, which the supervisor answers before any TLS with a status byte, a length byte, and a runtime listener address as ASCII `ip:port` (IPv6 -bracketed): `1` accepts, naming the member itself (empty before it has a -route directory), and the handshake proceeds as for version 1; `2` redirects +bracketed): `1` accepts, naming the member itself (empty before it knows its +pool address), and the handshake proceeds as for version 1; `2` redirects to the owner; `3` reports the route unknown and carries no address. A member -redirects routes it does not host according to the gateway's route directory -(`RuntimeRouter::set_directory`), never to its own address, and the directory -also wins over a local registration it no longer agrees with, which is being -released. Replies are unauthenticated hints like the handle: the member must +knows only the routes it owns (`RuntimeRouter::set_owned`). For any other +route it asks a resolver (`RuntimeRouter::set_resolver`; a pool member asks +the gateway) and redirects to the owner it names, never to its own address. +The answer also wins over a local registration the member no longer owns, +which is being released. A lookup that times out or names no owner falls back +to the local registration, or reports the route unknown. Replies are +unauthenticated hints like the handle: the member must still complete the pinned TLS handshake, and every request still carries the bearer token. A lone shared supervisor accepts without naming itself, which tells the runtime there is no pool to probe. Version 1 prefaces, from runtimes diff --git a/crates/openshell-sandbox-backend/src/runtime_routed.rs b/crates/openshell-sandbox-backend/src/runtime_routed.rs index 85f8284439..ea09e3c1cc 100644 --- a/crates/openshell-sandbox-backend/src/runtime_routed.rs +++ b/crates/openshell-sandbox-backend/src/runtime_routed.rs @@ -18,19 +18,21 @@ //! //! In a supervisor pool one member hosts each route, but a runtime reaches //! an arbitrary member. A version 2 preface is answered before any TLS: the -//! member that hosts the route accepts, naming itself, and the TLS handshake -//! follows, while any other member names the owner from its gateway-provided -//! route directory, or reports the route unknown, and closes. The directory -//! wins over a local registration it no longer agrees with, which is being -//! released. Replies are hints like the handle itself: the owner must still -//! complete the pinned TLS handshake, and every request still carries the -//! bearer token. - -use std::collections::HashMap; +//! member that owns the route accepts, naming itself, and the TLS handshake +//! follows, while any other member asks its [`ResolveRoute`] for the owner +//! and names it, or reports the route unknown, and closes. A local +//! registration of a route the member no longer owns is being released, so +//! the owner it resolves wins over it. Replies are hints like the handle +//! itself: the owner must still complete the pinned TLS handshake, and every +//! request still carries the bearer token. + +use std::collections::{HashMap, HashSet}; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::time::Duration; +use async_trait::async_trait; + use openshell_isolation_interface::contract::{BackendError, BoundaryDuplexStream}; use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; @@ -62,6 +64,9 @@ const MAX_PENDING_HANDSHAKES: usize = 64; const MAX_PENDING_HANDSHAKES_PER_ROUTE: usize = 4; /// Bound on reading the preface and completing TLS for one socket. const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5); +/// Bound on resolving the owner of a route this listener does not own, so +/// the handshake that may follow keeps most of its budget. +const ROUTE_LOOKUP_TIMEOUT: Duration = Duration::from_secs(2); /// Authenticated connections queued for a sandbox instance but not yet claimed. const MAX_QUEUED_CONNECTIONS: usize = 2; @@ -139,8 +144,8 @@ async fn read_route_preface(stream: &mut S) -> std::io::Re #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RouteReply { /// This supervisor hosts the route; the TLS handshake follows on the same - /// connection. Names the member's runtime listener as its route directory - /// does, when it has one; unauthenticated, like everything before TLS. + /// connection. Names the member's runtime listener, when it knows it; + /// unauthenticated, like everything before TLS. Accept(Option), /// Another pool member hosts the route, at this runtime listener address. /// Unauthenticated, like the handle that selected it. @@ -218,6 +223,22 @@ fn redirect_reply(owner: SocketAddr) -> Result, String> { address_reply(ROUTE_REPLY_REDIRECT, Some(owner)) } +/// Finds which pool member's runtime listener hosts a route. +#[async_trait] +pub trait ResolveRoute: Send + Sync { + /// The owner's runtime listener, or `None` when no member is known to + /// host `route`. + async fn owner(&self, route: &str) -> Option; +} + +/// A fixed map of route owners. +#[async_trait] +impl ResolveRoute for HashMap { + async fn owner(&self, route: &str) -> Option { + self.get(route).copied() + } +} + struct Route { /// Distinguishes a re-registered handle from the registration it replaced. id: u64, @@ -230,49 +251,61 @@ struct Route { struct Routes { next_id: u64, by_handle: HashMap, - /// This listener's address, as the route directory names it. + /// This listener's address, as other members name it. own_address: Option, - /// Runtime listener of the pool member that hosts each route. - owners: HashMap, + /// Routes this pool member owns; `None` outside a pool, where every + /// registration is owned. + owned: Option>, + resolver: Option>, +} + +/// A sandbox instance registered on this listener, which other members name +/// as `own`. +struct LocalRoute { + tls: SandboxTlsClientConfig, + spares: mpsc::Sender, + pending: Arc, + own: Option, } /// Where a routing preface's handle leads. enum Destination { - /// A sandbox instance registered on this listener, which the directory - /// names as `own`. - Local { - tls: SandboxTlsClientConfig, - spares: mpsc::Sender, - pending: Arc, + Local(LocalRoute), + /// Another member may own the route; `local` serves it when none does. + Resolve { + resolver: Arc, own: Option, + local: Option, }, - /// Another pool member's runtime listener. - Owner(SocketAddr), Unknown, } impl Routes { - /// The directory never sends a runtime back to this listener. For a - /// runtime that follows redirects, the directory also wins over a local - /// registration naming another owner: the gateway moved the route, and - /// the registration is being released. A runtime that cannot follow one - /// reaches the registration, as before pools existed. + /// Only a runtime that follows redirects is sent to another member, and + /// only for a route this member does not own: either one registered + /// elsewhere, or a local registration being released after the gateway + /// moved its route. A runtime that cannot follow a redirect reaches the + /// registration, as before pools existed. fn destination(&self, handle: &str, follows_redirects: bool) -> Destination { - let owner = self - .owners - .get(handle) - .copied() - .filter(|owner| Some(*owner) != self.own_address); - match (self.by_handle.get(handle), owner) { - (Some(_), Some(owner)) if follows_redirects => Destination::Owner(owner), - (Some(route), _) => Destination::Local { - tls: route.tls.clone(), - spares: route.spares.clone(), - pending: route.pending.clone(), + let local = self.by_handle.get(handle).map(|route| LocalRoute { + tls: route.tls.clone(), + spares: route.spares.clone(), + pending: route.pending.clone(), + own: self.own_address, + }); + let owned = self + .owned + .as_ref() + .is_none_or(|owned| owned.contains(handle)); + match (local, &self.resolver) { + (Some(local), _) if owned || !follows_redirects => Destination::Local(local), + (local, Some(resolver)) if follows_redirects => Destination::Resolve { + resolver: resolver.clone(), own: self.own_address, + local, }, - (None, Some(owner)) => Destination::Owner(owner), - (None, None) => Destination::Unknown, + (Some(local), _) => Destination::Local(local), + (None, _) => Destination::Unknown, } } } @@ -360,16 +393,31 @@ impl RuntimeRouter { })) } - /// Replace the route directory of a supervisor pool: the runtime listener - /// of the member that hosts each route. A runtime whose version 2 preface - /// names a route not registered here is redirected to that member. `own` - /// is this listener's address as the directory names it; an entry naming - /// it reports the route unknown instead, so a runtime is never redirected - /// back here. - pub fn set_directory(&self, own: Option, owners: HashMap) { + /// Join a supervisor pool: a runtime whose version 2 preface names a route + /// this member does not own is redirected to the member `resolver` names. + pub fn set_resolver(&self, resolver: Arc) { + lock(&self.routes).resolver = Some(resolver); + } + + /// Replace the routes this pool member owns. `own` is this listener's + /// address as other members name it; an owner resolved to it reports the + /// route unknown instead, so a runtime is never redirected back here. + pub fn set_owned(&self, own: Option, owned: HashSet) { let mut routes = lock(&self.routes); routes.own_address = own; - routes.owners = owners; + routes.owned = Some(owned); + } + + /// Serve a fixed route directory: the runtime listener of the member that + /// hosts each route. This member owns the routes it names as `own`. + pub fn set_directory(&self, own: Option, owners: HashMap) { + let owned = owners + .iter() + .filter(|(_, owner)| Some(**owner) == own) + .map(|(route, _)| route.clone()) + .collect(); + self.set_owned(own, owned); + self.set_resolver(Arc::new(owners)); } } @@ -508,24 +556,39 @@ async fn route_connection( // The handle only selects which pinned identity to expect, or which pool // member to name. let destination = lock(routes).destination(&handle, negotiated); - let (tls, spares, route_pending, own) = match destination { - Destination::Local { - tls, - spares, - pending, + let local = match destination { + Destination::Local(local) => Some(local), + Destination::Resolve { + resolver, own, - } => (tls, spares, pending, own), - Destination::Owner(owner) if negotiated => { - send_reply(&mut stream, deadline, &redirect_reply(owner)?).await?; - tracing::debug!(%owner, "redirected routed runtime connection to the route's owner"); - return Ok(()); - } - Destination::Owner(_) | Destination::Unknown => { - if negotiated { - send_reply(&mut stream, deadline, &[ROUTE_REPLY_UNKNOWN]).await?; + local, + } => { + let lookup_deadline = deadline.min(tokio::time::Instant::now() + ROUTE_LOOKUP_TIMEOUT); + let owner = tokio::time::timeout_at(lookup_deadline, resolver.owner(&handle)) + .await + .ok() + .flatten() + .filter(|owner| Some(*owner) != own); + if let Some(owner) = owner { + send_reply(&mut stream, deadline, &redirect_reply(owner)?).await?; + tracing::debug!(%owner, "redirected routed runtime connection to the route's owner"); + return Ok(()); } - return Err("unknown or retired runtime route handle".to_string()); + local + } + Destination::Unknown => None, + }; + let Some(LocalRoute { + tls, + spares, + pending: route_pending, + own, + }) = local + else { + if negotiated { + send_reply(&mut stream, deadline, &[ROUTE_REPLY_UNKNOWN]).await?; } + return Err("unknown or retired runtime route handle".to_string()); }; let Ok(_route_permit) = route_pending.try_acquire_owned() else { return Err("runtime route handshake limit reached".to_string()); @@ -768,6 +831,70 @@ mod tests { assert!(!delivered(®istration, &tls).await); } + #[tokio::test] + async fn only_routes_this_member_does_not_own_are_resolved() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Counting { + lookups: AtomicUsize, + owner: Mutex>, + } + #[async_trait] + impl ResolveRoute for Counting { + async fn owner(&self, _route: &str) -> Option { + self.lookups.fetch_add(1, Ordering::SeqCst); + *self.owner.lock().unwrap() + } + } + + let router = RuntimeRouter::bind("127.0.0.1:0".parse().unwrap()).unwrap(); + let address = router.local_addr(); + let identity = + generate_sandbox_tls_material(openshell_core::SandboxSessionId::new()).unwrap(); + let tls = client_tls(&identity); + let hosted = new_route_handle(); + let _registration = router.register(&hosted, &tls).unwrap(); + let owner: SocketAddr = "10.0.0.2:7443".parse().unwrap(); + let resolver = Arc::new(Counting { + lookups: AtomicUsize::new(0), + owner: Mutex::new(Some(owner)), + }); + router.set_resolver(resolver.clone()); + router.set_owned(Some(address), HashSet::from([hosted.clone()])); + + // An owned route is accepted without asking anyone. + assert_eq!( + negotiate(address, &hosted).await.1, + RouteReply::Accept(Some(address)) + ); + assert_eq!(resolver.lookups.load(Ordering::SeqCst), 0); + + // A route owned elsewhere, and a registration this member no longer + // owns, are resolved and redirected. + assert_eq!( + negotiate(address, &new_route_handle()).await.1, + RouteReply::Redirect(owner) + ); + router.set_owned(Some(address), HashSet::new()); + assert_eq!( + negotiate(address, &hosted).await.1, + RouteReply::Redirect(owner) + ); + assert_eq!(resolver.lookups.load(Ordering::SeqCst), 2); + + // When no other owner is known, the registration still serves its + // runtime and an unregistered route is unknown. + *resolver.owner.lock().unwrap() = None; + assert_eq!( + negotiate(address, &hosted).await.1, + RouteReply::Accept(Some(address)) + ); + assert_eq!( + negotiate(address, &new_route_handle()).await.1, + RouteReply::Unknown + ); + } + #[tokio::test] async fn preface_round_trips_and_rejects_malformed_input() { let handle = new_route_handle(); diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 038708c654..cae58370ab 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -1155,7 +1155,7 @@ mod linux { stream: tokio::net::TcpStream, /// The supervisor named itself, as only a pool member does. named: bool, - /// A member's route directory led here. + /// A member's redirect led here. redirected: bool, } diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index b524ed7ac6..2758f38338 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -33,7 +33,7 @@ re-implementing the control contracts. term with its credentials, or with the term alone when another gateway replica minted them), `stop_routes` for withdrawn instances it owns, `keep_routes` for owned desired instances whose material this replica has - not loaded yet, the route directory for runtime redirects, and the recovery + not loaded yet, and the recovery deadline its hosts offer each runtime (`POOL_RECOVERY_TIMEOUT_SECS`, 60 s, unless configured). Omission means release, never stop. Nothing is sent before the first view. An instance is judged by its owning process's diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 69ad6ded82..f780501c05 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -1086,9 +1086,30 @@ impl SupervisorHostController { Ok(()) } + /// Where `route` is supervised: the runtime listener of the live member + /// that owns it, or empty when none does. + fn route_owner(&self, route: String) -> RouteOwner { + let pool = lock(&self.inner.pool); + let runtime_address = pool + .view + .owners + .get(&route) + .and_then(|owner| { + pool.view + .members + .iter() + .find(|member| member.member_id == owner.member_id) + }) + .map(|member| member.runtime_address.clone()) + .unwrap_or_default(); + RouteOwner { + route, + runtime_address, + } + } + /// The snapshot for session `id`'s member: the instances its process - /// owns, the stop list, and the route directory. `None` until it can be - /// authoritative. + /// owns and the stop list. `None` until it can be authoritative. fn snapshot(&self, id: u64) -> Option { let mut desired = lock(&self.inner.desired); if !desired.initialized { @@ -1143,23 +1164,6 @@ impl SupervisorHostController { .collect::>() .into_iter() .collect(); - let addresses = pool - .view - .members - .iter() - .map(|member| (member.member_id.as_str(), member.runtime_address.as_str())) - .collect::>(); - let route_directory = pool - .view - .owners - .iter() - .filter_map(|(route, owner)| { - Some(RouteOwner { - route: route.clone(), - runtime_address: (*addresses.get(owner.member_id.as_str())?).to_string(), - }) - }) - .collect(); // Owned desired instances whose launch material this gateway has not // loaded yet are kept as they are rather than released. let kept_terms = pool @@ -1185,7 +1189,6 @@ impl SupervisorHostController { instances, pool: true, stop_routes, - route_directory, keep_routes, recovery_timeout: Some(prost_types::Duration { seconds: i64::from(pool.recovery_timeout_secs), @@ -1240,7 +1243,6 @@ impl SupervisorHostController { let unchanged = last_snapshot.as_ref().is_some_and(|previous| { previous.instances == snapshot.instances && previous.stop_routes == snapshot.stop_routes - && previous.route_directory == snapshot.route_directory && previous.keep_routes == snapshot.keep_routes }); if !unchanged { @@ -1275,6 +1277,13 @@ impl SupervisorHostController { Some(Ok(HostMessage { payload: Some(host_message::Payload::Heartbeat(_)) })) => { last_heard = tokio::time::Instant::now(); } + Some(Ok(HostMessage { payload: Some(host_message::Payload::RouteLookup(lookup)) })) => { + last_heard = tokio::time::Instant::now(); + let owner = self.route_owner(lookup.route); + if !send(host_gateway_message::Payload::RouteOwner(owner)).await { + return; + } + } Some(Ok(_)) => { let _ = tx .send_timeout( @@ -1603,6 +1612,32 @@ mod tests { assert!(changes.has_changed().unwrap(), "the member's stream ended"); } + #[tokio::test] + async fn a_member_snapshot_does_not_grow_with_the_pool() { + use prost::Message as _; + + let controller = SupervisorHostController::new(); + let (one, _) = controller + .begin_session(identity(), &member_hello("m1", "p1", 1)) + .unwrap(); + let mut view = loaded_view( + vec![member_view("m1", "p1"), member_view("m-2", "p2")], + [("rt-own-0000000000000", owner("m1", "p1", 1))], + ); + for index in 0..crate::pool_limits::MAX_POOL_INSTANCES_CEILING { + let route = format!("rt-{index:029}"); + view.desired.insert(route.clone()); + view.owners.insert(route, owner("m-2", "p2", 1)); + } + controller.update_pool(view, tokio::time::Instant::now()); + + let snapshot = controller.snapshot(one).unwrap(); + assert_eq!(routes(&snapshot), ["rt-own-0000000000000"]); + assert!( + snapshot.encoded_len() <= PoolLimits::new(1, 1).unwrap().max_gateway_message_bytes() + ); + } + #[tokio::test] async fn pool_members_receive_only_what_their_process_owns() { let controller = SupervisorHostController::new(); @@ -1641,14 +1676,11 @@ mod tests { assert_eq!(routes(&first), ["rt-a"]); assert!(first.instances[0].takeover.is_none()); assert_eq!(routes(&controller.snapshot(two).unwrap()), ["rt-b"]); - // Every member can redirect runtimes to any instance's owner. + // Every member can look up any instance's owner to redirect runtimes. + let owner_of = |route: &str| controller.route_owner(route.to_string()).runtime_address; assert_eq!( - first - .route_directory - .iter() - .map(|entry| (entry.route.as_str(), entry.runtime_address.as_str())) - .collect::>(), - [("rt-a", "10.0.0.2:5500"), ("rt-b", "10.0.0.3:5500")] + [owner_of("rt-a"), owner_of("rt-b"), owner_of("rt-unknown")], + ["10.0.0.2:5500", "10.0.0.3:5500", ""] ); // A takeover moves rt-b to m1 with the new term's credentials; m2's @@ -1935,10 +1967,10 @@ mod tests { assert_eq!(routes(&snapshot), ["rt-a", "rt-b"]); assert_eq!(snapshot.keep_routes, ["rt-c"]); assert!( - snapshot - .route_directory - .iter() - .any(|entry| entry.route == "rt-c") + !controller + .route_owner("rt-c".to_string()) + .runtime_address + .is_empty() ); // Once loaded, it is assigned. controller.update_pool( diff --git a/crates/openshell-supervisor-control/src/pool_limits.rs b/crates/openshell-supervisor-control/src/pool_limits.rs index c9fa4e479e..f8d241b534 100644 --- a/crates/openshell-supervisor-control/src/pool_limits.rs +++ b/crates/openshell-supervisor-control/src/pool_limits.rs @@ -9,8 +9,9 @@ //! accept. Across the pool, the gateway runs at most //! [`PoolLimits::max_pool_instances`] instances: its live replicas times the //! members each serves times each member's cap, never past -//! [`MAX_POOL_INSTANCES_CEILING`]. Buffers sized by these limits follow the -//! configured cap, not the largest one allowed. +//! [`MAX_POOL_INSTANCES_CEILING`]. A member's messages carry only its own +//! instances, so buffers sized by these limits follow the configured +//! per-member cap, not the size of the pool. use crate::registration::MAX_LAUNCH_MATERIAL_BYTES; @@ -21,7 +22,9 @@ pub const DEFAULT_MAX_INSTANCES_PER_MEMBER: usize = 128; pub const MAX_INSTANCES_PER_MEMBER: usize = 1024; /// Pool members one gateway replica is sized to serve unless configured. pub const DEFAULT_MAX_MEMBERS_PER_GATEWAY: usize = 32; -/// Most sandbox instances a pool runs, whatever its configuration. +/// Most sandbox instances a pool runs, whatever its configuration. It bounds +/// the pool-wide ownership state every gateway replica holds and reads when +/// it places a sandbox. pub const MAX_POOL_INSTANCES_CEILING: usize = 131_072; /// Framing allowance per assignment in a snapshot, beyond its launch material. @@ -30,9 +33,10 @@ const ASSIGNMENT_FRAMING_BYTES: usize = 1024; const REPORTED_INSTANCE_BYTES: usize = 1024; /// Smallest bound on a host message. const MIN_HOST_MESSAGE_BYTES: usize = 1024 * 1024; -/// Allowance per entry of the pool-wide route directory every snapshot -/// carries: a route handle of up to 64 bytes, an `IP:port`, and framing. -const ROUTE_DIRECTORY_ENTRY_BYTES: usize = 128; +/// Smallest bound on a gateway message, so a member with a small cap still +/// decodes a snapshot whose stop and keep lists outgrow its assignments. +const MIN_GATEWAY_MESSAGE_BYTES: usize = + 16 * (MAX_LAUNCH_MATERIAL_BYTES + ASSIGNMENT_FRAMING_BYTES); /// Fewest instances a status report may describe, so a member with a small /// cap can still report instances it is removing or keeping. const MIN_REPORTED_INSTANCES: usize = 64; @@ -107,12 +111,11 @@ impl PoolLimits { } /// Largest gateway message a member decodes: a full snapshot of its cap - /// of assignments at their largest, plus the route directory of the - /// largest pool. + /// of assignments at their largest, plus framing. #[must_use] pub fn max_gateway_message_bytes(self) -> usize { - self.max_instances_per_member * (MAX_LAUNCH_MATERIAL_BYTES + ASSIGNMENT_FRAMING_BYTES) - + MAX_POOL_INSTANCES_CEILING * ROUTE_DIRECTORY_ENTRY_BYTES + (self.max_instances_per_member * (MAX_LAUNCH_MATERIAL_BYTES + ASSIGNMENT_FRAMING_BYTES)) + .max(MIN_GATEWAY_MESSAGE_BYTES) } /// Largest member message: a status report of every instance it may @@ -159,29 +162,9 @@ mod tests { assert_eq!( PoolLimits::default().max_gateway_message_bytes(), 128 * (MAX_LAUNCH_MATERIAL_BYTES + ASSIGNMENT_FRAMING_BYTES) - + MAX_POOL_INSTANCES_CEILING * ROUTE_DIRECTORY_ENTRY_BYTES ); + assert_eq!(tiny.max_gateway_message_bytes(), MIN_GATEWAY_MESSAGE_BYTES); assert_eq!(tiny.max_host_message_bytes(), MIN_HOST_MESSAGE_BYTES); assert_eq!(largest.max_host_message_bytes(), 4 * 1024 * 1024); } - - #[test] - fn a_small_cap_decodes_the_route_directory_of_the_largest_pool() { - use crate::proto::{AssignmentSnapshot, RouteOwner}; - use prost::Message as _; - - let route_directory = (0..MAX_POOL_INSTANCES_CEILING) - .map(|index| RouteOwner { - route: format!("rt-{index:061}"), - runtime_address: "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535".to_string(), - }) - .collect(); - let snapshot = AssignmentSnapshot { - route_directory, - ..Default::default() - }; - let limits = PoolLimits::new(1, 1).unwrap(); - let own_assignments = MAX_LAUNCH_MATERIAL_BYTES + ASSIGNMENT_FRAMING_BYTES; - assert!(snapshot.encoded_len() <= limits.max_gateway_message_bytes() - own_assignments); - } } diff --git a/crates/openshell-supervisor/Cargo.toml b/crates/openshell-supervisor/Cargo.toml index 396d19e993..36b5ef4f33 100644 --- a/crates/openshell-supervisor/Cargo.toml +++ b/crates/openshell-supervisor/Cargo.toml @@ -29,6 +29,7 @@ openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-mid openshell-supervisor-network = { path = "../openshell-supervisor-network", default-features = false } openshell-supervisor-process = { path = "../openshell-supervisor-process" } +async-trait = "0.1" axum = { workspace = true } bytes = { workspace = true } clap = { workspace = true } diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index bddab556c7..a56b522951 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -259,8 +259,9 @@ control listener: it dials the gateway and receives its assignments from it. deferred, reported as starting, and retried at the heartbeat cadence. The host follows the gateway's heartbeat interval, offers each instance's runtime the recovery deadline of the latest snapshot - (`recovery_timeout_secs`) when it attaches, feeds the route directory to the - runtime router for redirects, and on SIGTERM announces that it is + (`recovery_timeout_secs`) when it attaches, redirects a runtime that reaches + it for a route it does not own to the owner the gateway names + (`RouteLookup`), and on SIGTERM announces that it is leaving, waits up to 40 seconds for the gateway to move its instances, and relinquishes what remains. diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index f8be6d1439..1f332b17b4 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -35,12 +35,12 @@ use miette::Result; use openshell_core::proto::supervisor_host::v1::supervisor_host_client::SupervisorHostClient; use openshell_core::proto::supervisor_host::v1::{ AssignmentSnapshot, HostGatewayMessage, HostHeartbeat, HostHello, HostMessage, HostStatus, - PoolMember, SandboxInstanceAssignment, SandboxInstanceTakeover, host_gateway_message, - host_message, + PoolMember, RouteLookup, RouteOwner, SandboxInstanceAssignment, SandboxInstanceTakeover, + host_gateway_message, host_message, }; use openshell_extension_core::BearerTokenSlot; use openshell_sandbox_backend::BoundaryTakeover; -use openshell_sandbox_backend::runtime_routed::RuntimeRouter; +use openshell_sandbox_backend::runtime_routed::{ResolveRoute, RuntimeRouter}; use openshell_supervisor_control::{ PoolLimits, SandboxInstancePhaseReport, SandboxInstanceRegistration, SandboxInstanceStatusReport, @@ -78,6 +78,85 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const SEND_TIMEOUT: Duration = Duration::from_secs(30); /// Host-to-gateway messages queued before the stream applies backpressure. const OUTBOUND_QUEUE: usize = 16; +/// Routes whose owner the host asks the gateway for at once. +const MAX_ROUTE_LOOKUPS: usize = 64; + +/// Asks the gateway that accepts the host's stream where a route this member +/// does not own is supervised. +#[derive(Default)] +struct RouteLookups { + /// The accepted stream's outbound queue. + stream: Mutex>>, + /// Connections waiting for each route's owner. + waiting: Mutex< + std::collections::HashMap>>>, + >, +} + +impl RouteLookups { + /// Send lookups on `stream`, or on none. Lookups sent on an earlier + /// stream are never answered, so their callers resolve no owner. + fn connect(&self, stream: Option>) { + *self + .stream + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = stream; + self.waiting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clear(); + } + + fn answer(&self, owner: RouteOwner) { + let waiters = self + .waiting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&owner.route); + let address = owner.runtime_address.parse().ok(); + for waiter in waiters.into_iter().flatten() { + let _ = waiter.send(address); + } + } +} + +#[async_trait::async_trait] +impl ResolveRoute for RouteLookups { + async fn owner(&self, route: &str) -> Option { + let (waiter, answer) = tokio::sync::oneshot::channel(); + { + let mut waiting = self + .waiting + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(waiters) = waiting.get_mut(route) { + waiters.push(waiter); + } else { + if waiting.len() >= MAX_ROUTE_LOOKUPS { + return None; + } + let stream = self + .stream + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone()?; + // Half the queue stays free for heartbeats and status reports. + if stream.capacity() <= OUTBOUND_QUEUE / 2 { + return None; + } + stream + .try_send(HostMessage { + payload: Some(host_message::Payload::RouteLookup(RouteLookup { + route: route.to_string(), + })), + }) + .ok()?; + waiting.insert(route.to_string(), vec![waiter]); + } + } + answer.await.ok().flatten() + } +} /// How a host notices a silent gateway and paces its reconnects: it must /// reach a responsive gateway replica well before its membership record @@ -182,6 +261,7 @@ pub struct SharedHost { app_listener: Option, host: SandboxInstanceHost, router: Arc, + route_lookups: Arc, gateway_endpoint: String, removal_grace: Duration, attach_request_timeout: Duration, @@ -299,10 +379,13 @@ impl SharedHost { let host = SandboxInstanceHost::new(config.instance_root)?; let router = RuntimeRouter::bind(config.runtime_listen) .map_err(|error| miette::miette!("{error}"))?; + let route_lookups = Arc::new(RouteLookups::default()); + router.set_resolver(route_lookups.clone()); Ok(Arc::new(Self { app_listener, host, router, + route_lookups, gateway_endpoint: config.gateway_endpoint, removal_grace: config.removal_grace, attach_request_timeout: config.attach_request_timeout, @@ -526,24 +609,15 @@ impl SharedHost { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = snapshot.stop_routes.iter().cloned().collect(); - // Runtimes that reach this member for an instance another member - // supervises are redirected there. - let owners = snapshot - .route_directory - .iter() - .filter_map(|entry| { - let address = entry.runtime_address.parse().ok(); - if address.is_none() { - tracing::warn!(route = %entry.route, "ignoring a malformed route directory address"); - } - Some((entry.route.clone(), address?)) - }) - .collect(); - self.router - .set_directory(Some(self.pool.runtime_address), owners); // Owned instances the gateway could not describe yet are kept as they // are: neither started, released, nor stopped. routes.extend(snapshot.keep_routes.iter().cloned()); + // Runtimes that reach this member for any other route are redirected + // to the owner the gateway names. + self.router.set_owned( + Some(self.pool.runtime_address), + routes.iter().cloned().collect(), + ); let hosted = self .host .list() @@ -1504,6 +1578,7 @@ async fn run_stream( accepted = true; host.gateway_connected.send_replace(true); host.gateway_home.send_replace(Some(accepted_message.peer_endpoint.clone())); + host.route_lookups.connect(Some(tx.clone())); tracing::info!(session = %accepted_message.session_id, "gateway accepted the supervisor host"); // A pool gateway detects failed members by silence, // so it asks for more frequent heartbeats. @@ -1542,6 +1617,7 @@ async fn run_stream( received_revision = snapshot.revision; reconciler.submit(stream, snapshot); } + Some(host_gateway_message::Payload::RouteOwner(owner)) => host.route_lookups.answer(owner), Some(host_gateway_message::Payload::Heartbeat(_)) | None => {} } } @@ -1607,6 +1683,7 @@ async fn run_stream( } } }; + host.route_lookups.connect(None); host.gateway_connected.send_replace(false); host.gateway_home.send_replace(None); end @@ -2017,17 +2094,34 @@ mod tests { pool: true, instances, stop_routes: vec![stopped_route.to_string()], - route_directory: vec![openshell_core::proto::supervisor_host::v1::RouteOwner { - route: elsewhere.to_string(), - runtime_address: owner.to_string(), - }], ..AssignmentSnapshot::default() }) .await .expect("an oversized snapshot is applied, not refused"); + // The gateway names the owner of a route this member does not own. + let (lookups, mut asked) = tokio::sync::mpsc::channel(OUTBOUND_QUEUE); + host.route_lookups.connect(Some(lookups)); + let gateway = { + let host = host.clone(); + tokio::spawn(async move { + while let Some(HostMessage { + payload: Some(host_message::Payload::RouteLookup(lookup)), + }) = asked.recv().await + { + host.route_lookups.answer(RouteOwner { + runtime_address: if lookup.route == elsewhere { + owner.to_string() + } else { + String::new() + }, + route: lookup.route, + }); + } + }) + }; - // The listed stop ran, the hosted instance stays, and the directory - // redirects runtimes of routes owned elsewhere. + // The listed stop ran, the hosted instance stays, and runtimes of + // routes owned elsewhere are redirected to the owner. assert_eq!(stops.try_recv(), Ok(())); assert!(host.status(stopped_route).is_none()); assert_eq!( @@ -2045,6 +2139,8 @@ mod tests { .unwrap(), openshell_sandbox_backend::runtime_routed::RouteReply::Redirect(owner) ); + host.route_lookups.connect(None); + gateway.abort(); // Only up to capacity was attempted: the hosted instance and all but // the last new one in route order; the last stays unstarted. let rejected = host.rejected.lock().unwrap().clone(); @@ -2056,6 +2152,55 @@ mod tests { host.shut_down().await; } + #[tokio::test] + async fn route_lookups_share_one_request_and_never_crowd_the_stream() { + let lookups = Arc::new(RouteLookups::default()); + assert_eq!(lookups.owner("rt-a").await, None, "no stream, no owner"); + + let (stream, mut sent) = tokio::sync::mpsc::channel(OUTBOUND_QUEUE); + lookups.connect(Some(stream.clone())); + let first = tokio::spawn({ + let lookups = lookups.clone(); + async move { lookups.owner("rt-a").await } + }); + let second = tokio::spawn({ + let lookups = lookups.clone(); + async move { lookups.owner("rt-a").await } + }); + let asked = sent.recv().await.expect("a lookup is sent"); + assert!(matches!( + asked.payload, + Some(host_message::Payload::RouteLookup(RouteLookup { ref route })) if route == "rt-a" + )); + while lookups.waiting.lock().unwrap().get("rt-a").map(Vec::len) != Some(2) { + tokio::task::yield_now().await; + } + assert!(sent.try_recv().is_err(), "the same route is asked once"); + let owner: SocketAddr = "10.0.0.2:5500".parse().unwrap(); + lookups.answer(RouteOwner { + route: "rt-a".to_string(), + runtime_address: owner.to_string(), + }); + assert_eq!(first.await.unwrap(), Some(owner)); + assert_eq!(second.await.unwrap(), Some(owner)); + + // A lookup the stream would have to queue behind heartbeats is not sent. + for _ in 0..=OUTBOUND_QUEUE / 2 { + stream.try_send(HostMessage::default()).unwrap(); + } + assert_eq!(lookups.owner("rt-b").await, None); + while sent.try_recv().is_ok() {} + + // Dropping the stream releases lookups it will never answer. + let pending = tokio::spawn({ + let lookups = lookups.clone(); + async move { lookups.owner("rt-c").await } + }); + sent.recv().await.expect("a lookup is sent"); + lookups.connect(None); + assert_eq!(pending.await.unwrap(), None); + } + /// How one connection attempt to a [`FakeGateway`] goes. #[derive(Clone, Copy)] enum Attempt { diff --git a/proto/supervisor_host.proto b/proto/supervisor_host.proto index 3195837eff..1fb264131b 100644 --- a/proto/supervisor_host.proto +++ b/proto/supervisor_host.proto @@ -40,6 +40,7 @@ message HostMessage { HostHello hello = 1; HostStatus status = 2; HostHeartbeat heartbeat = 3; + RouteLookup route_lookup = 4; } } @@ -51,6 +52,7 @@ message HostGatewayMessage { AssignmentSnapshot assignments = 3; HostGatewayHeartbeat heartbeat = 4; HostRedirect redirect = 5; + RouteOwner route_owner = 6; } } @@ -111,6 +113,9 @@ message HostRejected { // previous one; an instance absent from a snapshot must stop, except on a // pool host, which releases it without stopping its workload. message AssignmentSnapshot { + reserved 5; + reserved "route_directory"; + // Monotonic within the session, starting at 1. uint64 revision = 1; repeated SandboxInstanceAssignment instances = 2; @@ -120,9 +125,6 @@ message AssignmentSnapshot { // Pool hosts only: routes whose sandbox is stopping or deleted; the host // stops their workloads if it still hosts them. repeated string stop_routes = 4; - // Pool hosts only: where each instance placed in the pool is supervised, - // so a sandbox runtime that reaches this host is redirected to its owner. - repeated RouteOwner route_directory = 5; // Pool hosts only: routes this host's process owns whose launch material // this gateway replica has not loaded yet. The host keeps supervising them // unchanged; it neither releases nor stops them, and starts nothing for @@ -135,10 +137,18 @@ message AssignmentSnapshot { google.protobuf.Duration recovery_timeout = 7; } +// A pool host asks where a route it does not own is supervised, so a sandbox +// runtime that reached it can be redirected. The gateway answers each lookup +// with a RouteOwner for the same route. +message RouteLookup { + string route = 1; +} + // The pool member that supervises one route. message RouteOwner { string route = 1; - // Runtime listener address (IP:port) of the owning member. + // Runtime listener address (IP:port) of the owning member; empty when no + // live member owns the route. string runtime_address = 2; }