Skip to content

Commit 148f85f

Browse files
committed
feat(kubernetes): create SandboxClaims for matching warm pools
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent 57f1719 commit 148f85f

20 files changed

Lines changed: 2327 additions & 175 deletions

File tree

‎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: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ delete, reconciliation removes the row; otherwise it can remain `Deleting`.
6464
|---|---|---|---|
6565
| Docker | Local development with Docker available. | Container plus nested sandbox namespace. | Uses host networking so loopback gateway endpoints work from the supervisor. |
6666
| Podman | Rootless or single-machine deployments. | Container plus nested sandbox namespace. | Uses the Podman REST API, OCI image volumes, and CDI GPU devices when available. |
67-
| Kubernetes | Cluster deployment through Helm. | Pod plus nested sandbox namespace. | Uses Kubernetes API objects, service accounts, secrets, PVC-backed workspace storage, and GPU resources. |
67+
| Kubernetes | Cluster deployment through Helm. | Pod plus nested sandbox namespace. | Uses Kubernetes API objects, service accounts, secrets, PVC-backed workspace storage, GPU resources, and optionally Agent Sandbox v1beta1 warm-pool claims. |
6868
| VM | Experimental microVM isolation. | Per-sandbox libkrun VM. | Managed endpoint-backed driver. The gateway spawns `openshell-driver-vm`, waits for its Unix socket, and then consumes it through the same remote `compute_driver.proto` path used by unmanaged endpoint drivers. The VM driver boots a cached bootstrap `rootfs.ext4`, prepares requested OCI images inside a bootstrap VM with `umoci`, attaches the prepared image disk read-only, and gives each sandbox a writable `overlay.ext4` for merged-root changes and runtime material. The driver persists each accepted launch request beside the overlay and restarts those VMs on driver startup without recreating the overlay. |
6969
| Extension | Out-of-tree drivers operated alongside the gateway. | Whatever boundary the driver implements. | Selected by a non-reserved custom `compute_drivers = ["<name>"]` entry with `[openshell.drivers.<name>].socket_path`, or at launch time by pairing `--drivers <name>` with `--compute-driver-socket=<path>`. Reserved built-in names such as `vm`, `docker`, `podman`, and `kubernetes` cannot be used as unmanaged socket endpoints. The gateway connects to a UDS the operator already provisioned, runs `GetCapabilities`, logs the advertised `driver_name`, and dispatches all sandbox lifecycle calls through `compute_driver.proto`. The driver process and socket lifecycle are operator-owned; the gateway does not spawn, supervise, or remove unmanaged extension drivers. The trust boundary is the socket's filesystem permissions: the operator must ensure only the gateway uid can read/write it. |
7070

@@ -134,6 +134,13 @@ JWT. The supervisor installs that JWT in memory and starts the normal
134134
pod IPs or require an inbound activation port; activation is supervisor
135135
initiated over the existing outbound gRPC connection.
136136

137+
When compatible OpenShell-enabled Agent Sandbox warm pools exist, the
138+
Kubernetes driver can create a `SandboxClaim` instead of a direct `Sandbox`.
139+
The driver watches warm pools and templates into a local cache so create
140+
requests do not list or fetch extension objects on the hot path. This remains
141+
behind the compute-driver boundary: other drivers and the driver-agnostic
142+
gateway lifecycle continue to operate on OpenShell sandbox identity and status.
143+
137144
Kubernetes can run the supervisor in the default combined topology or in a
138145
sidecar topology. Combined mode keeps network and process supervision in the
139146
agent container. Sidecar mode runs network enforcement, the proxy, and gateway

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

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
2525
use crate::proto::{
2626
DenialSummary, GetDraftPolicyRequest, GetInferenceBundleRequest, GetInferenceBundleResponse,
2727
GetSandboxConfigRequest, GetSandboxProviderEnvironmentRequest, NetworkActivitySummary,
28-
PolicyChunk, PolicySource, PolicyStatus, RefreshSandboxTokenRequest,
28+
PodActivationMessage, PolicyChunk, PolicySource, PolicyStatus, RefreshSandboxTokenRequest,
2929
RegisterSupervisorPodRequest, ReportPolicyStatusRequest, SandboxPolicy as ProtoSandboxPolicy,
3030
SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, UpdateConfigRequest,
3131
inference_client::InferenceClient, open_shell_client::OpenShellClient,
@@ -272,7 +272,9 @@ async fn acquire_sandbox_token(endpoint: &str, plain_channel: &Channel) -> Resul
272272
&& !sa_path.is_empty()
273273
{
274274
return Ok(AcquiredToken {
275-
token: acquire_k8s_sandbox_token(endpoint, plain_channel, &sa_path).await?,
275+
token: acquire_k8s_supervisor_activation(endpoint, plain_channel, &sa_path)
276+
.await?
277+
.token,
276278
refresh_mode: RefreshMode::GatewayJwt(TokenSource::K8sServiceAccount),
277279
});
278280
}
@@ -290,6 +292,18 @@ async fn acquire_k8s_sandbox_token(
290292
plain_channel: &Channel,
291293
sa_path: &str,
292294
) -> Result<String> {
295+
Ok(
296+
acquire_k8s_supervisor_activation(endpoint, plain_channel, sa_path)
297+
.await?
298+
.token,
299+
)
300+
}
301+
302+
async fn acquire_k8s_supervisor_activation(
303+
endpoint: &str,
304+
plain_channel: &Channel,
305+
sa_path: &str,
306+
) -> Result<PodActivationMessage> {
293307
let sa_token = std::fs::read_to_string(sa_path)
294308
.into_diagnostic()
295309
.wrap_err_with(|| format!("failed to read K8s SA token from {sa_path}"))?
@@ -324,7 +338,61 @@ async fn acquire_k8s_sandbox_token(
324338
sandbox_name = %activation.sandbox_name,
325339
"received supervisor pod activation"
326340
);
327-
Ok(activation.token)
341+
Ok(activation)
342+
}
343+
344+
/// Register a Kubernetes supervisor pod and install the activated gateway JWT.
345+
///
346+
/// Warm pods call this before policy loading. The registration stream remains
347+
/// pending until the Kubernetes driver observes a claim binding and the gateway
348+
/// sends activation.
349+
pub async fn register_k8s_supervisor_pod(endpoint: &str) -> Result<PodActivationMessage> {
350+
let sa_path = std::env::var(sandbox_env::K8S_SA_TOKEN_FILE)
351+
.ok()
352+
.filter(|path| !path.is_empty())
353+
.ok_or_else(|| {
354+
miette::miette!(
355+
"{} must be set to register Kubernetes supervisor pod",
356+
sandbox_env::K8S_SA_TOKEN_FILE
357+
)
358+
})?;
359+
360+
let mut backoff = Duration::from_secs(1);
361+
loop {
362+
let activation = {
363+
let guard = TOKEN_INIT_LOCK.lock().await;
364+
if TOKEN_SLOT.get().is_some() {
365+
return Err(miette::miette!(
366+
"Kubernetes supervisor pod registration was requested after sandbox token initialization"
367+
));
368+
}
369+
370+
match async {
371+
let plain_channel = build_plain_channel(endpoint).await?;
372+
acquire_k8s_supervisor_activation(endpoint, &plain_channel, &sa_path).await
373+
}
374+
.await
375+
{
376+
Ok(activation) => activation,
377+
Err(err) => {
378+
warn!(
379+
endpoint = %endpoint,
380+
error = %err,
381+
retry_after_secs = backoff.as_secs(),
382+
"Kubernetes supervisor pod registration failed; retrying: {err:#}"
383+
);
384+
drop(guard);
385+
tokio::time::sleep(backoff).await;
386+
backoff = (backoff * 2).min(Duration::from_secs(30));
387+
continue;
388+
}
389+
}
390+
};
391+
392+
let _slot = install_token_slot(&activation.token)?;
393+
let _ = TOKEN_REFRESH_MODE.set(RefreshMode::GatewayJwt(TokenSource::K8sServiceAccount));
394+
return Ok(activation);
395+
}
328396
}
329397

330398
/// Build an authenticated channel for direct external use (e.g. the

‎crates/openshell-driver-kubernetes/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ kube-runtime = { workspace = true }
2929
k8s-openapi = { workspace = true }
3030
serde = { workspace = true }
3131
serde_json = { workspace = true }
32+
sha2 = { workspace = true }
3233
clap = { workspace = true }
3334
tracing = { workspace = true }
3435
tracing-subscriber = { workspace = true }

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,26 @@ by the gateway.
2626
Kubernetes API calls use explicit timeouts so gRPC handlers do not block
2727
indefinitely when the API server is slow or unavailable.
2828

29+
## Warm-Pool Allocation
30+
31+
The driver can use Agent Sandbox extension CRDs for transparent warm-pool
32+
allocation. When `warm_pooling.enabled` is true, the driver watches and caches
33+
`extensions.agents.x-k8s.io/v1beta1` `SandboxWarmPool` resources labelled
34+
`openshell.ai/enabled=true`, resolves each pool's referenced
35+
`SandboxTemplate`, and computes an in-memory fingerprint of the template spec.
36+
37+
On create, the driver renders the Kubernetes spec that direct `Sandbox`
38+
creation would use, strips per-sandbox identity values from the fingerprint,
39+
and matches it against the warm-pool cache for the target Kubernetes namespace.
40+
If exactly one pool matches, the driver creates a v1beta1 `SandboxClaim` with
41+
`spec.warmPoolRef.name` set to that pool. If no pool matches, multiple pools
42+
match, RBAC prevents cache maintenance, or the v1beta1 extension APIs are
43+
unavailable, the driver falls back to direct `Sandbox` creation.
44+
45+
The extension CRDs are intentionally v1beta1-only. The core
46+
`agents.x-k8s.io/Sandbox` CRD still supports the existing v1beta1-to-v1alpha1
47+
fallback.
48+
2949
## Workspace Persistence
3050

3151
Sandbox pods use a PVC-backed `/sandbox` workspace. An init container seeds the

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,20 @@ impl KubernetesSidecarConfig {
125125
}
126126
}
127127

128+
#[derive(Debug, Clone, Serialize, Deserialize)]
129+
#[serde(default, deny_unknown_fields)]
130+
pub struct KubernetesWarmPoolingConfig {
131+
/// Allow the Kubernetes driver to satisfy compatible create requests by
132+
/// creating v1beta1 Agent Sandbox `SandboxClaim` resources.
133+
pub enabled: bool,
134+
}
135+
136+
impl Default for KubernetesWarmPoolingConfig {
137+
fn default() -> Self {
138+
Self { enabled: true }
139+
}
140+
}
141+
128142
/// Kubernetes `AppArmor` profile requested for the sandbox agent container.
129143
#[derive(Debug, Clone, PartialEq, Eq)]
130144
pub enum AppArmorProfile {
@@ -253,6 +267,8 @@ pub struct KubernetesComputeConfig {
253267
pub topology: SupervisorTopology,
254268
/// Sidecar-only settings used when `topology = "sidecar"`.
255269
pub sidecar: KubernetesSidecarConfig,
270+
/// Warm-pool allocation settings.
271+
pub warm_pooling: KubernetesWarmPoolingConfig,
256272
pub grpc_endpoint: String,
257273
pub ssh_socket_path: String,
258274
pub client_tls_secret_name: String,
@@ -340,6 +356,7 @@ impl Default for KubernetesComputeConfig {
340356
supervisor_sideload_method: SupervisorSideloadMethod::default(),
341357
topology: SupervisorTopology::default(),
342358
sidecar: KubernetesSidecarConfig::default(),
359+
warm_pooling: KubernetesWarmPoolingConfig::default(),
343360
grpc_endpoint: String::new(),
344361
ssh_socket_path: "/run/openshell/ssh.sock".to_string(),
345362
client_tls_secret_name: String::new(),
@@ -533,6 +550,34 @@ mod tests {
533550
assert!(cfg.sidecar.process_binary_aware_network_policy);
534551
}
535552

553+
#[test]
554+
fn default_warm_pooling_is_enabled() {
555+
let cfg = KubernetesComputeConfig::default();
556+
assert!(cfg.warm_pooling.enabled);
557+
}
558+
559+
#[test]
560+
fn serde_override_warm_pooling_enabled() {
561+
let json = serde_json::json!({
562+
"warm_pooling": {
563+
"enabled": false
564+
}
565+
});
566+
let cfg: KubernetesComputeConfig = serde_json::from_value(json).unwrap();
567+
assert!(!cfg.warm_pooling.enabled);
568+
}
569+
570+
#[test]
571+
fn serde_rejects_unknown_warm_pooling_field() {
572+
let json = serde_json::json!({
573+
"warm_pooling": {
574+
"mode": "always"
575+
}
576+
});
577+
let err = serde_json::from_value::<KubernetesComputeConfig>(json).unwrap_err();
578+
assert!(err.to_string().contains("unknown field"));
579+
}
580+
536581
#[test]
537582
fn serde_override_topology_sidecar() {
538583
let json = serde_json::json!({

0 commit comments

Comments
 (0)