forge
Explore
Log in

Don't you dare go Hollow

The runner decides build parallelism, puts /tmp on disk, tells jobs their memory and matches its own arch and OS as labels

Browse files at this commit

67ea129f60f6158281cf11104b235825d3f7981bAhmet Kaan GümüşParent: b268eaf
  • feat
    • the runner decides build parallelism, puts /tmp on disk, tells jobs their memory and matches its own arch and OS as labels
Show full message
✨ feat: the runner decides build parallelism, puts /tmp on disk, tells jobs their memory and matches its own arch and OS as labels
.forge/ci.tomlmodified+4 -4
@@ -17,8 +17,8 @@ tags = ["v*"]
17 17
18 [jobs.test]18 [jobs.test]
19 image = "docker.io/library/rust:1"19 image = "docker.io/library/rust:1"
20-# 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.20+# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo.
21-env = { CARGO_BUILD_JOBS = "1", CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" }21+env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0" }
22 run = """22 run = """
23 cargo test --workspace23 cargo test --workspace
24 """24 """
@@ -28,8 +28,8 @@ timeout_minutes = 120
28 [jobs.build]28 [jobs.build]
29 image = "docker.io/library/rust:1"29 image = "docker.io/library/rust:1"
30 needs = ["test"]30 needs = ["test"]
31-# 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.31+# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit).
32-env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" }32+env = { CARGO_INCREMENTAL = "0" }
33 run = """33 run = """
34 cargo build --profile dist -p forge-web -p forge-runner34 cargo build --profile dist -p forge-web -p forge-runner
35 ARCH=$(uname -m)35 ARCH=$(uname -m)
crates/forge-core/src/store/ci.rsmodified+2 -2
@@ -194,8 +194,6 @@ fn spec_needs(spec: &str) -> Vec<String> {
194 .unwrap_or_default()194 .unwrap_or_default()
195 }195 }
196 196
197-/// True when every label in the spec's `runs_on` is one of the runner's labels. A missing
198-/// `runs_on` means no requirement. A malformed spec is never claimable.
199 /// The `memory` a job's stored spec declares, in bytes.197 /// The `memory` a job's stored spec declares, in bytes.
200 fn declared_memory(spec: &str) -> Option<u64> {198 fn declared_memory(spec: &str) -> Option<u64> {
201 serde_json::from_str::<serde_json::Value>(spec)199 serde_json::from_str::<serde_json::Value>(spec)
@@ -204,6 +202,8 @@ fn declared_memory(spec: &str) -> Option<u64> {
204 .as_u64()202 .as_u64()
205 }203 }
206 204
205+/// True when every label in the spec's `runs_on` is one of the runner's labels. A missing
206+/// `runs_on` means no requirement. A malformed spec is never claimable.
207 fn runs_on_covered(spec: &str, labels: &[String]) -> bool {207 fn runs_on_covered(spec: &str, labels: &[String]) -> bool {
208 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {208 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {
209 return false;209 return false;
crates/forge-runner/src/executor.rsmodified+58 -3
@@ -106,6 +106,45 @@ pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError>
106 Ok(pairs)106 Ok(pairs)
107 }107 }
108 108
109+/// How many things a job should build at once: its CPU limit rounded up, at least 1 and at most
110+/// the host's CPUs. The runner decides this, not the workflow, since only it knows the machine.
111+pub fn job_parallelism(limits: &Limits) -> u32 {
112+ let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
113+ let cpus = limits
114+ .cpus
115+ .trim()
116+ .parse::<f64>()
117+ .ok()
118+ .filter(|c| c.is_finite() && *c > 0.0)
119+ .map_or(host, |c| c.ceil() as u32);
120+ cpus.clamp(1, host.max(1))
121+}
122+
123+/// The job's env with the runner's defaults under it: `FORGE_CPUS`, `FORGE_MEMORY_BYTES` (the job's
124+/// memory limit) and the parallelism knobs common build tools read (cargo, make, cmake). A job that
125+/// sets one of them itself keeps its own value.
126+pub fn job_env_with_defaults(
127+ job: &JobAssignment,
128+ limits: &Limits,
129+) -> Result<Vec<(String, String)>, ExecError> {
130+ let n = job_parallelism(limits);
131+ let mut pairs: Vec<(String, String)> = [
132+ ("FORGE_CPUS", n.to_string()),
133+ ("FORGE_MEMORY_BYTES", crate::sandbox::spec::parse_bytes(&limits.memory).map_or_else(|_| "0".to_owned(), |b| b.to_string())),
134+ ("CARGO_BUILD_JOBS", n.to_string()),
135+ ("MAKEFLAGS", format!("-j{n}")),
136+ ("CMAKE_BUILD_PARALLEL_LEVEL", n.to_string()),
137+ ]
138+ .into_iter()
139+ .map(|(k, v)| (k.to_owned(), v))
140+ .collect();
141+ for (k, v) in job_env(job)? {
142+ pairs.retain(|(name, _)| *name != k);
143+ pairs.push((k, v));
144+ }
145+ Ok(pairs)
146+}
147+
109 /// The podman invocation for a job: argv (no values in it) and the env the child needs.148 /// The podman invocation for a job: argv (no values in it) and the env the child needs.
110 #[derive(Debug, PartialEq, Eq)]149 #[derive(Debug, PartialEq, Eq)]
111 pub struct PodmanInvocation {150 pub struct PodmanInvocation {
@@ -149,7 +188,7 @@ pub fn podman_invocation(
149 .filter(|s| !s.contains(':') && !s.contains(','))188 .filter(|s| !s.contains(':') && !s.contains(','))
150 .ok_or_else(|| ExecError::Invalid("workspace path has a ':' or ','".into()))?;189 .ok_or_else(|| ExecError::Invalid("workspace path has a ':' or ','".into()))?;
151 190
152- let env = job_env(job)?;191+ let env = job_env_with_defaults(job, limits)?;
153 let container = format!("forge-job-{}", job.job_id);192 let container = format!("forge-job-{}", job.job_id);
154 let network = if job.network { "slirp4netns" } else { "none" };193 let network = if job.network { "slirp4netns" } else { "none" };
155 194
@@ -609,7 +648,7 @@ impl<I: ImageSource> BuiltinExecutor<I> {
609 if let Err(e) = check_image(&job.image) {648 if let Err(e) = check_image(&job.image) {
610 return error_result(e.to_string());649 return error_result(e.to_string());
611 }650 }
612- let env = match job_env(job) {651+ let env = match job_env_with_defaults(job, &self.limits.for_job(job.memory_bytes)) {
613 Ok(env) => env,652 Ok(env) => env,
614 Err(e) => return error_result(e.to_string()),653 Err(e) => return error_result(e.to_string()),
615 };654 };
@@ -852,7 +891,10 @@ mod tests {
852 .filter(|w| w[0] == "-e")891 .filter(|w| w[0] == "-e")
853 .map(|w| w[1].as_str())892 .map(|w| w[1].as_str())
854 .collect();893 .collect();
855- assert_eq!(names, vec!["PLAIN", "MY_TOKEN"]);894+ assert_eq!(
895+ names,
896+ vec!["FORGE_CPUS", "FORGE_MEMORY_BYTES", "CARGO_BUILD_JOBS", "MAKEFLAGS", "CMAKE_BUILD_PARALLEL_LEVEL", "PLAIN", "MY_TOKEN"]
897+ );
856 }898 }
857 899
858 #[test]900 #[test]
@@ -891,6 +933,19 @@ mod tests {
891 );933 );
892 }934 }
893 935
936+ #[test]
937+ fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() {
938+ let mut job = fixture_job("true");
939+ let mut limits = Limits::default();
940+ limits.cpus = "0.5".to_owned();
941+ let env = job_env_with_defaults(&job, &limits).expect("env");
942+ assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned())));
943+ job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned());
944+ let env = job_env_with_defaults(&job, &limits).expect("env");
945+ let jobs: Vec<_> = env.iter().filter(|(k, _)| k == "CARGO_BUILD_JOBS").collect();
946+ assert_eq!(jobs, [&("CARGO_BUILD_JOBS".to_owned(), "7".to_owned())]);
947+ }
948+
894 #[test]949 #[test]
895 fn hostile_values_are_refused() {950 fn hostile_values_are_refused() {
896 let ws = Path::new("/w");951 let ws = Path::new("/w");
crates/forge-runner/src/sandbox/helper.rsmodified+6 -0
@@ -77,6 +77,8 @@ struct Layout {
77 bundle: PathBuf,77 bundle: PathBuf,
78 state: PathBuf,78 state: PathBuf,
79 etc: PathBuf,79 etc: PathBuf,
80+ /// Bind mounted at `/tmp`: on the runner's disk, so temp files do not count as job memory.
81+ tmp: PathBuf,
80 upper: PathBuf,82 upper: PathBuf,
81 work: PathBuf,83 work: PathBuf,
82 merged: PathBuf,84 merged: PathBuf,
@@ -90,6 +92,7 @@ impl Layout {
90 bundle: job_dir.join("bundle"),92 bundle: job_dir.join("bundle"),
91 state: job_dir.join("state"),93 state: job_dir.join("state"),
92 etc: job_dir.join("etc"),94 etc: job_dir.join("etc"),
95+ tmp: job_dir.join("tmp"),
93 upper: overlay.join("upper"),96 upper: overlay.join("upper"),
94 work: overlay.join("work"),97 work: overlay.join("work"),
95 merged: overlay.join("merged"),98 merged: overlay.join("merged"),
@@ -220,6 +223,7 @@ fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> {
220 &layout.bundle,223 &layout.bundle,
221 &layout.state,224 &layout.state,
222 &layout.etc,225 &layout.etc,
226+ &layout.tmp,
223 &layout.upper,227 &layout.upper,
224 &layout.work,228 &layout.work,
225 &layout.merged,229 &layout.merged,
@@ -231,6 +235,8 @@ fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> {
231 fs::set_permissions(dir, fs::Permissions::from_mode(0o700))235 fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
232 .map_err(SandboxError::io(format!("cannot chmod {}", dir.display())))?;236 .map_err(SandboxError::io(format!("cannot chmod {}", dir.display())))?;
233 }237 }
238+ fs::set_permissions(&layout.tmp, fs::Permissions::from_mode(0o1777))
239+ .map_err(SandboxError::io(format!("cannot chmod {}", layout.tmp.display())))?;
234 Ok(())240 Ok(())
235 }241 }
236 242
crates/forge-runner/src/sandbox/spec.rsmodified+6 -4
@@ -397,11 +397,13 @@ fn build_mounts(req: &SandboxRequest) -> Result<Vec<Mount>, SandboxError> {
397 &req.workspace,397 &req.workspace,
398 &["rbind", "rw", "nosuid", "nodev"],398 &["rbind", "rw", "nosuid", "nodev"],
399 )?);399 )?);
400- mounts.push(mount(400+ // /tmp is a directory in the job dir, on disk: a tmpfs would charge temp files to the job's
401+ // memory limit, and a test suite that writes many temp repos would be killed for it.
402+ mounts.push(mount_path(
401 "/tmp",403 "/tmp",
402- "tmpfs",404+ "bind",
403- "tmpfs",405+ &req.job_dir.join("tmp"),
404- &["nosuid", "nodev", "mode=1777"],406+ &["rbind", "rw", "nosuid", "nodev"],
405 )?);407 )?);
406 mounts.push(mount_path(408 mounts.push(mount_path(
407 "/etc/hosts",409 "/etc/hosts",
crates/forge-web/src/ci/api.rsmodified+30 -2
@@ -176,11 +176,20 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
176 #[route(POST "/api/v1/ci/runners/claim")]176 #[route(POST "/api/v1/ci/runners/claim")]
177 async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {177 async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
178 let state = app_context::<AppState>(cx);178 let state = app_context::<AppState>(cx);
179- // The labels in the request are ignored: the labels stored at registration are used.179+ // The labels in the request are ignored: the labels stored at registration are used, plus the
180- let runner = match runner_from(state, headers(cx)).await {180+ // arch and OS the runner reports, so `runs_on = ["aarch64"]` needs no admin to type a label.
181+ let mut runner = match runner_from(state, headers(cx)).await {
181 Ok(runner) => runner,182 Ok(runner) => runner,
182 Err(res) => return Ok(*res),183 Err(res) => return Ok(*res),
183 };184 };
185+ let target = headers(cx)
186+ .get(crate::self_update::TARGET_HEADER)
187+ .and_then(|v| v.to_str().ok());
188+ for label in target_labels(target) {
189+ if !runner.labels.contains(&label) {
190+ runner.labels.push(label);
191+ }
192+ }
184 // What the runner says about itself. An older runner sends only labels, and a body that does193 // What the runner says about itself. An older runner sends only labels, and a body that does
185 // not parse is not worth failing a claim over.194 // not parse is not worth failing a claim over.
186 let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {195 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<Response> {
225 Ok(res)234 Ok(res)
226 }235 }
227 236
237+/// The labels a runner's reported `<arch>-<os>` target stands for: the arch, the OS and the whole
238+/// target, such as `x86_64`, `linux` and `x86_64-linux`. Nothing for a missing or odd target.
239+fn target_labels(target: Option<&str>) -> Vec<String> {
240+ let Some(target) = target else {
241+ return Vec::new();
242+ };
243+ let plain = |part: &str| {
244+ !part.is_empty()
245+ && part.len() <= 32
246+ && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
247+ };
248+ match target.split_once('-') {
249+ Some((arch, os)) if plain(arch) && plain(os) => {
250+ vec![arch.to_owned(), os.to_owned(), target.to_owned()]
251+ }
252+ _ => Vec::new(),
253+ }
254+}
255+
228 /// Stores a runner's self report and wakes the admin pages when it changed something.256 /// Stores a runner's self report and wakes the admin pages when it changed something.
229 async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {257 async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
230 match state.store.record_runner_report(runner_id, report).await {258 match state.store.record_runner_report(runner_id, report).await {
docs/ci.mdmodified+10 -1
@@ -53,7 +53,7 @@ There must be at least one job, and at most 20.
53 | `secrets` | array of string | `[]` | Repo secret names, each `^[A-Z_][A-Z0-9_]{0,63}$`. Exported as env vars. |53 | `secrets` | array of string | `[]` | Repo secret names, each `^[A-Z_][A-Z0-9_]{0,63}$`. Exported as env vars. |
54 | `env` | table of string | `{}` | Plain env vars. Names match the same pattern. A secret with the same name wins. |54 | `env` | table of string | `{}` | Plain env vars. Names match the same pattern. A secret with the same name wins. |
55 | `artifacts` | array of string | `[]` | Relative globs in the workspace. No `..`, no leading `/`. |55 | `artifacts` | array of string | `[]` | Relative globs in the workspace. No `..`, no leading `/`. |
56-| `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. |56+| `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. Every runner also has its arch, OS and `<arch>-<os>` as labels, such as `x86_64`, `linux` and `x86_64-linux`. |
57 | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). |57 | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). |
58 | `timeout_minutes` | integer | `60` | Range 1 to 360. |58 | `timeout_minutes` | integer | `60` | Range 1 to 360. |
59 | `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). |59 | `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}$`.
65 The job's workspace is a fresh checkout of the exact commit, at `/workspace`. The job starts in that65 The job's workspace is a fresh checkout of the exact commit, at `/workspace`. The job starts in that
66 directory.66 directory.
67 67
68+### CPUs
69+
70+A job does not decide how parallel its build is; the runner does, since only it knows the machine.
71+It exports `FORGE_CPUS`, the job's CPU limit (`limits.cpus`) rounded up and capped at the host's
72+CPUs, and sets the same number for common build tools: `CARGO_BUILD_JOBS`, `MAKEFLAGS=-jN` and
73+`CMAKE_BUILD_PARALLEL_LEVEL`. The same workflow then builds with `-j1` on a one-core box and `-j32`
74+on a big one. A job that sets one of these in its `env` keeps its own value. Other tools can read
75+`$FORGE_CPUS`, for example `ninja -j"$FORGE_CPUS"`.
76+
68 ### Memory77 ### Memory
69 78
70 `memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a79 `memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a