Skip to content

Commit b3bae4a

Browse files
committed
feat(kubernetes): add template-driven sandbox warm pools
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent bdb8be3 commit b3bae4a

82 files changed

Lines changed: 13027 additions & 266 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.

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

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,8 @@ mod session {
188188
runtime_generation: SandboxGenerationId,
189189
auth_epoch: CredentialEpoch,
190190
component: SessionComponent,
191+
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
192+
resource_binding: BTreeMap<String, String>,
191193
}
192194

193195
/// Claims of the supervisor token. It names no sandbox, generation, or
@@ -889,6 +891,26 @@ mod session {
889891
gateway_token_id: Uuid,
890892
sandbox_token_id: Uuid,
891893
issued_at: i64,
894+
) -> Result<MintedSessionTokenPair, SessionJwtError> {
895+
self.mint_bound_pair_with_token_metadata(
896+
identity,
897+
gateway_token_id,
898+
sandbox_token_id,
899+
issued_at,
900+
BTreeMap::new(),
901+
)
902+
}
903+
904+
/// Mint a reproducible pair, binding only the Sandbox Protocol token
905+
/// to a prepared runtime's physical resources. Gateway authorization
906+
/// continues to use the persisted logical identity and token lineage.
907+
pub fn mint_bound_pair_with_token_metadata(
908+
&self,
909+
identity: &SandboxRuntimeIdentity,
910+
gateway_token_id: Uuid,
911+
sandbox_token_id: Uuid,
912+
issued_at: i64,
913+
resource_binding: BTreeMap<String, String>,
892914
) -> Result<MintedSessionTokenPair, SessionJwtError> {
893915
Ok(MintedSessionTokenPair {
894916
gateway: self.mint(
@@ -897,11 +919,12 @@ mod session {
897919
gateway_token_id,
898920
issued_at,
899921
)?,
900-
sandbox: self.mint(
922+
sandbox: self.mint_bound(
901923
SessionTokenProfile::Sandbox,
902924
identity,
903925
sandbox_token_id,
904926
issued_at,
927+
resource_binding,
905928
)?,
906929
auth_epoch: identity.auth_epoch,
907930
})
@@ -990,6 +1013,32 @@ mod session {
9901013
identity: &SandboxRuntimeIdentity,
9911014
token_id: Uuid,
9921015
issued_at: i64,
1016+
) -> Result<MintedSessionToken, SessionJwtError> {
1017+
self.mint_bound(profile, identity, token_id, issued_at, BTreeMap::new())
1018+
}
1019+
1020+
/// Authorize initial assignment to an exact driver-provisioned runtime.
1021+
pub fn mint_bound_sandbox_token(
1022+
&self,
1023+
identity: &SandboxRuntimeIdentity,
1024+
resource_binding: BTreeMap<String, String>,
1025+
) -> Result<MintedSessionToken, SessionJwtError> {
1026+
self.mint_bound(
1027+
SessionTokenProfile::Sandbox,
1028+
identity,
1029+
Uuid::new_v4(),
1030+
self.clock.now_unix_seconds(),
1031+
resource_binding,
1032+
)
1033+
}
1034+
1035+
fn mint_bound(
1036+
&self,
1037+
profile: SessionTokenProfile,
1038+
identity: &SandboxRuntimeIdentity,
1039+
token_id: Uuid,
1040+
issued_at: i64,
1041+
resource_binding: BTreeMap<String, String>,
9931042
) -> Result<MintedSessionToken, SessionJwtError> {
9941043
let expires_at = self.ttl.map_or(0, |ttl| {
9951044
issued_at.saturating_add(i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX))
@@ -1005,6 +1054,7 @@ mod session {
10051054
runtime_generation: identity.runtime_generation.clone(),
10061055
auth_epoch: identity.auth_epoch,
10071056
component: SessionComponent::OpenShellSupervisor,
1057+
resource_binding,
10081058
};
10091059
let mut header = Header::new(Algorithm::EdDSA);
10101060
header.kid = Some(self.key_id.clone());
@@ -1048,6 +1098,8 @@ mod session {
10481098

10491099
#[derive(Clone, Debug, PartialEq, Eq)]
10501100
pub struct AuthenticatedSandboxSession {
1101+
/// Signed physical-runtime binding, required for initial late assignment.
1102+
pub resource_binding: BTreeMap<String, String>,
10511103
pub sandbox_id: SandboxId,
10521104
pub runtime_generation: SandboxGenerationId,
10531105
pub auth_epoch: CredentialEpoch,
@@ -1152,6 +1204,7 @@ mod session {
11521204
let token_id = Uuid::parse_str(&claims.jti).map_err(|_| SessionJwtError::InvalidJti)?;
11531205
validate_lifetime(claims.iat, claims.exp, self.clock.now_unix_seconds())?;
11541206
Ok(AuthenticatedSandboxSession {
1207+
resource_binding: claims.resource_binding,
11551208
sandbox_id: claims.sandbox_id,
11561209
runtime_generation: claims.runtime_generation,
11571210
auth_epoch: claims.auth_epoch,

‎crates/openshell-driver-kubernetes/README.md‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,151 @@ must not create permissive policies, create Pods, read bootstrap Secrets, or
186186
spoof the OpenShell role labels. Exact supervisor-to-sandbox authorization is
187187
still enforced by TLS, JWT claims, session generation, and recorded Pod UIDs.
188188

189+
### Prepared runtime bootstrap
190+
191+
The `prepared_runtime` module supplies bootstrap persistence for OpenShell-owned
192+
warm runtimes. `KubernetesSandboxRuntimeBoundarySpec::provision_prepared`
193+
builds an unassigned runtime with a shared-supervisor route and physical resource
194+
claims. `PreparedRuntimeBootstrap::prepare` creates a Pod-owned immutable Secret
195+
containing its boundary configuration, TLS certificate and private key, and public
196+
preparation descriptor. It then reserves capacity through `SharedSupervision`.
197+
It supplies no logical Sandbox ID, gateway session token, or workload credentials.
198+
199+
The controller must persist the physical session, generation and route first,
200+
admit the Sandbox and gated Pod, and verify the namespace and network fences.
201+
The provisioning callback builds the boundary configuration and descriptor from
202+
those observations using the TLS pin supplied by the helper. On retry, the helper
203+
reads the existing Secret, checks its workspace and Pod UID ownership, and compares
204+
the complete bootstrap configuration with the expected one. Concurrent creators
205+
use the winning Secret's identity. Read failures, changed inputs and capacity
206+
refusals fail without replacing keys, deleting resources or releasing the gate.
207+
208+
`driver::warm_pool` now owns the physical provisioning sequence through
209+
`prepare_warm_runtime`, `resume_warm_runtime`, and `warm_runtime_inventory`. It
210+
uses the Agent Sandbox core `Sandbox` API, without extension templates or an
211+
admission webhook. Each resource records its physical session, public gateway
212+
trust, requested Pod shape and admission identities before its Pod is created.
213+
The Pod template references that runtime's own bootstrap Secret from creation.
214+
The physical CR has no logical Sandbox ID and does not appear as an assigned
215+
Sandbox in the gateway's watch stream.
216+
217+
Preparation records the first Pod UID, persists bootstrap material, and reserves
218+
shared-supervisor capacity before releasing the scheduling gate. Immediately
219+
before release it rechecks the CR, Pod, resource admission, namespace UID and
220+
network fences. Pod and CR mutations carry resource-version preconditions;
221+
gate removal preserves gates owned by other controllers. Lost responses recover
222+
through the CR journal and existing immutable Secret. Replacements, changed
223+
requests and premature gate removal fail closed. A replacement needs a fresh
224+
session, generation, route and Secret. Pool controllers must retain request
225+
identities across uncertain writes and never reuse retired names or sessions.
226+
227+
`retire_warm_runtime` journals retirement before asking the gateway to fence the
228+
physical route permanently, including when capacity admission never completed.
229+
Only a confirmed fence permits foreground deletion of the CR with UID and
230+
resource-version preconditions. Kubernetes collects its Pod, the Pod-owned
231+
bootstrap Secret and the CR-owned control policy; namespace-wide network fences
232+
remain. Ambiguous failures leave the journal for retry. Concurrent claims,
233+
replaced resources and changed reservations do not authorize deletion. If the
234+
CR is already absent, the controller must reconcile any remaining gateway
235+
preparation independently from its durable inventory.
236+
237+
These operations support dedicated and shared supervisors in shared and operator
238+
workspace modes. Managed namespaces need bootstrap journaling in the gateway
239+
namespace to preserve their create-only Secret permissions. Inventory includes preparing, retiring
240+
and deleting resources; a released gate does not mean that the supervisor has
241+
authenticated the runtime or that it is claimable.
242+
243+
Template-driven pooling is enabled by default through `warm_pool.enabled`.
244+
The gateway supplies stored template targets through the existing in-process
245+
supervision coordinator. Only templates with `startup.ready_within` and positive
246+
`startup.max_burst` request spares; the target is capped by `warm_pool.max_size`.
247+
No new runtime or gateway RPC is used for template discovery. Each pool is keyed
248+
by the immutable template ID, and creates can claim only their original template.
249+
The complete admitted workload spec supplies image, environment, resources, and
250+
driver configuration. Normal Pod admission and shape checks still apply.
251+
252+
The reconciler records a bounded plan in `warm_pool_journal` before creating
253+
resources. CAS writes coordinate replicas; `warm_pool.revision` fences older
254+
operator configurations. The fingerprint covers canonical driver settings,
255+
workload shape and public verification keys. Deleted templates leave journal
256+
tombstones that drain old inventory, even after restart. Recreating a name gets a
257+
new pool. Disabling pooling drains spares without affecting claimed sandboxes.
258+
Recovery requires namespace-scoped Secret `get`, granted by default in shared
259+
mode and by the operator workspace chart's `gateway.warmPoolSecretReads` setting.
260+
Kubernetes cannot constrain generated names by prefix; no list/watch is added.
261+
262+
Each pool attempts at most four operations concurrently per pass, retries
263+
unfinished operations no sooner than 30 seconds later, and bounds an operation
264+
to 25 seconds. Pending intents, retiring resources and untracked physical CRs
265+
all consume the pool maximum. Retirement resumes after restart, and late CR
266+
writes for completed intents are collected as untracked resources. A missing
267+
or replaced observed CR is retired rather than recreated. Failed inventory or
268+
journal reads stop the pass. Template deletion and the disable switch both drain unused capacity.
269+
270+
Shared readiness comes from the current supervisor owner's `PREPARED` report with an
271+
authenticated parked connection. Dedicated spares have a separate supervisor Pod:
272+
its startup probe succeeds only after TLS authenticates the runtime. Normal Pod
273+
readiness stays false until the claim has started supervision. The driver checks
274+
the original supervisor Pod UID, successful startup, and absence of restarts.
275+
If the parked runtime disconnects before a claim, its dedicated supervisor exits.
276+
Terminated or restarted supervisors cannot make that spare eligible again; the
277+
pool retires and replaces it. The startup verdict therefore lasts only as long as
278+
the process holding the authenticated connection.
279+
The loop counts reserved or released runtimes as pending until then. A missing
280+
owner, preparation timeout, maximum age or
281+
60 seconds without a ready observation retires the spare. Template workloads pass through the normal driver conversion and admission.
282+
Managed namespace pooling remains unsupported.
283+
284+
A dedicated supervisor starts with public runtime coordinates and gateway TLS trust
285+
mounted before the scheduling gate opens. It holds the authenticated runtime
286+
connection and opens the private `RegisterSupervisor` server stream using its
287+
Pod-bound ServiceAccount token. The gateway keeps the stream pending until the
288+
durable claim commits, revalidates the physical binding and current credential
289+
epoch, and returns the canonical `SandboxInstanceRegistration`. The response
290+
contains the logical identity, credentials, process configuration, and proxy CA.
291+
No claim-time volume update is needed. The supervisor validates the response
292+
against its preparation and adopts the existing route. Transport loss or bootstrap
293+
credential expiry reconnects registration; an unclaimed runtime does not. Gateway
294+
TLS is required. Shared supervisors keep their existing assignment stream.
295+
There is no registration RPC, runtime-to-gateway exchange, or claim retry on the
296+
runtime connection. Both Pods and the TLS pin survive the claim. Stop removes the
297+
original physical supervisor; restart provisions a fresh generation.
298+
299+
Sandbox creation from a template selects a ready spare from that template's
300+
current pool revision in the same workspace. Its rendered Pod shape and child environment must match exactly;
301+
non-matching requests and empty pools use cold creation. The driver writes a
302+
Pod-owned immutable claim Secret, then CAS-labels the physical CR with the logical
303+
Sandbox ID before gateway activation. Retirement and competing claims use the
304+
same CR fence. After this point an error never falls back to a second runtime.
305+
Activation atomically replaces the proposed cold identity with the physical
306+
binding and canonical credentials. The canonical registration is persisted under
307+
the logical Sandbox's generation Secret name for existing recovery. Reconciliation
308+
finishes interrupted claims. Restart uses a new generation and updates the Pod's
309+
pair label; the original physical CR name remains unchanged.
310+
311+
The focused gateway-backed claim E2E uses fresh branch images and checks physical
312+
Pod reuse, refill, exec, and stop/start with a new identity:
313+
314+
```shell
315+
OPENSHELL_E2E_KUBE_TLS=1 \
316+
OPENSHELL_E2E_KUBE_EXTRA_VALUES=deploy/helm/openshell/ci/values-supervisor.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml:e2e/kubernetes/values-warm-pool.yaml \
317+
e2e/with-kube-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml \
318+
--features e2e-kubernetes-shared-supervisor --test kubernetes_warm_pool -- --ignored --nocapture
319+
```
320+
321+
The Kubernetes API integration test exercises real Sandbox CRD defaulting, Pod
322+
creation, Secret ownership, gate release, journal recovery and conditional
323+
retirement. It uses an
324+
in-memory capacity authority; it does not test runtime activation. From the
325+
repository root, run it in an ephemeral cluster with:
326+
327+
```shell
328+
OPENSHELL_E2E_KUBE_TLS=1 \
329+
OPENSHELL_E2E_KUBE_EXTRA_VALUES=deploy/helm/openshell/ci/values-supervisor.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml \
330+
e2e/with-kube-gateway.sh cargo test -p openshell-driver-kubernetes --lib \
331+
warm_runtime_resources_on_kubernetes -- --ignored --nocapture
332+
```
333+
189334
### Shared supervisor topology
190335

191336
With `supervisor_topology = "gateway"`, each new runtime

‎crates/openshell-driver-kubernetes/src/config.rs‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,9 +286,68 @@ fn is_dns_label(value: &str) -> bool {
286286
&& !value.ends_with('-')
287287
}
288288

289+
/// Operator limits for template-driven spare capacity. Templates supply the
290+
/// workload and desired count; this switch only disables the optimization.
291+
#[derive(Debug, Clone, Serialize, Deserialize)]
292+
#[serde(default, deny_unknown_fields)]
293+
pub struct WarmPoolSettings {
294+
pub enabled: bool,
295+
/// Increment when changing driver configuration or runtime trust.
296+
pub revision: u64,
297+
/// Per-template bound, including provisioning and deleting spares.
298+
pub max_size: u32,
299+
pub max_age_secs: u64,
300+
pub preparation_timeout_secs: u64,
301+
}
302+
303+
impl Default for WarmPoolSettings {
304+
fn default() -> Self {
305+
Self {
306+
enabled: true,
307+
revision: 1,
308+
max_size: 16,
309+
max_age_secs: 3600,
310+
preparation_timeout_secs: 300,
311+
}
312+
}
313+
}
314+
315+
/// Internal plan derived from a persisted workload template, never TOML input.
316+
#[derive(Debug, Clone)]
317+
pub struct WarmPoolConfig {
318+
pub name: String,
319+
pub workspace: String,
320+
pub revision: u64,
321+
pub target_size: u32,
322+
pub max_size: u32,
323+
pub max_age_secs: u64,
324+
pub preparation_timeout_secs: u64,
325+
pub spec: openshell_core::proto::compute::v1::DriverSandboxSpec,
326+
}
327+
328+
impl WarmPoolConfig {
329+
pub fn validate(&self) -> Result<(), String> {
330+
if !is_dns_label(&self.name)
331+
|| !is_dns_label(&self.workspace)
332+
|| self.revision == 0
333+
|| self.max_size == 0
334+
|| self.max_size > 256
335+
|| self.target_size > self.max_size
336+
|| !(60..=86_400).contains(&self.max_age_secs)
337+
|| !(30..=3600).contains(&self.preparation_timeout_secs)
338+
|| self.preparation_timeout_secs > self.max_age_secs
339+
{
340+
return Err("invalid template warm-pool plan".into());
341+
}
342+
Ok(())
343+
}
344+
}
345+
289346
#[derive(Debug, Clone, Serialize, Deserialize)]
290347
#[serde(default, deny_unknown_fields)]
291348
pub struct KubernetesComputeConfig {
349+
/// Template-driven spare capacity, enabled by default.
350+
pub warm_pool: WarmPoolSettings,
292351
/// Supervise new sandbox generations with one supervisor shared by the
293352
/// gateway instead of a supervisor Pod per sandbox. Existing generations
294353
/// keep the topology recorded when they started.
@@ -500,6 +559,7 @@ pub const ANNOTATION_SCC_SUPPLEMENTAL_GROUPS: &str = "openshift.io/sa.scc.supple
500559
impl Default for KubernetesComputeConfig {
501560
fn default() -> Self {
502561
Self {
562+
warm_pool: WarmPoolSettings::default(),
503563
supervisor_topology: None,
504564
shared_supervisor: None,
505565
workspace_mode: WorkspaceMode::default(),
@@ -555,9 +615,24 @@ impl Default for KubernetesComputeConfig {
555615
}
556616

557617
impl KubernetesComputeConfig {
618+
pub fn validate_warm_pools(&self) -> Result<(), String> {
619+
let pool = &self.warm_pool;
620+
if pool.revision == 0
621+
|| pool.revision == u64::MAX
622+
|| pool.max_size == 0
623+
|| pool.max_size > 256
624+
|| !(60..=86_400).contains(&pool.max_age_secs)
625+
|| !(30..=3600).contains(&pool.preparation_timeout_secs)
626+
|| pool.preparation_timeout_secs > pool.max_age_secs
627+
{
628+
return Err("warm_pool requires a positive revision below u64::MAX, max_size 1..256, age 60..86400s, and preparation timeout 30..3600s <= age".into());
629+
}
630+
Ok(())
631+
}
558632
/// Validate startup configuration without connecting to Kubernetes.
559633
pub fn validate_configuration(&self) -> Result<(), String> {
560634
self.validate_bootstrap_windows()?;
635+
self.validate_warm_pools()?;
561636
self.validate_supervisor_topology()?;
562637
self.validate_workspace_mode()?;
563638
self.validate_provider_spiffe_workload_api_socket_path()?;

0 commit comments

Comments
 (0)