//! Pod read paths: cached and uncached sandbox pod reads, pod IP resolution, //! and remembering the node a resolved pod landed on. use super::*; use crate::controllers::substrate::PooledExecutionClaim; use crate::controllers::substrate::kubernetes::store::ConditionalPodMetadataWrite; use crate::controllers::substrate::kubernetes::wait_ready::PodProxyWaitTarget; const SUCCEEDED_POD_SUSPEND_PUBLICATION_GRACE: Duration = Duration::from_secs(180); #[derive(Debug)] pub(in crate::controllers::substrate::kubernetes) enum PodGet { Observed(Option>), DeadlineElapsed, } pub(super) enum MissingPodResolution { Retired, ClaimPreserved { updated_at: time::OffsetDateTime }, Reresolve, } pub(super) enum NoReachableRuntimeFence { Holds, Reresolve, Inactive, } /// How [`KubernetesSubstrate::lookup_cached_pod`] decides whether a cached /// [`SandboxPodView`] is authoritative without an apiserver `GET`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum CacheTrustPolicy { /// Post-watch readiness fallback polling (`poll_until_pod_ip_assigned`): /// terminal entries (`Succeeded`, `Failed`) short-circuit immediately, and /// settled non-terminal entries (`status.podIP` published or unbound /// `Pending`+`Unschedulable`) short-circuit while the reflector watch is /// healthy. After the per-pod watch ends or errors, an unsettled `Pending` /// entry in `pod_store` falls through to an uncached `GET` once /// `reflector_wait` elapses rather than suppressing fallback polling. SettledOnly, /// Resolution, initial readiness check, and status reads: terminal entries /// (`Succeeded`, `Failed`) are accepted even across a watch fault because /// `resolve_pod_instance_inner` re-verifies terminal phases with an /// uncached `GET` before retiring an execution; non-terminal cached pods /// (including `Running`+IP and `Pending`) are trusted only while the /// reflector watch is healthy so a degraded watch falls through to an /// uncached `GET`. SettledOrHealthyWatch, /// Warm-pool claim adoption (`read_pooled_claim_pod`): cached pods are /// trusted only while the reflector watch is healthy, because claim /// adoption hands a cached `Running`+IP pod directly to a caller without a /// follow-up uncached `GET` and must not adopt a pod that died during a /// watch disconnect. HealthyWatchOnly, /// Post-conflict unfenced teardown retry (`FenceReadFreshness::MustBeAuthoritative`): /// bypasses `pod_store` completely so a retry after a `409 Conflict` delete /// precondition failure cannot re-read the stale pre-conflict `resourceVersion` /// from cache. BypassCache, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum UnaddressedLivePodPolicy { /// Readiness, status, and wake callers treat a live pod without an IP yet /// as `Ok(None)` so readiness waiting can proceed. ReturnNone, /// Unfenced destructive teardown (`confirmed_unfenced_runtime`) returns a /// `(uid, resourceVersion)`-fenced `NoReachableRuntime` delete target for /// any live pod without a runtime IP yet (unbound or bound pre-CNI), so /// Kubernetes rejects the delete with `409 Conflict` if the pod acquires a /// runtime IP concurrently and Pass 2 re-resolves and stops the VM. FenceUnfencedTeardown { reject_in_flight_creating: bool }, } #[derive(Debug)] pub(in crate::controllers::substrate::kubernetes) enum UnfencedPodResolution { Live { instance: ResolvedPodInstance, tracked_pod_uid: Option, tracked_updated_at: Option, }, Absent { checked_generation: Option, checked_pod_name: Option, checked_pod_uid: Option, checked_updated_at: Option, retire_checked_generation: bool, }, } mod cache_lookup; pub(in crate::controllers::substrate::kubernetes) use cache_lookup::PooledClaimPodObservation; impl KubernetesSubstrate { pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance(sandbox_id) .await? .map(|pod| pod.ip)) } /// Like [`Self::resolve_pod_instance`], using [`CacheTrustPolicy::SettledOnly`] /// so single-shot callers (`completed_execution_binding`) verify the /// resolved execution's generation, pod name, and UID alongside its IP. pub(super) async fn resolve_pod_instance_settled( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { self.resolve_pod_instance_inner( sandbox_id, None, None, CacheTrustPolicy::SettledOnly, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::ReturnNone, ) .await .map_err(ResolvePodInstanceError::into_substrate_error) } /// Bound direct pod GETs without putting the store mutations in the /// resolver under the shorter GET timeout. An expired `deadline` returns /// `Ok(None)` so readiness reports its phase timeout, while a /// `readiness_pod_get` timeout before `deadline` or a transient apiserver /// read failure (`429`/`408`/`5xx`/transport) fails fast with /// [`SubstrateError::Unavailable`]. Only an address for the execution and /// pod `target` names is returned, with where it comes from. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip_for_readiness( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> Result, SubstrateError> { self.resolve_pod_ip_for_readiness_with_policy( sandbox_id, target, deadline, CacheTrustPolicy::SettledOrHealthyWatch, ) .await } /// Like [`Self::resolve_pod_ip_for_readiness`], for post-watch fallback /// polling (`poll_until_pod_ip_assigned`): uses [`CacheTrustPolicy::SettledOnly`] /// so an unsettled `Pending` entry in `pod_store` does not suppress fallback /// `GET`s after the per-pod watch ends or errors. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip_for_readiness_poll( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> Result, SubstrateError> { self.resolve_pod_ip_for_readiness_with_policy( sandbox_id, target, deadline, CacheTrustPolicy::SettledOnly, ) .await } async fn resolve_pod_ip_for_readiness_with_policy( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, policy: CacheTrustPolicy, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance_inner( sandbox_id, Some(deadline), Some((target.generation, target.pod_uid)), policy, PlacementRetryDisposition::RetryDuplicatesExecution, UnaddressedLivePodPolicy::ReturnNone, ) .await .map_err(ResolvePodInstanceError::into_substrate_error)? .filter(|pod| { pod.generation == target.generation && target .pod_uid .is_none_or(|uid| pod.pod_uid.as_ref().map(PodUid::as_str) == Some(uid)) }) .map(|pod| (pod.ip, pod.source))) } /// [`Self::resolve_pod_ip`], with the identity of the pod the address /// belongs to. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { self.resolve_pod_instance_classified(sandbox_id) .await .map_err(ResolvePodInstanceError::into_substrate_error) } pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance_classified( &self, sandbox_id: SandboxId, ) -> Result, ResolvePodInstanceError> { self.resolve_pod_instance_inner( sandbox_id, None, None, CacheTrustPolicy::SettledOrHealthyWatch, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::ReturnNone, ) .await } /// Like [`Self::resolve_pod_instance_classified`], using /// [`CacheTrustPolicy::SettledOnly`] (or [`CacheTrustPolicy::BypassCache`] /// on Pass 2 after a `409 Conflict` precondition miss) and /// [`UnaddressedLivePodPolicy::FenceUnfencedTeardown`] for unfenced /// destructive teardown (`confirmed_unfenced_runtime`), which has no /// caller-supplied `resourceVersion` delete precondition and therefore must /// re-verify unsettled cached `Pending` snapshots, fence IP-less deletes by /// `(uid, resourceVersion)` with `NoRuntimeNodeCheck` revalidation, and /// defer when a retry encounters an in-flight `creating` execution. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance_settled_classified( &self, sandbox_id: SandboxId, bypass_cache: bool, ) -> Result { let policy = if bypass_cache { CacheTrustPolicy::BypassCache } else { CacheTrustPolicy::SettledOnly }; self.resolve_pod_instance_inner_detailed( sandbox_id, None, None, policy, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::FenceUnfencedTeardown { reject_in_flight_creating: bypass_cache, }, ) .await } async fn resolve_pod_instance_inner( &self, sandbox_id: SandboxId, readiness_deadline: Option, expected_target: Option<(i64, Option<&str>)>, policy: CacheTrustPolicy, retry: PlacementRetryDisposition, unaddressed_policy: UnaddressedLivePodPolicy, ) -> Result, ResolvePodInstanceError> { self.resolve_pod_instance_inner_detailed( sandbox_id, readiness_deadline, expected_target, policy, retry, unaddressed_policy, ) .await .map(|outcome| match outcome { UnfencedPodResolution::Live { instance, .. } => Some(instance), UnfencedPodResolution::Absent { .. } => None, }) } async fn resolve_pod_instance_inner_detailed( &self, sandbox_id: SandboxId, readiness_deadline: Option, expected_target: Option<(i64, Option<&str>)>, policy: CacheTrustPolicy, retry: PlacementRetryDisposition, unaddressed_policy: UnaddressedLivePodPolicy, ) -> Result { let is_unfenced_teardown = matches!( unaddressed_policy, UnaddressedLivePodPolicy::FenceUnfencedTeardown { .. } ); for allow_reresolve in [true, false] { let Some(row) = self.store.active_execution_status(sandbox_id).await? else { return Ok(UnfencedPodResolution::Absent { checked_generation: None, checked_pod_name: None, checked_pod_uid: None, checked_updated_at: None, retire_checked_generation: false, }); }; let checked_pod_name = row.pod_name.clone(); let absent = |checked_generation, checked_pod_uid: Option<&str>, checked_updated_at, retire_checked_generation| { Ok(UnfencedPodResolution::Absent { checked_generation, checked_pod_name: Some(checked_pod_name.clone()), checked_pod_uid: checked_pod_uid.and_then(|uid| PodUid::parse(uid).ok()), checked_updated_at, retire_checked_generation, }) }; let observed_pod_uid = row.pod_uid.as_ref().map(PodUid::as_str); if is_suspended_lifecycle(&row.lifecycle) { return absent( Some(row.generation), observed_pod_uid, observed_pod_uid.is_none().then_some(row.updated_at), false, ); } if let Some((expected_generation, expected_uid)) = expected_target && (row.generation != expected_generation || expected_uid .is_some_and(|uid| observed_pod_uid.is_some_and(|tracked| tracked != uid))) { return absent(Some(row.generation), observed_pod_uid, None, false); } let (pod, verified_uncached) = if execution_pod_lookup_in_flight(row.state) { if !stale_restore_execution_create( &row.lifecycle, row.state, row.create_age_expired, ) { if matches!( unaddressed_policy, UnaddressedLivePodPolicy::FenceUnfencedTeardown { reject_in_flight_creating: true } ) { return Err(ResolvePodInstanceError::InFlightExecution { generation: row.generation, }); } if !is_unfenced_teardown { return absent(Some(row.generation), observed_pod_uid, None, false); } } ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify stale creating restore pod", ) .await?, true, ) } else if matches!(policy, CacheTrustPolicy::BypassCache) { ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to query K8s pod", ) .await?, true, ) } else { if readiness_deadline.is_some_and(|deadline| Instant::now() >= deadline) { return absent(Some(row.generation), observed_pod_uid, None, false); } let reflector_wait = readiness_deadline.map_or(self.budgets.reflector_wait, |deadline| { self.budgets .reflector_wait .min(deadline.saturating_duration_since(Instant::now())) }); let cache_expected_uid = observed_pod_uid.or(expected_target.and_then(|(_, uid)| uid)); if let Some(pod) = self .read_cached_sandbox_pod_for_uid( &row.pod_name, cache_expected_uid, reflector_wait, policy, ) .await { (PodGet::Observed(Some(pod)), false) } else { ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to query K8s pod", ) .await?, true, ) } }; let PodGet::Observed(pod) = pod else { return absent(Some(row.generation), observed_pod_uid, None, false); }; let (pod, verified_uncached) = match pod { Some(pod) => (pod, verified_uncached), None => { // A cache miss alone must never authorize execution retirement, // because a finalizer-blocked or unlisted pod can be absent // from the cache while still present on the apiserver. When the // `None` above already came from an uncached `GET` // (`verified_uncached`), reuse that 404 observation rather than // issuing a second back-to-back apiserver `GET`. let authoritative = if verified_uncached { None } else { let PodGet::Observed(pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify missing Kubernetes sandbox pod", ) .await? else { return absent(Some(row.generation), observed_pod_uid, None, false); }; pod }; match authoritative { Some(pod) => (pod, true), None => { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, is_unfenced_teardown, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => { return absent( Some(row.generation), observed_pod_uid, None, false, ); } MissingPodResolution::ClaimPreserved { updated_at } => { return absent( Some(row.generation), None, is_unfenced_teardown.then_some(updated_at), is_unfenced_teardown, ); } } } } } }; if let Some((_, Some(expected_uid))) = expected_target && pod.uid() != Some(expected_uid) { return absent(Some(row.generation), observed_pod_uid, None, false); } let (pod, verified_uncached) = if !verified_uncached && unbound_unschedulable_message(&pod).is_some() { let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify unschedulable Kubernetes sandbox pod", ) .await? else { return absent(Some(row.generation), observed_pod_uid, None, false); }; match authoritative_pod { Some(authoritative_pod) => (authoritative_pod, true), None => { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, is_unfenced_teardown, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => { return absent(Some(row.generation), observed_pod_uid, None, false); } MissingPodResolution::ClaimPreserved { updated_at } => { return absent( Some(row.generation), None, is_unfenced_teardown.then_some(updated_at), is_unfenced_teardown, ); } } } } } else { (pod, verified_uncached) }; if let Some((_, Some(expected_uid))) = expected_target && pod.uid() != Some(expected_uid) { return absent(Some(row.generation), observed_pod_uid, None, false); } let pod = if let Some(cached_phase) = terminal_pod_phase(&pod) { let authoritative_pod = if verified_uncached { Some(pod) } else { let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify terminal Kubernetes sandbox pod", ) .await? else { return absent(Some(row.generation), observed_pod_uid, None, false); }; authoritative_pod }; if let Some(phase) = terminal_cleanup_phase_after_uncached_check( cached_phase, authoritative_pod.as_deref(), ) { let Some(authoritative_pod) = authoritative_pod else { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, is_unfenced_teardown, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => { return absent(Some(row.generation), observed_pod_uid, None, false); } MissingPodResolution::ClaimPreserved { updated_at } => { return absent( Some(row.generation), None, is_unfenced_teardown.then_some(updated_at), is_unfenced_teardown, ); } } }; if let Some((_, Some(expected_uid))) = expected_target && authoritative_pod.uid() != Some(expected_uid) { return absent(Some(row.generation), observed_pod_uid, None, false); } // When a terminal pod sits at `row.pod_name` under a // different UID than `observed_pod_uid`, re-read the // execution row once first so a concurrent generation // advance or `pod_uid` persist settles before cleanup. If // the second pass still sees `row` pinned to // `observed_pod_uid`, that pod is gone and `authoritative_pod` // is an unpersisted terminal pod at the same per-generation // name: fall through to delete `authoritative_pod` fenced on // its UID and retire `row` fenced on `observed_pod_uid`. if observed_pod_uid.is_some() && authoritative_pod.uid() != observed_pod_uid && allow_reresolve { continue; } let publication_grace_remaining = (phase == TerminalPodPhase::Succeeded) .then(|| { succeeded_pod_publication_grace_remaining( &authoritative_pod, jiff::Timestamp::now(), ) }) .flatten(); if row.lifecycle == SandboxLifecycle::Suspending.as_str() && publication_grace_remaining.is_some() { tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, generation = row.generation, pod_uid = ?row.pod_uid, lifecycle = %row.lifecycle, grace_remaining_ms = publication_grace_remaining .map(|remaining| remaining.as_millis()), "deferring successful terminal pod cleanup while suspend publication may still arrive" ); return Err(SubstrateError::suspend_in_flight(sandbox_id).into()); } let delete_pod_uid = authoritative_pod.uid().or(observed_pod_uid); tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, tracked_pod_uid = ?observed_pod_uid, cached_phase = %cached_phase, phase = %phase, cached_pod_ip = ?row.pod_ip, "tracked Kubernetes sandbox pod is terminal after uncached verification; deleting it and clearing cached pod IP" ); match self .delete_terminal_pod_and_forget_missing_tracking( sandbox_id, &row.pod_name, row.generation, delete_pod_uid, observed_pod_uid, ) .await? { super::delete::TerminalPodCleanupOutcome::ReplacedOnApiserver if allow_reresolve => { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, "terminal-pod delete precondition rejected by replacement pod on apiserver; re-resolving" ); continue; } super::delete::TerminalPodCleanupOutcome::ReplacedOnApiserver => { return Err(kube_api_unavailable( "failed to confirm terminal Kubernetes sandbox pod deletion", format_args!("pod {}; keeping execution tracking", row.pod_name), ) .into()); } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::NotMatched, ) if allow_reresolve => { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, tracked_pod_uid = ?observed_pod_uid, "terminal-pod tracking cleanup skipped after concurrent execution update; re-resolving" ); continue; } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::NotMatched, ) => { if is_unfenced_teardown { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, false, true, ) .await? { MissingPodResolution::ClaimPreserved { updated_at } => { return absent( Some(row.generation), None, Some(updated_at), true, ); } MissingPodResolution::Retired | MissingPodResolution::Reresolve => { return absent( Some(row.generation), observed_pod_uid, None, false, ); } } } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "terminal-pod cleanup", ) .await?; return absent(Some(row.generation), observed_pod_uid, None, false); } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::Forgotten | MissingPodTrackingCleanupOutcome::DeferredToSuspend | MissingPodTrackingCleanupOutcome::SandboxAbsent, ) => { return absent(Some(row.generation), observed_pod_uid, None, false); } } } tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, cached_phase = %cached_phase, cached_pod_ip = ?row.pod_ip, "cached Kubernetes sandbox pod was terminal but uncached pod is still active; keeping tracking" ); let authoritative_pod = authoritative_pod .expect("non-terminal verification result requires an existing pod"); if let Some((_, Some(expected_uid))) = expected_target && authoritative_pod.uid() != Some(expected_uid) { return absent(Some(row.generation), observed_pod_uid, None, false); } authoritative_pod } else { pod }; let initial_tracked_updated_at = observed_pod_uid.is_none().then_some(row.updated_at); if let Some(message) = unbound_unschedulable_message(&pod) { match self .verify_no_reachable_runtime_fence( sandbox_id, &row, observed_pod_uid, initial_tracked_updated_at, row.pod_ip.as_deref(), row.k8s_node_name.as_deref(), pod.uid(), allow_reresolve, "unschedulable pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { let pod_fence = resolution_fences::no_reachable_runtime_delete_fence( row.generation, &row.pod_name, observed_pod_uid, initial_tracked_updated_at, &pod, true, None, ); if is_unfenced_teardown && pod_fence.is_none() { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "sandbox pod {} is unschedulable ({message}) and has no UID \ for fenced teardown", row.pod_name ), }, )); } return Err(ResolvePodInstanceError::NoReachableRuntime { err: SubstrateError::Unschedulable { message: format!("sandbox pod is unschedulable: {message}"), }, pod_fence, }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => { return absent(Some(row.generation), observed_pod_uid, None, false); } } } let pod_uid = pod.uid().map(str::to_owned); let resolved = current_pod_ip_with_source(&pod, row.pod_uid.as_ref(), row.pod_ip.as_deref())?; let pod_ip = resolved.map(|(ip, _)| ip); let pod_ip_string = pod_ip.map(|ip| ip.to_string()); let pod_client = pod.client_id(); let mut tracked_pod_uid = observed_pod_uid; let mut tracked_updated_at = initial_tracked_updated_at; let mut tracked_pod_ip = row.pod_ip.as_deref(); let mut tracked_node_name = row.k8s_node_name.as_deref(); if observed_pod_uid != pod_uid.as_deref() || row.pod_ip.as_deref() != pod_ip_string.as_deref() { match self .store .persist_pod_metadata_if_observed_pod_uid( sandbox_id, row.generation, observed_pod_uid, row.pod_ip.as_deref(), tracked_updated_at, pod_uid.as_deref(), pod_ip_string.as_deref(), pod_client.as_ref(), ) .await? { ConditionalPodMetadataWrite::Written(_) | ConditionalPodMetadataWrite::Unchanged(_) => { tracked_pod_uid = pod_uid.as_deref(); tracked_pod_ip = pod_ip_string.as_deref(); tracked_updated_at = if tracked_pod_uid.is_some() { None } else { self.store .active_execution_status(sandbox_id) .await? .filter(|r| r.generation == row.generation && r.pod_uid.is_none()) .map(|r| r.updated_at) }; } ConditionalPodMetadataWrite::ObservedMetadataChanged | ConditionalPodMetadataWrite::NoActiveGeneration | ConditionalPodMetadataWrite::Suspended => { if allow_reresolve { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, observed_pod_uid = ?observed_pod_uid, candidate_pod_uid = ?pod_uid, "pod metadata write lost its execution fence to a concurrent update; re-resolving" ); continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "pod metadata write", ) .await?; return absent(Some(row.generation), observed_pod_uid, None, false); } } } else if self.k8s.activation_client_attribution.is_enabled() && let Some(pod_uid) = pod_uid.as_deref() && crate::controllers::substrate::kubernetes::store::attribution_update( &row.lifecycle, Some(pod_uid), Some(pod_uid), pod_client.as_ref(), row.activating_client_id.as_ref(), ) .is_some() { // The pod is the one the row tracks, and only the record lags its // label: repair the record alone, leaving the row's state as it is. if let Err(err) = self .store .repair_runtime_attribution( sandbox_id, row.generation, pod_uid, pod_client.as_ref(), ) .await { tracing::warn!( sandbox_id = %sandbox_id, generation = row.generation, error = %err, "failed to repair the sandbox's activating client after pod lookup" ); } } let current_node_name = assigned_pod_node_name(&pod).map(str::to_owned); // Under unfenced teardown, also verify the node when `resolved` is // `None` and `row.k8s_node_name` already matches `current_node_name` // so a bound IP-less pod on a deleted (`404`) node still classifies // as `NodeUnreachable` rather than stalling teardown indefinitely. let should_check_node = row.k8s_node_name.as_deref() != current_node_name.as_deref() || (is_unfenced_teardown && resolved.is_none() && current_node_name.is_some()); if should_check_node { match self .remember_pod_node_placement_if_generation_pod_uid_with_node_lookup_deadline( sandbox_id, row.generation, tracked_pod_uid, &pod, readiness_deadline, retry, ) .await { Ok(node_placement::NodePlacementObservation::DeadlineElapsed) => { return absent(Some(row.generation), tracked_pod_uid, None, false); } Ok(node_placement::NodePlacementObservation::Observed(Some((_, false)))) => { if allow_reresolve { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, expected_pod_uid = ?tracked_pod_uid, "pod node placement write lost its execution fence to a concurrent update; re-resolving" ); continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "pod node-placement write", ) .await?; return absent(Some(row.generation), tracked_pod_uid, None, false); } Ok(node_placement::NodePlacementObservation::Observed(Some((_, true)))) => { tracked_node_name = current_node_name.as_deref(); if tracked_pod_uid.is_none() { tracked_updated_at = self .store .active_execution_status(sandbox_id) .await? .filter(|r| r.generation == row.generation && r.pod_uid.is_none()) .map(|r| r.updated_at); } } Ok(node_placement::NodePlacementObservation::Observed(None)) => {} Err(PodNodePlacementError::Substrate(err)) => { return Err(ResolvePodInstanceError::Substrate(err)); } Err(PodNodePlacementError::NodeUnreachable(err)) => { // Re-verify the pod directly even when `pod` came from an // uncached GET: the Node lookup and metadata write ran in // between, so a replacement pod may already occupy // `row.pod_name` on a healthy node before its UID reaches // `sandbox_k8s_executions`. let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify Kubernetes sandbox pod on unreachable node", ) .await? else { return absent(Some(row.generation), tracked_pod_uid, None, false); }; let Some(authoritative_pod) = authoritative_pod else { match self .retire_missing_pod_for_resolution( sandbox_id, &row, tracked_pod_uid, allow_reresolve, is_unfenced_teardown, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => { return absent( Some(row.generation), tracked_pod_uid, None, false, ); } MissingPodResolution::ClaimPreserved { updated_at } => { return absent( Some(row.generation), None, is_unfenced_teardown.then_some(updated_at), is_unfenced_teardown, ); } } }; if authoritative_pod.uid() != pod.uid() || assigned_pod_node_name(&authoritative_pod) != current_node_name.as_deref() || terminal_pod_phase(&authoritative_pod).is_some() { if allow_reresolve { continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "unreachable-node pod verification", ) .await?; return absent(Some(row.generation), tracked_pod_uid, None, false); } let live_pod_uid = authoritative_pod.uid().map(str::to_owned); match self .verify_no_reachable_runtime_fence( sandbox_id, &row, tracked_pod_uid, tracked_updated_at, tracked_pod_ip, tracked_node_name, live_pod_uid.as_deref(), allow_reresolve, "unreachable-node pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { // Record only kubelet's published `status.podIP`, never a // `NodeReported` DB address: if the `Node` regains an // `InternalIP` before pod `DELETE`, a `None` `published_pod_ip` // forces `node_sandboxes` worker verification instead of // bypassing runtime stop on a pre-publish worker address. let published_pod_ip = assigned_pod_ip(&authoritative_pod)?; let node_check = current_node_name.clone().map(|node_name| { NoRuntimeNodeCheck::NodeUnreachableAtResolve { node_name, published_pod_ip, } }); let pod_fence = resolution_fences::no_reachable_runtime_delete_fence( row.generation, &row.pod_name, tracked_pod_uid, tracked_updated_at, &authoritative_pod, true, node_check, ); if is_unfenced_teardown && pod_fence.is_none() { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "{err}; sandbox pod {} has no UID for fenced teardown", row.pod_name ), }, )); } return Err(ResolvePodInstanceError::NoReachableRuntime { err, pod_fence, }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => { return absent(Some(row.generation), tracked_pod_uid, None, false); } } } } } if resolved.is_none() && is_unfenced_teardown { match self .verify_no_reachable_runtime_fence( sandbox_id, &row, tracked_pod_uid, tracked_updated_at, tracked_pod_ip, tracked_node_name, pod_uid.as_deref(), allow_reresolve, "unaddressed pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { let node_check = current_node_name .clone() .map(|node_name| NoRuntimeNodeCheck::BoundWithoutPodIp { node_name }); let Some(pod_fence) = resolution_fences::no_reachable_runtime_delete_fence( row.generation, &row.pod_name, tracked_pod_uid, tracked_updated_at, &pod, true, node_check, ) else { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "sandbox pod {} has no runtime IP yet and has no UID \ for fenced teardown", row.pod_name ), }, )); }; let message = match current_node_name.as_deref() { Some(node_name) => format!( "sandbox pod {} is bound to node {node_name} without a runtime IP yet", row.pod_name ), None => { format!("sandbox pod {} is not bound to a node yet", row.pod_name) } }; return Err(ResolvePodInstanceError::NoReachableRuntime { err: SubstrateError::Unavailable { message }, pod_fence: Some(pod_fence), }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => { return absent(Some(row.generation), tracked_pod_uid, None, false); } } } let Some((ip, source)) = resolved else { return absent(Some(row.generation), tracked_pod_uid, None, false); }; return Ok(UnfencedPodResolution::Live { instance: ResolvedPodInstance { ip, source, pod_name: row.pod_name, pod_uid: pod_uid.as_deref().and_then(|uid| PodUid::parse(uid).ok()), generation: row.generation, sandbox_restoring: is_restoring_lifecycle(&row.lifecycle), }, tracked_pod_uid: tracked_pod_uid.and_then(|uid| PodUid::parse(uid).ok()), tracked_updated_at, }); } Ok(UnfencedPodResolution::Absent { checked_generation: None, checked_pod_name: None, checked_pod_uid: None, checked_updated_at: None, retire_checked_generation: false, }) } } mod node_placement; mod resolution_fences; pub(in crate::controllers::substrate::kubernetes) use node_placement::{ CompatibleNodePlacementObservation, NodePlacementObservation, UncachedNodeReachability, }; pub(super) use resolution_fences::{ succeeded_pod_publication_grace_remaining, terminal_cleanup_phase_after_uncached_check, }; #[cfg(test)] mod tests;