use std::{ collections::{HashMap, HashSet}, sync::{Arc, Mutex as StdMutex}, time::{Duration, Instant}, }; use base16ct::HexDisplay; use k8s_openapi::api::core::v1::Pod; use kube::{ Client, api::{Api, AttachParams, DeleteParams, PostParams}, }; use sha2::{Digest as _, Sha256}; use tokio::{ sync::{Mutex, OwnedMutexGuard}, time::{sleep, timeout}, }; use tonic::Status; use tracing::{info, warn}; use crate::{config::Config, error::kube_status, execution::Attachment, plugin::CreateRequest}; use super::pod; #[derive(Default)] struct EnvironmentLocks { locks: StdMutex>>>, } impl EnvironmentLocks { async fn acquire(&self, id: &str) -> EnvironmentGuard { let lock = { let mut locks = self.locks.lock().expect("environment lock map poisoned"); Arc::clone( locks .entry(id.to_owned()) .or_insert_with(|| Arc::new(Mutex::new(()))), ) }; EnvironmentGuard { _guard: lock.lock_owned().await, } } } /// Keeps operations for one environment serialized while hiding the lock itself. pub(super) struct EnvironmentGuard { _guard: OwnedMutexGuard<()>, } #[derive(Clone)] pub(super) struct JobEnvironments { cancelled_environments: Arc>>, config: Arc, environment_failures: Arc>>, locks: Arc, pods: Api, } impl JobEnvironments { pub(super) fn new(client: Client, config: Config) -> Self { let namespace = config.namespace.clone(); Self { config: Arc::new(config), pods: Api::namespaced(client, &namespace), locks: Arc::new(EnvironmentLocks::default()), cancelled_environments: Arc::new(StdMutex::new(HashSet::new())), environment_failures: Arc::new(StdMutex::new(HashMap::new())), } } pub(super) fn environment_id(name: &str) -> String { let digest = Sha256::digest(name.as_bytes()); let digest = HexDisplay(&digest); format!("kube-{digest:x}")[..29].to_owned() } pub(super) fn pod_name(id: &str) -> String { format!("forgejo-{id}") } pub(super) async fn create(&self, request: &CreateRequest) -> Result { let id = Self::environment_id(&request.name); let started = Instant::now(); let _guard = self.locks.acquire(&id).await; let pod = pod::build(&self.config, &id, request)?; let pod_name = Self::pod_name(&id); if self .pods .get_opt(&pod_name) .await .map_err(|error| { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, error = %error, "could not check for existing job pod"); kube_status("get existing job pod", error) })? .is_some() { info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, elapsed_ms = started.elapsed().as_millis(), "returning existing idempotent job environment"); } else { self.clear_environment_failure(&id); self.pods .create(&PostParams::default(), &pod) .await .map_err(|error| { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, image = ?pod.spec.as_ref().and_then(|spec| spec.containers.first()).and_then(|container| container.image.as_deref()), error = %error, "could not create job pod"); kube_status("create job pod", error) })?; info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, image = ?pod.spec.as_ref().and_then(|spec| spec.containers.first()).and_then(|container| container.image.as_deref()), elapsed_ms = started.elapsed().as_millis(), "created job pod"); } Ok(id) } pub(super) async fn acquire(&self, id: &str) -> Result { validate_environment_id(id)?; Ok(self.locks.acquire(id).await) } pub(super) async fn ensure_exists(&self, id: &str) -> Result<(), Status> { self.pod_for_environment(id).await.map(|_| ()) } pub(super) async fn wait_until_started(&self, id: &str) -> Result<(), Status> { let started = Instant::now(); let pod_name = Self::pod_name(id); info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, "waiting for job pod containers to start"); loop { let pod = self.pod_for_environment(id).await?; let status = pod.status.as_ref(); if let Some(phase) = status.and_then(|status| status.phase.as_deref()) && matches!(phase, "Failed" | "Succeeded") { let message = job_environment_failure_message(&pod) .unwrap_or_else(|| "job pod terminated before it was ready".to_owned()); warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, phase = ?phase, error = %message, elapsed_ms = started.elapsed().as_millis(), "job pod terminated before startup completed"); return Err(Status::failed_precondition(message)); } if containers_are_running(&pod) { info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, elapsed_ms = started.elapsed().as_millis(), "job pod started"); return Ok(()); } if let Some(message) = startup_failure_message(&pod) { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, error = %message, elapsed_ms = started.elapsed().as_millis(), "job pod container cannot start"); return Err(Status::failed_precondition(message)); } sleep(Duration::from_millis(500)).await; } } pub(super) async fn attach( &self, id: &str, command: Vec, stdin: bool, ) -> Result { if let Some(message) = self.environment_failure(id) { return Err(Status::failed_precondition(message)); } let job_pod = self.pod_for_environment(id).await?; if let Some(message) = job_environment_failure_message(&job_pod) { let message = self.record_environment_failure(id, message); return Err(Status::failed_precondition(message)); } match self .pods .exec( &Self::pod_name(id), command, &AttachParams::default() .container(pod::JOB_CONTAINER) .stdin(stdin) .stdout(true) .stderr(true) .tty(false), ) .await { Ok(process) => Ok(process.into()), Err(error) => { // Container termination and status publication can race with the // exec upgrade. Replace kubelet's opaque HTTP 500 with the Pod's // actionable termination reason whenever it is available. if exec_failure_indicates_stopped_container(&error.to_string()) { let message = self.stopped_environment_failure(id).await; warn!(environment_id = %id, pod = %Self::pod_name(id), namespace = %self.config.namespace, error = %message, "job environment is unavailable"); return Err(Status::failed_precondition(message)); } warn!(environment_id = %id, pod = %Self::pod_name(id), namespace = %self.config.namespace, error = %error, "Kubernetes exec request failed"); Err(kube_status("execute command in job pod", error)) } } } pub(super) async fn cancel(&self, id: &str) -> Result<(), Status> { self.cancelled_environments .lock() .expect("cancelled-environment map poisoned") .insert(id.to_owned()); self.delete_environment(id).await } pub(super) async fn remove(&self, id: &str) -> Result<(), Status> { validate_environment_id(id)?; let _guard = self.locks.acquire(id).await; match self.pod_for_environment(id).await { Ok(_) => { self.delete_environment(id).await?; self.take_cancelled_environment(id); } Err(error) if error.code() == tonic::Code::NotFound && self.take_cancelled_environment(id) => { } Err(error) => return Err(error), } self.clear_environment_failure(id); info!(environment_id = %id, pod = %Self::pod_name(id), namespace = %self.config.namespace, "removed job pod"); Ok(()) } pub(super) fn take_cancelled_environment(&self, id: &str) -> bool { self.cancelled_environments .lock() .expect("cancelled-environment map poisoned") .remove(id) } fn environment_failure(&self, id: &str) -> Option { self.environment_failures .lock() .expect("environment-failure map poisoned") .get(id) .cloned() } fn record_environment_failure(&self, id: &str, message: String) -> String { self.environment_failures .lock() .expect("environment-failure map poisoned") .insert(id.to_owned(), message.clone()); message } fn clear_environment_failure(&self, id: &str) { self.environment_failures .lock() .expect("environment-failure map poisoned") .remove(id); } async fn pod_for_environment(&self, id: &str) -> Result { validate_environment_id(id)?; self.pods .get_opt(&Self::pod_name(id)) .await .map_err(|error| kube_status("get job pod", error))? .ok_or_else(|| Status::not_found(format!("environment {id:?} was not found"))) } async fn delete_environment(&self, id: &str) -> Result<(), Status> { validate_environment_id(id)?; let started = Instant::now(); let pod_name = Self::pod_name(id); info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, "deleting job pod"); // Remove and stream cancellation mean the job must no longer execute. // Kubernetes otherwise defaults to the Pod's 30-second termination grace // period, which can exhaust this operation's own bounded wait. let delete_params = DeleteParams::default().grace_period(0); match self.pods.delete(&pod_name, &delete_params).await { Ok(_) => {} Err(kube::Error::Api(response)) if response.code == 404 => return Ok(()), Err(error) => { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, error = %error, "could not delete job pod"); return Err(kube_status("delete job pod", error)); } } let deleted = timeout(Duration::from_secs(30), async { loop { match self.pods.get_opt(&pod_name).await { Ok(None) => return Ok(()), Ok(Some(_)) => sleep(Duration::from_millis(250)).await, Err(error) => return Err(kube_status("wait for job pod deletion", error)), } } }) .await; match deleted { Ok(Ok(())) => { info!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, elapsed_ms = started.elapsed().as_millis(), "job pod deleted"); Ok(()) } Ok(Err(error)) => { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, error = %error, "failed while waiting for job pod deletion"); Err(error) } Err(_) => { warn!(environment_id = %id, pod = %pod_name, namespace = %self.config.namespace, elapsed_ms = started.elapsed().as_millis(), "timed out waiting for job pod deletion"); Err(Status::deadline_exceeded( "timed out waiting for job pod deletion; inspect the pod and namespace for finalizers or Kubernetes API issues", )) } } } pub(super) async fn wait_for_environment_failure(&self, id: &str) -> Option { if let Some(message) = self.environment_failure(id) { return Some(message); } // Exec completion can precede kubelet publishing the terminated state // by more than one status-update interval. This path runs only after a // forced exit or stopped-container error, where a short delay is worth // replacing an opaque exit 137 / HTTP 500 with the actual Pod reason. for attempt in 0..20 { if let Ok(pod) = self.pod_for_environment(id).await && let Some(message) = job_environment_failure_message(&pod) { return Some(self.record_environment_failure(id, message)); } if attempt < 19 { sleep(Duration::from_millis(100)).await; } } None } pub(super) async fn stopped_environment_failure(&self, id: &str) -> String { if let Some(message) = self.wait_for_environment_failure(id).await { return message; } self.record_environment_failure( id, "job container is stopped, but Kubernetes has not published its termination reason; if this followed exit code 137, the container was likely OOM-killed. Check KURANTO_JOB_MEMORY_LIMIT and the pod's events" .to_owned(), ) } } pub(super) fn validate_environment_id(id: &str) -> Result<(), Status> { if id.starts_with("kube-") && id.len() == 29 && id .bytes() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') { Ok(()) } else { Err(Status::invalid_argument("malformed environment_id")) } } fn containers_are_running(pod: &Pod) -> bool { let expected = pod.spec.as_ref().map_or(0, |spec| spec.containers.len()); let statuses = pod .status .as_ref() .and_then(|status| status.container_statuses.as_ref()); matches!(statuses, Some(statuses) if statuses.len() == expected && statuses.iter().all(|status| { status.state.as_ref().and_then(|state| state.running.as_ref()).is_some() })) } fn startup_failure_message(pod: &Pod) -> Option { let statuses = pod.status.as_ref()?.container_statuses.as_ref()?; statuses.iter().find_map(|status| { let waiting = status.state.as_ref()?.waiting.as_ref()?; matches!( waiting.reason.as_deref(), Some("ErrImagePull" | "ImagePullBackOff" | "CreateContainerConfigError") ) .then(|| { format!( "job pod container {} cannot start: {}", status.name, waiting .message .as_deref() .unwrap_or_else(|| waiting.reason.as_deref().unwrap_or("unknown error")) ) }) }) } fn job_environment_failure_message(pod: &Pod) -> Option { let pod_status = pod.status.as_ref()?; let terminated = pod_status .container_statuses .as_ref() .and_then(|statuses| { statuses .iter() .find(|status| status.name == pod::JOB_CONTAINER) }) .and_then(|status| status.state.as_ref()) .and_then(|state| state.terminated.as_ref()); if let Some(terminated) = terminated { let reason = terminated.reason.as_deref().unwrap_or("Unknown"); let signal = terminated .signal .map(|signal| format!(", signal={signal}")) .unwrap_or_default(); let memory_limit = pod .spec .as_ref() .and_then(|spec| { spec.containers .iter() .find(|container| container.name == pod::JOB_CONTAINER) }) .and_then(|container| container.resources.as_ref()) .and_then(|resources| resources.limits.as_ref()) .and_then(|limits| limits.get("memory")) .map(|quantity| format!(", memory_limit={}", quantity.0)) .unwrap_or_default(); let detail = terminated .message .as_deref() .map(|message| format!(": {message}")) .unwrap_or_default(); let hint = (reason == "OOMKilled") .then_some("; increase KURANTO_JOB_MEMORY_LIMIT or reduce the job's peak memory usage"); return Some(format!( "job container terminated (reason={reason}, exit_code={}{signal}{memory_limit}){detail}{}", terminated.exit_code, hint.unwrap_or_default() )); } matches!(pod_status.phase.as_deref(), Some("Failed" | "Succeeded")).then(|| { let reason = pod_status .reason .as_deref() .map(|reason| format!(", reason={reason}")) .unwrap_or_default(); let message = pod_status .message .as_deref() .unwrap_or("no details reported"); format!( "job pod is no longer running (phase={}{}): {message}", pod_status.phase.as_deref().unwrap_or("Unknown"), reason ) }) } pub(super) fn exec_failure_indicates_stopped_container(message: &str) -> bool { message.contains("cannot exec in a stopped state") } #[cfg(test)] mod tests { use k8s_openapi::api::core::v1::{ Container, ContainerState, ContainerStateTerminated, ContainerStatus, PodSpec, PodStatus, ResourceRequirements, }; use k8s_openapi::apimachinery::pkg::api::resource::Quantity; use std::collections::BTreeMap; use super::*; #[test] fn environment_ids_are_deterministic_and_kubernetes_safe() { let id = JobEnvironments::environment_id("runner-job-42"); assert_eq!(id, JobEnvironments::environment_id("runner-job-42")); assert!(id.starts_with("kube-")); assert_eq!(id.len(), 29); } #[test] fn oom_kill_message_includes_resource_limit_and_remediation() { let pod = Pod { spec: Some(PodSpec { containers: vec![Container { name: pod::JOB_CONTAINER.to_owned(), resources: Some(ResourceRequirements { limits: Some(BTreeMap::from([( "memory".to_owned(), Quantity("1Gi".to_owned()), )])), ..Default::default() }), ..Default::default() }], ..Default::default() }), status: Some(PodStatus { container_statuses: Some(vec![ContainerStatus { name: pod::JOB_CONTAINER.to_owned(), state: Some(ContainerState { terminated: Some(ContainerStateTerminated { exit_code: 137, reason: Some("OOMKilled".to_owned()), signal: Some(9), ..Default::default() }), ..Default::default() }), ..Default::default() }]), ..Default::default() }), ..Default::default() }; let message = job_environment_failure_message(&pod).expect("terminated container"); assert!(message.contains("reason=OOMKilled")); assert!(message.contains("exit_code=137")); assert!(message.contains("memory_limit=1Gi")); assert!(message.contains("increase KURANTO_JOB_MEMORY_LIMIT")); } #[test] fn stopped_exec_status_is_recognized() { assert!(exec_failure_indicates_stopped_container( "Internal error occurred: failed to create exec: cannot exec in a stopped state" )); assert!(!exec_failure_indicates_stopped_container( "command exited with status 1" )); } #[test] fn terminal_pod_message_preserves_kubernetes_reason() { let pod = Pod { status: Some(PodStatus { phase: Some("Failed".to_owned()), reason: Some("Evicted".to_owned()), message: Some("node was low on memory".to_owned()), ..Default::default() }), ..Default::default() }; assert_eq!( job_environment_failure_message(&pod).as_deref(), Some( "job pod is no longer running (phase=Failed, reason=Evicted): node was low on memory" ) ); } }