mod connected_command_ready; #[cfg(test)] mod tests; pub(super) use connected_command_ready::CommandReadyPod; #[cfg(test)] pub(super) use connected_command_ready::ConnectedCommandReadiness; use super::store::PlacementRetryDisposition; use super::support::*; use super::*; const LOG_TARGET: &str = module_path!(); /// Grace window for a newly created pod to enter the shared reflector store /// while the reflector watch reports healthy before falling back to a bounded /// direct `GET /pods/{name}`. Once the pod is observed in the reflector store, /// healthy readiness waits strictly on `PodEvents` without polling `GET`. const UNSEEN_POD_FALLBACK_DELAY: Duration = Duration::from_secs(5); enum PodEventWake { Signal, TimedOut, Closed, } #[derive(Debug)] pub(in crate::controllers::substrate::kubernetes) enum PodGet> { Observed(Option), TimedOut, } type PodArc = std::sync::Arc; type OptS = Option; type Snap = (OptS, time::OffsetDateTime); type Skipped = ((OptS, OptS), Instant); type StepSt<'a> = (&'a mut OptS, &'a mut Option, &'a mut Option); enum WaitPodStep { Ready(PodIp), Retired, Pending(bool), } fn pod_ver(p: &SandboxPodView) -> (OptS, OptS) { let u = p.uid().map(str::to_owned); (u, p.resource_version().map(str::to_owned)) } impl KubernetesSubstrate { async fn recv_relevant_pod_event( rx: &mut tokio::sync::broadcast::Receiver, pod_name: &str, wait_until: Instant, ) -> PodEventWake { loop { match timeout_at(wait_until, rx.recv()).await { Ok(Ok( pod_reflector::PodEventSignal::Relisted | pod_reflector::PodEventSignal::CacheDegraded, )) => { return PodEventWake::Signal; } Ok(Ok(pod_reflector::PodEventSignal::Pod(name))) if name == pod_name => { return PodEventWake::Signal; } Ok(Ok(pod_reflector::PodEventSignal::Pod(_))) => continue, Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped))) => { tracing::debug!( pod_name, skipped, "sandbox pod reflector event broadcast lagged during readiness wait; re-checking cache" ); return PodEventWake::Signal; } Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) => { return PodEventWake::Closed; } Err(_) => return PodEventWake::TimedOut, } } } /// Wait on the shared pod reflector until Kubernetes publishes `target`'s /// IP, sending scheduled views of `target` to `observed` once placement is /// recorded so [`Self::node_reported_pod_ip`] can race ahead of kubelet. /// Bounded `GET /pods/{name}` fallback resolution (including terminal or /// absence reconciliation) runs only when the reflector watch is unhealthy, /// when a previously cached pod disappears or turns terminal, or when a /// newly created pod never enters the store within /// [`UNSEEN_POD_FALLBACK_DELAY`]. async fn reflect_until_pod_ip_assigned( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, observed: &tokio::sync::watch::Sender>, ) -> Result, SubstrateError> { let PodProxyWaitTarget { pod_name, .. } = *target; let mut channel_closed = self.pod_events.is_closed(); let mut rx = self.pod_events.subscribe(); let started_at = Instant::now(); let unseen_fallback_at = started_at + UNSEEN_POD_FALLBACK_DELAY; let mut seen_in_store = false; let mut verified_terminal_or_absent = false; let mut terminal_retry_at: Option = None; let mut in_degraded_mode = false; let mut fallback_polled = false; let mut next_fallback_at: Option = None; let mut placed_node: Option = None; let (mut snapshot, mut skipped_cached) = (None, None); let skip_active = |s: &Option, p: &SandboxPodView| { s.as_ref() .is_some_and(|(v, d)| v == &pod_ver(p) && Instant::now() < *d) }; while Instant::now() < deadline { let mut unverified_terminal_or_absent = false; match self.lookup_sandbox_pod(pod_name) { Some(pod) if target.names(&pod) => { seen_in_store = true; if let Some(message) = unbound_unschedulable_message(&pod) { return Err(SubstrateError::Unschedulable { message: format!("sandbox pod is unschedulable: {message}"), }); } if terminal_pod_phase(&pod).is_some() { skipped_cached = None; unverified_terminal_or_absent = !verified_terminal_or_absent; } else if !skip_active(&skipped_cached, &pod) { verified_terminal_or_absent = false; terminal_retry_at = None; let (uv, win) = (!verified_terminal_or_absent, (started_at, deadline)); let st = (&mut placed_node, &mut snapshot, &mut skipped_cached); let step = self.step_cached_wait_pod(sandbox_id, target, win, pod, st, observed); match step.await? { WaitPodStep::Ready(ip) => { return Ok(Some(((ip, PodIpSource::Published), "reflector"))); } WaitPodStep::Retired => return Ok(None), WaitPodStep::Pending(t) => unverified_terminal_or_absent = t && uv, } } } Some(_) => skipped_cached = None, None if seen_in_store => { skipped_cached = None; unverified_terminal_or_absent = !verified_terminal_or_absent; } None => skipped_cached = None, } if unverified_terminal_or_absent && terminal_retry_at.is_none_or(|due| Instant::now() >= due) { fallback_polled = true; match self .fallback_resolve_pod_ip_for_readiness(sandbox_id, target, deadline, observed) .await? { PodGet::Observed(Some(resolved)) => { return Ok(Some((resolved, "fallback_get"))); } PodGet::Observed(None) => { verified_terminal_or_absent = true; unverified_terminal_or_absent = false; terminal_retry_at = None; next_fallback_at = None; } PodGet::TimedOut => { let retry_at = deadline.min(Instant::now() + start_wait_poll_interval(started_at)); terminal_retry_at = Some(retry_at); next_fallback_at = Some(retry_at); } } if let Some(pod) = observed.borrow().as_ref() { placed_node = assigned_pod_node_name(pod).map(str::to_owned); } } let now = Instant::now(); if now >= deadline { break; } let skip_due = skipped_cached.as_ref().map(|(_, due)| *due); let min_opt = |a: Option, b: Option| a.into_iter().chain(b).min(); let healthy = !channel_closed && self.pod_reflector_watch_healthy(); if !healthy { if !in_degraded_mode { in_degraded_mode = true; let delay = if fallback_polled { start_wait_poll_interval(started_at) } else { self.budgets.reflector_wait }; let degraded_due = deadline.min(now + delay); next_fallback_at = Some(next_fallback_at.map_or(degraded_due, |due| due.min(degraded_due))); } else if next_fallback_at.is_none() { next_fallback_at = Some(deadline.min(now + start_wait_poll_interval(started_at))); } next_fallback_at = min_opt(next_fallback_at, skip_due); } else if seen_in_store && !unverified_terminal_or_absent { in_degraded_mode = false; next_fallback_at = skip_due; } else if seen_in_store { in_degraded_mode = false; next_fallback_at = min_opt(terminal_retry_at, skip_due); } else { if in_degraded_mode { in_degraded_mode = false; if !fallback_polled { next_fallback_at = None; } } next_fallback_at.get_or_insert_with(|| { if fallback_polled { deadline.min(now + start_wait_poll_interval(started_at)) } else { deadline.min(unseen_fallback_at) } }); } let wait_until = next_fallback_at.map_or(deadline, |due| deadline.min(due)); if channel_closed { tokio::time::sleep_until(wait_until).await; } else if Instant::now() < wait_until && matches!( Self::recv_relevant_pod_event(&mut rx, pod_name, wait_until).await, PodEventWake::Closed ) { channel_closed = true; } let now = Instant::now(); if now >= deadline { break; } if next_fallback_at.is_none_or(|due| now < due) { continue; } let cached = self .lookup_sandbox_pod(pod_name) .filter(|pod| target.names(pod) && !skip_active(&skipped_cached, pod)); if cached.as_deref().is_some_and(|pod| { assigned_pod_ip(pod).ok().flatten().is_some() || unbound_unschedulable_message(pod).is_some() || (terminal_pod_phase(pod).is_some() && verified_terminal_or_absent) }) { next_fallback_at = None; continue; } if cached .as_deref() .is_some_and(|pod| terminal_pod_phase(pod).is_none()) && !channel_closed && self.pod_reflector_watch_healthy() { next_fallback_at = None; continue; } fallback_polled = true; match self .fallback_resolve_pod_ip_for_readiness(sandbox_id, target, deadline, observed) .await? { PodGet::Observed(Some(resolved)) => { return Ok(Some((resolved, "fallback_get"))); } PodGet::Observed(None) => { if unverified_terminal_or_absent || cached .as_deref() .is_some_and(|pod| terminal_pod_phase(pod).is_some()) { verified_terminal_or_absent = true; terminal_retry_at = None; } } PodGet::TimedOut => { if unverified_terminal_or_absent || cached .as_deref() .is_some_and(|pod| terminal_pod_phase(pod).is_some()) { terminal_retry_at = Some( deadline.min(Instant::now() + start_wait_poll_interval(started_at)), ); } } } if let Some(pod) = observed.borrow().as_ref() { placed_node = assigned_pod_node_name(pod).map(str::to_owned); } next_fallback_at = Some(deadline.min(Instant::now() + start_wait_poll_interval(started_at))); } Ok(None) } async fn step_cached_wait_pod( &self, id: SandboxId, tgt: &PodProxyWaitTarget<'_>, (started_at, dl): (Instant, Instant), mut pod: PodArc, (placed_node, snap, skipped): StepSt<'_>, observed: &tokio::sync::watch::Sender>, ) -> Result { *skipped = None; let (ver, g) = (pod_ver(&pod), tgt.generation); let mk_skip = |v| { Some(( v, dl.min(Instant::now() + start_wait_poll_interval(started_at)), )) }; if snap.is_none() { *snap = self.live_execution_pod_snapshot(id, g).await?; } let Some((mut su, mut sts)) = snap.clone() else { return Ok(WaitPodStep::Retired); }; if tgt.pod_uid.is_none() && su.as_deref().is_some_and(|u| pod.uid() != Some(u)) { match self .reval_wait_pod(id, tgt, (started_at, dl), ver.clone(), (snap, skipped)) .await? { Ok(v) => (pod, su, sts) = v, Err(step) => return Ok(step), } } let mut node = assigned_pod_node_name(&pod); let disp = PlacementRetryDisposition::RetryDuplicatesExecution; if let Some(mut ip) = assigned_pod_ip(&pod)? { let wp = placed_node.as_deref() != node && node.is_some(); let (ip_s, exp) = (ip.to_string(), (g, (su.as_deref(), Some(sts)))); let rem = self.remember_pod_metadata_and_placement(id, exp, &pod, Some(&ip_s), (wp, disp)); match rem.await { Ok(Some(_)) => {} Ok(None) => { let r = self .reval_wait_pod(id, tgt, (started_at, dl), ver.clone(), (snap, skipped)) .await?; let (f, u, ts) = match r { Ok(v) => v, Err(step) => return Ok(step), }; let fe = (g, (u.as_deref(), Some(ts))); let fd = (assigned_pod_node_name(&f).is_some(), disp); let ok_ip = if let Some(ip2) = assigned_pod_ip(&f)? { let s = ip2.to_string(); let r = self.remember_pod_metadata_and_placement(id, fe, &f, Some(&s), fd); r.await?.map(|_| ip2) } else { None }; let Some(ip2) = ok_ip else { *skipped = mk_skip(ver); return Ok(WaitPodStep::Pending(false)); }; (pod, ip) = (f, ip2); } Err(err) if wp || su.as_deref() != pod.uid() => return Err(err), Err(e) => tracing::warn!(%id, g, ?e, "failed to persist pod metadata"), } let node = assigned_pod_node_name(&pod); *placed_node = node.map(str::to_owned); if node.is_some() { observed.send_replace(Some((*pod).clone())); } return Ok(WaitPodStep::Ready(ip)); } if placed_node.as_deref() != node { let exp = Some((g, (su.as_deref(), Some(sts)), pod.uid())); let r = self.remember_pod_node_placement_for_execution(id, &pod, exp, disp); if r.await?.is_none() && node.is_some() { (*skipped, *snap, node) = (mk_skip(ver), None, None); } else { *placed_node = node.map(str::to_owned); *snap = self.live_execution_pod_snapshot(id, g).await?; } } if node.is_some() { observed.send_replace(Some((*pod).clone())); } Ok(WaitPodStep::Pending(false)) } async fn reval_wait_pod( &self, id: SandboxId, tgt: &PodProxyWaitTarget<'_>, (started_at, dl): (Instant, Instant), ver: (OptS, OptS), (snap, skipped): (&mut Option, &mut Option), ) -> Result, SubstrateError> { let Some((u, ts)) = self.live_execution_pod_snapshot(id, tgt.generation).await? else { return Ok(Err(WaitPodStep::Retired)); }; *snap = Some((u.clone(), ts)); let kind = super::pod_ops::ResolutionGetKind::FreshConfirmation; let got = self .get_pod_for_resolution(tgt.pod_name, Some(dl), kind, "failed to verify pod") .await?; let t = match got { PodGet::Observed(Some(f)) if tgt.names(&f) && terminal_pod_phase(&f).is_none() => { return Ok(Ok((f, u, ts))); } PodGet::Observed(_) => true, PodGet::TimedOut => false, }; *skipped = Some(( ver, dl.min(Instant::now() + start_wait_poll_interval(started_at)), )); Ok(Err(WaitPodStep::Pending(t))) } /// The pod IP the pod's node reports for it, once `observed` places the /// pod. The node manager reads it from the pod's network namespace when /// it allocates the sandbox's network, so the node knows it before /// kubelet's status sync publishes the same address. Only an address /// reported for this execution generation and the observed pod's UID is /// taken, as a candidate the readiness probe must confirm before anything /// records it. Only a wait that knows its pod's UID can confirm one. async fn node_reported_pod_ip( &self, sandbox_id: SandboxId, generation: i64, expected_pod_uid: Option<&str>, mut observed: tokio::sync::watch::Receiver>, ) -> Option { let expected_pod_uid = expected_pod_uid?; let pod = observed .wait_for(|pod| { pod.as_ref().is_some_and(|pod| { pod.uid() == Some(expected_pod_uid) && assigned_pod_node_name(pod).is_some() }) }) .await .ok()? .clone()?; let node_name = assigned_pod_node_name(&pod)?; let pod_uid = pod.uid()?; let target = NodeApiTarget { managed_by: pplx_space_node_model::NodeManagedBy::Kubernetes, role: SpaceNodeRole::Worker, direct_endpoint: None, substrate_node_id: Some(node_name), }; let started_at = Instant::now(); let mut worker = None; loop { if worker.is_none() && let Ok(endpoint) = self.try_resolve_node_api_endpoint(&target) { worker = Self::worker_client_at(&endpoint, POD_WORKER_CONNECT_TIMEOUT).await; } if let Some(client) = worker.as_mut() { let state = timeout( POD_WORKER_CONNECT_TIMEOUT, client.sandbox_state(pplx_space_sbx_mgr_client::proto::StateRequest { sandbox_ids: vec![sandbox_id.to_string()], }), ) .await; match state { Ok(Ok(response)) => { if let Some(pod_ip) = node_reported_address( response.into_inner().sandboxes, sandbox_id, generation, pod_uid, ) { return Some(pod_ip); } } Ok(Err(_)) | Err(_) => worker = None, } } tokio::time::sleep(start_wait_poll_interval(started_at)).await; } } pub(super) async fn wait_for_pod_ip_assignment( &self, metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, refusal: Option<&(super::pod_sandbox_rejections::RejectionWait, bool)>, ) -> Result, SubstrateError> { let PodProxyWaitTarget { pod_name, pod_uid, generation, } = *target; let started_at = Instant::now(); let recorded_refusal = || refusal.and_then(|(wait, fail_fast)| wait.recorded(*fail_fast)); let has_cached_pod_ip = || { self.lookup_sandbox_pod(pod_name).is_some_and(|pod| { target.names(&pod) && assigned_pod_ip(&pod).ok().flatten().is_some() }) }; if let Some((wait, _)) = refusal && let Some(invalid) = wait.recorded(false) && !has_cached_pod_ip() { return Err(invalid); } let initial_ip = if let Some(rejection) = recorded_refusal() { tokio::select! { biased; outcome = timeout_at( deadline, self.resolve_pod_ip_for_readiness(sandbox_id, target, deadline), ) => match outcome { Ok(Ok(Some(resolved))) => Some(resolved), Ok(Ok(None)) | Ok(Err(_)) | Err(_) => { return Err(recorded_refusal().unwrap_or(rejection)); } }, invalid = async { match refusal { Some((wait, _)) => { let invalid = wait.refused(false).await; if has_cached_pod_ip() { std::future::pending().await } else { invalid } } None => std::future::pending().await, } } => return Err(invalid), } } else { let resolve = self.resolve_cached_pod_ip_for_readiness(sandbox_id, target, deadline); tokio::pin!(resolve); let first = tokio::select! { biased; outcome = &mut resolve => match outcome { Ok(resolved) => Ok(resolved), Err(err) => return Err(recorded_refusal().unwrap_or(err)), }, rejection = async { match refusal { Some((wait, fail_fast)) => wait.refused(*fail_fast).await, None => std::future::pending().await, } } => Err(rejection), }; match first { Ok(resolved) => resolved, Err(rejection) if !has_cached_pod_ip() => return Err(rejection), Err(rejection) => match timeout_at(deadline, &mut resolve).await { Ok(Ok(Some(resolved))) => Some(resolved), Ok(Ok(None)) | Ok(Err(_)) | Err(_) => { return Err(recorded_refusal().unwrap_or(rejection)); } }, } }; if let Some(resolved) = initial_ip { record_pod_ip_ready(metric_identity, sandbox_id, started_at, "cached"); return Ok(Some(resolved)); } if let Some(rejection) = recorded_refusal() { return Err(rejection); } if Instant::now() >= deadline { return Ok(None); } let raced = async { // The pod's node usually reports the address before Kubernetes does; // whichever answers first binds the execution. let (observed, observed_by_node) = tokio::sync::watch::channel(None); // Both waits are large futures; keep them off the caller's stack. let kubernetes = Box::pin( self.reflect_until_pod_ip_assigned(sandbox_id, target, deadline, &observed) .instrument(tracing::info_span!( "substrate.k8s.reflect_pod_ip", sandbox_id = %sandbox_id, pod_name = %pod_name, namespace = %self.k8s.sandbox_namespace, )), ); let node_reported = Box::pin( self.node_reported_pod_ip(sandbox_id, generation, pod_uid, observed_by_node) .instrument(tracing::info_span!( "substrate.k8s.node_pod_ip", sandbox_id = %sandbox_id, )), ); tokio::select! { kubernetes = kubernetes => kubernetes, Some(pod_ip) = node_reported => { Ok(Some(((pod_ip, PodIpSource::NodeReported), "node"))) } } }; let resolved = tokio::select! { biased; outcome = timeout_at(deadline, raced) => match outcome { Ok(Ok(resolved)) => resolved, Err(_) => None, Ok(Err(err)) => return Err(recorded_refusal().unwrap_or(err)), }, rejection = async { match refusal { Some((refusal, fail_fast)) => refusal.refused(*fail_fast).await, None => std::future::pending().await, } } => return Err(rejection), }; if let Some((resolved, label)) = resolved { record_pod_ip_ready(metric_identity, sandbox_id, started_at, label); return Ok(Some(resolved)); } if let Some(rejection) = recorded_refusal() { return Err(rejection); } Ok(None) } pub(super) async fn wait_for_pod_proxy_reachable( &self, metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, sandbox_id: SandboxId, target: PodProxyWaitTarget<'_>, phase: &'static str, // Phase deadline of the enclosing budget-bounded wait (see // `ready_phase_deadline`). The configured data-plane timeout is // clamped to it so this wait's phase-tagged timeout fires before // the outer budget swallows it into a generic phase-less one. phase_deadline: Instant, ) -> Result<(PodIp, ExecutionBinding), SubstrateError> { let started_at = Instant::now(); let mut connect_attempts = 0u64; let deadline = (Instant::now() + self.k8s.create_data_plane_ready_timeout).min(phase_deadline); let sandbox_id_string = sandbox_id.to_string(); // A pod whose sandbox the node refuses never gets an IP: kubelet // retries it until the wait's deadline. Register before checking the // pod's IP so a cached IP (or an uncached IP resolved before a memory // refusal fails the wait) wins over a refusal without missing one // recorded concurrently. let refusal = target.pod_uid.map(|pod_uid| { let fail_fast = pplx_space_env_vars::env_flag_var( "SPACE_CREATE_FAIL_FAST_ON_NODE_REJECTION", false, ); (self.pod_sandbox_rejections.register(pod_uid), fail_fast) }); let pod_ip = self .wait_for_pod_ip_assignment( metric_identity, sandbox_id, &target, deadline, refusal.as_ref(), ) .instrument(tracing::info_span!( "substrate.k8s.wait_pod_ip", phase = %phase, sandbox_id = %sandbox_id, pod_name = %target.pod_name, namespace = %self.k8s.sandbox_namespace, )) .await?; drop(refusal); let Some((mut pod_ip, mut source)) = pod_ip else { record_pod_proxy_wait_timeout(metric_identity, sandbox_id, started_at); // Pod never reached scheduled / IP-assigned in the window. No // node-mgr probe ran on this path, so the message names only // the phase that stalled; the create path's defer-cleanup // decision keys off the `Timeout` variant itself, not a // node-mgr label. let phase = WaitReadyTimeoutPhase::PodNeverReady; return Err(SubstrateError::Timeout { message: format!( "timed out waiting for sandbox pod to become ready (phase: {phase})" ), phase: Some(phase), }); }; loop { connect_attempts += 1; let connect_started_at = Instant::now(); let serves = self .probe_pod_proxy(sandbox_id, pod_ip, source, &target, deadline) .instrument(tracing::info_span!( "substrate.k8s.connect_pod_proxy", sandbox_id = %sandbox_id, pod_ip = %pod_ip, port = self.k8s.sandbox_proxy_port, attempt = connect_attempts, )) .await && timeout_at( deadline, self.record_confirmed(sandbox_id, pod_ip, source, &target), ) .await .unwrap_or(Ok(false))?; if serves { record_pod_proxy_wait_ready( metric_identity, sandbox_id, started_at, connect_started_at, ); return Ok(( pod_ip, ExecutionBinding { execution_object_id: target .pod_uid .map(ToOwned::to_owned) .unwrap_or_else(|| sandbox_id_string.clone()), runtime_endpoint: Self::endpoint_for_pod_ip( pod_ip, self.k8s.sandbox_proxy_port, )?, execution_generation: execution_generation_to_u64(target.generation)?, }, )); } if Instant::now() >= deadline { record_pod_proxy_wait_timeout(metric_identity, sandbox_id, started_at); // Pod IP was assigned but no probe through it reached a node // serving this execution. Name the phase that stalled and let // the `Timeout` variant drive the defer-cleanup decision. let phase = WaitReadyTimeoutPhase::ProxyUnreachable; return Err(SubstrateError::Timeout { message: format!( "timed out waiting for sandbox pod proxy to become reachable \ (phase: {phase})" ), phase: Some(phase), }); } // An address that does not serve the target is re-resolved. The // recorded address for the target's UID is kept until kubelet // publishes another, so after a runtime sandbox is recreated under // the same UID the wait binds its new address at kubelet's pace, // as without a node report. if let Some(current) = self .resolve_pod_ip_for_readiness(sandbox_id, &target, deadline) .await? { (pod_ip, source) = current; } sleep(start_wait_poll_interval(started_at)).await; } } /// Whether the node behind `pod_ip` answers that it serves `target`'s /// execution at that address, as [`serves_target`] compares it for /// `source`. The address forwards to its node's node-api, so a stale or /// reused address reaches a node that does not, or that reports another /// address for the execution's current network allocation. pub(super) async fn probe_pod_proxy( &self, sandbox_id: SandboxId, pod_ip: PodIp, source: PodIpSource, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> bool { let timeout = START_WAIT_CONNECT_TIMEOUT.min(remaining_ready_window(deadline)); let Some(mut client) = Self::pod_worker_client(pod_ip, self.k8s.sandbox_proxy_port, timeout).await else { return false; }; node_sandboxes(&mut client, sandbox_id, timeout) .await .is_some_and(|sandboxes| serves_target(sandboxes, sandbox_id, target, pod_ip, source)) } /// `pod_ip` when it is safe to act on as `target`'s runtime address: a /// kubelet-published address as it is, a node-reported one only once the /// node behind it affirms the execution (see [`Self::runtime_at`]). pub(super) async fn verified_runtime_pod_ip( &self, sandbox_id: SandboxId, (pod_ip, source): (PodIp, PodIpSource), target: &PodProxyWaitTarget<'_>, ) -> Result, SubstrateError> { if source == PodIpSource::Published { return Ok(Some(pod_ip)); } let mut client = Self::pod_worker_client( pod_ip, self.k8s.sandbox_proxy_port, START_WAIT_CONNECT_TIMEOUT, ) .await .ok_or_else(|| SubstrateError::Failed { message: format!( "no node answered at the node-reported address {pod_ip} of sandbox {sandbox_id}" ), })?; Self::runtime_at(&mut client, sandbox_id, pod_ip, target).await } /// `pod_ip` when the worker behind `client` reports `target`'s execution, /// `None` when it reports the sandbox elsewhere or not at all (see /// [`runtime_answer`]). A worker that does not answer, or does not report /// enough to tell, is an error, so a teardown keeps the execution tracked /// for retry. pub(super) async fn runtime_at( client: &mut crate::controllers::substrate::RuntimeClient, sandbox_id: SandboxId, pod_ip: PodIp, target: &PodProxyWaitTarget<'_>, ) -> Result, SubstrateError> { let answer = node_sandboxes(client, sandbox_id, START_WAIT_CONNECT_TIMEOUT) .await .map(|sandboxes| runtime_answer(sandboxes, sandbox_id, target, pod_ip)); match answer { Some(RuntimeAnswer::Serves) => Ok(Some(pod_ip)), Some(RuntimeAnswer::Elsewhere) => Ok(None), Some(RuntimeAnswer::Unconfirmed) | None => Err(SubstrateError::Failed { message: format!( "the worker at {pod_ip} did not confirm sandbox {sandbox_id}'s runtime" ), }), } } /// Whether the execution row records `pod_ip` for `target`, recording a /// node-reported address its node has just confirmed. A row a suspend, /// retire or newer pod has moved on does not take it. async fn record_confirmed( &self, sandbox_id: SandboxId, pod_ip: PodIp, source: PodIpSource, target: &PodProxyWaitTarget<'_>, ) -> Result { match (source, target.pod_uid) { (PodIpSource::Published, _) => Ok(true), (PodIpSource::NodeReported, Some(pod_uid)) => { self.store .record_confirmed_pod_ip(sandbox_id, target.generation, pod_uid, pod_ip) .await } (PodIpSource::NodeReported, None) => Ok(false), } } pub(super) async fn ensure_active_execution_pod_proxy_reachable( &self, metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, sandbox_id: SandboxId, // Forwarded to `wait_for_pod_proxy_reachable`; see its doc. phase_deadline: Instant, ) -> Result<(), SubstrateError> { let execution = self .store .active_execution_status(sandbox_id) .await? .ok_or_else(|| SubstrateError::Unavailable { message: "sandbox has no active Kubernetes execution".to_string(), })?; if execution.pod_ip.is_some() { return Ok(()); } // A node whose drain sealed its activations refuses this pod's, and // kubelet then retries the pod until the deadline without an IP. // Registered before the wait, so a refusal recorded meanwhile is // seen; only that refusal ends this wait early. let sealed = execution .pod_uid .as_ref() .map(|pod_uid| self.pod_sandbox_rejections.register(pod_uid.as_str())); let reachable = self .wait_for_pod_proxy_reachable( metric_identity, sandbox_id, PodProxyWaitTarget { pod_name: &execution.pod_name, pod_uid: None, generation: execution.generation, }, "wake", phase_deadline, ) .instrument(tracing::info_span!( "substrate.k8s.wait_wake_pod_proxy_reachable", sandbox_id = %sandbox_id, pod_name = %execution.pod_name, namespace = %self.k8s.sandbox_namespace, )); tokio::pin!(reachable); let node_said = tokio::select! { biased; reached = &mut reachable => return reached.map(drop), node_said = async { match &sealed { Some(wait) => wait.sealed().await, None => std::future::pending().await, } } => node_said, }; // A refusal the node has since got past, its drain cancelled and the // pod given an IP on kubelet's retry, is not this wait's answer. if self .lookup_sandbox_pod(&execution.pod_name) .is_some_and(|pod| assigned_pod_ip(&pod).ok().flatten().is_some()) { return reachable.await.map(drop); } let orphaned = self.store.note_sealed_refusal(sandbox_id, &node_said).await; Err(sealed_wake_refusal(orphaned, &node_said)) } } /// Identity of the execution pod a proxy-reachability wait targets. Groups /// the execution-row fields so `wait_for_pod_proxy_reachable`'s signature /// stays under clippy's `too_many_arguments` ceiling as knobs are added. #[derive(Clone, Copy)] pub(super) struct PodProxyWaitTarget<'a> { pub pod_name: &'a str, /// Becomes the binding's `execution_object_id` when present; the wake /// path passes `None` (the binding it produces is discarded). pub pod_uid: Option<&'a str>, pub generation: i64, } /// Whether `sandboxes` show `target`'s execution served at `pod_ip`. For a /// kubelet-published address, a field the node does not report (an older /// node, or a sandbox manager that has restarted since the allocation) is not /// compared. A node-reported address is confirmed only by a node that reports /// the target's generation, Pod UID and that address. fn serves_target( sandboxes: Vec, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, pod_ip: PodIp, source: PodIpSource, ) -> bool { let strict = source == PodIpSource::NodeReported; let matches = |compared: Option| compared.unwrap_or(!strict); let sandbox_id = sandbox_id.to_string(); sandboxes.iter().any(|info| { info.sandbox_id == sandbox_id && matches( info.execution_generation .map(|generation| generation == target.generation), ) && match (target.pod_uid, info.pod_uid.as_deref()) { (Some(expected), Some(reported)) => expected == reported, _ => !strict, } && matches( info.external_address .as_deref() .map(|reported| PodIp::parse(reported).ok() == Some(pod_ip)), ) }) } /// `sandbox_id`'s entries as the worker behind `client` reports them, or /// `None` when it does not answer within `wait`. async fn node_sandboxes( client: &mut crate::controllers::substrate::RuntimeClient, sandbox_id: SandboxId, wait: Duration, ) -> Option> { let state = timeout( wait, client.sandbox_state(pplx_space_sbx_mgr_client::proto::StateRequest { sandbox_ids: vec![sandbox_id.to_string()], }), ) .await; match state { Ok(Ok(response)) => Some(response.into_inner().sandboxes), _ => None, } } /// What a worker's report says about `target`'s runtime there. #[derive(Debug, PartialEq, Eq)] pub(super) enum RuntimeAnswer { /// The worker reports the target's generation and Pod UID, and `pod_ip` /// whenever it reports an address. Serves, /// The worker does not report the sandbox, or reports a different /// generation or Pod UID. Elsewhere, /// The worker reports the sandbox without its generation or Pod UID (an /// older node, or a sandbox manager that has restarted), or reports the /// target's execution at another address. Unconfirmed, } /// [`RuntimeAnswer`] for `sandboxes`. Unlike readiness ([`serves_target`]), /// acting on a runtime that is there does not need its address reported: the /// identity fields name the execution. pub(super) fn runtime_answer( sandboxes: Vec, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, pod_ip: PodIp, ) -> RuntimeAnswer { let sandbox_id = sandbox_id.to_string(); let Some(info) = sandboxes.iter().find(|info| info.sandbox_id == sandbox_id) else { return RuntimeAnswer::Elsewhere; }; let identity_differs = info .execution_generation .is_some_and(|generation| generation != target.generation) || info .pod_uid .as_deref() .zip(target.pod_uid) .is_some_and(|(reported, expected)| reported != expected); let address_differs = info .external_address .as_deref() .is_some_and(|reported| PodIp::parse(reported).ok() != Some(pod_ip)); let identified = info.execution_generation.is_some() && info.pod_uid.is_some() && target.pod_uid.is_some(); if identity_differs { RuntimeAnswer::Elsewhere } else if identified && !address_differs { RuntimeAnswer::Serves } else { RuntimeAnswer::Unconfirmed } } impl PodProxyWaitTarget<'_> { /// Whether `pod` is the pod this wait binds: with a target UID, only the /// pod that has it. pub(super) fn names(&self, pod: &SandboxPodView) -> bool { self.pod_uid.is_none_or(|uid| pod.uid() == Some(uid)) } } /// The address `sandboxes` report for `sandbox_id` while its pod is `pod_uid`. fn node_reported_address( sandboxes: Vec, sandbox_id: SandboxId, generation: i64, pod_uid: &str, ) -> Option { let sandbox_id = sandbox_id.to_string(); sandboxes .into_iter() .find(|info| { info.sandbox_id == sandbox_id && info.execution_generation == Some(generation) && info.pod_uid.as_deref() == Some(pod_uid) }) .and_then(|info| PodIp::parse(info.external_address.as_deref()?).ok()) } #[cfg(test)] mod node_reported_address_tests { use super::*; use pplx_space_sbx_mgr_client::proto::SandboxInfo; fn info(sandbox_id: SandboxId, generation: i64, pod_uid: &str, pod_ip: &str) -> SandboxInfo { SandboxInfo { sandbox_id: sandbox_id.to_string(), execution_generation: Some(generation), pod_uid: Some(pod_uid.to_owned()), external_address: Some(pod_ip.to_owned()), ..Default::default() } } #[test] fn only_the_observed_executions_address_is_taken() { let sandbox_id = SandboxId::new(); let other_sandbox = SandboxId::new(); let reported = vec![ info(other_sandbox, 1, "pod-a", "10.0.0.1"), info(sandbox_id, 1, "pod-old", "10.0.0.2"), info(sandbox_id, 1, "pod-a", "10.0.0.3"), ]; let taken = |reported, generation, pod_uid| { node_reported_address(reported, sandbox_id, generation, pod_uid) }; assert_eq!( taken(reported.clone(), 1, "pod-a"), Some(PodIp::parse("10.0.0.3").unwrap()) ); assert_eq!(taken(reported.clone(), 1, "pod-new"), None); assert_eq!(taken(reported, 2, "pod-a"), None); assert_eq!( taken(vec![info(sandbox_id, 1, "pod-a", "not-an-ip")], 1, "pod-a"), None ); } /// The readiness probe accepts only a node serving the target execution /// at the probed address. For a kubelet-published address, fields an older /// node omits are not compared; a node-reported one needs them all. #[test] fn a_probe_accepts_only_the_target_served_at_its_address() { let sandbox_id = SandboxId::new(); let probed = PodIp::parse("10.0.0.3").unwrap(); let target = PodProxyWaitTarget { pod_name: "pod", pod_uid: Some("pod-a"), generation: 1, }; let degraded = SandboxInfo { sandbox_id: sandbox_id.to_string(), ..Default::default() }; for source in [PodIpSource::Published, PodIpSource::NodeReported] { let serves = |info: SandboxInfo| serves_target(vec![info], sandbox_id, &target, probed, source); assert!(serves(info(sandbox_id, 1, "pod-a", "10.0.0.3"))); // A recreated runtime sandbox's node reports its new allocation. assert!(!serves(info(sandbox_id, 1, "pod-a", "10.0.0.4"))); assert!(!serves(info(sandbox_id, 1, "pod-b", "10.0.0.3"))); assert!(!serves(info(sandbox_id, 2, "pod-a", "10.0.0.3"))); assert!(!serves(info(SandboxId::new(), 1, "pod-a", "10.0.0.3"))); assert!(!serves_target( Vec::new(), sandbox_id, &target, probed, source )); assert_eq!(serves(degraded.clone()), source == PodIpSource::Published); } } /// A teardown acts on a runtime its worker names by identity, skips it /// only when the worker reports another execution, and does not read /// missing fields or a moved address as either. #[test] fn a_runtime_answer_skips_only_a_worker_that_reports_another_runtime() { let sandbox_id = SandboxId::new(); let probed = PodIp::parse("10.0.0.3").unwrap(); let target = PodProxyWaitTarget { pod_name: "pod", pod_uid: Some("pod-a"), generation: 1, }; let answer = |info: SandboxInfo| runtime_answer(vec![info], sandbox_id, &target, probed); assert_eq!( answer(info(sandbox_id, 1, "pod-a", "10.0.0.3")), RuntimeAnswer::Serves ); // A restarted sandbox manager no longer reports the address. let restarted = SandboxInfo { external_address: None, ..info(sandbox_id, 1, "pod-a", "10.0.0.3") }; assert_eq!(answer(restarted), RuntimeAnswer::Serves); for elsewhere in [ info(sandbox_id, 1, "pod-b", "10.0.0.3"), info(sandbox_id, 2, "pod-a", "10.0.0.3"), info(SandboxId::new(), 1, "pod-a", "10.0.0.3"), ] { assert_eq!(answer(elsewhere), RuntimeAnswer::Elsewhere); } // The target's execution at another address is still a runtime to // clean up, so the teardown waits for an address it can confirm. let moved = info(sandbox_id, 1, "pod-a", "10.0.0.4"); let unidentified_moved = SandboxInfo { pod_uid: None, ..info(sandbox_id, 1, "pod-a", "10.0.0.4") }; let degraded = SandboxInfo { sandbox_id: sandbox_id.to_string(), ..Default::default() }; for unconfirmed in [moved, unidentified_moved, degraded] { assert_eq!(answer(unconfirmed), RuntimeAnswer::Unconfirmed); } } }