@prestyj/cli 5.36.0 → 5.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/command-routing.d.ts +1 -1
- package/dist/cli/command-routing.js +3 -1
- package/dist/cli/command-routing.js.map +1 -1
- package/dist/cli/fleet.d.ts +6 -0
- package/dist/cli/fleet.js +304 -0
- package/dist/cli/fleet.js.map +1 -0
- package/dist/cli/node.d.ts +5 -0
- package/dist/cli/node.js +308 -0
- package/dist/cli/node.js.map +1 -0
- package/dist/cli/validate.js +31 -7
- package/dist/cli/validate.js.map +1 -1
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-notifications.d.ts +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/agent-session.js +6 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/fleet/browser.d.ts +13 -0
- package/dist/core/fleet/browser.js +50 -0
- package/dist/core/fleet/browser.js.map +1 -0
- package/dist/core/fleet/client.d.ts +70 -0
- package/dist/core/fleet/client.js +240 -0
- package/dist/core/fleet/client.js.map +1 -0
- package/dist/core/fleet/discovery.d.ts +33 -0
- package/dist/core/fleet/discovery.js +82 -0
- package/dist/core/fleet/discovery.js.map +1 -0
- package/dist/core/fleet/fleet-scheduler.d.ts +44 -0
- package/dist/core/fleet/fleet-scheduler.js +108 -0
- package/dist/core/fleet/fleet-scheduler.js.map +1 -0
- package/dist/core/fleet/git.d.ts +32 -0
- package/dist/core/fleet/git.js +113 -0
- package/dist/core/fleet/git.js.map +1 -0
- package/dist/core/fleet/node/agents.d.ts +15 -0
- package/dist/core/fleet/node/agents.js +461 -0
- package/dist/core/fleet/node/agents.js.map +1 -0
- package/dist/core/fleet/node/config.d.ts +52 -0
- package/dist/core/fleet/node/config.js +191 -0
- package/dist/core/fleet/node/config.js.map +1 -0
- package/dist/core/fleet/node/context.d.ts +43 -0
- package/dist/core/fleet/node/context.js +2 -0
- package/dist/core/fleet/node/context.js.map +1 -0
- package/dist/core/fleet/node/docker.d.ts +23 -0
- package/dist/core/fleet/node/docker.js +214 -0
- package/dist/core/fleet/node/docker.js.map +1 -0
- package/dist/core/fleet/node/exec.d.ts +24 -0
- package/dist/core/fleet/node/exec.js +64 -0
- package/dist/core/fleet/node/exec.js.map +1 -0
- package/dist/core/fleet/node/info.d.ts +36 -0
- package/dist/core/fleet/node/info.js +209 -0
- package/dist/core/fleet/node/info.js.map +1 -0
- package/dist/core/fleet/node/jobs.d.ts +88 -0
- package/dist/core/fleet/node/jobs.js +702 -0
- package/dist/core/fleet/node/jobs.js.map +1 -0
- package/dist/core/fleet/node/server.d.ts +37 -0
- package/dist/core/fleet/node/server.js +416 -0
- package/dist/core/fleet/node/server.js.map +1 -0
- package/dist/core/fleet/node/services.d.ts +71 -0
- package/dist/core/fleet/node/services.js +532 -0
- package/dist/core/fleet/node/services.js.map +1 -0
- package/dist/core/fleet/node/state.d.ts +48 -0
- package/dist/core/fleet/node/state.js +43 -0
- package/dist/core/fleet/node/state.js.map +1 -0
- package/dist/core/fleet/node/workspace.d.ts +41 -0
- package/dist/core/fleet/node/workspace.js +153 -0
- package/dist/core/fleet/node/workspace.js.map +1 -0
- package/dist/core/fleet/project-config.d.ts +52 -0
- package/dist/core/fleet/project-config.js +449 -0
- package/dist/core/fleet/project-config.js.map +1 -0
- package/dist/core/fleet/protocol.d.ts +225 -0
- package/dist/core/fleet/protocol.js +11 -0
- package/dist/core/fleet/protocol.js.map +1 -0
- package/dist/core/fleet/registry.d.ts +34 -0
- package/dist/core/fleet/registry.js +79 -0
- package/dist/core/fleet/registry.js.map +1 -0
- package/dist/core/fleet/remote-agent-nodes.d.ts +31 -0
- package/dist/core/fleet/remote-agent-nodes.js +96 -0
- package/dist/core/fleet/remote-agent-nodes.js.map +1 -0
- package/dist/core/fleet/remote-agent.d.ts +115 -0
- package/dist/core/fleet/remote-agent.js +590 -0
- package/dist/core/fleet/remote-agent.js.map +1 -0
- package/dist/core/fleet/service.d.ts +185 -0
- package/dist/core/fleet/service.js +1140 -0
- package/dist/core/fleet/service.js.map +1 -0
- package/dist/core/fleet/session-hook.d.ts +3 -0
- package/dist/core/fleet/session-hook.js +45 -0
- package/dist/core/fleet/session-hook.js.map +1 -0
- package/dist/core/fleet/store.d.ts +37 -0
- package/dist/core/fleet/store.js +115 -0
- package/dist/core/fleet/store.js.map +1 -0
- package/dist/core/fleet/types.d.ts +88 -0
- package/dist/core/fleet/types.js +16 -0
- package/dist/core/fleet/types.js.map +1 -0
- package/dist/core/mcp/store.d.ts +2 -2
- package/dist/core/subagent-manager.d.ts +39 -0
- package/dist/core/subagent-manager.js +67 -7
- package/dist/core/subagent-manager.js.map +1 -1
- package/dist/core/validation/backends.d.ts +5 -2
- package/dist/core/validation/backends.js +17 -1
- package/dist/core/validation/backends.js.map +1 -1
- package/dist/core/validation/config.d.ts +10 -2
- package/dist/core/validation/config.js +30 -3
- package/dist/core/validation/config.js.map +1 -1
- package/dist/core/validation/exec.js +6 -1
- package/dist/core/validation/exec.js.map +1 -1
- package/dist/core/validation/github-actions-backend.d.ts +49 -2
- package/dist/core/validation/github-actions-backend.js +257 -3
- package/dist/core/validation/github-actions-backend.js.map +1 -1
- package/dist/core/validation/node-backend.d.ts +56 -0
- package/dist/core/validation/node-backend.js +184 -0
- package/dist/core/validation/node-backend.js.map +1 -0
- package/dist/core/validation/scheduler.d.ts +38 -0
- package/dist/core/validation/scheduler.js +133 -0
- package/dist/core/validation/scheduler.js.map +1 -0
- package/dist/core/validation/service.d.ts +53 -3
- package/dist/core/validation/service.js +272 -56
- package/dist/core/validation/service.js.map +1 -1
- package/dist/core/validation/session-hook.js +9 -2
- package/dist/core/validation/session-hook.js.map +1 -1
- package/dist/core/validation/types.d.ts +52 -1
- package/dist/core/validation/types.js +2 -0
- package/dist/core/validation/types.js.map +1 -1
- package/dist/tools/browser-session.d.ts +24 -1
- package/dist/tools/browser-session.js +31 -10
- package/dist/tools/browser-session.js.map +1 -1
- package/dist/tools/fleet.d.ts +26 -0
- package/dist/tools/fleet.js +144 -0
- package/dist/tools/fleet.js.map +1 -0
- package/dist/tools/index.js +6 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/prompt-hints.js +2 -0
- package/dist/tools/prompt-hints.js.map +1 -1
- package/dist/tools/steroids.d.ts +1 -1
- package/dist/tools/subagent-control.js +10 -1
- package/dist/tools/subagent-control.js.map +1 -1
- package/dist/tools/tasks.d.ts +1 -1
- package/dist/tools/tool-tiers.js +1 -0
- package/dist/tools/tool-tiers.js.map +1 -1
- package/dist/tools/validate.js +4 -5
- package/dist/tools/validate.js.map +1 -1
- package/package.json +7 -5
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
// Jobs on a fleet node: one command per job in its own workspace, run by a
|
|
2
|
+
// detached shell wrapper (exit file, pid, timeout) so it keeps going — and its
|
|
3
|
+
// result is still collected — if the node restarts meanwhile. Host shell or
|
|
4
|
+
// Docker (image / Dockerfile / compose). Artifacts are copied out by glob when
|
|
5
|
+
// the job ends, then the workspace is removed.
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import fg from "fast-glob";
|
|
10
|
+
import { readSecrets } from "./config.js";
|
|
11
|
+
import { containerCacheEnv, containerName, envFlags, FLEET_LABEL, hostCacheEnv, isValidEnvName, resourceArgs, validateDockerArgs, validateDockerSpec, } from "./docker.js";
|
|
12
|
+
import { isSafeId, pidAlive, shQuote } from "./exec.js";
|
|
13
|
+
import { cacheDir, cleanupWorkspace, isRealPathInside, prepareWorkspaceDetailed, resolveInside, sanitizeCacheKey, workspaceRoot, } from "./workspace.js";
|
|
14
|
+
const WRAPPER = `
|
|
15
|
+
set -m
|
|
16
|
+
cd "$EZF_CWD" || { echo 127 > "$EZF_DIR/exit"; exit; }
|
|
17
|
+
( eval "$EZF_CMD" ) >> "$EZF_DIR/output.log" 2>&1 < /dev/null &
|
|
18
|
+
p=$!
|
|
19
|
+
echo $p > "$EZF_DIR/pid"
|
|
20
|
+
( sleep "$EZF_TIMEOUT"; echo timeout > "$EZF_DIR/timeout"; kill -TERM -- -$p 2>/dev/null; sleep "$EZF_GRACE"; kill -KILL -- -$p 2>/dev/null ) &
|
|
21
|
+
w=$!
|
|
22
|
+
wait $p; c=$?
|
|
23
|
+
kill -- -$w 2>/dev/null || kill $w 2>/dev/null
|
|
24
|
+
echo $c > "$EZF_DIR/exit.tmp" && mv "$EZF_DIR/exit.tmp" "$EZF_DIR/exit"
|
|
25
|
+
`;
|
|
26
|
+
const JOB_KINDS = new Set([
|
|
27
|
+
"validate",
|
|
28
|
+
"build",
|
|
29
|
+
"test",
|
|
30
|
+
"browser",
|
|
31
|
+
"render",
|
|
32
|
+
"deploy",
|
|
33
|
+
"custom",
|
|
34
|
+
]);
|
|
35
|
+
const TERMINAL = new Set([
|
|
36
|
+
"passed",
|
|
37
|
+
"failed",
|
|
38
|
+
"error",
|
|
39
|
+
"cancelled",
|
|
40
|
+
"lost",
|
|
41
|
+
]);
|
|
42
|
+
const KEEP_DAYS = 14;
|
|
43
|
+
const MAX_ARTIFACT_FILES = 5000;
|
|
44
|
+
const MAX_ARTIFACT_BYTES = 10 * 1024 ** 3;
|
|
45
|
+
const MAX_LOG_CHUNK = 8 * 1024 * 1024;
|
|
46
|
+
export function isTerminalJob(state) {
|
|
47
|
+
return TERMINAL.has(state);
|
|
48
|
+
}
|
|
49
|
+
const err = (status, error) => ({ status, body: { error } });
|
|
50
|
+
export class JobManager {
|
|
51
|
+
opts;
|
|
52
|
+
cfg;
|
|
53
|
+
state;
|
|
54
|
+
exec;
|
|
55
|
+
slots;
|
|
56
|
+
log;
|
|
57
|
+
timer;
|
|
58
|
+
finalizing = new Set();
|
|
59
|
+
grace;
|
|
60
|
+
constructor(opts) {
|
|
61
|
+
this.opts = opts;
|
|
62
|
+
this.cfg = opts.config;
|
|
63
|
+
this.state = opts.state;
|
|
64
|
+
this.exec = opts.exec;
|
|
65
|
+
this.slots = opts.slots;
|
|
66
|
+
this.log = opts.log ?? (() => { });
|
|
67
|
+
this.grace = opts.killGraceSeconds ?? 10;
|
|
68
|
+
}
|
|
69
|
+
// ── paths ──────────────────────────────────────────────────────────────
|
|
70
|
+
runDir(id) {
|
|
71
|
+
return path.join(this.cfg.dataDir, "run", id);
|
|
72
|
+
}
|
|
73
|
+
artifactsDir(id) {
|
|
74
|
+
return path.join(this.cfg.dataDir, "artifacts", id);
|
|
75
|
+
}
|
|
76
|
+
logFile(id) {
|
|
77
|
+
return path.join(this.runDir(id), "output.log");
|
|
78
|
+
}
|
|
79
|
+
records() {
|
|
80
|
+
return this.state.data.jobs;
|
|
81
|
+
}
|
|
82
|
+
find(id) {
|
|
83
|
+
return this.records().find((r) => r.status.id === id);
|
|
84
|
+
}
|
|
85
|
+
// ── lifecycle ──────────────────────────────────────────────────────────
|
|
86
|
+
/** Re-adopt jobs from the previous node process, prune old ones, start polling. */
|
|
87
|
+
async init() {
|
|
88
|
+
const rebooted = this.state.rebooted();
|
|
89
|
+
const cutoff = Date.now() - KEEP_DAYS * 86_400_000;
|
|
90
|
+
for (const rec of [...this.records()]) {
|
|
91
|
+
const s = rec.status;
|
|
92
|
+
if (isTerminalJob(s.state)) {
|
|
93
|
+
if (s.finishedAt && Date.parse(s.finishedAt) < cutoff)
|
|
94
|
+
this.removeFiles(rec, true);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (s.state === "preparing") {
|
|
98
|
+
await this.finalize(rec, "lost", undefined, "the node restarted while preparing the workspace");
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (fs.existsSync(path.join(this.runDir(s.id), "exit"))) {
|
|
102
|
+
await this.collect(rec);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (!rebooted && pidAlive(rec.wrapperPid)) {
|
|
106
|
+
this.slots.acquire(s.id, true);
|
|
107
|
+
this.log(`job ${s.id}: re-adopted (pid ${rec.wrapperPid})`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (rec.docker && (await this.containerRunning(s.id))) {
|
|
111
|
+
this.slots.acquire(s.id, true);
|
|
112
|
+
this.reattachContainer(rec);
|
|
113
|
+
this.log(`job ${s.id}: re-adopted container ${containerName(s.id)}`);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
await this.finalize(rec, "lost", undefined, "the node restarted and the job could not be re-adopted");
|
|
117
|
+
}
|
|
118
|
+
this.state.data.jobs = this.records().filter((r) => !(isTerminalJob(r.status.state) &&
|
|
119
|
+
r.status.finishedAt &&
|
|
120
|
+
Date.parse(r.status.finishedAt) < cutoff));
|
|
121
|
+
this.state.save();
|
|
122
|
+
this.timer = setInterval(() => void this.pollAll(), this.opts.pollMs ?? 1000);
|
|
123
|
+
this.timer.unref();
|
|
124
|
+
}
|
|
125
|
+
/** Stop polling. Running jobs keep going (detached) and are re-adopted next start. */
|
|
126
|
+
close() {
|
|
127
|
+
if (this.timer)
|
|
128
|
+
clearInterval(this.timer);
|
|
129
|
+
this.timer = undefined;
|
|
130
|
+
}
|
|
131
|
+
list() {
|
|
132
|
+
return this.records().map((r) => this.status(r));
|
|
133
|
+
}
|
|
134
|
+
get(id) {
|
|
135
|
+
const rec = this.find(id);
|
|
136
|
+
return rec && this.status(rec);
|
|
137
|
+
}
|
|
138
|
+
running() {
|
|
139
|
+
return this.records().filter((r) => !isTerminalJob(r.status.state)).length;
|
|
140
|
+
}
|
|
141
|
+
status(rec) {
|
|
142
|
+
let logBytes = rec.status.logBytes;
|
|
143
|
+
try {
|
|
144
|
+
logBytes = fs.statSync(this.logFile(rec.status.id)).size;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// no log yet / purged
|
|
148
|
+
}
|
|
149
|
+
return { ...rec.status, logBytes };
|
|
150
|
+
}
|
|
151
|
+
// ── submit ─────────────────────────────────────────────────────────────
|
|
152
|
+
validate(req) {
|
|
153
|
+
if (!req || typeof req !== "object")
|
|
154
|
+
return "body must be a JobRequest";
|
|
155
|
+
if (!isSafeId(req.id))
|
|
156
|
+
return "invalid job id";
|
|
157
|
+
if (!JOB_KINDS.has(req.kind))
|
|
158
|
+
return `invalid job kind: ${String(req.kind)}`;
|
|
159
|
+
if (typeof req.project !== "string" || !req.project)
|
|
160
|
+
return "project is required";
|
|
161
|
+
if (typeof req.command !== "string" || !req.command.trim())
|
|
162
|
+
return "command is required";
|
|
163
|
+
if (typeof req.timeoutMinutes !== "number" ||
|
|
164
|
+
!(req.timeoutMinutes > 0) ||
|
|
165
|
+
req.timeoutMinutes > 7 * 24 * 60) {
|
|
166
|
+
return "timeoutMinutes must be between 0 and 10080";
|
|
167
|
+
}
|
|
168
|
+
for (const [k, v] of Object.entries(req.env ?? {})) {
|
|
169
|
+
if (!isValidEnvName(k) || typeof v !== "string")
|
|
170
|
+
return `invalid env var: ${k}`;
|
|
171
|
+
}
|
|
172
|
+
for (const s of req.secrets ?? [])
|
|
173
|
+
if (!isValidEnvName(s))
|
|
174
|
+
return `invalid secret name: ${s}`;
|
|
175
|
+
for (const g of req.artifacts ?? []) {
|
|
176
|
+
if (typeof g !== "string" || path.isAbsolute(g) || g.split(/[\\/]/).includes("..")) {
|
|
177
|
+
return `invalid artifact glob: ${String(g)}`;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (req.docker) {
|
|
181
|
+
const e = validateDockerSpec(req.docker, this.cfg.dataDir);
|
|
182
|
+
if (e)
|
|
183
|
+
return e;
|
|
184
|
+
}
|
|
185
|
+
if (req.source && (typeof req.source.git !== "string" || typeof req.source.sha !== "string")) {
|
|
186
|
+
return "source needs git and sha";
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
async submit(req) {
|
|
191
|
+
const existing = req && isSafeId(req.id) ? this.find(req.id) : undefined;
|
|
192
|
+
if (existing)
|
|
193
|
+
return { status: 200, body: this.status(existing) };
|
|
194
|
+
const invalid = this.validate(req);
|
|
195
|
+
if (invalid)
|
|
196
|
+
return err(400, invalid);
|
|
197
|
+
let secrets = {};
|
|
198
|
+
if (req.secrets?.length) {
|
|
199
|
+
if (!this.cfg.labels.includes("deploy")) {
|
|
200
|
+
return err(403, "this node is not labelled 'deploy' and does not accept jobs with secrets");
|
|
201
|
+
}
|
|
202
|
+
const all = readSecrets(this.cfg.dataDir);
|
|
203
|
+
const missing = req.secrets.filter((n) => !(n in all));
|
|
204
|
+
if (missing.length)
|
|
205
|
+
return err(400, `secret not set on this node: ${missing.join(", ")}`);
|
|
206
|
+
secrets = Object.fromEntries(req.secrets.map((n) => [n, all[n]]));
|
|
207
|
+
}
|
|
208
|
+
const needLabels = (req.resources?.labels ?? []).filter((l) => !this.cfg.labels.includes(l) && l !== "gpu");
|
|
209
|
+
if (needLabels.length)
|
|
210
|
+
return err(409, `node lacks labels: ${needLabels.join(", ")}`);
|
|
211
|
+
if (req.docker && this.opts.dockerAvailable && !(await this.opts.dockerAvailable())) {
|
|
212
|
+
return err(409, "docker is not available on this node");
|
|
213
|
+
}
|
|
214
|
+
if (!this.slots.acquire(req.id))
|
|
215
|
+
return err(429, "all slots are busy");
|
|
216
|
+
const rec = {
|
|
217
|
+
status: {
|
|
218
|
+
id: req.id,
|
|
219
|
+
kind: req.kind,
|
|
220
|
+
project: req.project,
|
|
221
|
+
state: "preparing",
|
|
222
|
+
startedAt: new Date().toISOString(),
|
|
223
|
+
logBytes: 0,
|
|
224
|
+
},
|
|
225
|
+
timeoutMinutes: req.timeoutMinutes,
|
|
226
|
+
docker: req.docker,
|
|
227
|
+
artifactGlobs: req.artifacts,
|
|
228
|
+
};
|
|
229
|
+
this.records().push(rec);
|
|
230
|
+
this.state.save();
|
|
231
|
+
fs.rmSync(this.runDir(req.id), { recursive: true, force: true });
|
|
232
|
+
fs.rmSync(this.artifactsDir(req.id), { recursive: true, force: true });
|
|
233
|
+
fs.mkdirSync(this.runDir(req.id), { recursive: true });
|
|
234
|
+
void this.start(rec, req, secrets);
|
|
235
|
+
return { status: 201, body: this.status(rec) };
|
|
236
|
+
}
|
|
237
|
+
appendLog(id, line) {
|
|
238
|
+
try {
|
|
239
|
+
fs.appendFileSync(this.logFile(id), line.endsWith("\n") ? line : line + "\n");
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// purged meanwhile
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async start(rec, req, secrets) {
|
|
246
|
+
const id = req.id;
|
|
247
|
+
try {
|
|
248
|
+
if (req.source)
|
|
249
|
+
this.appendLog(id, `[ezcoder node] preparing ${req.source.git} @ ${req.source.sha}`);
|
|
250
|
+
const ws = await (this.opts.prepare
|
|
251
|
+
? this.opts.prepare("job", id, req.source)
|
|
252
|
+
: prepareWorkspaceDetailed({
|
|
253
|
+
dataDir: this.cfg.dataDir,
|
|
254
|
+
kind: "job",
|
|
255
|
+
id,
|
|
256
|
+
source: req.source,
|
|
257
|
+
exec: this.exec,
|
|
258
|
+
}));
|
|
259
|
+
rec.root = ws.root;
|
|
260
|
+
rec.cwd = ws.cwd;
|
|
261
|
+
rec.subdir = ws.subdir;
|
|
262
|
+
if (this.find(id) !== rec) {
|
|
263
|
+
cleanupWorkspace(this.cfg.dataDir, "job", id); // purged while preparing
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (rec.cancelRequested) {
|
|
267
|
+
await this.finalize(rec, "cancelled", undefined, "cancelled before start");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (req.docker) {
|
|
271
|
+
// Re-check host mounts now that the workspace (and any symlinks in it) exists.
|
|
272
|
+
const argsErr = validateDockerArgs(req.docker.args, this.cfg.dataDir);
|
|
273
|
+
if (argsErr)
|
|
274
|
+
throw new Error(argsErr);
|
|
275
|
+
for (const p of [req.docker.dockerfile, req.docker.compose]) {
|
|
276
|
+
if (p && !isRealPathInside(ws.root, path.join(ws.cwd, p)))
|
|
277
|
+
throw new Error(`docker paths must stay inside the workspace: ${p}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
this.launch(rec, req, secrets);
|
|
281
|
+
}
|
|
282
|
+
catch (e) {
|
|
283
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
284
|
+
this.appendLog(id, `[ezcoder node] ${msg}`);
|
|
285
|
+
await this.finalize(rec, "error", undefined, msg.split("\n")[0].slice(0, 300));
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/** The shell command for the job (host or docker) and the env the wrapper needs. */
|
|
289
|
+
buildCommand(req, ws, secrets = {}) {
|
|
290
|
+
const cache = cacheDir(this.cfg.dataDir, sanitizeCacheKey(req.cacheKey ?? req.project));
|
|
291
|
+
const userEnv = { ...(req.env ?? {}), ...secrets };
|
|
292
|
+
const d = req.docker;
|
|
293
|
+
if (!d)
|
|
294
|
+
return { command: req.command, env: { ...hostCacheEnv(cache), ...userEnv } };
|
|
295
|
+
const id = req.id;
|
|
296
|
+
const name = containerName(id);
|
|
297
|
+
const label = `${FLEET_LABEL}=${id}`;
|
|
298
|
+
const cEnv = { ...containerCacheEnv(), ...userEnv };
|
|
299
|
+
const flags = envFlags(Object.keys(cEnv));
|
|
300
|
+
const entry = d.entrypoint ?? "sh";
|
|
301
|
+
const q = (parts) => parts.map(shQuote).join(" ");
|
|
302
|
+
if (d.compose && d.service) {
|
|
303
|
+
const file = path.join(ws.cwd, d.compose);
|
|
304
|
+
const base = ["docker", "compose", "-p", name, "-f", file];
|
|
305
|
+
const run = q([
|
|
306
|
+
...base,
|
|
307
|
+
"run",
|
|
308
|
+
"--rm",
|
|
309
|
+
"-T",
|
|
310
|
+
"--label",
|
|
311
|
+
label,
|
|
312
|
+
"-v",
|
|
313
|
+
`${cache}:/cache`,
|
|
314
|
+
...flags,
|
|
315
|
+
"--entrypoint",
|
|
316
|
+
entry,
|
|
317
|
+
d.service,
|
|
318
|
+
"-c",
|
|
319
|
+
req.command,
|
|
320
|
+
]);
|
|
321
|
+
return {
|
|
322
|
+
command: `export COMPOSE_PROJECT_NAME=${name}; ${run}; c=$?; ${q([...base, "down", "-v", "--remove-orphans"])} >/dev/null 2>&1; exit $c`,
|
|
323
|
+
env: { ...cEnv, COMPOSE_PROJECT_NAME: name },
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
const workdir = ws.subdir ? `/w/${ws.subdir}` : "/w";
|
|
327
|
+
const image = d.image ?? name;
|
|
328
|
+
const runArgs = [
|
|
329
|
+
"docker",
|
|
330
|
+
"run",
|
|
331
|
+
"--rm",
|
|
332
|
+
"--name",
|
|
333
|
+
name,
|
|
334
|
+
"--label",
|
|
335
|
+
label,
|
|
336
|
+
"-v",
|
|
337
|
+
`${ws.root}:/w`,
|
|
338
|
+
"-w",
|
|
339
|
+
workdir,
|
|
340
|
+
"-v",
|
|
341
|
+
`${cache}:/cache`,
|
|
342
|
+
...flags,
|
|
343
|
+
...(d.gpu ? ["--gpus", "all"] : []),
|
|
344
|
+
...resourceArgs(req.resources),
|
|
345
|
+
...(d.args ?? []),
|
|
346
|
+
"--entrypoint",
|
|
347
|
+
entry,
|
|
348
|
+
image,
|
|
349
|
+
"-c",
|
|
350
|
+
req.command,
|
|
351
|
+
];
|
|
352
|
+
let command = q(runArgs);
|
|
353
|
+
if (!d.image && d.dockerfile) {
|
|
354
|
+
const build = q([
|
|
355
|
+
"docker",
|
|
356
|
+
"build",
|
|
357
|
+
"-t",
|
|
358
|
+
name,
|
|
359
|
+
"--label",
|
|
360
|
+
label,
|
|
361
|
+
"-f",
|
|
362
|
+
path.join(ws.cwd, d.dockerfile),
|
|
363
|
+
ws.cwd,
|
|
364
|
+
]);
|
|
365
|
+
command = `${build} && ${command}`;
|
|
366
|
+
}
|
|
367
|
+
return { command, env: cEnv };
|
|
368
|
+
}
|
|
369
|
+
launch(rec, req, secrets) {
|
|
370
|
+
const ws = { root: rec.root, cwd: rec.cwd, subdir: rec.subdir ?? "" };
|
|
371
|
+
const { command, env } = this.buildCommand(req, ws, secrets);
|
|
372
|
+
const unit = this.opts.secondsPerMinute ?? 60;
|
|
373
|
+
const child = spawn("bash", ["-c", WRAPPER], {
|
|
374
|
+
detached: true,
|
|
375
|
+
stdio: "ignore",
|
|
376
|
+
cwd: ws.cwd,
|
|
377
|
+
env: {
|
|
378
|
+
...process.env,
|
|
379
|
+
...env,
|
|
380
|
+
CI: "1",
|
|
381
|
+
EZF_CWD: ws.cwd,
|
|
382
|
+
EZF_CMD: command,
|
|
383
|
+
EZF_DIR: this.runDir(req.id),
|
|
384
|
+
EZF_TIMEOUT: String(Math.max(1, Math.round(req.timeoutMinutes * unit))),
|
|
385
|
+
EZF_GRACE: String(this.grace),
|
|
386
|
+
},
|
|
387
|
+
});
|
|
388
|
+
child.on("error", (e) => {
|
|
389
|
+
this.appendLog(req.id, `[ezcoder node] could not start: ${e.message}`);
|
|
390
|
+
void this.finalize(rec, "error", undefined, e.message);
|
|
391
|
+
});
|
|
392
|
+
child.unref();
|
|
393
|
+
rec.wrapperPid = child.pid;
|
|
394
|
+
rec.status.state = "running";
|
|
395
|
+
rec.status.startedAt = new Date().toISOString();
|
|
396
|
+
this.state.save();
|
|
397
|
+
this.log(`job ${req.id}: running (${req.docker ? "docker" : "host"})`);
|
|
398
|
+
}
|
|
399
|
+
/** After a restart: a container still runs but its wrapper is gone; wait on the container. */
|
|
400
|
+
reattachContainer(rec) {
|
|
401
|
+
const id = rec.status.id;
|
|
402
|
+
const name = containerName(id);
|
|
403
|
+
const started = Date.parse(rec.status.startedAt ?? "") || Date.now();
|
|
404
|
+
const left = Math.max(60, Math.round((started + rec.timeoutMinutes * 60_000 - Date.now()) / 1000));
|
|
405
|
+
fs.mkdirSync(this.runDir(id), { recursive: true });
|
|
406
|
+
const cmd = `docker logs -f --since 1s ${shQuote(name)} & l=$!; c=$(docker wait ${shQuote(name)}); kill $l 2>/dev/null; exit \${c:-1}`;
|
|
407
|
+
const child = spawn("bash", ["-c", WRAPPER], {
|
|
408
|
+
detached: true,
|
|
409
|
+
stdio: "ignore",
|
|
410
|
+
env: {
|
|
411
|
+
...process.env,
|
|
412
|
+
EZF_CWD: rec.cwd && fs.existsSync(rec.cwd) ? rec.cwd : this.runDir(id),
|
|
413
|
+
EZF_CMD: cmd,
|
|
414
|
+
EZF_DIR: this.runDir(id),
|
|
415
|
+
EZF_TIMEOUT: String(left),
|
|
416
|
+
EZF_GRACE: String(this.grace),
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
child.on("error", () => { });
|
|
420
|
+
child.unref();
|
|
421
|
+
rec.wrapperPid = child.pid;
|
|
422
|
+
}
|
|
423
|
+
// ── polling / finalize ─────────────────────────────────────────────────
|
|
424
|
+
async pollAll() {
|
|
425
|
+
for (const rec of [...this.records()]) {
|
|
426
|
+
if (rec.status.state !== "running")
|
|
427
|
+
continue;
|
|
428
|
+
const id = rec.status.id;
|
|
429
|
+
if (fs.existsSync(path.join(this.runDir(id), "exit"))) {
|
|
430
|
+
await this.collect(rec);
|
|
431
|
+
}
|
|
432
|
+
else if (rec.wrapperPid && !pidAlive(rec.wrapperPid)) {
|
|
433
|
+
// Wrapper gone without writing an exit file (killed / crashed).
|
|
434
|
+
await this.finalize(rec, fs.existsSync(path.join(this.runDir(id), "cancelled")) ? "cancelled" : "error", undefined, "the job runner stopped without a result");
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
readText(file) {
|
|
439
|
+
try {
|
|
440
|
+
return fs.readFileSync(file, "utf8").trim();
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
return undefined;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
async collect(rec) {
|
|
447
|
+
const dir = this.runDir(rec.status.id);
|
|
448
|
+
const code = Number(this.readText(path.join(dir, "exit")) ?? "1");
|
|
449
|
+
if (fs.existsSync(path.join(dir, "cancelled"))) {
|
|
450
|
+
await this.finalize(rec, "cancelled", code, "cancelled");
|
|
451
|
+
}
|
|
452
|
+
else if (this.readText(path.join(dir, "timeout"))) {
|
|
453
|
+
await this.finalize(rec, "failed", code, `timed out after ${rec.timeoutMinutes} min`);
|
|
454
|
+
}
|
|
455
|
+
else if (code === 0) {
|
|
456
|
+
await this.finalize(rec, "passed", 0);
|
|
457
|
+
}
|
|
458
|
+
else {
|
|
459
|
+
await this.finalize(rec, "failed", code, `exited ${code}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
async finalize(rec, state, exitCode, summary) {
|
|
463
|
+
const id = rec.status.id;
|
|
464
|
+
if (this.finalizing.has(id) || isTerminalJob(rec.status.state))
|
|
465
|
+
return;
|
|
466
|
+
this.finalizing.add(id);
|
|
467
|
+
try {
|
|
468
|
+
if (rec.docker)
|
|
469
|
+
await this.dockerCleanup(rec);
|
|
470
|
+
if (rec.cwd && rec.artifactGlobs?.length && fs.existsSync(rec.cwd)) {
|
|
471
|
+
try {
|
|
472
|
+
rec.status.artifacts = await this.collectArtifacts(id, rec.cwd, rec.artifactGlobs);
|
|
473
|
+
}
|
|
474
|
+
catch (e) {
|
|
475
|
+
this.appendLog(id, `[ezcoder node] artifact collection failed: ${e.message}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
cleanupWorkspace(this.cfg.dataDir, "job", id);
|
|
480
|
+
}
|
|
481
|
+
catch (e) {
|
|
482
|
+
this.log(`job ${id}: workspace cleanup failed: ${e.message}`);
|
|
483
|
+
}
|
|
484
|
+
rec.status.state = state;
|
|
485
|
+
if (exitCode !== undefined && Number.isFinite(exitCode))
|
|
486
|
+
rec.status.exitCode = exitCode;
|
|
487
|
+
if (summary)
|
|
488
|
+
rec.status.summary = summary;
|
|
489
|
+
rec.status.finishedAt = new Date().toISOString();
|
|
490
|
+
rec.status.logBytes = this.status(rec).logBytes;
|
|
491
|
+
rec.wrapperPid = undefined;
|
|
492
|
+
this.slots.release(id);
|
|
493
|
+
if (this.find(id))
|
|
494
|
+
this.state.save();
|
|
495
|
+
this.log(`job ${id}: ${state}${summary ? ` (${summary})` : ""}`);
|
|
496
|
+
}
|
|
497
|
+
finally {
|
|
498
|
+
this.finalizing.delete(id);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
async containerRunning(id) {
|
|
502
|
+
const r = await this.exec("docker", ["ps", "-q", "--filter", `label=${FLEET_LABEL}=${id}`], {
|
|
503
|
+
timeoutMs: 15_000,
|
|
504
|
+
});
|
|
505
|
+
return r.code === 0 && r.stdout.trim().length > 0;
|
|
506
|
+
}
|
|
507
|
+
async dockerCleanup(rec) {
|
|
508
|
+
const id = rec.status.id;
|
|
509
|
+
await this.reclaimWorkspace(rec);
|
|
510
|
+
const ps = await this.exec("docker", ["ps", "-aq", "--filter", `label=${FLEET_LABEL}=${id}`], {
|
|
511
|
+
timeoutMs: 15_000,
|
|
512
|
+
});
|
|
513
|
+
const ids = ps.code === 0 ? ps.stdout.split(/\s+/).filter(Boolean) : [];
|
|
514
|
+
if (ids.length)
|
|
515
|
+
await this.exec("docker", ["rm", "-f", ...ids], { timeoutMs: 60_000 });
|
|
516
|
+
if (rec.docker?.compose && rec.cwd) {
|
|
517
|
+
await this.exec("docker", [
|
|
518
|
+
"compose",
|
|
519
|
+
"-p",
|
|
520
|
+
containerName(id),
|
|
521
|
+
"-f",
|
|
522
|
+
path.join(rec.cwd, rec.docker.compose),
|
|
523
|
+
"down",
|
|
524
|
+
"-v",
|
|
525
|
+
"--remove-orphans",
|
|
526
|
+
], { timeoutMs: 120_000, cwd: fs.existsSync(rec.cwd) ? rec.cwd : undefined });
|
|
527
|
+
}
|
|
528
|
+
if (!rec.docker?.image && rec.docker?.dockerfile) {
|
|
529
|
+
await this.exec("docker", ["rmi", "-f", containerName(id)], { timeoutMs: 60_000 });
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Containers often run as root, so files they write into the mounted
|
|
534
|
+
* workspace can't be read or removed by the node's user afterwards. Hand
|
|
535
|
+
* them back (Linux only; Docker Desktop on macOS maps ownership itself).
|
|
536
|
+
*/
|
|
537
|
+
async reclaimWorkspace(rec) {
|
|
538
|
+
if (process.platform !== "linux" || typeof process.getuid !== "function")
|
|
539
|
+
return;
|
|
540
|
+
const uid = process.getuid();
|
|
541
|
+
const gid = process.getgid?.() ?? uid;
|
|
542
|
+
if (uid === 0)
|
|
543
|
+
return;
|
|
544
|
+
const root = workspaceRoot(this.cfg.dataDir, "job", rec.status.id);
|
|
545
|
+
if (!fs.existsSync(root))
|
|
546
|
+
return;
|
|
547
|
+
const owner = `${uid}:${gid}`;
|
|
548
|
+
const run = (image) => this.exec("docker", [
|
|
549
|
+
"run",
|
|
550
|
+
"--rm",
|
|
551
|
+
"--network",
|
|
552
|
+
"none",
|
|
553
|
+
"-v",
|
|
554
|
+
`${root}:/w`,
|
|
555
|
+
"--entrypoint",
|
|
556
|
+
"chown",
|
|
557
|
+
image,
|
|
558
|
+
"-R",
|
|
559
|
+
owner,
|
|
560
|
+
"/w",
|
|
561
|
+
], { timeoutMs: 120_000 });
|
|
562
|
+
const own = rec.docker?.image ?? (rec.docker?.dockerfile ? containerName(rec.status.id) : undefined);
|
|
563
|
+
if (own && (await run(own)).code === 0)
|
|
564
|
+
return;
|
|
565
|
+
const r = await run("alpine:3");
|
|
566
|
+
if (r.code !== 0)
|
|
567
|
+
this.log(`job ${rec.status.id}: could not reclaim workspace ownership`);
|
|
568
|
+
}
|
|
569
|
+
async collectArtifacts(id, cwd, globs) {
|
|
570
|
+
const files = await fg(globs, {
|
|
571
|
+
cwd,
|
|
572
|
+
dot: true,
|
|
573
|
+
onlyFiles: true,
|
|
574
|
+
followSymbolicLinks: false,
|
|
575
|
+
unique: true,
|
|
576
|
+
suppressErrors: true,
|
|
577
|
+
});
|
|
578
|
+
const out = [];
|
|
579
|
+
let total = 0;
|
|
580
|
+
const dest = this.artifactsDir(id);
|
|
581
|
+
for (const rel of files.sort()) {
|
|
582
|
+
if (out.length >= MAX_ARTIFACT_FILES)
|
|
583
|
+
break;
|
|
584
|
+
const src = resolveInside(cwd, rel);
|
|
585
|
+
const st = fs.lstatSync(src);
|
|
586
|
+
if (!st.isFile())
|
|
587
|
+
continue;
|
|
588
|
+
// A symlinked parent folder (`link/etc/passwd`) must not pull in host files.
|
|
589
|
+
if (!isRealPathInside(cwd, src))
|
|
590
|
+
continue;
|
|
591
|
+
if (total + st.size > MAX_ARTIFACT_BYTES)
|
|
592
|
+
break;
|
|
593
|
+
const target = path.join(dest, rel);
|
|
594
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
595
|
+
fs.copyFileSync(src, target);
|
|
596
|
+
total += st.size;
|
|
597
|
+
out.push({ path: rel.split(path.sep).join("/"), bytes: st.size });
|
|
598
|
+
}
|
|
599
|
+
return out;
|
|
600
|
+
}
|
|
601
|
+
// ── reads ──────────────────────────────────────────────────────────────
|
|
602
|
+
readLog(id, offset = 0) {
|
|
603
|
+
if (!this.find(id))
|
|
604
|
+
return undefined;
|
|
605
|
+
let fd;
|
|
606
|
+
try {
|
|
607
|
+
fd = fs.openSync(this.logFile(id), "r");
|
|
608
|
+
}
|
|
609
|
+
catch {
|
|
610
|
+
return { data: Buffer.alloc(0), size: 0 };
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
const size = fs.fstatSync(fd).size;
|
|
614
|
+
const start = Math.max(0, Math.min(offset, size));
|
|
615
|
+
const len = Math.min(size - start, MAX_LOG_CHUNK);
|
|
616
|
+
const data = Buffer.alloc(len);
|
|
617
|
+
if (len > 0)
|
|
618
|
+
fs.readSync(fd, data, 0, len, start);
|
|
619
|
+
return { data, size };
|
|
620
|
+
}
|
|
621
|
+
finally {
|
|
622
|
+
fs.closeSync(fd);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
/** Absolute path of a collected artifact, or undefined. */
|
|
626
|
+
artifactFile(id, rel) {
|
|
627
|
+
const rec = this.find(id);
|
|
628
|
+
if (!rec?.status.artifacts?.some((a) => a.path === rel))
|
|
629
|
+
return undefined;
|
|
630
|
+
try {
|
|
631
|
+
const file = resolveInside(this.artifactsDir(id), rel);
|
|
632
|
+
return fs.statSync(file).isFile() ? file : undefined;
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
return undefined;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// ── cancel / purge ─────────────────────────────────────────────────────
|
|
639
|
+
async cancel(id) {
|
|
640
|
+
const rec = this.find(id);
|
|
641
|
+
if (!rec)
|
|
642
|
+
return undefined;
|
|
643
|
+
if (isTerminalJob(rec.status.state))
|
|
644
|
+
return this.status(rec);
|
|
645
|
+
rec.cancelRequested = true;
|
|
646
|
+
fs.mkdirSync(this.runDir(id), { recursive: true });
|
|
647
|
+
fs.writeFileSync(path.join(this.runDir(id), "cancelled"), "cancelled\n");
|
|
648
|
+
if (rec.status.state === "preparing") {
|
|
649
|
+
this.state.save();
|
|
650
|
+
return this.status(rec);
|
|
651
|
+
}
|
|
652
|
+
const pid = Number(this.readText(path.join(this.runDir(id), "pid")));
|
|
653
|
+
const target = pid > 0 ? -pid : rec.wrapperPid ? -rec.wrapperPid : 0;
|
|
654
|
+
const kill = (sig) => {
|
|
655
|
+
if (!target)
|
|
656
|
+
return;
|
|
657
|
+
try {
|
|
658
|
+
process.kill(target, sig);
|
|
659
|
+
}
|
|
660
|
+
catch {
|
|
661
|
+
// already gone
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
kill("SIGTERM");
|
|
665
|
+
if (rec.docker)
|
|
666
|
+
await this.dockerCleanup(rec);
|
|
667
|
+
setTimeout(() => kill("SIGKILL"), this.grace * 1000).unref();
|
|
668
|
+
this.state.save();
|
|
669
|
+
return this.status(rec);
|
|
670
|
+
}
|
|
671
|
+
async purge(id) {
|
|
672
|
+
const rec = this.find(id);
|
|
673
|
+
if (!rec)
|
|
674
|
+
return undefined;
|
|
675
|
+
if (!isTerminalJob(rec.status.state)) {
|
|
676
|
+
await this.cancel(id);
|
|
677
|
+
rec.status.state = "cancelled";
|
|
678
|
+
rec.status.summary = "cancelled";
|
|
679
|
+
rec.status.finishedAt = new Date().toISOString();
|
|
680
|
+
this.slots.release(id);
|
|
681
|
+
}
|
|
682
|
+
const last = this.status(rec);
|
|
683
|
+
this.removeFiles(rec, true);
|
|
684
|
+
this.state.data.jobs = this.records().filter((r) => r !== rec);
|
|
685
|
+
this.state.save();
|
|
686
|
+
return last;
|
|
687
|
+
}
|
|
688
|
+
removeFiles(rec, all) {
|
|
689
|
+
const id = rec.status.id;
|
|
690
|
+
try {
|
|
691
|
+
fs.rmSync(workspaceRoot(this.cfg.dataDir, "job", id), { recursive: true, force: true });
|
|
692
|
+
if (all) {
|
|
693
|
+
fs.rmSync(this.runDir(id), { recursive: true, force: true });
|
|
694
|
+
fs.rmSync(this.artifactsDir(id), { recursive: true, force: true });
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
catch (e) {
|
|
698
|
+
this.log(`job ${id}: cleanup failed: ${e.message}`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
//# sourceMappingURL=jobs.js.map
|