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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 9 additions & 6 deletions crates/openshell-sandbox-backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
299 changes: 236 additions & 63 deletions crates/openshell-sandbox-backend/src/runtime_routed.rs

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions crates/openshell-sandbox/src/boundary_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ mod linux {
/// Bounds connecting to one supervisor address and negotiating the route
/// there, so an unreachable cached owner leaves time for the configured
/// addresses.
const RUNTIME_ROUTE_HOP_TIMEOUT: Duration = Duration::from_secs(2);
const RUNTIME_ROUTE_HOP_TIMEOUT: Duration =
openshell_sandbox_backend::runtime_routed::ROUTE_HOP_TIMEOUT;
/// Redirects followed from each supervisor address a dial starts at.
const MAX_RUNTIME_ROUTE_REDIRECTS: usize = 2;
/// Spares a routed runtime keeps unused at once: one at its owner, and in
Expand Down Expand Up @@ -1155,7 +1156,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,
}

Expand Down
2 changes: 1 addition & 1 deletion crates/openshell-supervisor-control/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
98 changes: 66 additions & 32 deletions crates/openshell-supervisor-control/src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,7 @@ impl SupervisorHostController {
nanos: 0,
}),
peer_endpoint,
route_lookups: true,
})),
}))
.await
Expand Down Expand Up @@ -1086,9 +1087,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<AssignmentSnapshot> {
let mut desired = lock(&self.inner.desired);
if !desired.initialized {
Expand Down Expand Up @@ -1143,23 +1165,6 @@ impl SupervisorHostController {
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let addresses = pool
.view
.members
.iter()
.map(|member| (member.member_id.as_str(), member.runtime_address.as_str()))
.collect::<BTreeMap<_, _>>();
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
Expand All @@ -1185,12 +1190,12 @@ impl SupervisorHostController {
instances,
pool: true,
stop_routes,
route_directory,
keep_routes,
recovery_timeout: Some(prost_types::Duration {
seconds: i64::from(pool.recovery_timeout_secs),
nanos: 0,
}),
..AssignmentSnapshot::default()
})
}

Expand Down Expand Up @@ -1240,7 +1245,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 {
Expand Down Expand Up @@ -1275,6 +1279,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(
Expand Down Expand Up @@ -1603,6 +1614,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();
Expand Down Expand Up @@ -1641,14 +1678,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::<Vec<_>>(),
[("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
Expand Down Expand Up @@ -1935,10 +1969,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(
Expand Down
45 changes: 14 additions & 31 deletions crates/openshell-supervisor-control/src/pool_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}
1 change: 1 addition & 0 deletions crates/openshell-supervisor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
5 changes: 3 additions & 2 deletions crates/openshell-supervisor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading