Something went wrong. Try again.
A Forgejo Runner plugin that spawn jobs as Kubernetes pods
kubernetes ci forgejo runner
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293use std::time::Instant;
use tokio::sync::{mpsc, oneshot};use tonic::Status;use tracing::{debug, info, warn};
use crate::{ execution::{self, Failure}, plugin::{ CopyInChunk, CopyOutChunk, CopyOutRequest, ExecComplete, ExecFailed, ExecOutput, ExecRequest, exec_output, },};
use super::{ DEFAULT_WORKDIR, environment::{self, JobEnvironments},};
#[derive(Clone)]pub(super) struct WorkflowOperations { environments: JobEnvironments,}
impl WorkflowOperations { pub(super) const fn new(environments: JobEnvironments) -> Self { Self { environments } }
pub(super) async fn exec( &self, request: ExecRequest, sender: mpsc::Sender<Result<ExecOutput, Status>>, completion: &mut Option<oneshot::Sender<()>>, ) -> Result<(), Status> { let id = request.environment_id.clone(); let _guard = self.environments.acquire(&id).await?; let workdir = if request.workdir.is_empty() { DEFAULT_WORKDIR.to_owned() } else { request.workdir.clone() };
let executable = request.command[0].clone(); let command_started = Instant::now(); debug!( environment_id = %id, executable = %executable, arguments = request.command.len(), environment_variables = request.env.len(), workdir = %workdir, "starting job command" );
let mut command = vec![ "/bin/sh".to_owned(), "-c".to_owned(), "mkdir -p \"$1\"; cd \"$1\"; shift; exec env -- \"$@\"".to_owned(), "kuranto".to_owned(), workdir, ]; command.extend( request .env .iter() .map(|(key, value)| format!("{key}={value}")), ); command.extend(request.command);
let process = self.environments.attach(&id, command, false).await?; debug!(environment_id = %id, executable = %executable, "attached to Kubernetes exec stream"); let outcome = execution::command(process, &sender).await; self.finish_exec( &id, &executable, command_started, outcome, sender, completion, ) .await }
pub(super) async fn finish_exec( &self, id: &str, executable: &str, command_started: Instant, outcome: Result<i32, Failure>, sender: mpsc::Sender<Result<ExecOutput, Status>>, completion: &mut Option<oneshot::Sender<()>>, ) -> Result<(), Status> { let outcome = match outcome { Ok(exit_code) => Ok(exit_code), Err(Failure::Remote(message)) => Err(message), Err(Failure::Stream(error)) => return Err(error), };
// Disarm before terminal publication so the runner may start CopyOut for // this environment as soon as it receives the terminal message. if let Some(completion) = completion.take() { let _ = completion.send(()); }
let output = match outcome { Ok(137) if let Some(message) = self.environments.wait_for_environment_failure(id).await => { warn!( environment_id = %id, executable = %executable, elapsed_ms = command_started.elapsed().as_millis(), error = %message, "job container terminated while executing command" ); exec_output::Output::ExecFailed(ExecFailed { error_message: message, }) } Ok(exit_code) => { debug!( environment_id = %id, executable = %executable, exit_code, elapsed_ms = command_started.elapsed().as_millis(), "job command finished" ); exec_output::Output::ExecComplete(ExecComplete { exit_code }) } Err(message) => { let message = if environment::exec_failure_indicates_stopped_container(&message) { self.environments.stopped_environment_failure(id).await } else { message }; warn!( environment_id = %id, executable = %executable, elapsed_ms = command_started.elapsed().as_millis(), error = %message, "job command could not be completed" ); exec_output::Output::ExecFailed(ExecFailed { error_message: message, }) } }; sender .send(Ok(ExecOutput { output: Some(output), })) .await .map_err(|_| Status::cancelled("Exec stream closed")) }
pub(super) async fn copy_in( &self, mut stream: tonic::Streaming<CopyInChunk>, ) -> Result<(), Status> { let first = stream .message() .await .map_err(|error| Status::invalid_argument(format!("read first CopyIn chunk: {error}")))? .ok_or_else(|| Status::invalid_argument("CopyIn requires at least one chunk"))?; let id = first.environment_id.clone().ok_or_else(|| { Status::invalid_argument("first CopyIn chunk requires environment_id") })?; let destination = first .dest_path .clone() .ok_or_else(|| Status::invalid_argument("first CopyIn chunk requires dest_path"))?; environment::validate_environment_id(&id)?; validate_absolute_path(&destination, "CopyIn.dest_path")?; let _guard = self.environments.acquire(&id).await?;
let command = vec![ "/bin/sh".to_owned(), "-c".to_owned(), "mkdir -p \"$1\" && exec tar -xmf - -C \"$1\"".to_owned(), "kuranto".to_owned(), destination.clone(), ]; let transfer_started = Instant::now(); debug!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), destination = %destination, "starting CopyIn archive transfer"); let process = self.environments.attach(&id, command, true).await?; let bytes_transferred = match execution::upload_archive(process, first.data, stream).await { Ok(bytes_transferred) => bytes_transferred, Err(failure) => { let status = self.copy_failure_status(&id, failure).await; warn!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), destination = %destination, error = %status, elapsed_ms = transfer_started.elapsed().as_millis(), "CopyIn archive transfer failed"); return Err(status); } }; debug!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), destination = %destination, bytes_transferred, elapsed_ms = transfer_started.elapsed().as_millis(), "completed CopyIn archive transfer"); Ok(()) }
pub(super) async fn run_copy_out( self, request: CopyOutRequest, sender: mpsc::Sender<Result<CopyOutChunk, Status>>, ) { let result = tokio::select! { _ = sender.closed() => Err(Status::cancelled("CopyOut stream closed")), result = self.run_copy_out_inner(request, sender.clone()) => result, }; if let Err(error) = result { let _ = sender.send(Err(error)).await; } }
async fn run_copy_out_inner( &self, request: CopyOutRequest, sender: mpsc::Sender<Result<CopyOutChunk, Status>>, ) -> Result<(), Status> { validate_absolute_path(&request.src_path, "CopyOut.src_path")?; let id = request.environment_id.clone(); let _guard = self.environments.acquire(&id).await?; let transfer_started = Instant::now(); info!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), source = %request.src_path, "starting CopyOut archive transfer"); let command = vec![ "tar".to_owned(), "-cf".to_owned(), "-".to_owned(), "-C".to_owned(), "/".to_owned(), request.src_path.trim_start_matches('/').to_owned(), ]; let process = self.environments.attach(&id, command, false).await?; match execution::download_archive(process, &sender).await { Ok(()) => { info!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), source = %request.src_path, elapsed_ms = transfer_started.elapsed().as_millis(), "completed CopyOut archive transfer"); Ok(()) } Err(failure) => { let status = self.copy_failure_status(&id, failure).await; warn!(environment_id = %id, pod = %JobEnvironments::pod_name(&id), source = %request.src_path, error = %status, elapsed_ms = transfer_started.elapsed().as_millis(), "CopyOut archive transfer failed"); Err(status) } } }
async fn copy_failure_status(&self, id: &str, failure: Failure) -> Status { match failure { Failure::Remote(message) if environment::exec_failure_indicates_stopped_container(&message) => { Status::failed_precondition(self.environments.stopped_environment_failure(id).await) } Failure::Remote(message) => Status::internal(message), Failure::Stream(status) => status, } }}
pub(super) fn validate_exec_request(request: &ExecRequest) -> Result<(), Status> { if request.command.is_empty() { return Err(Status::invalid_argument("Exec.command must not be empty")); } if request.user.is_some() { return Err(Status::unimplemented( "per-command users are not supported by Kubernetes exec; configure the image user instead", )); } if !request.workdir.is_empty() { validate_absolute_path(&request.workdir, "Exec.workdir")?; } for (name, value) in &request.env { if name.is_empty() || name.contains('=') || name.contains('\0') { return Err(Status::invalid_argument(format!( "invalid Exec environment variable name {name:?}" ))); } if value.contains('\0') { return Err(Status::invalid_argument(format!( "Exec environment variable {name:?} contains a NUL byte" ))); } } Ok(())}
fn validate_absolute_path(path: &str, field: &str) -> Result<(), Status> { if path.starts_with('/') && !path.contains('\0') { Ok(()) } else { Err(Status::invalid_argument(format!( "{field} must be an absolute path" ))) }}