Skip to content

Commit e6d5206

Browse files
committed
feat(kubernetes): warm pool support
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent 484f076 commit e6d5206

74 files changed

Lines changed: 8839 additions & 1721 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎architecture/compute-runtimes.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,66 @@ credentials. The driver removes its scheduling gate only after the companions
397397
exist; measured confirmation and supervisor-session registration gate public
398398
readiness.
399399

400+
Kubernetes supervisor startup uses `RegisterSupervisor` before any tenant RPC.
401+
The driver validates the projected token, live proxy/workload Pods and Sandbox
402+
ownership, and returns the prepared runtime coordinates to the gateway. The
403+
driver requires Secret read permission in sandbox namespaces to validate the
404+
proxy descriptor and its owner UID during registration, plus list/delete
405+
permission for generation Secret cleanup during stop and rollback. The
406+
gateway checks the persisted runtime generation and delivers the operational
407+
authentication bundle and launch configuration. Proxy Secrets retain physical
408+
transport and proxy-CA material, but contain no operational auth bundle.
409+
410+
The workload listener can wait without a logical sandbox ID. Its first token
411+
must carry a signed binding matching all protected runtime resource claims;
412+
only then does it pin the logical sandbox identity. Later tokens must match that
413+
identity, generation and epoch. Transport retries preserve assignment and the
414+
existing agent-launch replay protection. Other compute drivers retain their
415+
file-provisioned authentication path.
416+
417+
Optional Kubernetes warm pooling uses the same provisioning path.
418+
The gateway periodically supplies complete template snapshots and public trust;
419+
the driver elects a controller using a Kubernetes Lease. Templates from unavailable
420+
operator workspaces are excluded without blocking snapshot refreshes for eligible
421+
workspaces. Template startup hints set desired spare capacity, bounded by a
422+
driver-wide spare-pair cap. Preparing and ready pairs count toward capacity.
423+
A Kubernetes Sandbox owns each pair and
424+
records its physical identity, preparation revision and state without a logical
425+
sandbox ID. Pool inventory selects managed resources by gateway and pool labels;
426+
it must not require the logical sandbox-ID label. Ordinary sandbox listing and lifecycle reconciliation exclude it.
427+
An immutable parent-owned Secret journals both bootstrap Secrets so interrupted
428+
preparation preserves TLS material. Recovery accepts an already released workload
429+
only when its recorded Pod, Service and network-policy identities still match;
430+
it requires the existing journal and validates both bootstrap Secrets before
431+
finishing release. Generation cleanup also removes this journal.
432+
The authentication generation is also used in Sandbox metadata and generation-scoped
433+
resource names, so allocation and proxy registration refer to the same runtime.
434+
435+
Standby readiness requires a local workload-listener probe, a live paired proxy
436+
with recent authenticated registration, the boundary Service and network fence.
437+
It does not mean the agent has started. The leader conditionally retires spare
438+
pairs when preparation stalls, standby age expires, templates or trust change,
439+
or pooling is disabled. Retirement competes with allocation through resource
440+
versions. Claimed resources remain under ordinary lifecycle management.
441+
442+
Template-based creation selects a compatible ready pair and persists its Sandbox
443+
UID and prepared generation in the logical record before attempting a conditional
444+
claim. The claim removes availability and records the logical ID and command on
445+
the parent Sandbox. Registration checks that parent UID against the persisted
446+
assignment before delivering credentials. Both Pods retain their physical identity;
447+
stop/start and cleanup derive companion names from that identity.
448+
449+
Uncertain claims remain pending against the same candidate across gateway restarts.
450+
Recovery fences a rejected, still-unassigned candidate before recording another;
451+
it adopts an already committed claim instead of retiring it. With no eligible
452+
candidate, creation uses the cold path. Readiness and terminal main-process results
453+
finalize claim recovery. Explicit restart also clears pending claim recovery
454+
atomically with the new provisioning attempt, retaining the physical assignment
455+
and its reservation so recovery cannot replace a restarting runtime's identity.
456+
Pending deletion fences allocation before removing the logical record. Assigned
457+
pairs are single-use and are deleted with the sandbox; template changes or removal
458+
retire only spare inventory.
459+
400460
## Images
401461

402462
The gateway image and Helm chart are built from this repository. Sandbox images

‎architecture/gateway.md‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ attachments; and asks compute runtimes to create or delete sandbox workloads.
77
## Responsibilities
88

99
- Authenticate clients and sandbox supervisor sessions.
10+
- Authorize Kubernetes proxy registration against driver-verified physical
11+
runtime identity and persisted logical assignment. `RegisterSupervisor`
12+
supplies initial credentials; it does not bypass generation checks or recover
13+
a credential lineage that has already advanced through refresh.
1014
- Serve gRPC APIs for sandbox lifecycle, provider management, policy updates,
1115
settings, logs, watch streams, and relay forwarding.
1216
- Serve HTTP endpoints for health, WebSocket tunnels, and edge-auth flows.
@@ -314,7 +318,9 @@ identity inspection without client-side token decoding.
314318
Sandbox secrets are gateway-signed JWTs bound to a single sandbox ID. Docker,
315319
Podman, and VM drivers deliver the initial token through supervisor-only
316320
runtime material; Kubernetes supervisors exchange a projected ServiceAccount
317-
token through `IssueSandboxToken`. The gateway delegates that opaque credential
321+
token through `RegisterSupervisor` to receive their runtime assignment and
322+
in-memory authentication bundle. `IssueSandboxToken` remains available for
323+
existing bootstrap clients. The gateway delegates that opaque credential
318324
to the selected compute driver's `AuthenticateSandbox` RPC. A capable driver is
319325
trusted to return the authenticated sandbox ID, while the gateway still requires
320326
a matching durable sandbox record before minting a JWT. The Kubernetes driver
@@ -397,6 +403,11 @@ The storage schema is intentionally narrow:
397403

398404
Public RPC contracts and durable protobuf formats have separate ownership. The `openshell.v1.OpenShell` service's request and response roots, streaming flags, and transitive message closure come from the public descriptor set generated by `openshell-core`. The `public_and_durable_schema_inventories_are_complete` test in `openshell-server` owns the counts and fingerprints and requires this inventory to be reviewed whenever it changes. Compute-driver, credential-driver, gateway-interceptor, and supervisor-middleware services are compiled contracts for internal extension boundaries.
399405

406+
`RegisterSupervisor` adds request and response messages to the public closure.
407+
Its assignment response carries initial runtime credentials but is not persisted
408+
as a protobuf storage root. Warm-pool selection and synchronization extend the
409+
internal compute-driver contract; neither changes the durable schema inventory.
410+
400411
`ReportEndpointStatus` is a sandbox-authenticated public gateway RPC. Its request, response, and `EndpointObservation` messages belong only to the public closure. `EndpointStatus` and `EndpointResult` also belong to the durable closure because `Sandbox.status.endpoint_statuses` persists them. The repeated status field uses a new wire tag; stored sandboxes without it decode with an empty endpoint list and retain their lifecycle fields. A fixed payload encoded with the earlier sandbox schema verifies that no database rewrite is required.
401412

402413
Allow and deny append requests carry `L7RuleTarget` to declare the rule, endpoint, and complete affected scope. The removed `host` and `port` fields remain reserved by number and name, and requests without a target are rejected. These mutation requests are not persisted formats.
@@ -548,6 +559,20 @@ revisions commit in one database transaction. SQLite serializes this operation
548559
with an immediate transaction, while Postgres locks the sandbox row. A failed
549560
resource-version check or revision insert rolls back the entire operation.
550561

562+
Warm allocation intent and its exclusive target reservation commit in one
563+
transaction. The `allocation_claims` table keys ownership by configured driver,
564+
namespace, and physical UID; the owner is a sandbox provisioning attempt and
565+
runtime generation. A uniqueness conflict rolls back the sandbox write and
566+
allows immediate selection of another target. Reservations have no TTL and
567+
survive ambiguous driver outcomes and gateway restart. Only fenced or reclaimed
568+
allocations release ownership; deleting the owning sandbox cascades its claims.
569+
The driver's resource CAS still arbitrates physical assignment and retirement.
570+
Creates with attached providers hold the gateway-wide sandbox lock from provider
571+
validation through the sandbox and reservation commit, including reservation
572+
retries. They release it before submitting creation to the driver. Allocation
573+
completion and recovery then acquire their own synchronization and lifecycle
574+
locks.
575+
551576
SQLite is the default local store; Postgres is supported for deployments that
552577
need an external database or multi-replica coordination. Both backends expose
553578
the same `Store` API and the same logical schema. Backend differences stay

‎architecture/sandbox.md‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,26 @@ A sandbox is the runtime boundary where agent code executes. A compute driver
44
creates it and connects two dedicated components: `openshell-sandbox` inside
55
the workload boundary and `openshell-supervisor` outside it.
66

7+
Kubernetes warm pooling is enabled by default, but only templates with startup
8+
hints request spare workload/supervisor pairs. The driver caps total unassigned
9+
inventory; operators can disable pooling through driver configuration or Helm.
10+
Each claimed pair belongs to one logical sandbox and is never returned to the pool.
11+
The gateway reserves each physical target in its database atomically with the
12+
logical allocation intent before sending a claim to the driver. Concurrent
13+
requests that lose the reservation immediately select another candidate without
14+
retiring the winner's pair. Create and recovery use bounded retries for definite
15+
claim rejection and persist each replacement before claiming it. Exhausted warm
16+
capacity falls back to cold creation in the same invocation. Uncertain claims
17+
retain their target and generation for idempotent recovery.
18+
The Sandbox resource owns the assignment. Reconciliation copies its logical
19+
sandbox name and ID onto both Pods as display labels and updates their sandbox-ID
20+
annotations for SPIFFE identity. Physical pair selectors and registration
21+
bindings remain stable. A successful claim wakes
22+
registration waiters on the same gateway replica; polling durable state remains
23+
the fallback for other replicas and recovery. Every wake revalidates identity.
24+
Prepared pairs also carry template name and ID labels on their parent and both
25+
Pods. These display labels survive assignment and do not affect pool compatibility.
26+
727
## Runtime Model
828

929
Each sandbox has three trust levels:
@@ -27,6 +47,10 @@ TCP Service, or VM vsock channel. Independent bidirectional `Exchange` RPCs
2747
carry lifecycle, exec, TCP, and forwarding traffic, while one persistent
2848
bidirectional `Mediate` RPC carries multiplexed DNS traffic. General application
2949
UDP is unsupported; UDP DNS remains mediated by the supervisor.
50+
Boundary connection attempts bound transport establishment and TLS negotiation
51+
to two seconds per attempt within a 30-second retry window. The window also
52+
cancels an in-flight attempt at its deadline. Initial attachment can retry calls
53+
for up to five minutes while the workload boots.
3054
The sandbox probes HTTP/2 connection liveness every five seconds and closes
3155
connections that miss a ten-second acknowledgement deadline. Closing a
3256
connection freezes the owned workload process tree and cancels its stream
@@ -50,9 +74,13 @@ connections, including loopback aliases. Unix control listeners reject workload
5074
descendants using kernel peer credentials and process ancestry, while ordinary
5175
workload loopback and Unix services remain available.
5276
NetworkPolicy is an outer reachability fence, not a confidentiality boundary.
53-
Each sandbox generation receives a fresh CA and distinct server/client leaves;
54-
both endpoints bind the same workload identity and immutable driver resource
55-
claims. Driver crates do not appear in generic process, network, SSH, or
77+
Each sandbox generation receives a fresh CA and server certificate. The
78+
supervisor verifies server TLS; the workload authenticates the supervisor using
79+
a gateway-signed boundary JWT, not a TLS client certificate. Both endpoints bind
80+
the workload identity and immutable driver resource claims. Kubernetes can
81+
prepare the listener before logical assignment: the first JWT must also contain
82+
the exact protected resource binding before the workload accepts its sandbox ID.
83+
Driver crates do not appear in generic process, network, SSH, or
5684
session code.
5785

5886
The supervisor exposes readiness only after the sandbox is confirmed and the
@@ -651,6 +679,14 @@ A leader-owned scan runs independently of driver inventory. Expiry records
651679
`Error`/`ProvisioningTimedOut` before reclaiming compute; cleanup progress and
652680
backoff survive restart. Late runtime reports cannot replace that result. The
653681
record and restartable storage survive cleanup, including for ephemeral creates.
682+
Allocation recovery checks the same persisted deadline before retrying compute.
683+
Timeout cleanup retires an unclaimed warm candidate through the driver's claim
684+
CAS before acknowledging reclamation; a candidate already claimed by the sandbox
685+
uses normal stop semantics to retain storage. Cleanup clears allocation intent
686+
only after retirement and reclamation succeed. Late allocation results are fenced
687+
by provisioning attempt and runtime generation, and cannot rearm an expired
688+
attempt. Records with leftover allocation intent require cleanup even if an older
689+
gateway already recorded cleanup completion.
654690
Explicit start is blocked while cleanup is pending, then creates a fresh attempt
655691
using the latest configuration. Configuration edits alone never restart an
656692
expired sandbox. Legacy provisioning records receive one persisted rollout

‎crates/openshell-cli/tests/ensure_providers_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,13 @@ impl OpenShell for TestOpenShell {
677677
Err(Status::unimplemented("not implemented in test"))
678678
}
679679

680+
async fn register_supervisor(
681+
&self,
682+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
683+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
684+
Err(Status::unimplemented("not implemented in test"))
685+
}
686+
680687
async fn issue_sandbox_token(
681688
&self,
682689
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/mtls_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,13 @@ impl OpenShell for TestOpenShell {
529529
Err(Status::unimplemented("not implemented in test"))
530530
}
531531

532+
async fn register_supervisor(
533+
&self,
534+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
535+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
536+
Err(Status::unimplemented("not implemented in test"))
537+
}
538+
532539
async fn issue_sandbox_token(
533540
&self,
534541
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/provider_commands_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1405,6 +1405,13 @@ impl OpenShell for TestOpenShell {
14051405
Err(Status::unimplemented("not implemented in test"))
14061406
}
14071407

1408+
async fn register_supervisor(
1409+
&self,
1410+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
1411+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
1412+
Err(Status::unimplemented("not implemented in test"))
1413+
}
1414+
14081415
async fn issue_sandbox_token(
14091416
&self,
14101417
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -988,6 +988,13 @@ impl OpenShell for TestOpenShell {
988988
Err(Status::unimplemented("not implemented in test"))
989989
}
990990

991+
async fn register_supervisor(
992+
&self,
993+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
994+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
995+
Err(Status::unimplemented("not implemented in test"))
996+
}
997+
991998
async fn issue_sandbox_token(
992999
&self,
9931000
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-cli/tests/sandbox_name_fallback_integration.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,13 @@ impl OpenShell for TestOpenShell {
620620
Err(Status::unimplemented("not implemented in test"))
621621
}
622622

623+
async fn register_supervisor(
624+
&self,
625+
_request: tonic::Request<openshell_core::proto::RegisterSupervisorRequest>,
626+
) -> Result<Response<openshell_core::proto::RegisterSupervisorResponse>, Status> {
627+
Err(Status::unimplemented("not implemented in test"))
628+
}
629+
623630
async fn issue_sandbox_token(
624631
&self,
625632
_request: tonic::Request<openshell_core::proto::IssueSandboxTokenRequest>,

‎crates/openshell-core/src/grpc_client.rs‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,60 @@ async fn build_plain_channel(endpoint: &str) -> Result<Channel> {
274274
.wrap_err("failed to connect to OpenShell server")
275275
}
276276

277+
/// Register with a driver-native projected credential, before installing any
278+
/// operational token slots. Re-read the token on every reconnect for rotation.
279+
pub async fn register_supervisor(
280+
endpoint: &str,
281+
) -> Result<crate::proto::RegisterSupervisorResponse> {
282+
let path = std::env::var(sandbox_env::K8S_SA_TOKEN_FILE)
283+
.into_diagnostic()
284+
.wrap_err("registration requires a projected service-account token")?;
285+
loop {
286+
let token = tokio::fs::read_to_string(&path).await.into_diagnostic()?;
287+
let result = match build_plain_channel(endpoint).await {
288+
Ok(channel) => {
289+
let mut client = OpenShellClient::new(channel);
290+
let mut request = tonic::Request::new(crate::proto::RegisterSupervisorRequest {});
291+
request.metadata_mut().insert(
292+
"authorization",
293+
format!("Bearer {}", token.trim())
294+
.parse()
295+
.into_diagnostic()?,
296+
);
297+
request.set_timeout(Duration::from_secs(45));
298+
client
299+
.register_supervisor(request)
300+
.await
301+
.map(tonic::Response::into_inner)
302+
}
303+
Err(_) => Err(Status::unavailable("registration transport unavailable")),
304+
};
305+
match result {
306+
Ok(assignment) => return Ok(assignment),
307+
Err(error)
308+
if matches!(
309+
error.code(),
310+
tonic::Code::Unavailable
311+
| tonic::Code::DeadlineExceeded
312+
| tonic::Code::Cancelled
313+
| tonic::Code::Aborted
314+
| tonic::Code::Unauthenticated
315+
) =>
316+
{
317+
// Log only the code, never credential-bearing response bodies.
318+
debug!(code = ?error.code(), "supervisor registration unavailable; retrying");
319+
tokio::time::sleep(Duration::from_secs(2)).await;
320+
}
321+
Err(error) => {
322+
return Err(miette::miette!(
323+
"supervisor registration rejected ({:?})",
324+
error.code()
325+
));
326+
}
327+
}
328+
}
329+
}
330+
277331
/// Build a Bearer-authenticated channel to the gateway.
278332
///
279333
/// First call per process resolves the sandbox JWT via the three-step

0 commit comments

Comments
 (0)