Skip to content

Commit 810e1e5

Browse files
committed
fix(kubernetes): recover warm claims and reuse prepared runtimes
Signed-off-by: Gordon Sim <gsim@redhat.com>
1 parent e892dcd commit 810e1e5

18 files changed

Lines changed: 778 additions & 264 deletions

File tree

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,8 @@ The `prepared_runtime` module supplies bootstrap persistence for OpenShell-owned
192192
warm runtimes. `KubernetesSandboxRuntimeBoundarySpec::provision_prepared`
193193
builds an unassigned runtime with a shared-supervisor route and physical resource
194194
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`.
195+
containing its boundary configuration, TLS certificate, and private key. The gateway
196+
stores the public preparation descriptor when it reserves capacity through `SharedSupervision`.
197197
It supplies no logical Sandbox ID, gateway session token, or workload credentials.
198198

199199
The controller must persist the physical session, generation and route first,
@@ -279,7 +279,8 @@ its startup probe succeeds only after TLS authenticates the runtime. Before clai
279279
readiness requires both the parked runtime and an accepted gateway registration.
280280
A disconnected registration closes the readiness listener until it reconnects.
281281
The driver checks Pod readiness, the original supervisor UID, successful startup,
282-
and absence of restarts. After claim, normal supervision owns readiness.
282+
and absence of restarts. Dedicated bootstrap completes after the gateway observes
283+
the claimed generation’s authenticated supervisor session.
283284
If the parked runtime disconnects before a claim, its dedicated supervisor exits.
284285
Terminated or restarted supervisors cannot make that spare eligible again; the
285286
pool retires and replaces it. The startup verdict therefore lasts only as long as

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

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3087,21 +3087,29 @@ impl KubernetesComputeDriver {
30873087
namespace: &str,
30883088
names: &SandboxRuntimeNames,
30893089
) -> Result<(), KubernetesDriverError> {
3090+
let policies = Api::namespaced(self.client.clone(), namespace);
3091+
for policy in self.sandbox_runtime_fences(namespace, names) {
3092+
create_or_validate_sandbox_runtime_fence(&policies, &policy).await?;
3093+
}
3094+
Ok(())
3095+
}
3096+
3097+
fn sandbox_runtime_fences(
3098+
&self,
3099+
namespace: &str,
3100+
names: &SandboxRuntimeNames,
3101+
) -> [NetworkPolicy; 2] {
30903102
let fence = workload_fence(namespace, names, self.config.sandbox_runtime.boundary_port);
3091-
let policies: Api<NetworkPolicy> = Api::namespaced(self.client.clone(), namespace);
3092-
for (mut policy, component) in [
3103+
[
30933104
(fence.workload_policy, "sandbox-workload-fence"),
30943105
(fence.supervisor_policy, "sandbox-supervisor-egress"),
3095-
] {
3106+
]
3107+
.map(|(mut policy, component)| {
30963108
let labels = policy.metadata.labels.get_or_insert_default();
3097-
labels.insert(
3098-
LABEL_MANAGED_BY.to_string(),
3099-
LABEL_MANAGED_BY_VALUE.to_string(),
3100-
);
3101-
labels.insert("openshell.ai/component".to_string(), component.to_string());
3102-
create_or_validate_sandbox_runtime_fence(&policies, &policy).await?;
3103-
}
3104-
Ok(())
3109+
labels.insert(LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into());
3110+
labels.insert("openshell.ai/component".into(), component.into());
3111+
policy
3112+
})
31053113
}
31063114

31073115
/// Create or validate the gateway-owned destination-trust generation for
@@ -5282,15 +5290,25 @@ impl KubernetesComputeDriver {
52825290
}
52835291
}
52845292
if sandbox_runtime_bootstrap_in_progress(&object) {
5285-
if generation_control_availability(
5286-
&self.client,
5287-
self.shared_supervisor.as_ref(),
5288-
namespace,
5289-
&sandbox_id,
5290-
&object,
5291-
)
5292-
.await
5293-
== SandboxRuntimeControlAvailability::Available
5293+
// A dedicated spare already passes the Pod readiness probe before delivery.
5294+
// Wait for the claimed generation's authenticated supervision session.
5295+
let started = match self.dedicated_bootstrap_started(&object, &sandbox_id).await {
5296+
Ok(started) => started,
5297+
Err(error) => {
5298+
warn!(%sandbox_id, %error, "could not check warm supervisor session");
5299+
continue;
5300+
}
5301+
};
5302+
if started
5303+
&& generation_control_availability(
5304+
&self.client,
5305+
self.shared_supervisor.as_ref(),
5306+
namespace,
5307+
&sandbox_id,
5308+
&object,
5309+
)
5310+
.await
5311+
== SandboxRuntimeControlAvailability::Available
52945312
&& sandbox_runtime_bootstrap_is_ready_to_complete(&object)
52955313
{
52965314
self.complete_sandbox_runtime_bootstrap(&lookup_api, &object)

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

Lines changed: 18 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ use crate::sandbox_runtime::{
3232
BOUNDARY_PRIVATE_KEY_PATH,
3333
};
3434

35-
const REGISTRATION_KEY: &str = "prepared-runtime.json";
3635
const WORKSPACE_ANNOTATION: &str = "openshell.ai/prepared-runtime-workspace";
3736
const MAX_BOOTSTRAP_BYTES: usize = 512 * 1024;
3837

@@ -90,7 +89,7 @@ impl PreparedRuntimeBootstrap {
9089
let material = generate_sandbox_tls_material(self.session_id).map_err(backend_error)?;
9190
let provisioning = provision(tls_pin(&material)).map_err(backend_error)?;
9291
let request = self.request(&provisioning)?;
93-
let candidate = self.secret(&provisioning, &request.registration, material)?;
92+
let candidate = self.secret(&provisioning, material)?;
9493
Api::<Secret>::namespaced(client, &self.namespace)
9594
.create(&PostParams::default(), &candidate)
9695
.await
@@ -192,15 +191,24 @@ impl PreparedRuntimeBootstrap {
192191
fn secret(
193192
&self,
194193
provisioning: &KubernetesSandboxRuntimeBoundaryProvisioning,
195-
registration: &PreparedRuntimeRegistration,
196194
material: SandboxTlsMaterial,
197195
) -> Result<Secret, KubernetesDriverError> {
198-
if registration.runtime_descriptor.tls != tls_pin(&material) {
196+
if provisioning.runtime_descriptor.tls != tls_pin(&material) {
199197
return Err(invalid(
200198
"provisioning did not preserve the generated TLS identity",
201199
));
202200
}
203-
let secret = Secret {
201+
let config = provisioning
202+
.boundary_config
203+
.encode()
204+
.map_err(backend_error)?;
205+
if config.len() + material.certificate_chain_pem.len() + material.private_key_pem.len()
206+
> MAX_BOOTSTRAP_BYTES
207+
{
208+
return Err(invalid("prepared bootstrap Secret exceeds its size limit"));
209+
}
210+
validate_server_key(&material)?;
211+
Ok(Secret {
204212
metadata: ObjectMeta {
205213
namespace: Some(self.namespace.clone()),
206214
name: Some(self.secret_name.clone()),
@@ -214,22 +222,7 @@ impl PreparedRuntimeBootstrap {
214222
immutable: Some(true),
215223
type_: Some("Opaque".into()),
216224
data: Some(BTreeMap::from([
217-
(
218-
BOUNDARY_CONFIG_KEY.into(),
219-
ByteString(
220-
provisioning
221-
.boundary_config
222-
.encode()
223-
.map_err(backend_error)?,
224-
),
225-
),
226-
(
227-
REGISTRATION_KEY.into(),
228-
ByteString(
229-
serde_json::to_vec(registration)
230-
.map_err(|_| invalid("cannot encode prepared registration"))?,
231-
),
232-
),
225+
(BOUNDARY_CONFIG_KEY.into(), ByteString(config)),
233226
(
234227
BOUNDARY_CERTIFICATE_KEY.into(),
235228
ByteString(material.certificate_chain_pem.into_bytes()),
@@ -240,66 +233,18 @@ impl PreparedRuntimeBootstrap {
240233
),
241234
])),
242235
..Default::default()
243-
};
244-
self.read_registration(&secret)?;
245-
Ok(secret)
246-
}
247-
248-
fn read_registration(
249-
&self,
250-
secret: &Secret,
251-
) -> Result<PreparedRuntimeRegistration, KubernetesDriverError> {
252-
if secret.metadata.namespace.as_ref() != Some(&self.namespace)
253-
|| secret.metadata.name.as_ref() != Some(&self.secret_name)
254-
|| secret.metadata.deletion_timestamp.is_some()
255-
|| secret.metadata.owner_references.as_deref() != Some(&[self.owner()])
256-
|| secret
257-
.metadata
258-
.annotations
259-
.as_ref()
260-
.and_then(|a| a.get(WORKSPACE_ANNOTATION))
261-
!= Some(&self.workspace)
262-
|| secret.immutable != Some(true)
263-
|| secret.type_.as_deref() != Some("Opaque")
264-
{
265-
return Err(invalid(
266-
"prepared bootstrap Secret ownership or immutability changed",
267-
));
268-
}
269-
let data = secret
270-
.data
271-
.as_ref()
272-
.ok_or_else(|| invalid("prepared bootstrap Secret is empty"))?;
273-
if data.len() != 4 || data.values().map(|v| v.0.len()).sum::<usize>() > MAX_BOOTSTRAP_BYTES
274-
{
275-
return Err(invalid("invalid prepared bootstrap Secret size or keys"));
276-
}
277-
for key in [
278-
BOUNDARY_CONFIG_KEY,
279-
BOUNDARY_CERTIFICATE_KEY,
280-
BOUNDARY_PRIVATE_KEY,
281-
] {
282-
secret_value(secret, key)?;
283-
}
284-
let registration: PreparedRuntimeRegistration =
285-
serde_json::from_slice(secret_value(secret, REGISTRATION_KEY)?)
286-
.map_err(|_| invalid("invalid stored prepared runtime registration"))?;
287-
registration
288-
.validate()
289-
.map_err(|_| invalid("invalid stored prepared runtime registration"))?;
290-
validate_server_key(secret)?;
291-
Ok(registration)
236+
})
292237
}
293238
}
294239

295-
fn validate_server_key(secret: &Secret) -> Result<(), KubernetesDriverError> {
240+
fn validate_server_key(material: &SandboxTlsMaterial) -> Result<(), KubernetesDriverError> {
296241
// PEM is a parsing type; all key loading and matching use the crypto facade's
297242
// TLS provider, just as they do when the runtime starts its listener.
298243
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
299-
let certs = CertificateDer::pem_slice_iter(secret_value(secret, BOUNDARY_CERTIFICATE_KEY)?)
244+
let certs = CertificateDer::pem_slice_iter(material.certificate_chain_pem.as_bytes())
300245
.collect::<Result<Vec<_>, _>>()
301246
.map_err(|_| invalid("invalid prepared TLS certificate"))?;
302-
let key = PrivateKeyDer::from_pem_slice(secret_value(secret, BOUNDARY_PRIVATE_KEY)?)
247+
let key = PrivateKeyDer::from_pem_slice(material.private_key_pem.as_bytes())
303248
.map_err(|_| invalid("invalid prepared TLS key"))?;
304249
openshell_crypto::tls::try_server_builder()
305250
.map_err(|_| invalid("cannot configure prepared runtime TLS"))?
@@ -309,16 +254,6 @@ fn validate_server_key(secret: &Secret) -> Result<(), KubernetesDriverError> {
309254
Ok(())
310255
}
311256

312-
fn secret_value<'a>(secret: &'a Secret, key: &str) -> Result<&'a [u8], KubernetesDriverError> {
313-
secret
314-
.data
315-
.as_ref()
316-
.and_then(|data| data.get(key))
317-
.filter(|v| !v.0.is_empty())
318-
.map(|v| v.0.as_slice())
319-
.ok_or_else(|| invalid("prepared bootstrap Secret is incomplete"))
320-
}
321-
322257
fn tls_pin(material: &SandboxTlsMaterial) -> SandboxTlsClientConfig {
323258
SandboxTlsClientConfig {
324259
server_name: material.server_name.clone(),

‎crates/openshell-driver-kubernetes/src/prepared_runtime/tests.rs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,18 @@ async fn preparation_recovers_public_identity_without_reading_secrets() {
232232
.await
233233
.unwrap();
234234
assert_eq!(first, recovered);
235+
let state = state.lock().unwrap();
236+
let keys = state.secret.as_ref().unwrap().data.as_ref().unwrap();
237+
assert_eq!(keys.len(), 3);
238+
for key in [
239+
BOUNDARY_CONFIG_KEY,
240+
BOUNDARY_CERTIFICATE_KEY,
241+
BOUNDARY_PRIVATE_KEY,
242+
] {
243+
assert!(keys.contains_key(key));
244+
}
235245
assert_eq!(
236-
state.lock().unwrap().events,
246+
state.events,
237247
["create", "other-bootstrap-writes", "prepare"]
238248
);
239249
}

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -341,13 +341,15 @@ impl KubernetesComputeDriver {
341341
&self,
342342
workspace: &str,
343343
) -> Result<Vec<WarmRuntimeResource>, KubernetesDriverError> {
344-
self.list_warm_runtime_inventory(workspace, None).await
344+
self.list_warm_runtime_inventory(workspace, None, false)
345+
.await
345346
}
346347

347348
async fn list_warm_runtime_inventory(
348349
&self,
349350
workspace: &str,
350351
pool_id: Option<&str>,
352+
unclaimed_only: bool,
351353
) -> Result<Vec<WarmRuntimeResource>, KubernetesDriverError> {
352354
self.check_warm_runtime_support()?;
353355
let namespace = self.warm_runtime_namespace(workspace).await?;
@@ -357,10 +359,14 @@ impl KubernetesComputeDriver {
357359
.map_err(KubernetesDriverError::Message)?;
358360
let pool_selector =
359361
pool_id.map_or_else(|| POOL_LABEL.to_string(), |id| format!("{POOL_LABEL}={id}"));
360-
let selector = format!(
362+
let mut selector = format!(
361363
"{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_GATEWAY_ID}={},{}={workspace},{pool_selector}",
362364
self.config.gateway_id, LABEL_SANDBOX_WORKSPACE
363365
);
366+
if unclaimed_only {
367+
selector.push_str(",!");
368+
selector.push_str(LABEL_SANDBOX_ID);
369+
}
364370
let objects = api
365371
.api
366372
.list(&ListParams::default().labels(&selector))
@@ -415,7 +421,7 @@ impl KubernetesComputeDriver {
415421
if annotation_or_label(&object, LABEL_SANDBOX_ID).is_some()
416422
&& !self
417423
.warm_supervision()?
418-
.pending_warm_claims(&record.workspace, &record.pool_id)
424+
.pool_claim_inventory(&record.workspace, &record.pool_id, Some(record.route()))
419425
.await
420426
.map_err(KubernetesDriverError::Message)?
421427
.retired

0 commit comments

Comments
 (0)