diff --git a/.forge/ci.toml b/.forge/ci.toml index 95d1abc..3516be3 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -17,8 +17,8 @@ tags = ["v*"] [jobs.test] image = "docker.io/library/rust:1" -# Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB. Also drops debuginfo. -env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } +# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo. +env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" } run = """ cargo test --workspace """ @@ -28,8 +28,8 @@ timeout_minutes = 120 [jobs.build] image = "docker.io/library/rust:1" needs = ["test"] -# Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB. -env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" } +# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). +env = { CARGO_INCREMENTAL = "0" } run = """ cargo build --profile dist -p forge-web -p forge-runner ARCH=$(uname -m) diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index b4ab39d..df3b965 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -194,8 +194,6 @@ fn spec_needs(spec: &str) -> Vec { .unwrap_or_default() } -/// True when every label in the spec's `runs_on` is one of the runner's labels. A missing -/// `runs_on` means no requirement. A malformed spec is never claimable. /// The `memory` a job's stored spec declares, in bytes. fn declared_memory(spec: &str) -> Option { serde_json::from_str::(spec) @@ -204,6 +202,8 @@ fn declared_memory(spec: &str) -> Option { .as_u64() } +/// True when every label in the spec's `runs_on` is one of the runner's labels. A missing +/// `runs_on` means no requirement. A malformed spec is never claimable. fn runs_on_covered(spec: &str, labels: &[String]) -> bool { let Ok(value) = serde_json::from_str::(spec) else { return false; diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 96cde84..356af31 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -106,6 +106,45 @@ 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 + .cpus + .trim() + .parse::() + .ok() + .filter(|c| c.is_finite() && *c > 0.0) + .map_or(host, |c| c.ceil() as 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, +) -> Result, ExecError> { + let n = job_parallelism(limits); + let mut pairs: Vec<(String, String)> = [ + ("FORGE_CPUS", n.to_string()), + ("FORGE_MEMORY_BYTES", crate::sandbox::spec::parse_bytes(&limits.memory).map_or_else(|_| "0".to_owned(), |b| b.to_string())), + ("CARGO_BUILD_JOBS", n.to_string()), + ("MAKEFLAGS", format!("-j{n}")), + ("CMAKE_BUILD_PARALLEL_LEVEL", n.to_string()), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + for (k, v) in job_env(job)? { + pairs.retain(|(name, _)| *name != k); + pairs.push((k, v)); + } + 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 { @@ -149,7 +188,7 @@ pub fn podman_invocation( .filter(|s| !s.contains(':') && !s.contains(',')) .ok_or_else(|| ExecError::Invalid("workspace path has a ':' or ','".into()))?; - let env = job_env(job)?; + let env = job_env_with_defaults(job, limits)?; let container = format!("forge-job-{}", job.job_id); let network = if job.network { "slirp4netns" } else { "none" }; @@ -609,7 +648,7 @@ impl BuiltinExecutor { if let Err(e) = check_image(&job.image) { return error_result(e.to_string()); } - let env = match job_env(job) { + let env = match job_env_with_defaults(job, &self.limits.for_job(job.memory_bytes)) { Ok(env) => env, Err(e) => return error_result(e.to_string()), }; @@ -852,7 +891,10 @@ mod tests { .filter(|w| w[0] == "-e") .map(|w| w[1].as_str()) .collect(); - assert_eq!(names, vec!["PLAIN", "MY_TOKEN"]); + assert_eq!( + names, + vec!["FORGE_CPUS", "FORGE_MEMORY_BYTES", "CARGO_BUILD_JOBS", "MAKEFLAGS", "CMAKE_BUILD_PARALLEL_LEVEL", "PLAIN", "MY_TOKEN"] + ); } #[test] @@ -891,6 +933,19 @@ mod tests { ); } + #[test] + fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { + let mut job = fixture_job("true"); + let mut limits = Limits::default(); + limits.cpus = "0.5".to_owned(); + let env = job_env_with_defaults(&job, &limits).expect("env"); + assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned()))); + job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned()); + let env = job_env_with_defaults(&job, &limits).expect("env"); + let jobs: Vec<_> = env.iter().filter(|(k, _)| k == "CARGO_BUILD_JOBS").collect(); + assert_eq!(jobs, [&("CARGO_BUILD_JOBS".to_owned(), "7".to_owned())]); + } + #[test] fn hostile_values_are_refused() { let ws = Path::new("/w"); diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index 821527a..1cda787 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -77,6 +77,8 @@ struct Layout { bundle: PathBuf, state: PathBuf, etc: PathBuf, + /// Bind mounted at `/tmp`: on the runner's disk, so temp files do not count as job memory. + tmp: PathBuf, upper: PathBuf, work: PathBuf, merged: PathBuf, @@ -90,6 +92,7 @@ impl Layout { bundle: job_dir.join("bundle"), state: job_dir.join("state"), etc: job_dir.join("etc"), + tmp: job_dir.join("tmp"), upper: overlay.join("upper"), work: overlay.join("work"), merged: overlay.join("merged"), @@ -220,6 +223,7 @@ fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> { &layout.bundle, &layout.state, &layout.etc, + &layout.tmp, &layout.upper, &layout.work, &layout.merged, @@ -231,6 +235,8 @@ fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> { fs::set_permissions(dir, fs::Permissions::from_mode(0o700)) .map_err(SandboxError::io(format!("cannot chmod {}", dir.display())))?; } + fs::set_permissions(&layout.tmp, fs::Permissions::from_mode(0o1777)) + .map_err(SandboxError::io(format!("cannot chmod {}", layout.tmp.display())))?; Ok(()) } diff --git a/crates/forge-runner/src/sandbox/spec.rs b/crates/forge-runner/src/sandbox/spec.rs index 836fb07..de81684 100644 --- a/crates/forge-runner/src/sandbox/spec.rs +++ b/crates/forge-runner/src/sandbox/spec.rs @@ -397,11 +397,13 @@ fn build_mounts(req: &SandboxRequest) -> Result, SandboxError> { &req.workspace, &["rbind", "rw", "nosuid", "nodev"], )?); - mounts.push(mount( + // /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( "/tmp", - "tmpfs", - "tmpfs", - &["nosuid", "nodev", "mode=1777"], + "bind", + &req.job_dir.join("tmp"), + &["rbind", "rw", "nosuid", "nodev"], )?); mounts.push(mount_path( "/etc/hosts", diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index c22fbaf..c773b1e 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -176,11 +176,20 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result { #[route(POST "/api/v1/ci/runners/claim")] async fn claim(cx: &Cx, body: Body) -> topcoat::Result { let state = app_context::(cx); - // The labels in the request are ignored: the labels stored at registration are used. - let runner = match runner_from(state, headers(cx)).await { + // The labels in the request are ignored: the labels stored at registration are used, plus the + // arch and OS the runner reports, so `runs_on = ["aarch64"]` needs no admin to type a label. + let mut runner = match runner_from(state, headers(cx)).await { Ok(runner) => runner, Err(res) => return Ok(*res), }; + let target = headers(cx) + .get(crate::self_update::TARGET_HEADER) + .and_then(|v| v.to_str().ok()); + for label in target_labels(target) { + if !runner.labels.contains(&label) { + runner.labels.push(label); + } + } // What the runner says about itself. An older runner sends only labels, and a body that does // not parse is not worth failing a claim over. let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await { @@ -225,6 +234,25 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result { Ok(res) } +/// The labels a runner's reported `-` target stands for: the arch, the OS and the whole +/// target, such as `x86_64`, `linux` and `x86_64-linux`. Nothing for a missing or odd target. +fn target_labels(target: Option<&str>) -> Vec { + let Some(target) = target else { + return Vec::new(); + }; + let plain = |part: &str| { + !part.is_empty() + && part.len() <= 32 + && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') + }; + match target.split_once('-') { + Some((arch, os)) if plain(arch) && plain(os) => { + vec![arch.to_owned(), os.to_owned(), target.to_owned()] + } + _ => Vec::new(), + } +} + /// Stores a runner's self report and wakes the admin pages when it changed something. async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) { match state.store.record_runner_report(runner_id, report).await { diff --git a/docs/ci.md b/docs/ci.md index 87e475f..f5c3b32 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -53,7 +53,7 @@ There must be at least one job, and at most 20. | `secrets` | array of string | `[]` | Repo secret names, each `^[A-Z_][A-Z0-9_]{0,63}$`. Exported as env vars. | | `env` | table of string | `{}` | Plain env vars. Names match the same pattern. A secret with the same name wins. | | `artifacts` | array of string | `[]` | Relative globs in the workspace. No `..`, no leading `/`. | -| `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | +| `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. Every runner also has its arch, OS and `-` as labels, such as `x86_64`, `linux` and `x86_64-linux`. | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | @@ -65,6 +65,15 @@ Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. The job's workspace is a fresh checkout of the exact commit, at `/workspace`. The job starts in that directory. +### CPUs + +A job does not decide how parallel its build is; the runner does, since only it knows the machine. +It exports `FORGE_CPUS`, the job's CPU limit (`limits.cpus`) rounded up and capped at the host's +CPUs, and sets the same number for common build tools: `CARGO_BUILD_JOBS`, `MAKEFLAGS=-jN` and +`CMAKE_BUILD_PARALLEL_LEVEL`. The same workflow then builds with `-j1` on a one-core box and `-j32` +on a big one. A job that sets one of these in its `env` keeps its own value. Other tools can read +`$FORGE_CPUS`, for example `ninja -j"$FORGE_CPUS"`. + ### Memory `memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a