diff --git a/crates/forge-ci/src/proto.rs b/crates/forge-ci/src/proto.rs index cc25967..b68d1bf 100644 --- a/crates/forge-ci/src/proto.rs +++ b/crates/forge-ci/src/proto.rs @@ -8,6 +8,8 @@ use std::fmt; use serde::{Deserialize, Serialize}; +pub const RESTART_EXIT_CODE: u8 = 75; + /// `POST /api/v1/ci/runners/register` #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RegisterRequest { @@ -122,6 +124,21 @@ pub struct RunnerLogLine { pub text: String, } +/// Longest text kept for one runner log line, in bytes. +pub const RUNNER_LOG_MAX_TEXT: usize = 4096; + +/// `text` cut to at most `max` bytes, on a character boundary. +pub fn truncate_text(text: &str, max: usize) -> &str { + if text.len() <= max { + return text; + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + /// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot /// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it /// still holds; lines it no longer holds are skipped. diff --git a/crates/forge-runner/src/artifacts.rs b/crates/forge-runner/src/artifacts.rs index 1639220..8464d4d 100644 --- a/crates/forge-runner/src/artifacts.rs +++ b/crates/forge-runner/src/artifacts.rs @@ -11,9 +11,9 @@ use std::path::{Path, PathBuf}; use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; /// The server accepts names matching `[A-Za-z0-9._+-]{1,128}` and not starting with `.`. -pub const MAX_NAME_LEN: usize = 128; +const MAX_NAME_LEN: usize = 128; /// The server caps artifacts per job at 50 by default. -pub const MAX_FILES: usize = 50; +const MAX_FILES: usize = 50; /// Errors from collecting artifacts. Any of them fails the job. #[derive(Debug, thiserror::Error)] @@ -41,12 +41,11 @@ pub struct Artifact { pub name: String, /// The file on disk, inside the workspace. pub path: PathBuf, - pub size: u64, } /// Turns a workspace-relative path into one upload name: `/` becomes `_`, characters outside /// the server alphabet become `_`, and a leading `.` is replaced so the name is never hidden. -pub fn flatten_name(rel: &str) -> Result { +fn flatten_name(rel: &str) -> Result { let joined = rel .split('/') .filter(|c| !c.is_empty()) @@ -72,7 +71,7 @@ pub fn flatten_name(rel: &str) -> Result { } /// Rejects patterns that are absolute or climb out of the workspace. -pub fn check_pattern(pattern: &str) -> Result<(), ArtifactError> { +fn check_pattern(pattern: &str) -> Result<(), ArtifactError> { let bad = pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == ".."); if bad { @@ -161,11 +160,7 @@ pub fn collect( limit: max_bytes_per_file, }); } - out.push(Artifact { - name, - path: real, - size: meta.len(), - }); + out.push(Artifact { name, path: real }); } Ok(out) } diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index 657d41a..2bd95d1 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -108,9 +108,6 @@ where return ExitCode::FAILURE; } }; - // Another subscriber may already be installed, for example by forge-web. Keep that one. - // The env filter applies to the terminal output only. The runner's own log that is shipped to - // the forge is always INFO and above, whatever the env filter says, see `selflog`. let _ = tracing_subscriber::registry() .with( tracing_subscriber::fmt::layer() @@ -190,6 +187,8 @@ async fn run(cli: Cli) -> Result> { config: path, work_dir, } => { + let path = path.map_or_else(config::default_config_path, Ok)?; + let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; let client = ForgeClient::new(&url)?; let resp = client .register(&RegisterRequest { @@ -198,14 +197,6 @@ async fn run(cli: Cli) -> Result> { labels: labels.clone(), }) .await?; - let path = match path { - Some(p) => p, - None => config::default_config_path()?, - }; - let work_dir = match work_dir { - Some(w) => w, - None => config::default_work_dir()?, - }; let cfg = RunnerConfig { url, runner_id: resp.runner_id.clone(), @@ -231,15 +222,10 @@ async fn run(cli: Cli) -> Result> { Ok(ExitCode::SUCCESS) } Command::Run { config: path } => { - let path = match path { - Some(p) => p, - None => config::default_config_path()?, - }; + let path = path.map_or_else(config::default_config_path, Ok)?; let mut cfg = config::load(&path)?; sync_config_with_forge(&mut cfg).await; let shutdown = CancellationToken::new(); - // Only the builtin executor puts its jobs under the box. With the box, a lone job may - // use all of it, so an undeclared job's cgroup limit is the box budget. let pressure = match cfg.executor { ExecutorKind::Builtin => { let budget = crate::memory::MemoryGate::for_host(&cfg.limits).ram_budget(); @@ -253,14 +239,12 @@ async fn run(cli: Cli) -> Result> { }; let cache_root = cfg.work_dir.join(".cache"); let cache_cap = cfg.cache_max_gib; - // The id map is what the executor's jobs run under. The cache removes its dirs with it. let (executor, map): (Arc, IdMap) = match cfg.executor { ExecutorKind::Podman => ( Arc::new(PodmanExecutor::new(cfg.limits.clone())), IdMap::single(), ), ExecutorKind::Builtin => { - // Resolved once. In subuid mode a failure here is a startup error. let map = IdMap::resolve(cfg.sandbox.userns)?; tracing::info!("sandbox ids: {}", map.describe()); let helper = std::env::current_exe()?; @@ -275,7 +259,6 @@ async fn run(cli: Cli) -> Result> { let images = ImageStore::new(root) .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) .with_idmap(map.clone(), helper.clone()); - // Before the first job: what an earlier run left behind. crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; let jobs_dir = cfg.work_dir.join("jobs"); let executor = @@ -304,20 +287,14 @@ async fn run(cli: Cli) -> Result> { }); match runner.run(shutdown).await { RunEnd::Stopped => Ok(ExitCode::SUCCESS), - // systemd restarts the runner on this code, and it starts the new binary. - RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), - // An admin asked for a restart. The same exit code, the same systemd restart. - RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), + RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), } } Command::Check { work_dir, config: config_path, } => { - let work_dir = match work_dir { - Some(w) => w, - None => config::default_work_dir()?, - }; + let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; let mode = check_userns_mode(config_path)?; let helper = std::env::current_exe()?; if crate::check::run(&helper, &work_dir, mode).await { diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 4ed73f0..719770d 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -172,27 +172,20 @@ impl ForgeClient { .send() .await?; let binary_sha256 = advertised_sha256(resp.headers()); - let concurrency = advertised_concurrency(resp.headers()); - let restart = advertised_restart(resp.headers()); - let memory_budget = header_text(resp.headers(), MEMORY_BUDGET_HEADER); - let reserve_memory = header_text(resp.headers(), RESERVE_MEMORY_HEADER); + let mut reply = ClaimReply { + job: None, + binary_sha256, + concurrency: advertised_concurrency(resp.headers()), + restart: advertised_restart(resp.headers()), + memory_budget: header_text(resp.headers(), MEMORY_BUDGET_HEADER), + reserve_memory: header_text(resp.headers(), RESERVE_MEMORY_HEADER), + }; match resp.status() { - StatusCode::NO_CONTENT => Ok(ClaimReply { - job: None, - binary_sha256, - concurrency, - restart, - memory_budget, - reserve_memory, - }), - status if status.is_success() => Ok(ClaimReply { - job: Some(resp.json().await?), - binary_sha256, - concurrency, - restart, - memory_budget, - reserve_memory, - }), + StatusCode::NO_CONTENT => Ok(reply), + status if status.is_success() => { + reply.job = Some(resp.json().await?); + Ok(reply) + } _ => Err(status_error(resp).await), } } @@ -261,11 +254,7 @@ impl ForgeClient { .timeout(REQUEST_TIMEOUT) .send() .await?; - if resp.status().is_success() { - Ok(()) - } else { - Err(status_error(resp).await) - } + empty_or_error(resp).await } /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the @@ -379,11 +368,7 @@ impl ForgeClient { .timeout(ARTIFACT_TIMEOUT) .send() .await?; - if resp.status().is_success() { - Ok(()) - } else { - Err(status_error(resp).await) - } + empty_or_error(resp).await } /// `POST /api/v1/ci/jobs/{id}/finish`. @@ -401,11 +386,7 @@ impl ForgeClient { .timeout(REQUEST_TIMEOUT) .send() .await?; - if resp.status().is_success() { - Ok(()) - } else { - Err(status_error(resp).await) - } + empty_or_error(resp).await } /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place. @@ -425,11 +406,7 @@ impl ForgeClient { .timeout(REQUEST_TIMEOUT) .send() .await?; - if resp.status().is_success() { - Ok(()) - } else { - Err(status_error(resp).await) - } + empty_or_error(resp).await } } @@ -479,17 +456,10 @@ fn host_facts() -> HostFacts { .and_then(|n| u32::try_from(n.get()).ok()); let memory_bytes = std::fs::read_to_string("/proc/meminfo") .ok() - .and_then(|text| parse_mem_total(&text)); + .and_then(|text| crate::memory::meminfo(&text).total); HostFacts { cpus, memory_bytes } } -/// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes. -fn parse_mem_total(meminfo: &str) -> Option { - let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?; - let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; - kib.checked_mul(1024) -} - async fn json_or_error(resp: reqwest::Response) -> Result { if resp.status().is_success() { Ok(resp.json().await?) @@ -498,6 +468,14 @@ async fn json_or_error(resp: reqwest::Response) -> Result Result<(), ClientError> { + if resp.status().is_success() { + Ok(()) + } else { + Err(status_error(resp).await) + } +} + async fn status_error(resp: reqwest::Response) -> ClientError { let status = resp.status(); let body = short_body(&resp.text().await.unwrap_or_default()); @@ -524,13 +502,6 @@ fn short_body(text: &str) -> String { mod tests { use super::*; - #[test] - fn reads_mem_total_in_bytes() { - let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n"; - assert_eq!(parse_mem_total(text), Some(16384 * 1024)); - assert_eq!(parse_mem_total("nothing"), None); - } - #[test] fn restart_header_must_name_a_mode() { let mut headers = HeaderMap::new(); diff --git a/crates/forge-runner/src/config.rs b/crates/forge-runner/src/config.rs index 547a377..af6dc0a 100644 --- a/crates/forge-runner/src/config.rs +++ b/crates/forge-runner/src/config.rs @@ -99,7 +99,6 @@ impl Limits { let mut limits = self.clone(); let configured = forge_ci::size::parse_size(&self.memory); match self.job_memory_limit(declared) { - // The configured text stays as it is when it already is the limit. Some(bytes) if declared.is_some() || Some(bytes) != configured => { limits.memory = bytes.to_string(); } @@ -311,9 +310,7 @@ impl RunnerConfig { } Ok(()) } -} -impl RunnerConfig { /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner /// secret and registry passwords are never included: the secret shows as `` and a /// registry shows only as `host (username)`. @@ -354,18 +351,9 @@ impl RunnerConfig { json!(self.limits.image_max_gb), ); m.insert("limits.job_disk_gb".into(), json!(self.limits.job_disk_gb)); - let executor = match self.executor { - ExecutorKind::Builtin => "builtin", - ExecutorKind::Podman => "podman", - }; - m.insert("executor".into(), json!(executor)); + m.insert("executor".into(), json!(self.executor)); m.insert("images.keep_days".into(), json!(self.images.keep_days)); - let userns = match self.sandbox.userns { - UsernsMode::Auto => "auto", - UsernsMode::Single => "single", - UsernsMode::Subuid => "subuid", - }; - m.insert("sandbox.userns".into(), json!(userns)); + m.insert("sandbox.userns".into(), json!(self.sandbox.userns)); m.insert("auto_update".into(), json!(self.auto_update)); m.insert("cache_max_gib".into(), json!(self.cache_max_gib)); let registries: Vec = self @@ -444,32 +432,12 @@ impl RunnerConfig { .map(|v| self.images.keep_days = v) .is_some(), "cache_max_gib" => value.as_u64().map(|v| self.cache_max_gib = v).is_some(), - "executor" => match value.as_str() { - Some("builtin") => { - self.executor = ExecutorKind::Builtin; - true - } - Some("podman") => { - self.executor = ExecutorKind::Podman; - true - } - _ => false, - }, - "sandbox.userns" => match value.as_str() { - Some("auto") => { - self.sandbox.userns = UsernsMode::Auto; - true - } - Some("single") => { - self.sandbox.userns = UsernsMode::Single; - true - } - Some("subuid") => { - self.sandbox.userns = UsernsMode::Subuid; - true - } - _ => false, - }, + "executor" => ExecutorKind::deserialize(value) + .map(|v| self.executor = v) + .is_ok(), + "sandbox.userns" => UsernsMode::deserialize(value) + .map(|v| self.sandbox.userns = v) + .is_ok(), _ => continue, }; if !ok { @@ -495,16 +463,19 @@ impl RunnerConfig { } } +fn home_join(rel: &str) -> Result { + let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; + Ok(PathBuf::from(home).join(rel)) +} + /// The default config path: `$HOME/.config/forge-runner/runner.toml`. pub fn default_config_path() -> Result { - let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; - Ok(PathBuf::from(home).join(".config/forge-runner/runner.toml")) + home_join(".config/forge-runner/runner.toml") } /// The default work directory: `$HOME/.cache/forge-runner/work`. pub fn default_work_dir() -> Result { - let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; - Ok(PathBuf::from(home).join(".cache/forge-runner/work")) + home_join(".cache/forge-runner/work") } /// Reads and validates the config file. @@ -536,7 +507,6 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> { .mode(0o600) .open(path) .map_err(io_err)?; - // `mode` only applies when the file is created; tighten a pre-existing file too. file.set_permissions(std::fs::Permissions::from_mode(0o600)) .map_err(io_err)?; file.write_all(text.as_bytes()).map_err(io_err)?; @@ -546,6 +516,8 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> { #[cfg(test)] mod tests { + use super::*; + #[test] fn report_redacts_secrets() { let dir = tempfile::tempdir().expect("tempdir"); @@ -579,7 +551,6 @@ mod tests { ); assert_eq!(lines.len(), 2, "{lines:?}"); - // A value that breaks validation drops the whole set and keeps the config. let before = config.clone(); let mut bad = BTreeMap::new(); bad.insert("limits.image_max_gb".to_owned(), serde_json::json!(0)); @@ -587,8 +558,6 @@ mod tests { assert_eq!(config, before); } - use super::*; - fn sample(dir: &Path) -> RunnerConfig { RunnerConfig { url: "https://forge.example".to_owned(), @@ -685,15 +654,12 @@ mod tests { fn cgroup_memory_is_the_declared_memory_plus_slack() { let limits = Limits::default(); let gib = 1u64 << 30; - // Declared 4g: 4g plus 1/16, which is the 256 MiB minimum here. assert_eq!( limits.job_memory_limit(Some(4 * gib)), Some(4 * gib + (256 << 20)) ); - // Slack grows with big jobs and has a floor for small ones. assert_eq!(memory_slack(32 * gib), 2 * gib); assert_eq!(memory_slack(512 << 20), 256 << 20); - // The declared value wins over limits.memory, in both directions. let small = Limits { memory: "8g".into(), ..Limits::default() @@ -710,7 +676,6 @@ mod tests { let gib = 1u64 << 30; let limits = Limits::default(); assert_eq!(limits.job_memory_limit(None), Some(4 * gib)); - // The configured text is kept as it is. assert_eq!(limits.for_job(None).memory, "4g"); let big_reserve = Limits { reserve_memory: "6g".into(), @@ -724,7 +689,6 @@ mod tests { }; assert_eq!(bad.job_memory_limit(None), None); assert_eq!(bad.for_job(None).memory, "lots"); - // Builtin: no `memory` means the whole budget; a declared one keeps its slack. assert_eq!( limits.for_builtin_job(None, Some(6 * gib), 0).memory, (6 * gib).to_string() @@ -796,7 +760,6 @@ mod tests { assert_eq!(config.registries.len(), 1); assert_eq!(config.registries[0].host, "ghcr.io"); - // A save keeps the image cap and the registry, and the file still loads. save(&path, &config).expect("save"); assert_eq!(load(&path).expect("reload"), config); } diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 51826b0..42fc678 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -1,16 +1,3 @@ -//! Running a job's `run` script. -//! -//! `BuiltinExecutor` is the default: the image is prepared by an [`ImageSource`] (the -//! [`ImageStore`] in production), and the script runs in a sandbox started by a helper process -//! (`forge-runner __sandbox`). No external tool is needed. -//! -//! `PodmanExecutor` is the optional path: a rootless podman container with the workspace -//! mounted at `/workspace`. Secret values and job env travel in the child process environment, -//! and podman receives only `-e NAME`, so no value ever appears in argv. -//! -//! `HostExecutor` runs the script directly on the host. It exists only for tests and is compiled -//! only under `cfg(test)` or the `test-host-executor` feature. - use std::fs; use std::future::Future; use std::path::{Path, PathBuf}; @@ -39,34 +26,21 @@ use crate::sandbox::idmap::{IdMap, remove_tree}; use crate::sandbox::{SandboxRequest, job_cgroup_path}; use crate::workspace::validate_job_id; -/// The prefix of the sandbox helper's own error lines on stderr. const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: "; -/// How long to wait for the output readers to drain after the child has exited. const READER_GRACE: Duration = Duration::from_secs(10); -/// How long to wait for the child to exit after it has been told to stop. const STOP_GRACE: Duration = Duration::from_secs(30); -/// Everything an executor needs to run one job. pub struct ExecRequest<'a> { pub job: &'a JobAssignment, - /// The checked-out source tree. The script runs with it as `/workspace` or as its cwd. pub workspace: &'a Path, - /// Where merged stdout and stderr go, one line per message. pub logs: mpsc::Sender>, - /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`. pub cancel: CancellationToken, - /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see - /// them leave it alone. pub oom: OomSink, - /// The RAM part of the runner's memory budget now. The builtin executor gives a job without - /// `memory` this as its cgroup limit; `None` keeps the configured `limits.memory`. pub memory_budget: Option, - /// The swap part of the budget, which a job without `memory` may use on top of it. pub memory_swap: u64, } -/// The executor's answer. The runner adds timeouts and artifact results on top of it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExecResult { pub outcome: Outcome, @@ -74,23 +48,18 @@ pub struct ExecResult { pub message: Option, } -/// The boxed future an executor returns. Written out so `Executor` stays object safe. pub type ExecFuture<'a> = Pin + Send + 'a>>; -/// Runs jobs. The runner holds one as `Arc`. pub trait Executor: Send + Sync { fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>; } -/// An executor failure, reported as `Outcome::Error`. #[derive(Debug, thiserror::Error)] pub enum ExecError { #[error("invalid job: {0}")] Invalid(String), } -/// Env names go to podman as `-e NAME`, so they must be plain identifiers. A name with `=` in it -/// would carry a value into argv. pub fn validate_env_name(name: &str) -> Result<(), ExecError> { let mut chars = name.chars(); let first_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_'); @@ -102,7 +71,6 @@ pub fn validate_env_name(name: &str) -> Result<(), ExecError> { } } -/// The job's env and secrets as name/value pairs. Secrets win over plain env on a clash. pub fn job_env(job: &JobAssignment) -> Result, ExecError> { let mut pairs: Vec<(String, String)> = Vec::new(); for (k, v) in job.env.iter().chain(job.secrets.iter()) { @@ -113,8 +81,6 @@ pub fn job_env(job: &JobAssignment) -> Result, ExecError> Ok(pairs) } -/// How many things a job should build at once: its CPU limit rounded up, at least 1 and at most -/// the host's CPUs. The runner decides this, not the workflow, since only it knows the machine. pub fn job_parallelism(limits: &Limits) -> u32 { let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); let cpus = limits @@ -127,9 +93,6 @@ pub fn job_parallelism(limits: &Limits) -> u32 { cpus.clamp(1, host.max(1)) } -/// The job's env with the runner's defaults under it: `FORGE_CPUS`, `FORGE_MEMORY_BYTES` (the job's -/// memory limit) and the parallelism knobs common build tools read (cargo, make, cmake). A job that -/// sets one of them itself keeps its own value. pub fn job_env_with_defaults( job: &JobAssignment, limits: &Limits, @@ -156,7 +119,6 @@ pub fn job_env_with_defaults( Ok(pairs) } -/// The podman invocation for a job: argv (no values in it) and the env the child needs. #[derive(Debug, PartialEq, Eq)] pub struct PodmanInvocation { pub args: Vec, @@ -165,7 +127,6 @@ pub struct PodmanInvocation { } fn check_image(image: &str) -> Result<(), ExecError> { - // Podman would read a leading `-` as an option, and whitespace is never valid in a reference. if image.is_empty() || image.starts_with('-') || image.contains(char::is_whitespace) { return Err(ExecError::Invalid(format!("bad image {image:?}"))); } @@ -183,7 +144,6 @@ fn check_limit(value: &str, what: &str) -> Result<(), ExecError> { } } -/// Builds the podman invocation for `job`. Pure, so the argv can be tested. pub fn podman_invocation( job: &JobAssignment, workspace: &Path, @@ -252,7 +212,6 @@ pub fn podman_invocation( }) } -/// How a finished child maps to a job result. fn classify(status: ExitStatus) -> ExecResult { match status.code() { Some(0) => ExecResult { @@ -260,7 +219,6 @@ fn classify(status: ExitStatus) -> ExecResult { exit_code: Some(0), message: None, }, - // podman itself exits 125 when it cannot run the container (no image, no storage, ...). Some(125) => ExecResult { outcome: Outcome::Error, exit_code: Some(125), @@ -287,7 +245,6 @@ fn error_result(message: impl Into) -> ExecResult { } } -/// How to stop a job when it is cancelled. enum Stopper { Podman { container: String, @@ -296,7 +253,6 @@ enum Stopper { ProcessGroup { pid: u32, }, - /// The sandbox helper. It is sent SIGTERM and stops its own container, see [`stop_child`]. Helper { pid: u32, }, @@ -334,10 +290,6 @@ impl Stopper { } } -/// Stops the child on cancellation and returns its exit status. -/// -/// The sandbox helper gets SIGTERM and gets to kill and delete its container itself. SIGKILL -/// follows only if it does not exit within [`STOP_GRACE`]. Other children are killed at once. async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result { if let Stopper::Helper { pid } = stopper { let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM); @@ -356,17 +308,13 @@ async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result, - /// The sandbox helper's last `forge-sandbox: ` line on stderr, when it printed one. sandbox_error: Option, - /// The OOM counters the helper printed, when something in the job was OOM-killed. oom: Option, } -/// Copies stderr lines to the log and remembers the last sandbox error line. async fn tap_sandbox_errors( mut lines: mpsc::Receiver>, logs: mpsc::Sender>, @@ -374,7 +322,6 @@ async fn tap_sandbox_errors( let mut found = None; let mut oom = None; while let Some(chunk) = lines.recv().await { - // The OOM line is for the runner, not for the job log. if chunk.starts_with(SANDBOX_PREFIX) && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) { @@ -393,9 +340,6 @@ async fn tap_sandbox_errors( (found, oom) } -/// Forwards the child's output, waits for it, and reports how it ended. On cancellation the -/// child is stopped first. `cleanup` runs as soon as the child has exited, before the output is -/// drained: a container keeps the output pipes open until it is killed. async fn supervise( mut child: Child, logs: mpsc::Sender>, @@ -415,7 +359,6 @@ async fn supervise( } drop(logs); - // The wait future must be dropped before the stop path borrows the child again. let early = tokio::select! { status = child.wait() => Some(status), _ = cancel.cancelled() => None, @@ -434,7 +377,6 @@ async fn supervise( } }; if tokio::time::timeout(READER_GRACE, drain).await.is_err() { - // A grandchild still holds the pipe. Stop reading rather than hang the job. for reader in &readers { reader.abort(); } @@ -455,7 +397,6 @@ async fn supervise( } } -/// The result for a child that was supervised with the podman or host rules. fn finish(supervised: Supervised) -> ExecResult { if supervised.cancelled { return cancelled_result(); @@ -474,7 +415,6 @@ fn cancelled_result() -> ExecResult { } } -/// Runs jobs in rootless podman. #[derive(Clone, Debug)] pub struct PodmanExecutor { limits: Limits, @@ -520,7 +460,6 @@ impl Executor for PodmanExecutor { } } -/// Runs the script on the host with no isolation. Tests only. #[cfg(any(test, feature = "test-host-executor"))] #[derive(Clone, Copy, Debug, Default)] pub struct HostExecutor; @@ -563,10 +502,7 @@ impl Executor for HostExecutor { } } -/// Where the builtin executor gets its rootfs. [`ImageStore`] pulls and unpacks images. Tests -/// supply a local rootfs directory instead. pub trait ImageSource: Send + Sync { - /// Makes `image` available and returns its rootfs and config. Progress lines go to `log`. fn prepare<'a>( &'a self, image: &'a str, @@ -586,17 +522,12 @@ impl ImageSource for ImageStore { } } -/// Runs jobs in a libcontainer sandbox, started as `helper` (`forge-runner __sandbox`). It needs -/// no external container tool. See `docs/ci.md`. pub struct BuiltinExecutor { images: I, limits: Limits, helper: PathBuf, - /// Holds one `` directory per running job, for the overlay and container state. jobs_dir: PathBuf, - /// `[[registry]]` logins, as (host, login). registries: Vec<(String, RegistryAuth)>, - /// The id map jobs run under. Single unless set by [`BuiltinExecutor::with_idmap`]. idmap: IdMap, } @@ -612,13 +543,11 @@ impl BuiltinExecutor { } } - /// Sets the id map that jobs run under. Job dirs are removed under it too. pub fn with_idmap(mut self, map: IdMap) -> Self { self.idmap = map; self } - /// Sets the `[[registry]]` logins. Each one is used for images on its host. pub fn with_registries(mut self, registries: &[RegistryConfig]) -> Self { self.registries = registries .iter() @@ -635,7 +564,6 @@ impl BuiltinExecutor { self } - /// The login for `image`, matched by its registry host. Docker Hub is `docker.io`. fn auth_for(&self, image: &str) -> Option<&RegistryAuth> { let reference: Reference = image.parse().ok()?; let host = reference.registry(); @@ -684,8 +612,6 @@ impl BuiltinExecutor { .await; let job_dir = self.jobs_dir.join(&job.job_id); - // A leftover from an earlier run of this job id would hold stale overlay state, and maybe - // the pid of a pasta that outlived its helper. crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); @@ -718,7 +644,6 @@ impl BuiltinExecutor { limits, idmap: self.idmap.clone(), }; - // The request holds the secrets. It goes to the helper's stdin and nowhere else. let json = match serde_json::to_vec(&request) { Ok(json) => json, Err(e) => return error_result(format!("cannot encode the sandbox request: {e}")), @@ -739,15 +664,12 @@ impl BuiltinExecutor { return error_result("sandbox helper exited before its pid was read"); }; if let Some(mut stdin) = child.stdin.take() { - // The helper reads the whole request before it does anything else. if let Err(e) = stdin.write_all(&json).await { return error_result(format!("cannot send the job to the sandbox helper: {e}")); } } drop(json); - // The disk cap stops the job through its own token, so a stop for disk can be told apart - // from a cancel. let job_cancel = cancel.child_token(); let over_disk = Arc::new(AtomicBool::new(false)); let disk_cap = disk_gb.saturating_mul(1 << 30); @@ -811,7 +733,6 @@ impl BuiltinExecutor { exit_code: Some(0), message: None, }, - // The helper's own setup failure. A job that exits 125 by itself is a failure. Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { let line = sandbox_error.unwrap_or_default(); let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line); @@ -836,14 +757,10 @@ impl BuiltinExecutor { } } -/// Where cgroup2 is mounted. Job cgroup paths are relative to it. const CGROUP_ROOT: &str = "/sys/fs/cgroup"; -/// How often, and how many times, to retry removing a job cgroup while its processes exit. const REAP_POLL: Duration = Duration::from_millis(100); const REAP_POLLS: u32 = 50; -/// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up). -/// Older kernels get a SIGKILL to each pid in `cgroup.procs`. pub(crate) fn kill_cgroup(dir: &Path) { if fs::write(dir.join("cgroup.kill"), "1").is_ok() { return; @@ -859,7 +776,6 @@ pub(crate) fn kill_cgroup(dir: &Path) { } } -/// What to clean up once a job's sandbox helper has exited. See [`reap_job`]. struct JobCleanup { helper_pid: u32, job_id: String, @@ -868,15 +784,11 @@ struct JobCleanup { helper: PathBuf, } -/// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL -/// cannot delete its container, so the container could otherwise keep running. This kills what is -/// left in the job cgroup, removes the cgroup, stops a leftover pasta, and removes the job dir. async fn reap_job(job: &JobCleanup) { if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); if dir.exists() { kill_cgroup(&dir); - // rmdir fails while processes remain, so retry until they have exited. for _ in 0..REAP_POLLS { if fs::remove_dir(&dir).is_ok() || !dir.exists() { break; @@ -885,18 +797,12 @@ async fn reap_job(job: &JobCleanup) { } } } - // A helper killed with SIGKILL could not stop its pasta either. crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); } } -/// Cleans up after an earlier run of the runner that did not get to (a crash, a SIGKILL, a power -/// cut): for every leftover `work_dir/jobs/` it stops a pasta, kills the job's cgroups and -/// removes the dir, and it removes leftover workspaces `work_dir/`. Call it at startup, -/// before any job runs. Only job ids found in this runner's own dirs are touched, so another -/// runner's jobs in a shared cgroup are left alone. pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; @@ -944,8 +850,6 @@ fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { tracing::warn!("cannot remove {}: {e}", job_dir.display()); } } - // `work_dir` may be shared with other files (an operator could point it at a home dir), so - // only names shaped like the forge's job ids (ULIDs) count as workspaces. for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { let workspace = work_dir.join(&job_id); tracing::info!("removing leftover workspace {job_id}"); @@ -955,7 +859,6 @@ fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { } } -/// 26 Crockford base32 digits, the shape of every job id the forge hands out. fn is_ulid(name: &str) -> bool { name.len() == 26 && name @@ -963,7 +866,6 @@ fn is_ulid(name: &str) -> bool { .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) } -/// The names of the dirs in `dir` that are valid job ids. Symlinks are skipped. fn job_ids_in(dir: &Path) -> Vec { let Ok(entries) = fs::read_dir(dir) else { return Vec::new(); @@ -976,9 +878,6 @@ fn job_ids_in(dir: &Path) -> Vec { .collect() } -/// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through -/// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async -/// runtime. async fn remove_job_dir(map: &IdMap, helper: &Path, job_dir: &Path) -> std::io::Result<()> { let (map, helper, job_dir) = (map.clone(), helper.to_owned(), job_dir.to_owned()); tokio::task::spawn_blocking(move || remove_tree(&map, &job_dir, &helper)) @@ -1051,7 +950,6 @@ mod tests { .expect("invocation"); assert!(inv.args.iter().all(|a| !a.contains(SECRET))); assert!(inv.args.iter().all(|a| !a.contains("visible"))); - // The values travel in the child env, by name. assert!( inv.env .contains(&("MY_TOKEN".to_owned(), SECRET.to_owned())) @@ -1108,7 +1006,6 @@ mod tests { job.memory_bytes = Some(4 << 30); let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); let joined = inv.args.join(" "); - // 4 GiB plus the 256 MiB slack, and no swap on top. let limit = (4u64 << 30) + (256 << 20); assert!( joined.contains(&format!("--memory {limit} --memory-swap {limit}")), @@ -1166,7 +1063,6 @@ mod tests { assert_eq!(podman.outcome, Outcome::Error); } - /// Needs rootless podman and network access to pull the image. #[tokio::test] #[ignore = "requires rootless podman and registry access"] async fn podman_runs_a_real_container() { diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 89788b3..d0727dc 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -1,27 +1,26 @@ //! The forge CI runner: claims jobs from a forge over HTTPS and runs them in a rootless sandbox //! (builtin) or rootless podman. //! -//! The binaries are thin wrappers over [`cli`] and these modules. They are public so that the -//! forge's end-to-end tests can drive a runner with `HostExecutor`. +//! The binaries are thin wrappers over [`cli`] and these modules. -pub mod artifacts; -pub mod cache; +pub(crate) mod artifacts; +pub(crate) mod cache; pub mod check; pub mod cli; pub mod client; pub mod config; -pub mod disk; +pub(crate) mod disk; pub mod executor; -pub mod limiter; +pub(crate) mod limiter; pub mod logs; -pub mod memory; -pub mod metrics; +pub(crate) mod memory; +pub(crate) mod metrics; pub mod oci; pub mod oom; -pub mod pressure; -pub mod restart; +pub(crate) mod pressure; +pub(crate) mod restart; pub mod runner; pub mod sandbox; -pub mod selflog; -pub mod update; -pub mod workspace; +pub(crate) mod selflog; +pub(crate) mod update; +pub(crate) mod workspace; diff --git a/crates/forge-runner/src/logs.rs b/crates/forge-runner/src/logs.rs index 64886a8..d1da37e 100644 --- a/crates/forge-runner/src/logs.rs +++ b/crates/forge-runner/src/logs.rs @@ -295,11 +295,13 @@ where Ok(b) if !b.is_empty() => b, _ => break, }; - let (take, done) = match available.iter().position(|&b| b == b'\n') { + let room = MAX_LINE - line.len(); + let window = &available[..available.len().min(room)]; + let (take, done) = match window.iter().position(|&b| b == b'\n') { Some(i) => (i + 1, true), - None => (available.len(), false), + None => (window.len(), false), }; - line.extend_from_slice(&available[..take]); + line.extend_from_slice(&window[..take]); (take, done) }; reader.consume(take); diff --git a/crates/forge-runner/src/memory.rs b/crates/forge-runner/src/memory.rs index ab89f29..6c401bd 100644 --- a/crates/forge-runner/src/memory.rs +++ b/crates/forge-runner/src/memory.rs @@ -17,12 +17,6 @@ const FALLBACK_RESERVE: u64 = 1 << 30; /// The smallest budget the runner will run with, so a typo cannot stop it from taking any job. const MIN_BUDGET: u64 = 256 << 20; -/// Pure admission rule: a job fits when the running jobs' reservations plus its own stay within -/// the budget. -pub fn fits(reserved: u64, request: u64, budget: u64) -> bool { - reserved.saturating_add(request) <= budget -} - /// What a job reserves: its declared memory or the default, never more than the budget. A job /// bigger than the whole budget therefore still runs, alone, instead of waiting forever. pub fn reservation(declared: Option, default_reserve: u64, budget: u64) -> u64 { @@ -39,37 +33,48 @@ pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: ram.saturating_add(swap).max(MIN_BUDGET) } -/// `(MemTotal, SwapTotal)` of a `/proc/meminfo` text, in bytes. -pub fn parse_meminfo(text: &str) -> (Option, Option) { +/// The fields of a `/proc/meminfo` text the runner reads, in bytes. A missing field is `None`. +#[derive(Default)] +pub struct Meminfo { + pub total: Option, + pub available: Option, + pub swap_total: Option, +} + +/// Parses a `/proc/meminfo` text. The file reports kibibytes. +pub fn meminfo(text: &str) -> Meminfo { let find = |key: &str| { let line = text.lines().find(|l| l.starts_with(key))?; let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; kib.checked_mul(1024) }; - (find("MemTotal:"), find("SwapTotal:")) + Meminfo { + total: find("MemTotal:"), + available: find("MemAvailable:"), + swap_total: find("SwapTotal:"), + } } -fn host_memory() -> (Option, Option) { +fn host_memory() -> Meminfo { std::fs::read_to_string("/proc/meminfo") - .map(|t| parse_meminfo(&t)) - .unwrap_or((None, None)) + .map(|t| meminfo(&t)) + .unwrap_or_default() +} + +/// A budget set in `runner.toml` or by the forge. `None` in `auto` mode. +fn fixed_budget(limits: &Limits) -> Option { + limits.memory_budget.as_deref().and_then(parse_size) } /// The budget `limits` asks for on a host with this much memory and swap. fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 { - match limits.memory_budget.as_deref() { - None | Some("auto") => { + fixed_budget(limits).map_or_else( + || { let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) - } - Some(text) => parse_size(text).map_or_else( - || { - let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); - auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) - }, - |n| n.max(MIN_BUDGET), - ), - } + }, + |n| n.max(MIN_BUDGET), + ) } struct State { @@ -82,11 +87,7 @@ struct State { /// The part of the budget that is swap: `swap_percent` of the swap in `auto` mode, none with a set /// budget. A lone job may use it as swap on top of the rest of the budget, which is RAM. fn swap_share(limits: &Limits, swap_total: u64) -> u64 { - let set = limits - .memory_budget - .as_deref() - .is_some_and(|text| text != "auto" && parse_size(text).is_some()); - if set { + if fixed_budget(limits).is_some() { return 0; } (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64 @@ -106,12 +107,6 @@ pub struct Reservation { gate: Arc, } -impl Reservation { - pub fn bytes(&self) -> u64 { - self.bytes - } -} - impl Drop for Reservation { fn drop(&mut self) { let mut state = self.gate.lock(); @@ -123,8 +118,12 @@ impl MemoryGate { /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have /// 8 GiB. pub fn for_host(limits: &Limits) -> Arc { - let (mem, swap) = host_memory(); - Self::new(limits, mem.unwrap_or(8 << 30), swap.unwrap_or(0)) + let host = host_memory(); + Self::new( + limits, + host.total.unwrap_or(8 << 30), + host.swap_total.unwrap_or(0), + ) } pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc { @@ -166,10 +165,6 @@ impl MemoryGate { self.lock().reserve } - pub fn reserved(&self) -> u64 { - self.lock().reserved - } - /// What a new claim may admit: the budget minus the running jobs' reservations. pub fn free(&self) -> u64 { let state = self.lock(); @@ -250,28 +245,11 @@ mod tests { assert_eq!(MemoryGate::new(&set, 8 * GIB, 8 * GIB).swap(), 0); } - #[test] - fn a_job_fits_when_the_sum_stays_within_the_budget() { - // 6.5 GiB budget, one 4 GiB job running. - let budget = 6 * GIB + GIB / 2; - assert!(fits(0, 4 * GIB, budget)); - assert!(fits(4 * GIB, 2 * GIB, budget)); - assert!( - fits(4 * GIB, 2 * GIB + GIB / 2, budget), - "exactly the budget" - ); - assert!(!fits(4 * GIB, 4 * GIB, budget), "second heavy job waits"); - assert!(!fits(budget, 1, budget)); - assert!(!fits(u64::MAX, 1, budget), "no overflow"); - } - #[test] fn a_job_without_memory_reserves_the_default() { assert_eq!(reservation(None, GIB, 6 * GIB), GIB); assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB); - // Bigger than the whole budget: capped, so it still runs when the runner is idle. assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB); - assert!(fits(0, reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB)); } #[test] @@ -291,12 +269,12 @@ mod tests { #[test] fn meminfo_is_parsed() { - let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nSwapTotal: 8388604 kB\n"; - assert_eq!( - parse_meminfo(text), - (Some(7_971_680 * 1024), Some(8_388_604 * 1024)) - ); - assert_eq!(parse_meminfo(""), (None, None)); + let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\nSwapTotal: 8388604 kB\n"; + let m = meminfo(text); + assert_eq!(m.total, Some(7_971_680 * 1024)); + assert_eq!(m.available, Some(4_000_000 * 1024)); + assert_eq!(m.swap_total, Some(8_388_604 * 1024)); + assert_eq!(meminfo("").total, None); } #[test] @@ -311,7 +289,6 @@ mod tests { let heavy = gate.reserve(Some(4 * GIB)); assert_eq!(gate.free(), 2 * GIB); let light = gate.reserve(None); - assert_eq!(gate.reserved(), 5 * GIB); assert_eq!(gate.free(), GIB); drop(heavy); assert_eq!(gate.free(), 5 * GIB); diff --git a/crates/forge-runner/src/metrics.rs b/crates/forge-runner/src/metrics.rs index fec64d8..ae68d99 100644 --- a/crates/forge-runner/src/metrics.rs +++ b/crates/forge-runner/src/metrics.rs @@ -55,16 +55,6 @@ pub fn parse_cpu(text: &str) -> Option<(u64, u64)> { Some((total.saturating_sub(idle), total)) } -/// `(MemTotal, MemAvailable)` of `/proc/meminfo`, in bytes. The file reports kibibytes. -pub fn parse_mem(text: &str) -> Option<(u64, u64)> { - let find = |key: &str| { - let line = text.lines().find(|l| l.starts_with(key))?; - let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; - kib.checked_mul(1024) - }; - Some((find("MemTotal:")?, find("MemAvailable:")?)) -} - /// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header /// lines have no colon and are skipped. pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> { @@ -99,7 +89,8 @@ pub fn read_snapshot(work_dir: &Path) -> Option { let mem = std::fs::read_to_string("/proc/meminfo").ok()?; let net = std::fs::read_to_string("/proc/net/dev").ok()?; let (busy, total) = parse_cpu(&stat)?; - let (mem_total, mem_available) = parse_mem(&mem)?; + let info = crate::memory::meminfo(&mem); + let (mem_total, mem_available) = (info.total?, info.available?); let (rx, tx) = parse_net_dev(&net)?; let (disk_used, disk_total) = disk_usage(work_dir).unwrap_or((0, 0)); Some(Snapshot { @@ -230,12 +221,6 @@ mod tests { assert_eq!(parse_cpu(text), Some((170, 1010))); } - #[test] - fn mem_reads_total_and_available_in_bytes() { - let text = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\n"; - assert_eq!(parse_mem(text), Some((16_000_000 * 1024, 4_000_000 * 1024))); - } - #[test] fn net_sums_every_interface_but_loopback() { let text = "Inter-| Receive | Transmit\n \ diff --git a/crates/forge-runner/src/oci/pull.rs b/crates/forge-runner/src/oci/pull.rs index 6c05b4b..5080bf9 100644 --- a/crates/forge-runner/src/oci/pull.rs +++ b/crates/forge-runner/src/oci/pull.rs @@ -1,7 +1,6 @@ //! Resolving an image reference, pulling its manifest and layers, and unpacking them. use std::fs::{self, Permissions}; -use std::io::{self, Read}; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; @@ -148,7 +147,10 @@ impl ImageStore { fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?; let unpacked = staging.keep(); let final_dir = self.rootfs_path(&hex); - if let Err(err) = fs::rename(&unpacked, &final_dir) { + if let Err(err) = self + .remove_entry(&final_dir) + .and_then(|()| fs::rename(&unpacked, &final_dir)) + { let _ = self.remove_entry(&unpacked); return Err(err.into()); } @@ -285,23 +287,8 @@ fn verify_bytes(bytes: &[u8], digest: &str) -> Result<(), ImageError> { } } -/// Hashes a file on a blocking thread and returns the hex digest. async fn sha256_file(path: PathBuf) -> Result { - let hash = tokio::task::spawn_blocking(move || -> io::Result { - let mut file = fs::File::open(&path)?; - let mut hasher = Sha256::new(); - let mut buf = vec![0u8; 64 * 1024]; - loop { - let n = file.read(&mut buf)?; - if n == 0 { - break; - } - hasher.update(&buf[..n]); - } - Ok(hex::encode(hasher.finalize())) - }) - .await??; - Ok(hash) + Ok(tokio::task::spawn_blocking(move || crate::update::file_sha256(&path)).await??) } /// Sends one line to the job log. A closed log channel is not an error for the pull. diff --git a/crates/forge-runner/src/oci/store.rs b/crates/forge-runner/src/oci/store.rs index f4c040d..3577e56 100644 --- a/crates/forge-runner/src/oci/store.rs +++ b/crates/forge-runner/src/oci/store.rs @@ -302,9 +302,9 @@ fn older_than(time: SystemTime, now: SystemTime, max_age: Duration) -> bool { /// The rootfs dir name for `hex`: `` in single mode, and `-s-` for a subuid /// range, so each range has its own unpacked tree. fn rootfs_dir_name(map: &IdMap, hex: &str) -> String { - match map.sub_uid { - Some((start, n)) if map.is_subuid() => format!("{hex}-s{start}-{n}"), - _ => hex.to_owned(), + match map.sub { + Some(s) => format!("{hex}-s{}-{}", s.uid_start, s.count), + None => hex.to_owned(), } } @@ -318,6 +318,7 @@ fn remove_file_if_exists(path: &Path) -> io::Result<()> { #[cfg(test)] mod tests { use super::*; + use crate::sandbox::idmap::SubRange; #[test] fn rootfs_dir_names_follow_the_mode() { @@ -326,15 +327,22 @@ mod tests { let subuid = IdMap { uid: 1000, gid: 1000, - sub_uid: Some((524_288, 65_536)), - sub_gid: Some((524_288, 65_536)), + sub: Some(SubRange { + uid_start: 524_288, + gid_start: 524_288, + count: 65_536, + }), }; assert_eq!( rootfs_dir_name(&subuid, &hex), format!("{hex}-s524288-65536") ); let other_range = IdMap { - sub_uid: Some((600_000, 65_536)), + sub: Some(SubRange { + uid_start: 600_000, + gid_start: 524_288, + count: 65_536, + }), ..subuid }; assert_ne!( diff --git a/crates/forge-runner/src/pressure.rs b/crates/forge-runner/src/pressure.rs index bcea73b..3a595a8 100644 --- a/crates/forge-runner/src/pressure.rs +++ b/crates/forge-runner/src/pressure.rs @@ -65,14 +65,16 @@ pub enum Cause { // ----- pure rules ----- +fn field_u64(text: &str, key: &str) -> Option { + text.lines().find_map(|line| { + let (k, v) = line.split_once(' ')?; + (k == key).then(|| v.trim().parse().ok())? + }) +} + /// The `high` counter of a `memory.events` text. Missing means 0. pub fn parse_high(text: &str) -> u64 { - text.lines() - .find_map(|line| { - let (key, value) = line.split_once(' ')?; - (key == "high").then(|| value.trim().parse().ok())? - }) - .unwrap_or(0) + field_u64(text, "high").unwrap_or(0) } /// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen: @@ -82,24 +84,18 @@ pub fn high_value(unfrozen: usize, budget: u64) -> Option { return None; } let margin = HIGH_MARGIN_MIN.max(budget / 20); - Some(budget.saturating_sub(margin)) -} - -/// A running job, as far as victim choice cares. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Running { - /// Start order: higher is younger. - pub seq: u64, - pub frozen: bool, + Some(budget.saturating_sub(margin).max(budget / 2)) } -/// The job to park: the youngest unfrozen one, and only while at least two are unfrozen. -pub fn pick_victim(jobs: &[Running]) -> Option { - let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen); - if unfrozen().count() < 2 { +/// The job to park: the youngest, and only while at least two run. +pub fn pick_victim(seqs: &[u64]) -> Option { + if seqs.len() < 2 { return None; } - unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i) + seqs.iter() + .enumerate() + .max_by_key(|(_, seq)| **seq) + .map(|(i, _)| i) } /// A parked job, as far as thaw choice cares. @@ -197,12 +193,7 @@ impl Registration { self.handle.requeued.load(Ordering::SeqCst) } - /// How long the job has spent frozen so far. Its timeout does not count that time. - pub fn paused(&self) -> Duration { - self.handle.paused() - } - - /// A handle for reading [`Registration::paused`] from another task. + /// A handle for reading [`JobHandle::paused`] from another task. pub fn pause_clock(&self) -> Arc { self.handle.clone() } @@ -263,12 +254,8 @@ impl Pressure { create_box(&parent, budget) }) .await; - let dir = match setup { - Ok(Ok(dir)) => dir, - Ok(Err(e)) => { - tracing::warn!("memory control is off: {e}"); - return None; - } + let dir = match setup.map_err(|e| e.to_string()).and_then(|r| r) { + Ok(dir) => dir, Err(e) => { tracing::warn!("memory control is off: {e}"); return None; @@ -446,14 +433,8 @@ impl Pressure { let live: Vec = (0..state.entries.len()) .filter(|&i| is_live(&state.entries[i])) .collect(); - let running: Vec = live - .iter() - .map(|&i| Running { - seq: state.entries[i].seq, - frozen: false, - }) - .collect(); - if let Some(pick) = pick_victim(&running) { + let seqs: Vec = live.iter().map(|&i| state.entries[i].seq).collect(); + if let Some(pick) = pick_victim(&seqs) { let victim = live[pick]; let waiting_for = live .iter() @@ -626,10 +607,7 @@ fn read_u64(dir: &Path, file: &str) -> Option { fn stat_field(dir: &Path, key: &str) -> Option { let text = fs::read_to_string(dir.join("memory.stat")).ok()?; - text.lines().find_map(|line| { - let (k, v) = line.split_once(' ')?; - (k == key).then(|| v.trim().parse().ok())? - }) + field_u64(&text, key) } fn job_swap(dir: &Path) -> Option { @@ -897,20 +875,15 @@ mod tests { assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); // 5% of 20 GiB is 1 GiB. assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); + assert_eq!(high_value(2, 256 << 20), Some(128 << 20)); } #[test] - fn victim_is_the_youngest_unfrozen_with_a_partner() { - let job = |seq, frozen| Running { seq, frozen }; + fn victim_is_the_youngest_with_a_partner() { assert_eq!(pick_victim(&[]), None); - assert_eq!(pick_victim(&[job(1, false)]), None); - assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1)); - assert_eq!( - pick_victim(&[job(5, false), job(2, false), job(9, true)]), - Some(0) - ); - // One unfrozen job left: nothing to pause. - assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None); + assert_eq!(pick_victim(&[1]), None); + assert_eq!(pick_victim(&[1, 2]), Some(1)); + assert_eq!(pick_victim(&[5, 2, 9]), Some(2)); } #[test] @@ -1045,13 +1018,13 @@ mod tests { let (_tmp, pressure) = fake_box(GIB); let (tx, mut rx) = mpsc::channel(8); let reg = pressure.register("a", "build", tx); - assert_eq!(reg.paused(), Duration::ZERO); + assert_eq!(reg.handle.paused(), Duration::ZERO); reg.handle.pause(); std::thread::sleep(Duration::from_millis(5)); - assert!(reg.paused() > Duration::ZERO); + assert!(reg.handle.paused() > Duration::ZERO); let lasted = reg.handle.resume(); assert!(lasted > Duration::ZERO); - assert!(reg.paused() >= lasted); + assert!(reg.handle.paused() >= lasted); drop(reg); // The sender is gone with the registration, so the log shipper can finish. assert!(matches!( diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 64191b7..e5897a6 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -1,5 +1,3 @@ -//! The runner loop: claim a job, run it, ship its logs and artifacts, and report the result. - use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; @@ -28,23 +26,16 @@ use crate::selflog; use crate::update::{self, Installed, UpdateState}; use crate::workspace; -/// Log lines queued between the executor and the log shipper. const LOG_CHANNEL: usize = 64; -/// How many times the runner tries to report a finished job. -/// How long a result is retried while the forge cannot be reached (a restart or a self-update). const FINISH_PATIENCE: Duration = Duration::from_secs(10 * 60); -/// Largest single artifact the runner will upload. The forge enforces its own total cap. const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; -/// How long a stopping runner waits for its last log lines to reach the forge. const LOG_FLUSH: Duration = Duration::from_secs(5); -/// Timing knobs. Production uses the defaults. Tests shorten them. #[derive(Clone, Copy, Debug)] pub struct RunOptions { pub heartbeat_every: Duration, pub claim_backoff: Duration, pub pump: PumpConfig, - /// When set, replaces `timeout_minutes` from the job. pub timeout_override: Option, } @@ -59,34 +50,23 @@ impl Default for RunOptions { } } -/// How [`Runner::run`] ended. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RunEnd { - /// Shutdown was requested. Stopped, - /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. Updated, - /// An admin asked for a restart and the jobs are done. The caller exits with - /// [`update::RESTART_EXIT_CODE`], like for an update. Restart, } -/// A runner bound to one forge and one executor. #[derive(Clone)] pub struct Runner { client: ForgeClient, config: Arc, executor: Arc, options: RunOptions, - /// The build cache, when it is on. See [`CacheStore`]. cache: Option>, - /// The live job limit. Starts at `runner.toml` and follows the forge's override. limiter: Arc, - /// The memory budget and the running jobs' reservations, see [`crate::memory`]. memory: Arc, - /// A restart an admin asked for, see [`restart`]. restart: Arc, - /// The memory box and its controller, when the host allows it, see [`crate::pressure`]. pressure: Option>, } @@ -112,14 +92,11 @@ impl Runner { }) } - /// Turns on reactive memory control: jobs are paused under pressure, and no job is claimed - /// while one is parked. pub fn with_pressure(mut self, pressure: Option>) -> Self { self.pressure = pressure; self } - /// Turns on the build cache for every job this runner runs. pub fn with_cache(mut self, cache: CacheStore) -> Self { self.cache = Some(Arc::new(cache)); self @@ -129,15 +106,8 @@ impl Runner { &self.client } - /// Claims and runs jobs, up to `concurrency` at a time, until `shutdown` is cancelled. Jobs - /// still running at shutdown are cancelled and reported as cancelled. - /// - /// When the forge advertises a different binary and `auto_update` is on, no new jobs are - /// claimed. Once the running jobs finish, the binary is replaced and the loop returns - /// [`RunEnd::Updated`]. pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { let mut jobs: JoinSet<()> = JoinSet::new(); - // Hashed once at startup. Without it, or with auto_update off, updates stay disabled. let exe = if self.config.auto_update { match update::locate_self() { Ok(found) => Some(found), @@ -161,16 +131,13 @@ impl Runner { auto_update = updates.enabled(), "runner started" ); - // Parent of every job's token, so a `now` restart can cancel them all at once. let jobs_cancel = shutdown.child_token(); - // Ships the runner's own log to the forge until the loop has ended. See `selflog`. let ship_stop = CancellationToken::new(); let shipper = tokio::spawn(selflog::ship( self.client.clone(), self.config.runner_secret.clone(), ship_stop.clone(), )); - // Host samples for the graphs, stopped with the same token. Jobs in use = slots taken. let limiter = self.limiter.clone(); let metrics_shipper = tokio::spawn(metrics::ship( self.client.clone(), @@ -182,7 +149,6 @@ impl Runner { }, ship_stop.clone(), )); - // The reason the claim loop last logged for not claiming, see `not_claiming`. let mut blocked: Option = None; let end = loop { match restart::decide( @@ -208,11 +174,7 @@ impl Runner { ); tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, - Some(joined) = jobs.join_next() => { - if let Err(e) = joined { - tracing::error!(error = %e, "job task panicked"); - } - } + Some(joined) = jobs.join_next() => log_joined(joined), () = self.restart.changed() => {} } continue; @@ -222,18 +184,13 @@ impl Runner { && let Some(sha) = updates.pending().map(str::to_owned) { if !jobs.is_empty() { - // Claiming is paused until the running jobs finish. not_claiming( &mut blocked, "a new binary is pending, waiting for the running jobs".to_owned(), ); tokio::select! { _ = shutdown.cancelled() => break RunEnd::Stopped, - Some(joined) = jobs.join_next() => { - if let Err(e) = joined { - tracing::error!(error = %e, "job task panicked"); - } - } + Some(joined) = jobs.join_next() => log_joined(joined), } continue; } @@ -257,8 +214,6 @@ impl Runner { } if let Some(pressure) = &self.pressure { - // A parked job or a box under pressure means no new job. The controller wakes - // this when that changes. let gate = pressure.gate(); if !gate.open() { let hot = if gate.hot { ", box under pressure" } else { "" }; @@ -273,7 +228,6 @@ impl Runner { () = pressure.wait_open() => {} } } - // Every slot taken: the loop waits below for a job to finish. A free slot ends the block. if self.limiter.free_slots() == 0 { let limit = self.limiter.current(); not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); @@ -298,7 +252,6 @@ impl Runner { &self.config.labels, Some(self.limiter.current()), Some(MemoryClaim { - // Real room in the box when memory control is on, else what is promised. free: self .pressure .as_ref() @@ -311,7 +264,6 @@ impl Runner { }; match claimed { Ok(reply) => { - // No header means no override: back to the runner.toml value. self.limiter.apply_logged(reply.concurrency); self.memory.apply_logged( reply.memory_budget.as_deref(), @@ -340,7 +292,6 @@ impl Runner { ); let runner = self.clone(); let cancel = jobs_cancel.child_token(); - // Reserved before the next claim, so that claim sees less free memory. let reservation = self.memory.reserve(job.memory_bytes); jobs.spawn(async move { let _permit = permit; @@ -361,27 +312,20 @@ impl Runner { } } while let Some(joined) = jobs.try_join_next() { - if let Err(e) = joined { - tracing::error!(error = %e, "job task panicked"); - } + log_joined(joined); } }; while let Some(joined) = jobs.join_next().await { - if let Err(e) = joined { - tracing::error!(error = %e, "job task panicked"); - } + log_joined(joined); } tracing::info!("runner stopped"); - // The last lines go out too, but a dead forge must not hold up the exit. ship_stop.cancel(); let _ = tokio::time::timeout(LOG_FLUSH, shipper).await; let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await; end } - /// Runs one claimed job end to end and reports its result. Returns the final outcome. pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome { - // Mask the job's secret values and its own token, both raw and base64 (done by Masker). let mut secret_values: Vec = job.secrets.values().cloned().collect(); secret_values.push(job.job_token.clone()); let masker = Masker::new(secret_values); @@ -426,7 +370,6 @@ impl Runner { let flag = timed_out.clone(); let pause = registration.as_ref().map(|r| r.pause_clock()); tokio::spawn(async move { - // Time spent frozen does not count, so the deadline moves out by the pauses. let started = Instant::now(); loop { let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); @@ -474,16 +417,12 @@ impl Runner { }, }; - // The memory controller killed this job to run it again later: give it back to the queue - // without a result. if registration.as_ref().is_some_and(|r| r.requeued()) { heartbeat.abort(); timer.abort(); drop(registration); drop(tx); let _ = pump.await; - // The workspace is named after the job, so it goes before the job is handed back: a - // free slot here may claim it again at once and build in the same folder. if let Some(dir) = workspace_dir.take() && let Err(e) = workspace::cleanup(&dir).await { @@ -509,7 +448,6 @@ impl Runner { return Outcome::Cancelled; } - // Artifacts only come from a successful run. let upload_error = match workspace_dir.as_deref() { Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { self.upload_artifacts(&job, dir).await.err() @@ -526,7 +464,6 @@ impl Runner { heartbeat.abort(); timer.abort(); - // The log sender it holds must go before the log shipper can finish. drop(registration); if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { result = ExecResult { @@ -540,7 +477,6 @@ impl Runner { result.message = Some("cancelled because an admin restarted the runner".to_owned()); } - // The save decides on the final outcome. It also clears the job's scratch dirs. if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { for line in cache.save(&job, result.outcome, dir).await { send_line(&tx, line).await; @@ -600,7 +536,6 @@ impl Runner { cancel.cancel(); return; } - // A runner at its limit does not claim, so the heartbeat carries changes too. Ok(beat) => { limiter.apply_logged(beat.concurrency); restart.observe(beat.restart); @@ -611,7 +546,6 @@ impl Runner { }) } - /// Collects the job's artifacts and uploads them. The error is a message for the job record. async fn upload_artifacts( &self, job: &JobAssignment, @@ -637,8 +571,6 @@ impl Runner { oom_killed: oom_kills.map(|_| true), oom_kills, }; - // A forge that is down or restarting is waited for; a forge that refuses the result - // (the job was reaped, cancelled or its token ended) is not asked again. let started = Instant::now(); let mut attempt = 0u32; loop { @@ -652,7 +584,7 @@ impl Runner { ClientError::Status { status, .. } => status.is_server_error(), _ => false, }; - if (!away && attempt >= 3) || started.elapsed() >= FINISH_PATIENCE { + if !away || started.elapsed() >= FINISH_PATIENCE { break; } let wait = Duration::from_secs((2 * u64::from(attempt)).min(15)); @@ -667,8 +599,6 @@ impl Runner { } } -/// Logs why the claim loop is not claiming, at info level, but only when the reason differs from -/// the one logged last. `last` is cleared once the loop passes the checks and has a free slot. fn not_claiming(last: &mut Option, reason: String) { if last.as_deref() != Some(reason.as_str()) { tracing::info!("not claiming: {reason}"); @@ -676,6 +606,12 @@ fn not_claiming(last: &mut Option, reason: String) { } } +fn log_joined(joined: Result<(), tokio::task::JoinError>) { + if let Err(e) = joined { + tracing::error!(error = %e, "job task panicked"); + } +} + async fn send_line(tx: &mpsc::Sender>, line: String) { let mut bytes = line.into_bytes(); bytes.push(b'\n'); diff --git a/crates/forge-runner/src/sandbox/exec.rs b/crates/forge-runner/src/sandbox/exec.rs index 85ca63c..65b63f8 100644 --- a/crates/forge-runner/src/sandbox/exec.rs +++ b/crates/forge-runner/src/sandbox/exec.rs @@ -53,11 +53,9 @@ fn exec_process(spec: &Spec) -> Result<(), ExecutorError> { .iter() .map(|s| CString::new(s.as_bytes()).map_err(|_| ExecutorError::InvalidArg)) .collect::, ExecutorError>>()?; - match unistd::execvp(&path, &argv) { - Ok(never) => match never {}, - Err(err) => Err(ExecutorError::Other(format!( - "cannot exec {}: {err}", - path.to_string_lossy() - ))), - } + let err = unistd::execvp(&path, &argv).unwrap_err(); + Err(ExecutorError::Other(format!( + "cannot exec {}: {err}", + path.to_string_lossy() + ))) } diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index 2547841..f1b714d 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -58,7 +58,6 @@ const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopba /// Entry point for `forge-runner __sandbox`. Returns the process exit code. pub fn helper_main() -> i32 { - // libcontainer logs through tracing. Its logs appear only when the operator sets RUST_LOG. if std::env::var_os("RUST_LOG").is_some() { let _ = tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) @@ -113,7 +112,6 @@ fn run() -> Result { prepare_dirs(&layout)?; write_etc_files(&layout)?; - // The job's own network, when it asked for one and pasta is installed. See `net`. let pasta_pid = net::pid_file(&layout.job_dir); let pending_net = match (&req.pasta, req.network) { (Some(pasta), true) => Some(net::prepare(pasta, &pasta_pid)?), @@ -125,12 +123,8 @@ fn run() -> Result { None => Ok(()), } .and_then(|()| mount_rootfs(&req, &layout)) - // Clean up on failure too: the state dir holds the job env. .and_then(|rootfs| run_job(&req, &layout, &rootfs, &signals)); net::stop_pasta(&pasta_pid); - // The container is gone, so nothing writes to the workspace now. In subuid mode the job may - // have left files owned by subordinate ids, which the runner can't remove, so they go back - // to the runner. if req.idmap.is_subuid() { reown_workspace(&req.workspace); } @@ -212,7 +206,6 @@ fn install_signal_handlers() -> Result { let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}")); let (wake, write_end) = UnixStream::pair().map_err(SandboxError::io("cannot create the signal pipe"))?; - // Both ends are non-blocking. A signal handler must never block on a full pipe. wake.set_nonblocking(true) .map_err(SandboxError::io("cannot configure the signal pipe"))?; write_end @@ -261,7 +254,6 @@ fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> { let hostname = layout.etc.join("hostname"); fs::write(&hostname, format!("{HOSTNAME}\n")) .map_err(SandboxError::io("cannot write hostname"))?; - // Only bind mounted when the job has its own network (see `spec`). let resolv = layout.etc.join("resolv.conf"); fs::write(&resolv, format!("nameserver {}\n", net::DNS_ADDR)) .map_err(SandboxError::io("cannot write resolv.conf"))?; @@ -288,8 +280,6 @@ fn mount_rootfs(req: &SandboxRequest, layout: &Layout) -> Result Result<(), SandboxError> { - // Overlay options are comma separated, and the colon separates lower dirs, so paths - // containing either can't be expressed. for p in [lower, &layout.upper, &layout.work] { let s = p.to_string_lossy(); if s.contains(',') || s.contains(':') { @@ -377,13 +367,11 @@ fn run_job( /// `/sys/fs/cgroup` joined with it. pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result { let base = job_cgroup_base()?; - // With the runner's box in place (see `crate::pressure`), jobs live inside it. let base = if box_ready(&base) { base.join(BOX_NAME) } else { base }; - // The helper's pid keeps the name unique even if two helpers share a job id. Ok(base.join(format!("forge-job-{job_id}-{helper_pid}"))) } @@ -445,8 +433,6 @@ fn launch_and_wait( spec: &Spec, signals: &Signals, ) -> Result { - // Start each attempt with an empty state dir, so a failed attempt leaves no state behind. - // The dir may not exist yet on the first attempt, so a failure here is not an error. let _ = fs::remove_dir_all(&layout.state); fs::create_dir_all(&layout.state).map_err(SandboxError::io("cannot create state dir"))?; fs::set_permissions(&layout.state, fs::Permissions::from_mode(0o700)) @@ -454,8 +440,6 @@ fn launch_and_wait( write_bundle(layout, spec)?; let built = build_container(layout, id); - // libcontainer has read the bundle config during build, and the env it holds is now in - // state. Delete the bundle copy now. let _ = fs::remove_file(layout.bundle.join("config.json")); let mut container = match built { Ok(c) => c, @@ -508,7 +492,6 @@ fn build_container(layout: &Layout, id: &str) -> Result { let devnull = fs::File::open("/dev/null").map_err(io_err)?; let stdout = io::stdout().as_fd().try_clone_to_owned().map_err(io_err)?; let stderr = io::stderr().as_fd().try_clone_to_owned().map_err(io_err)?; - // The seccomp BPF is compiled here, before libcontainer forks. The executor only installs it. let filter = build_filter().map_err(|e| e.to_string())?; let builder = ContainerBuilder::new(id.to_owned(), SyscallType::default()) .validate_id() @@ -531,7 +514,6 @@ fn start_container(container: &mut Container) -> Result { container .start() .map_err(|e| SandboxError::Setup(format!("container: cannot start: {e}")))?; - // libcontainer has its own nix, so its Pid is a different type. The raw value is the same. container .pid() .map(|pid| Pid::from_raw(pid.as_raw())) @@ -566,8 +548,6 @@ fn wait_for_init( } match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { Ok(WaitStatus::StillAlive) => { - // A signal that arrived since the checks above has already written to the pipe, - // so this returns at once and nothing is missed. if let Err(e) = wait_for_signal(&signals.wake) { let _ = kill_container(container); delete_container(container); @@ -601,7 +581,6 @@ fn wait_for_init( fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)]; match poll(&mut fds, PollTimeout::NONE) { - // EINTR means a handler ran, and it wrote to the pipe. The drain below picks that up. Ok(_) | Err(Errno::EINTR) => {} Err(e) => return Err(e), } @@ -611,7 +590,6 @@ fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { Ok(0) => return Ok(()), Ok(_) => {} Err(e) if e.kind() == io::ErrorKind::Interrupted => {} - // WouldBlock means the pipe is empty. Any other read error can't be acted on either. Err(_) => return Ok(()), } } diff --git a/crates/forge-runner/src/sandbox/idmap.rs b/crates/forge-runner/src/sandbox/idmap.rs index 5b1d6f5..cc48bd6 100644 --- a/crates/forge-runner/src/sandbox/idmap.rs +++ b/crates/forge-runner/src/sandbox/idmap.rs @@ -47,16 +47,19 @@ pub enum UsernsMode { Subuid, } +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct SubRange { + pub uid_start: u32, + pub gid_start: u32, + pub count: u32, +} + /// The id mapping a sandbox uses. The helper receives it as JSON. -/// -/// `sub_uid` and `sub_gid` are `(start, count)` ranges on the host. Both are set in subuid mode. -/// Both must have the same count, so container ids `1..=count` are valid for uids and gids. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct IdMap { pub uid: u32, pub gid: u32, - pub sub_uid: Option<(u32, u32)>, - pub sub_gid: Option<(u32, u32)>, + pub sub: Option, } /// Errors from resolving or entering an id mapping. @@ -79,8 +82,7 @@ impl IdMap { Self { uid: getuid().as_raw(), gid: getgid().as_raw(), - sub_uid: None, - sub_gid: None, + sub: None, } } @@ -98,22 +100,19 @@ impl IdMap { /// Whether the map has subordinate ranges. pub fn is_subuid(&self) -> bool { - self.sub_uid.is_some() && self.sub_gid.is_some() + self.sub.is_some() } /// How many container ids are mapped, including container 0. `1 + n` in subuid mode. pub fn size(&self) -> u32 { - match (self.sub_uid, self.sub_gid) { - (Some((_, n_uid)), Some((_, n_gid))) => 1 + n_uid.min(n_gid), - _ => 1, - } + self.sub.map_or(1, |s| 1 + s.count) } /// A short description for logs, for example `subuid 524288+65536`. pub fn describe(&self) -> String { - match (self.sub_uid, self.sub_gid) { - (Some((start, count)), Some(_)) => format!("subuid {start}+{count}"), - _ => format!("single uid {}", self.uid), + match self.sub { + Some(s) => format!("subuid {}+{}", s.uid_start, s.count), + None => format!("single uid {}", self.uid), } } } @@ -209,8 +208,11 @@ fn subuid_map() -> Result { Ok(IdMap { uid, gid, - sub_uid: Some((uid_start, count)), - sub_gid: Some((gid_start, count)), + sub: Some(SubRange { + uid_start, + gid_start, + count, + }), }) } @@ -235,12 +237,9 @@ fn find_tool(name: &str) -> Option { /// Must be called from a single-threaded process, because the unshare needs one. The caller is /// the sandbox helper, which has no other threads. pub fn enter_mapped_userns(map: &IdMap) -> Result<(), IdMapError> { - match (map.sub_uid, map.sub_gid) { - (Some((uid_start, count_uid)), Some((gid_start, count_gid))) => { - let count = count_uid.min(count_gid).min(MAX_SUBID_COUNT); - enter_subuid(map, uid_start, gid_start, count)?; - } - _ => enter_single(map)?, + match map.sub { + Some(s) => enter_subuid(map, s.uid_start, s.gid_start, s.count)?, + None => enter_single(map)?, } mount( None::<&str>, @@ -614,8 +613,7 @@ mod tests { let single = IdMap { uid: 1000, gid: 1000, - sub_uid: None, - sub_gid: None, + sub: None, }; assert!(!single.is_subuid()); assert_eq!(single.size(), 1); @@ -624,18 +622,15 @@ mod tests { let sub = IdMap { uid: 1000, gid: 1000, - sub_uid: Some((524288, 65536)), - sub_gid: Some((524288, 65536)), + sub: Some(SubRange { + uid_start: 524288, + gid_start: 524288, + count: 65536, + }), }; assert!(sub.is_subuid()); assert_eq!(sub.size(), 65537); assert_eq!(sub.describe(), "subuid 524288+65536"); - - let uneven = IdMap { - sub_gid: Some((600000, 10)), - ..sub - }; - assert_eq!(uneven.size(), 11); } fn os(args: &[&str]) -> Vec { diff --git a/crates/forge-runner/src/sandbox/spec.rs b/crates/forge-runner/src/sandbox/spec.rs index f1f4adb..355ceee 100644 --- a/crates/forge-runner/src/sandbox/spec.rs +++ b/crates/forge-runner/src/sandbox/spec.rs @@ -69,6 +69,11 @@ pub fn build_spec(req: &SandboxRequest, rootfs_mount: &Path) -> Result = if req.idmap.is_subuid() { + SUBUID_CAPABILITIES.into_iter().collect() + } else { + HashSet::new() + }; let process = ProcessBuilder::default() .terminal(false) .user( @@ -81,7 +86,7 @@ pub fn build_spec(req: &SandboxRequest, rootfs_mount: &Path) -> Result Result, SandboxError> { fn check_nul(entry: &str) -> Result<(), SandboxError> { if entry.contains('\0') { - // The name is safe to show, the value is not. let name = entry.split('=').next().unwrap_or_default(); return Err(SandboxError::Invalid(format!("env {name} contains NUL"))); } @@ -164,38 +168,19 @@ const SUBUID_CAPABILITIES: [Capability; 13] = [ Capability::Mknod, ]; -/// The job's capability sets. Single mode has none. Subuid mode has [`SUBUID_CAPABILITIES`] in -/// the bounding, effective and permitted sets. Inheritable and ambient stay empty, so an exec -/// doesn't gain more. -fn job_capabilities( - req: &SandboxRequest, +fn capabilities( + active: HashSet, ) -> Result { - if !req.idmap.is_subuid() { - return no_capabilities(); - } - let set: HashSet = SUBUID_CAPABILITIES.into_iter().collect(); LinuxCapabilitiesBuilder::default() - .bounding(set.clone()) - .effective(set.clone()) - .permitted(set) + .bounding(active.clone()) + .effective(active.clone()) + .permitted(active) .inheritable(HashSet::new()) .ambient(HashSet::new()) .build() .map_err(spec_err) } -fn no_capabilities() -> Result { - let empty: HashSet = HashSet::new(); - LinuxCapabilitiesBuilder::default() - .bounding(empty.clone()) - .effective(empty.clone()) - .inheritable(empty.clone()) - .permitted(empty.clone()) - .ambient(empty) - .build() - .map_err(spec_err) -} - fn rlimit( typ: PosixRlimitType, value: u64, @@ -209,10 +194,6 @@ fn rlimit( } fn build_linux(req: &SandboxRequest) -> Result { - // In subuid mode the job runs in the helper's own user namespace, which already maps the - // runner's uid and the subordinate range. libcontainer writes only one id range for a new - // user namespace, and the kernel refuses a multi-id root map written from the parent. So the - // job can't get its own namespace with the full range, and it uses the helper's. let subuid = req.idmap.is_subuid(); let mut namespaces = Vec::new(); if !subuid { @@ -230,25 +211,10 @@ fn build_linux(req: &SandboxRequest) -> Result Result Result { + LinuxIdMappingBuilder::default() + .container_id(0u32) + .host_id(0u32) + .size(1u32) + .build() + .map_err(spec_err) +} + fn ns(typ: LinuxNamespaceType) -> Result { LinuxNamespaceBuilder::default() .typ(typ) @@ -282,8 +257,6 @@ fn build_resources(limits: &Limits) -> Result Result { .trim() .parse() .map_err(|_| SandboxError::Invalid(format!("bad cpus limit {text:?}")))?; - if !value.is_finite() || value <= 0.0 { + if !value.is_finite() || value < 0.01 { return Err(SandboxError::Invalid(format!("bad cpus limit {text:?}"))); } Ok(value) @@ -369,31 +342,18 @@ fn build_mounts(req: &SandboxRequest) -> Result, SandboxError> { mounts.push(mount(&host, "bind", &host, &["bind", "nosuid", "noexec"])?); } if req.network { - // A sysfs mount needs a network namespace owned by the user namespace, and the shared - // host one is not. A read-only recursive bind of the host's /sys is the fallback. mounts.push(mount( "/sys", "bind", "/sys", &["rbind", "nosuid", "noexec", "nodev", "ro"], )?); - // An isolated network asks pasta's DNS forwarder; the host's resolver may be on its - // loopback, which the job cannot reach. - if req.pasta.is_some() { - mounts.push(mount_path( - "/etc/resolv.conf", - "bind", - &req.job_dir.join("etc/resolv.conf"), - &["bind", "ro"], - )?); + let resolv = if req.pasta.is_some() { + req.job_dir.join("etc/resolv.conf") } else { - mounts.push(mount( - "/etc/resolv.conf", - "bind", - "/etc/resolv.conf", - &["bind", "ro"], - )?); - } + PathBuf::from("/etc/resolv.conf") + }; + mounts.push(mount("/etc/resolv.conf", "bind", resolv, &["bind", "ro"])?); } else { mounts.push(mount( "/sys", @@ -402,27 +362,25 @@ fn build_mounts(req: &SandboxRequest) -> Result, SandboxError> { &["nosuid", "noexec", "nodev", "ro"], )?); } - mounts.push(mount_path( + mounts.push(mount( WORKSPACE, "bind", &req.workspace, &["rbind", "rw", "nosuid", "nodev"], )?); - // /tmp is a directory in the job dir, on disk: a tmpfs would charge temp files to the job's - // memory limit, and a test suite that writes many temp repos would be killed for it. - mounts.push(mount_path( + mounts.push(mount( "/tmp", "bind", &req.job_dir.join("tmp"), &["rbind", "rw", "nosuid", "nodev"], )?); - mounts.push(mount_path( + mounts.push(mount( "/etc/hosts", "bind", &req.job_dir.join("etc/hosts"), &["bind", "ro"], )?); - mounts.push(mount_path( + mounts.push(mount( "/etc/hostname", "bind", &req.job_dir.join("etc/hostname"), @@ -431,20 +389,16 @@ fn build_mounts(req: &SandboxRequest) -> Result, SandboxError> { Ok(mounts) } -fn mount(dest: &str, typ: &str, source: &str, options: &[&str]) -> Result { - mount_path(dest, typ, Path::new(source), options) -} - -fn mount_path( +fn mount( dest: &str, typ: &str, - source: &Path, + source: impl AsRef, options: &[&str], ) -> Result { MountBuilder::default() .destination(PathBuf::from(dest)) .typ(typ) - .source(source) + .source(source.as_ref()) .options(options.iter().map(|s| (*s).to_owned()).collect::>()) .build() .map_err(spec_err) @@ -457,7 +411,7 @@ fn spec_err(e: impl std::fmt::Display) -> SandboxError { #[cfg(test)] mod tests { use super::*; - use crate::sandbox::idmap::IdMap; + use crate::sandbox::idmap::{IdMap, SubRange}; use std::collections::HashSet; fn request(network: bool) -> SandboxRequest { @@ -527,8 +481,11 @@ mod tests { req.idmap = IdMap { uid: 1000, gid: 1000, - sub_uid: Some((524_288, 65_536)), - sub_gid: Some((524_288, 65_536)), + sub: Some(SubRange { + uid_start: 524_288, + gid_start: 524_288, + count: 65_536, + }), }; let spec = build_spec(&req, Path::new("/rootfs")).expect("spec"); assert!(!namespace_types(&spec).contains("user")); @@ -578,8 +535,6 @@ mod tests { #[test] fn spec_has_no_seccomp_section() { - // The seccomp filter is built in `seccomp.rs` and installed by `exec.rs`. A seccomp - // section here would be dead config that libcontainer ignores. let spec = spec_for(false); assert!(spec.linux().as_ref().expect("linux").seccomp().is_none()); } @@ -648,7 +603,6 @@ mod tests { res.memory().as_ref().and_then(|m| m.limit()), Some(2 * 1024 * 1024 * 1024) ); - // Memory plus swap equals memory, so the cgroup gets memory.swap.max = 0. assert_eq!( res.memory().as_ref().and_then(|m| m.swap()), Some(2 * 1024 * 1024 * 1024) @@ -691,7 +645,6 @@ mod tests { assert!(pos("LANG=C.UTF-8") < pos("HOME=/root")); assert!(pos("FORGE_CI=true") < pos("BUILD=1")); assert!(pos("BUILD=1") < pos("TOKEN=s3cret-token")); - // The image PATH is used, so no default PATH is added. assert_eq!(env.iter().filter(|e| e.starts_with("PATH=")).count(), 1); } @@ -758,6 +711,7 @@ mod tests { fn parse_cpus_rejects_zero_and_junk() { assert_eq!(parse_cpus("2").expect("2"), 2.0); assert!(parse_cpus("0").is_err()); + assert!(parse_cpus("0.005").is_err()); assert!(parse_cpus("nan").is_err()); assert!(parse_cpus("two").is_err()); } diff --git a/crates/forge-runner/src/selflog.rs b/crates/forge-runner/src/selflog.rs index fa0b9cc..73f34a8 100644 --- a/crates/forge-runner/src/selflog.rs +++ b/crates/forge-runner/src/selflog.rs @@ -8,7 +8,7 @@ use std::fmt::{Debug, Write as _}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use forge_ci::proto::{RunnerLogBatch, RunnerLogLine}; +use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, RunnerLogLine, truncate_text}; use reqwest::StatusCode; use tokio_util::sync::CancellationToken; use tracing::field::{Field, Visit}; @@ -20,8 +20,6 @@ use crate::client::{ClientError, ForgeClient}; /// Most lines the ring holds. The oldest are dropped first. pub const CAPACITY: usize = 2000; -/// Longest text kept for one line, in bytes. Longer text is cut on a character boundary. -pub const MAX_TEXT: usize = 4096; /// Most lines in one batch. pub const BATCH: usize = 500; /// Time between two shipping attempts. @@ -79,11 +77,6 @@ impl Ring { state.next += 1; } - /// The number the next line will get. - pub fn end(&self) -> u64 { - self.lock().next - } - /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first /// returned number is `from` or later. The number is returned with the lines. pub fn batch(&self, from: u64, max: usize) -> (u64, Vec) { @@ -121,7 +114,7 @@ impl Layer for SelfLog { self.ring.push(RunnerLogLine { at_ms: now_ms(), level: level_name(*meta.level()).to_owned(), - text: truncate(text.finish()), + text: truncate_text(&text.finish(), RUNNER_LOG_MAX_TEXT).to_owned(), }); } } @@ -178,18 +171,6 @@ pub(crate) fn now_ms() -> i64 { .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) } -/// Cuts `text` to at most [`MAX_TEXT`] bytes, on a character boundary. -fn truncate(mut text: String) -> String { - if text.len() > MAX_TEXT { - let mut end = MAX_TEXT; - while !text.is_char_boundary(end) { - end -= 1; - } - text.truncate(end); - } - text -} - /// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this /// process. Failures are logged at debug level and retried on the next tick. When `stop` is /// cancelled, the lines still held are sent before returning, so the caller may bound this with a @@ -257,7 +238,7 @@ mod tests { for i in 0..5 { ring.push(line(&i.to_string())); } - assert_eq!(ring.end(), 5); + assert_eq!(ring.batch(5, 10).0, 5); let (first, lines) = ring.batch(0, 10); assert_eq!(first, 2); let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect(); @@ -280,9 +261,9 @@ mod tests { #[test] fn long_text_is_cut_on_a_char_boundary() { - let text = "é".repeat(MAX_TEXT); - let cut = truncate(text); - assert!(cut.len() <= MAX_TEXT); + let text = "é".repeat(RUNNER_LOG_MAX_TEXT); + let cut = truncate_text(&text, RUNNER_LOG_MAX_TEXT); + assert!(cut.len() <= RUNNER_LOG_MAX_TEXT); assert!(cut.ends_with('é')); } } diff --git a/crates/forge-runner/src/update.rs b/crates/forge-runner/src/update.rs index 1b7198e..a1af971 100644 --- a/crates/forge-runner/src/update.rs +++ b/crates/forge-runner/src/update.rs @@ -15,8 +15,8 @@ use sha2::{Digest, Sha256}; use crate::client::{ClientError, ForgeClient}; -/// The exit code after a successful swap. systemd restarts the runner on any non-zero code. -pub const RESTART_EXIT_CODE: u8 = 75; +pub use forge_ci::proto::RESTART_EXIT_CODE; + /// How long the new binary gets to answer `--version`. const SMOKE_TIMEOUT: Duration = Duration::from_secs(10); /// The temp file, next to the running binary, that the download goes to. diff --git a/crates/forge-runner/src/workspace.rs b/crates/forge-runner/src/workspace.rs index b6c2152..12f2ec1 100644 --- a/crates/forge-runner/src/workspace.rs +++ b/crates/forge-runner/src/workspace.rs @@ -46,18 +46,6 @@ pub fn validate_commit(commit: &str) -> Result<(), WorkspaceError> { } } -/// Whether `file://` clone URLs are accepted. Only test builds may fetch from a local path. -#[cfg(any(test, feature = "test-host-executor"))] -const fn local_file_urls_allowed() -> bool { - true -} - -/// Whether `file://` clone URLs are accepted. Production builds never accept them. -#[cfg(not(any(test, feature = "test-host-executor")))] -const fn local_file_urls_allowed() -> bool { - false -} - /// Clone URLs must be a URL with a plain scheme. A leading `-` would be read as a git option. /// /// Production accepts `https://` only, plus `http://` when the forge itself is `http://`. @@ -65,7 +53,7 @@ const fn local_file_urls_allowed() -> bool { pub fn validate_clone_url(url: &str, forge_url: &str) -> Result<(), WorkspaceError> { let allowed = url.starts_with("https://") || (url.starts_with("http://") && forge_url.starts_with("http://")) - || (url.starts_with("file://") && local_file_urls_allowed()); + || (url.starts_with("file://") && cfg!(any(test, feature = "test-host-executor"))); if allowed && !url.contains(char::is_whitespace) { Ok(()) } else { @@ -242,7 +230,6 @@ mod tests { fn file_urls_are_accepted_in_test_builds_only() { // This test builds with cfg(test), so file:// is allowed here. Production builds refuse it. assert!(validate_clone_url("file:///nonexistent/repo", "https://forge.example").is_ok()); - assert!(local_file_urls_allowed()); } #[tokio::test] diff --git a/crates/forge-runner/tests/integration/flow.rs b/crates/forge-runner/tests/integration/flow.rs index ef19ade..a45d060 100644 --- a/crates/forge-runner/tests/integration/flow.rs +++ b/crates/forge-runner/tests/integration/flow.rs @@ -31,6 +31,7 @@ const RUNNER_SECRET: &str = "runner-secret-for-tests"; const SECRET_VALUE: &str = "s3cr3t-value-echoed-by-job"; const LOG_SIZE: &str = "X-Forge-Log-Size"; const LOG_OFFSET: &str = "X-Forge-Log-Offset"; +const JOB_ID: &str = "job-1"; /// What the mock forge saw and what it should do. #[derive(Default)] @@ -115,7 +116,7 @@ fn route( let job = st.pending.remove(0); Reply::json(&job) } - ("POST" | "PUT" | "GET", ["api", "v1", "ci", "jobs", job_id, rest @ ..]) => { + ("POST" | "PUT", ["api", "v1", "ci", "jobs", job_id, rest @ ..]) => { let Some(job) = st.by_id.get(*job_id) else { return Reply::empty(StatusCode::NOT_FOUND); }; @@ -369,15 +370,14 @@ async fn start( mut options: RunOptions, setup: impl FnOnce(&mut MockState), timeout: Option, -) -> (Harness, String) { +) -> Harness { let dir = tempfile::tempdir().expect("tempdir"); let commit = make_repo(dir.path()); let clone_url = format!("file://{}", dir.path().join("repo").display()); - let job_id = "job-1"; let state: Shared = Arc::new(Mutex::new(MockState::default())); { let mut st = state.lock().expect("lock"); - let j = job(job_id, &commit, &clone_url, run); + let j = job(JOB_ID, &commit, &clone_url, run); st.by_id.insert(j.job_id.clone(), j.clone()); st.pending.push(j); setup(&mut st); @@ -391,24 +391,20 @@ async fn start( let stop = stop.clone(); tokio::spawn(async move { runner.run(stop).await }) }; - ( - Harness { - state, - stop, - runner_task, - _dir: dir, - }, - job_id.to_owned(), - ) + Harness { + state, + stop, + runner_task, + _dir: dir, + } } -async fn finish_of(h: &Harness, job_id: &str) -> FinishRequest { +async fn finish_of(h: &Harness) -> FinishRequest { let state = h.state.clone(); - let id = job_id.to_owned(); wait_until("the job to finish", || { state .lock() - .map(|st| st.finished.contains_key(&id)) + .map(|st| st.finished.contains_key(JOB_ID)) .unwrap_or(false) }) .await; @@ -416,7 +412,7 @@ async fn finish_of(h: &Harness, job_id: &str) -> FinishRequest { .lock() .expect("lock") .finished - .get(job_id) + .get(JOB_ID) .cloned() .expect("finish recorded") } @@ -434,9 +430,9 @@ fn log_text(h: &Harness) -> String { async fn full_flow_masks_secrets_and_uploads_artifacts() { let run = "mkdir -p dist && echo built > dist/out.txt && echo \"token is $MY_TOKEN\" && \ echo \"b64 $(printf %s \"$MY_TOKEN\" | base64)\" && echo \"env is $GREETING\""; - let (h, job_id) = start(run, fast_options(), |_| {}, None).await; + let h = start(run, fast_options(), |_| {}, None).await; - let finish = finish_of(&h, &job_id).await; + let finish = finish_of(&h).await; assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); assert_eq!(finish.exit_code, Some(0)); @@ -470,18 +466,16 @@ fn base64_of(text: &str) -> String { #[tokio::test] async fn heartbeat_cancel_stops_the_job() { - let mut options = fast_options(); - options.heartbeat_every = Duration::from_millis(50); - let (h, job_id) = start( + let h = start( "echo start; sleep 60", - options, + fast_options(), |st| st.cancel_from_heartbeat = Some(2), None, ) .await; let started = Instant::now(); - let finish = finish_of(&h, &job_id).await; + let finish = finish_of(&h).await; assert_eq!(finish.outcome, Outcome::Cancelled, "{finish:?}"); assert!( started.elapsed() < Duration::from_secs(30), @@ -492,7 +486,7 @@ async fn heartbeat_cancel_stops_the_job() { #[tokio::test] async fn timeout_fails_the_job() { - let (h, job_id) = start( + let h = start( "sleep 60", fast_options(), |_| {}, @@ -500,7 +494,7 @@ async fn timeout_fails_the_job() { ) .await; - let finish = finish_of(&h, &job_id).await; + let finish = finish_of(&h).await; assert_eq!(finish.outcome, Outcome::Failure, "{finish:?}"); assert!( finish @@ -518,9 +512,9 @@ async fn log_offset_mismatch_resyncs_without_loss_or_duplicates() { // Log POST #2 is applied by the forge for its first 3 bytes, then answered 409. The runner // must drop those 3 bytes and continue, so the stored log has every line exactly once. let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; - let (h, job_id) = start(run, fast_options(), |st| st.ghost = Some((2, 3)), None).await; + let h = start(run, fast_options(), |st| st.ghost = Some((2, 3)), None).await; - let finish = finish_of(&h, &job_id).await; + let finish = finish_of(&h).await; assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); let log = log_text(&h); @@ -540,9 +534,9 @@ async fn acknowledged_batch_the_forge_lost_is_resent_in_order() { // Log POST #2 is acknowledged but never stored. The next POST gets 409 with the smaller size, // and the runner must resend the lost bytes from its retained buffer, with no gap marker. let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; - let (h, job_id) = start(run, fast_options(), |st| st.drop_post = Some(2), None).await; + let h = start(run, fast_options(), |st| st.drop_post = Some(2), None).await; - let finish = finish_of(&h, &job_id).await; + let finish = finish_of(&h).await; assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); let log = log_text(&h); diff --git a/crates/forge-runner/tests/integration/idmap.rs b/crates/forge-runner/tests/integration/idmap.rs index df5c398..0151d52 100644 --- a/crates/forge-runner/tests/integration/idmap.rs +++ b/crates/forge-runner/tests/integration/idmap.rs @@ -5,7 +5,7 @@ use std::fs; use std::path::Path; use std::process::{Command, Stdio}; -use forge_runner::sandbox::idmap::{IdMap, UsernsMode, remove_tree}; +use forge_runner::sandbox::idmap::{IdMap, SubRange, UsernsMode, remove_tree}; #[test] fn remove_tree_deletes_files_owned_by_subordinate_ids() { @@ -47,8 +47,11 @@ fn remove_tree_treats_a_missing_path_as_done() { let map = IdMap { uid: 1000, gid: 1000, - sub_uid: Some((524288, 65536)), - sub_gid: Some((524288, 65536)), + sub: Some(SubRange { + uid_start: 524288, + gid_start: 524288, + count: 65536, + }), }; remove_tree(&map, &missing, exe).expect("subuid mode"); } diff --git a/crates/forge-runner/tests/integration/sandbox.rs b/crates/forge-runner/tests/integration/sandbox.rs index fda3ee7..fe04804 100644 --- a/crates/forge-runner/tests/integration/sandbox.rs +++ b/crates/forge-runner/tests/integration/sandbox.rs @@ -1,93 +1,24 @@ -//! Real sandbox tests. They run `forge-runner __sandbox` with a rootfs built here from the host's -//! shell and a few utilities plus their shared libraries. Nothing is pulled from a registry, and -//! there is no network access. The tests skip, with a message, when unprivileged user -//! namespaces are unavailable. - use std::fs; use std::io::Write; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::{Command, Output, Stdio}; use std::time::{Duration, Instant}; use std::os::unix::fs::MetadataExt; +use forge_runner::check; use forge_runner::config::Limits; use forge_runner::sandbox::SandboxRequest; use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; use crate::common::can_run; -/// Utilities copied into the test rootfs. `sh` is the job shell, and the rest are used by the -/// test scripts. const BINARIES: &[&str] = &[ "sh", "id", "cat", "grep", "touch", "sleep", "unshare", "chown", "stat", "mkdir", ]; -/// The shared libraries `ldd` reports for `binary`, as absolute host paths. -fn shared_libs(binary: &Path) -> Vec { - let Ok(out) = Command::new("ldd").arg(binary).output() else { - return Vec::new(); - }; - String::from_utf8_lossy(&out.stdout) - .lines() - .filter_map(|line| { - let line = line.trim(); - let path = match line.split_once(" => ") { - Some((_, rest)) => rest.split(" (").next()?, - None => line.split(" (").next()?, - }; - path.starts_with('/').then(|| PathBuf::from(path)) - }) - .collect() -} - -fn copy_into(root: &Path, host: &Path) { - let real = fs::canonicalize(host).expect("canonicalize host file"); - let dest = root.join(host.strip_prefix("/").unwrap_or(host)); - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent).expect("create dest dir"); - } - fs::copy(&real, &dest).expect("copy file into rootfs"); -} - -/// Builds a tiny rootfs in `root`: the binaries in `/bin`, their shared libraries at the same -/// absolute paths, and the empty mount points the spec needs. fn build_rootfs(root: &Path) { - for dir in [ - "bin", - "proc", - "dev", - "sys", - "tmp", - "workspace", - "etc", - "root", - ] { - fs::create_dir_all(root.join(dir)).expect("create rootfs dir"); - } - for name in ["null", "zero", "full", "random", "urandom"] { - fs::write(root.join("dev").join(name), b"").expect("placeholder device"); - } - fs::write(root.join("etc/hosts"), b"").expect("placeholder hosts"); - fs::write(root.join("etc/hostname"), b"").expect("placeholder hostname"); - fs::write(root.join("etc/resolv.conf"), b"").expect("placeholder resolv.conf"); - - let mut libs: Vec = Vec::new(); - for name in BINARIES { - let host = ["/usr/bin", "/bin"] - .iter() - .map(|dir| Path::new(dir).join(name)) - .find(|p| p.exists()) - .unwrap_or_else(|| panic!("{name} not found on this host")); - let real = fs::canonicalize(&host).expect("canonicalize binary"); - fs::copy(&real, root.join("bin").join(name)).expect("copy binary"); - libs.extend(shared_libs(&real)); - } - libs.sort(); - libs.dedup(); - for lib in &libs { - copy_into(root, lib); - } + check::build_rootfs(root, BINARIES).expect("build rootfs"); } fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxRequest { @@ -108,7 +39,6 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques } } -/// The subuid map, or `None` with a message when the host can't provide one. fn subuid_map() -> Option { match IdMap::resolve(UsernsMode::Subuid) { Ok(map) if map.is_subuid() => Some(map), @@ -120,7 +50,6 @@ fn subuid_map() -> Option { } } -/// Spawns the helper and writes the request to its stdin. Returns the child, not yet waited on. fn spawn_helper(req: &SandboxRequest) -> std::process::Child { let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner")) .arg("__sandbox") @@ -174,7 +103,6 @@ fn job_runs_as_root_with_no_capabilities() { stdout.contains("NoNewPrivs:\t1"), "no_new_privs off: {stdout}" ); - // Seccomp mode 2 is a filter. The profile is installed by `sandbox::exec::FilteredExecutor`. assert!( stdout.contains("Seccomp:\t2"), "seccomp filter not active: {stdout}" @@ -211,8 +139,6 @@ fn unshare_is_denied_inside_the_job() { let dir = tempfile::tempdir().expect("tempdir"); let rootfs = dir.path().join("rootfs"); build_rootfs(&rootfs); - // Creating a user namespace works on the host. The seccomp filter makes unshare(2) fail with - // EPERM inside the job, so this must print "denied". let run = "if unshare --user true 2>/dev/null; then echo allowed; else echo denied; fi"; let out = run_helper(&request(dir.path(), &rootfs, run, false)); let stdout = stdout_of(&out); @@ -313,7 +239,6 @@ fn sigterm_kills_the_container_and_the_helper_exits() { build_rootfs(&rootfs); let req = request(dir.path(), &rootfs, "sleep 60", false); let child = spawn_helper(&req); - // Give the container time to start, so that SIGTERM hits a running job. std::thread::sleep(Duration::from_secs(2)); let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).expect("pid fits i32")); nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGTERM).expect("send SIGTERM"); @@ -347,8 +272,6 @@ fn rootfs_is_copied_when_the_overlay_cannot_be_mounted() { return; } let dir = tempfile::tempdir().expect("tempdir"); - // A comma in a lower dir can't be written in overlay options, so the overlay mount fails - // and the helper falls back to copying the rootfs. let rootfs = dir.path().join("rootfs,copy"); build_rootfs(&rootfs); let out = run_helper(&request( @@ -368,7 +291,6 @@ fn rootfs_is_copied_when_the_overlay_cannot_be_mounted() { assert!(!rootfs.join("etc/forge-marker").exists()); } -/// A request that runs under `map` (subuid mode when `map` has a range). fn subuid_request(dir: &Path, rootfs: &Path, run: &str, map: &IdMap) -> SandboxRequest { let mut req = request(dir, rootfs, run, false); req.idmap = map.clone(); @@ -411,8 +333,6 @@ fn subuid_uid_and_gid_maps_have_one_plus_the_range() { )); let stdout = stdout_of(&out); assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); - // Each line is `inside outside count`. The job's root plus the subordinate range make the - // map's size, which is `1 + n`, in one or two lines. Sum the counts for each map. let sizes: Vec = stdout .lines() .filter_map(|l| l.split_whitespace().nth(2)?.parse().ok()) @@ -451,6 +371,7 @@ fn subuid_job_files_are_owned_by_the_runner_afterwards() { ); let out = run_helper(&req); assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); + assert!(!req.job_dir.exists(), "the job dir was left behind"); for path in ["a", "d", "d/x"] { let path = req.workspace.join(path); let meta = fs::symlink_metadata(&path).expect("stat workspace entry"); @@ -462,23 +383,3 @@ fn subuid_job_files_are_owned_by_the_runner_afterwards() { ); } } - -#[test] -fn subuid_job_dir_is_removed_afterwards() { - let Some(map) = subuid_map() else { return }; - if !can_run() { - return; - } - let dir = tempfile::tempdir().expect("tempdir"); - let rootfs = dir.path().join("rootfs"); - build_rootfs(&rootfs); - let req = subuid_request( - dir.path(), - &rootfs, - "touch /workspace/a && chown 1000:1000 /workspace/a", - &map, - ); - let out = run_helper(&req); - assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); - assert!(!req.job_dir.exists(), "the job dir was left behind"); -} diff --git a/crates/forge-runner/tests/integration/unpack_subuid.rs b/crates/forge-runner/tests/integration/unpack_subuid.rs index 3abf09a..551dae0 100644 --- a/crates/forge-runner/tests/integration/unpack_subuid.rs +++ b/crates/forge-runner/tests/integration/unpack_subuid.rs @@ -10,7 +10,7 @@ use std::path::Path; use std::process::{Command, Output, Stdio}; use forge_runner::oci::UnpackStats; -use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; +use forge_runner::sandbox::idmap::{IdMap, UsernsMode, remove_tree}; /// The subuid map for this user, or None when the test should skip. fn subuid_map() -> Option { @@ -86,30 +86,13 @@ fn run_unpack(map: &IdMap, rootfs: &Path, layer: &Path) -> Output { child.wait_with_output().expect("wait for helper") } -/// Removes a tree that holds subordinate-owned files, through `forge-runner __sandbox-rm`. -fn remove_with_helper(map: &IdMap, path: &Path) { - let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner")) - .arg("__sandbox-rm") - .arg(path) - .stdin(Stdio::piped()) - .spawn() - .expect("spawn rm helper"); - if let Some(mut stdin) = child.stdin.take() { - let _ = stdin.write_all(&serde_json::to_vec(map).expect("serialize map")); - } - match child.wait() { - Ok(status) if status.success() => {} - other => eprintln!("warning: could not remove {}: {other:?}", path.display()), - } -} - #[test] fn subuid_unpack_gives_files_their_subordinate_owner() { let Some(map) = subuid_map() else { return; }; - let (uid_start, _) = map.sub_uid.expect("subuid map has a uid range"); - let (gid_start, _) = map.sub_gid.expect("subuid map has a gid range"); + let range = map.sub.expect("subuid map has a range"); + let (uid_start, gid_start) = (range.uid_start, range.gid_start); let dir = tempfile::tempdir().expect("tempdir"); let layer = dir.path().join("layer.tar"); @@ -132,5 +115,6 @@ fn subuid_unpack_gives_files_their_subordinate_owner() { assert_eq!(file.uid(), uid_start + 999, "host uid of srv/owned"); assert_eq!(file.gid(), gid_start + 999, "host gid of srv/owned"); - remove_with_helper(&map, &rootfs); + remove_tree(&map, &rootfs, Path::new(env!("CARGO_BIN_EXE_forge-runner"))) + .expect("remove rootfs"); } diff --git a/crates/forge-web-account/src/pages/settings_live.rs b/crates/forge-web-account/src/pages/settings_live.rs index 731d116..ad34f88 100644 --- a/crates/forge-web-account/src/pages/settings_live.rs +++ b/crates/forge-web-account/src/pages/settings_live.rs @@ -66,9 +66,9 @@ pub async fn account_state( let Some(user) = state.store.user_by_id(user_id).await? else { return Ok((String::new(), String::new(), String::new())); }; - let theme = match crate::theme::resolve_preference(&user.theme) { - "auto" => "", - theme => theme, + let theme = match crate::theme::Theme::from_stored(&user.theme) { + crate::theme::Theme::Auto => "", + theme => theme.as_str(), }; let sidebar = if user.sidebar_side == "right" { "right" diff --git a/crates/forge-web-app/src/alerts.rs b/crates/forge-web-app/src/alerts.rs index cddb6f7..288a790 100644 --- a/crates/forge-web-app/src/alerts.rs +++ b/crates/forge-web-app/src/alerts.rs @@ -160,7 +160,7 @@ async fn deliver( ); let outgoing = OutgoingMail { to: address.to_owned(), - subject: text::mail_subject(lang, &title), + subject: text::mail_subject(&title), body, message_id: None, in_reply_to: None, diff --git a/crates/forge-web-app/src/ci/runner_log.rs b/crates/forge-web-app/src/ci/runner_log.rs index 5fdf769..f5d4ecb 100644 --- a/crates/forge-web-app/src/ci/runner_log.rs +++ b/crates/forge-web-app/src/ci/runner_log.rs @@ -9,14 +9,12 @@ use std::collections::{HashMap, VecDeque}; use std::sync::{Mutex, MutexGuard}; -use forge_ci::proto::RunnerLogBatch; +use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, truncate_text}; /// Most lines kept per runner. The oldest go first. const MAX_LINES: usize = 2000; /// Most lines taken from one batch. The rest are left for the runner to resend. const MAX_BATCH_LINES: usize = 1000; -/// Longest text kept per line, in bytes. Longer text is cut on a character boundary. -const MAX_TEXT_BYTES: usize = 4096; /// Longest boot id kept, in bytes. const MAX_BOOT_ID_BYTES: usize = 64; /// The levels a runner may send. Any other level is stored as `info`. @@ -72,7 +70,7 @@ impl RunnerLogs { push(entry, forge_line(format!("{missing} lines missing"))); } for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() { - let seq = batch.first_seq + i as u64; + let seq = batch.first_seq.saturating_add(i as u64); if seq < entry.next_seq { continue; } @@ -81,13 +79,13 @@ impl RunnerLogs { Line { at_ms: line.at_ms, level: level_of(&line.level), - text: cut(&line.text, MAX_TEXT_BYTES), + text: truncate_text(&line.text, RUNNER_LOG_MAX_TEXT).to_owned(), from_forge: false, }, ); } let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64; - entry.next_seq = entry.next_seq.max(batch.first_seq + taken); + entry.next_seq = entry.next_seq.max(batch.first_seq.saturating_add(taken)); entry.next_seq } @@ -160,18 +158,6 @@ fn level_of(level: &str) -> String { } } -/// `text` cut to at most `max` bytes, on a character boundary. -fn cut(text: &str, max: usize) -> String { - if text.len() <= max { - return text.to_owned(); - } - let mut end = max; - while !text.is_char_boundary(end) { - end -= 1; - } - text[..end].to_owned() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-web-app/src/self_update.rs b/crates/forge-web-app/src/self_update.rs index fcc14e1..3155ec3 100644 --- a/crates/forge-web-app/src/self_update.rs +++ b/crates/forge-web-app/src/self_update.rs @@ -25,8 +25,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, response::Response}; use crate::state::AppState; -/// Exit code after a swap. systemd `Restart=on-failure` restarts the unit on any non-zero exit. -pub const RESTART_EXIT_CODE: u8 = 75; +pub use forge_ci::proto::RESTART_EXIT_CODE; /// Response header carrying the sha256 of the running binary, lowercase hex. pub const SHA_HEADER: &str = "Forge-Binary-Sha256"; /// Request header a runner sends with its `-` target. diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index 49eec29..3397524 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -48,6 +48,7 @@ use crate::i18n::s; use crate::i18n::{self, Key, Lang, t}; use crate::render::highlight::highlight_css; use crate::state::AppState; +use crate::theme::Theme; /// Stylesheet URL. The version is a hash of the compiled CSS (build.rs), so a changed stylesheet /// gets a new URL and an unchanged one keeps its cache entry. @@ -632,16 +633,16 @@ pub async fn shell( // The stored preference, "auto" included, drives the button: its icon, its label and the // value it posts (the next preference in the cycle auto, light, dark). let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); - let next_theme = crate::theme::next_preference(theme_pref); + let next_theme = theme_pref.next().as_str(); let theme_state = match theme_pref { - "light" => mi::t(lang, MK::Light), - "dark" => mi::t(lang, MK::Dark), - _ => mi::t(lang, MK::MatchSystem), + Theme::Light => mi::t(lang, MK::Light), + Theme::Dark => mi::t(lang, MK::Dark), + Theme::Auto => mi::t(lang, MK::MatchSystem), }; - let theme_next = match next_theme { - "light" => MK::SwitchToLight, - "dark" => MK::SwitchToDark, - _ => MK::SwitchToMatchSystem, + let theme_next = match theme_pref.next() { + Theme::Light => MK::SwitchToLight, + Theme::Dark => MK::SwitchToDark, + Theme::Auto => MK::SwitchToMatchSystem, }; let switch_label = format!( "{}: {}. {}", @@ -814,9 +815,9 @@ pub async fn shell( }