mirror of
https://github.com/storytold/autocraft.git
synced 2026-12-01 10:33:55 +01:00
Copy the warm target and CARGO_HOME with several cp processes at once
This commit is contained in:
1 parent
96d7887af1
commit
24dec53ff8
3 files changed
+90
-7
No files matched your search
+1
-1
@@ -1197,7 +1197,7 @@ A repository's warm target lets its build pods start from the warm version their
|
||||
For each offline step pod of such a task the runner reads the node's `warm-status-<node>`. The pod starts warm when the status lists the repository's key with the pod's toolchain image and CI env, and the target's rule holds; the task log says which version it starts from, or why it starts cold. The pod mounts the node's claim `craft-warm-<node>` read-only with `subPath: <key>` at `/warm`, runs its steps at the CI checkout paths, and first runs `warm-copy` (AutoCraft image), which:
|
||||
|
||||
1. Resolves `current` once and reads everything from the version dir it names, so a swap by warm-sync during the copy cannot mix versions. Verifies the version's `latest.json` with the public key from the ConfigMap `warm-verify-key` (key `public.pem`, mounted at `/keys/verify`) and the manifest's sha256 against it, and checks that the commit is the one the runner chose and that paths, image, CI env (the gate env, cache version and craft-fonts and craft-i18n commits) and (for `pvc`) Cargo.lock match. Anything else is a cold start, logged.
|
||||
2. Copies the target (`cp -a`), and CARGO_HOME into a dir beside it whose entries then move in with renames, keeping what an earlier step already fetched, and logs `warm copy N GB in X s`. A failed copy leaves neither behind and starts cold. A volume target that already holds a finished copy or a build (a later offline pod of the same task, a rerun) is kept, and a task whose first offline pod started cold stays cold.
|
||||
2. Copies the target and CARGO_HOME with 8 `cp -a` processes at once (the top four directory levels are split into batches of entries; modes, mtimes and symlinks are kept; CARGO_HOME goes into a dir beside it) whose entries then move in with renames, keeping what an earlier step already fetched, and logs `warm copy N GB in X s`. A failed copy leaves neither behind and starts cold. A volume target that already holds a finished copy or a build (a later offline pod of the same task, a rerun) is kept, and a task whose first offline pod started cold stays cold.
|
||||
3. Sets every checkout file's mtime to 2001-01-01 and the files that changed since the warm commit to now, so cargo rebuilds only what changed. It also sets every file of the gate's extra checkouts (`/craft-fonts`, `/craft-i18n`, under the volume's `ext/`) to 2001-01-01, because their path-dependency inputs (such as the font manifest) would otherwise make cargo rebuild every crate that reads them; the warm-copy container does this while the volume is still writable (the steps mount them read-only), and only after the version's env hash, which covers both commits, matched. A cold start leaves all mtimes alone. For a file of the warm commit that the checkout no longer has, the nearest `Cargo.toml` above it and its nearest remaining dir count as changed. The source pod makes that list from a tree-only fetch of the warm commit from GitHub. This needs a version whose manifest is `trimmed`: the producer's publish left out every unit its build did not read, so each unit kept was checked at the warm commit. Without that, or without the list (the fetch failed, more than 5,000 files changed, or the node took a newer version meanwhile), every file counts as changed: correct, but every workspace crate rebuilds.
|
||||
|
||||
**Fetching dependencies.** The workspace pod has no network, so a session that adds a crate or a newer version of one calls `fetch_dependencies` after editing `Cargo.toml` (src/build/workspace-fetch.ts). The job starts a fetch pod (`<workspace pod>-fetch-<call>`, label `craft.build/network=mirror`) on the workspace's volume, at its paths and env without `CARGO_NET_OFFLINE` (with `HOME=/tmp` and no global or system git config), with a build pod's mirror parts: the mirror's CA, `mirror-wait` (30 s) and hostAliases that send crates.io and GitHub to the crate mirror. It runs `cargo fetch` (not `--locked`, `CARGO_NET_RETRY=10`, 10 min limit) in `/work/src` or the `path` given, which updates `Cargo.lock` and `CARGO_HOME` on the volume. The result is the `Cargo.lock` diff against the base commit (`git diff -- ':(glob)**/Cargo.lock'` in the workspace pod, cut at 30 KiB), or the end of cargo's output. A fetch holds all of the session's exec slots, so it waits for the foreground commands running and the session's other calls wait for it (background commands keep running); the launcher's checkpoint waits for it too. A failed read of the pod is retried until the call's deadline. Without the environment's `crateMirror` setting the tool refuses, and a mirror that does not accept connections fails the call: there is no fallback to the public network. The implement prompt mentions the tool only where the environment has a mirror; elsewhere a session that needs a dependency reports blocked. The job deletes the pod when the fetch ends; the launcher's pass deletes a fetch pod whose workspace is no longer ready on the pod it was made for (parked, ended, resumed elsewhere) or that is older than any fetch can take (about 16 min). A runner restart hands the call back to the session, which waits for the same pod.
|
||||
|
||||
+63
-4
@@ -202,13 +202,72 @@ export function copyFailure(stderr: string): string {
|
||||
return `cp: ${lines.slice(-2).join(" ")}`;
|
||||
}
|
||||
|
||||
function cp(from: string, to: string): Promise<void> {
|
||||
/** Copies run at once, directory levels below the root that are split into separate copies, and entries per `cp` call. */
|
||||
export const COPY_PARALLEL = 8;
|
||||
const COPY_SPLIT_DEPTH = 4;
|
||||
const COPY_BATCH = 64;
|
||||
|
||||
function cpRun(args: string[]): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile("cp", ["-a", "--", `${from}/.`, `${to}/`], { timeout: 30 * 60_000, maxBuffer: 1024 * 1024 }, (err, _o, stderr) =>
|
||||
execFile("cp", args, { timeout: 30 * 60_000, maxBuffer: 1024 * 1024 }, (err, _o, stderr) =>
|
||||
err ? reject(new Error(copyFailure(stderr || err.message))) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function attrs(from: string, to: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile("chmod", [`--reference=${from}`, "--", to], (e1) => {
|
||||
if (e1) return reject(e1);
|
||||
execFile("touch", ["-r", from, "--", to], (e2) => (e2 ? reject(e2) : resolve()));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `cp -a from/. to/` (modes, mtimes, symlinks), with COPY_PARALLEL `cp` processes at once: the top COPY_SPLIT_DEPTH
|
||||
* directory levels are created here and their entries copied in batches, and deeper trees are copied whole. Directory
|
||||
* modes and mtimes are set after their contents. The first failure rejects once the running copies end.
|
||||
*/
|
||||
export async function copyTree(from: string, to: string): Promise<void> {
|
||||
const dirs: { from: string; to: string }[] = [];
|
||||
const jobs: string[][] = [];
|
||||
const split = (a: string, b: string, depth: number) => {
|
||||
dirs.push({ from: a, to: b });
|
||||
let batch: string[] = [];
|
||||
const flush = () => {
|
||||
if (batch.length) jobs.push(["-a", "-t", b, "--", ...batch]);
|
||||
batch = [];
|
||||
};
|
||||
for (const e of readdirSync(a, { withFileTypes: true })) {
|
||||
if (e.isDirectory() && depth + 1 < COPY_SPLIT_DEPTH) {
|
||||
mkdirSync(join(b, e.name));
|
||||
split(join(a, e.name), join(b, e.name), depth + 1);
|
||||
continue;
|
||||
}
|
||||
batch.push(join(a, e.name));
|
||||
if (batch.length >= COPY_BATCH) flush();
|
||||
}
|
||||
flush();
|
||||
};
|
||||
mkdirSync(to, { recursive: true });
|
||||
split(from, to, 0);
|
||||
let next = 0;
|
||||
let failure: Error | null = null;
|
||||
const worker = async () => {
|
||||
while (!failure && next < jobs.length) {
|
||||
try {
|
||||
await cpRun(jobs[next++]);
|
||||
} catch (e) {
|
||||
failure ??= e as Error;
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(COPY_PARALLEL, jobs.length) }, worker));
|
||||
if (failure) throw failure;
|
||||
// Deepest first: setting a directory's mtime after its children keeps it.
|
||||
for (const d of dirs.reverse()) await attrs(d.from, d.to);
|
||||
}
|
||||
|
||||
const isEmpty = (d: string) => !existsSync(d) || readdirSync(d).length === 0;
|
||||
/** The names warm-sync gives a version of `commit` (src/warm/sync-agent.ts). */
|
||||
const genOf = (commit: string) => new RegExp(`^gen-${commit.slice(0, 12)}(-[0-9]+)?$`);
|
||||
@@ -297,11 +356,11 @@ export async function warmCopyPhase(work: string, env: NodeJS.ProcessEnv, log: L
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
if (volume) write({ state: "copying", commit });
|
||||
await cp(join(cur, "target"), target);
|
||||
await copyTree(join(cur, "target"), target);
|
||||
// cp -a keeps hard links, and cargo deadlocks on flocks of lock files that share an inode.
|
||||
await removeCargoLocks(target);
|
||||
mkdirSync(cargoTmp, { recursive: true });
|
||||
await cp(join(cur, "cargo"), cargoTmp);
|
||||
await copyTree(join(cur, "cargo"), cargoTmp);
|
||||
} catch (e) {
|
||||
return cold(`copying ${at} failed (${(e as Error).message})`);
|
||||
}
|
||||
|
||||
+26
-2
@@ -2,13 +2,14 @@
|
||||
// unchanged sources to an old mtime only when the version's manifest says its build checked every unit it holds.
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash, generateKeyPairSync } from "node:crypto";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { CHANGED_FILE } from "../src/build/warm-mount.ts";
|
||||
import { encodeManifest, makeHeader, signLatest } from "../src/warm/manifest.ts";
|
||||
import { OLD_MTIME_SEC, setExtMtimes, setMtimes, warmCopyPhase } from "../src/worker/warm-copy.ts";
|
||||
import { OLD_MTIME_SEC, copyTree, setExtMtimes, setMtimes, warmCopyPhase } from "../src/worker/warm-copy.ts";
|
||||
|
||||
const A = "a".repeat(40), B = "b".repeat(40);
|
||||
|
||||
@@ -76,3 +77,26 @@ test("the gate's extra checkouts are set to the old mtime", (t) => {
|
||||
assert.ok(statSync(join(dir, "manifest.txt")).mtimeMs / 1000 <= OLD_MTIME_SEC);
|
||||
assert.equal(setExtMtimes(join(work, "none")), 0);
|
||||
});
|
||||
|
||||
test("the parallel copy of a tree matches cp -a", async (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), "warm-cp-"));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const from = join(root, "from"), to = join(root, "to"), ref = join(root, "ref");
|
||||
const deep = join(from, "debug", "deps", "u1", "a", "b", "c");
|
||||
mkdirSync(deep, { recursive: true });
|
||||
mkdirSync(to);
|
||||
mkdirSync(ref);
|
||||
writeFileSync(join(deep, "empty"), "");
|
||||
for (let i = 0; i < 150; i++) writeFileSync(join(from, "debug", "deps", `f${i}`), String(i));
|
||||
symlinkSync("f1", join(from, "debug", "deps", "link"));
|
||||
chmodSync(join(from, "debug", "deps", "f2"), 0o755);
|
||||
chmodSync(join(from, "debug", "deps"), 0o750);
|
||||
utimesSync(join(from, "debug", "deps", "f3"), 1e9, 1e9);
|
||||
utimesSync(join(from, "debug", "deps"), 1e9, 1e9);
|
||||
await copyTree(from, to);
|
||||
execFileSync("cp", ["-a", `${from}/.`, `${ref}/`]);
|
||||
const listing = (d: string) => execFileSync("find", [d, "-printf", "%P %y %m %T@ %l %s\\n"]).toString().split("\\n").sort().join("\\n");
|
||||
const [x, y] = [listing(to).split("\n"), listing(ref).split("\n")];
|
||||
assert.equal(x.length, y.length);
|
||||
assert.deepEqual(x.filter((l) => !y.includes(l)), y.filter((l) => !x.includes(l)));
|
||||
});
|
||||
Reference in new issue
Block a user