hammerkit 2.2.0-next.6 → 2.2.0-next.8
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.
|
@@ -10,6 +10,7 @@ const log_1 = require("../log");
|
|
|
10
10
|
const sleep_1 = require("../utils/sleep");
|
|
11
11
|
const version_1 = require("../version");
|
|
12
12
|
const apply_1 = require("./apply");
|
|
13
|
+
const cluster_state_1 = require("./cluster-state");
|
|
13
14
|
const container_resources_1 = require("./container-resources");
|
|
14
15
|
const job_placement_1 = require("./job-placement");
|
|
15
16
|
const network_policy_1 = require("./network-policy");
|
|
@@ -118,6 +119,13 @@ exports.getRunCommandsDirectory = getRunCommandsDirectory;
|
|
|
118
119
|
const RUNNER_TOOLS = { busybox: BUSYBOX, sandbox: exports.RUNNER_SANDBOX_PATH };
|
|
119
120
|
// How long a command waits for one of its run that still runs before it starts (s)
|
|
120
121
|
const RUN_COMMAND_WAIT = 3600;
|
|
122
|
+
// Time limits of the execs of a runner, which a cancel or a stalled connection must not outlast:
|
|
123
|
+
// an exec that does not connect in EXEC_CONNECT_MS is given up; a start may wait for the commands
|
|
124
|
+
// of its run as long as RUN_COMMAND_WAIT (and a little more); a follow session is opened again
|
|
125
|
+
// after FOLLOW_SESSION_MS, its command may run on (not a failure, see execInRunner)
|
|
126
|
+
const EXEC_CONNECT_MS = 30 * 1000;
|
|
127
|
+
const START_SESSION_MS = (RUN_COMMAND_WAIT + 600) * 1000;
|
|
128
|
+
const FOLLOW_SESSION_MS = 10 * 60 * 1000;
|
|
121
129
|
/**
|
|
122
130
|
* The scripts that start a command in the runner and follow, stop, find and remove the
|
|
123
131
|
* commands of a run, each run as `sh -c <script> hammerkit <args>`. `cleanUp` is what kills
|
|
@@ -766,10 +774,8 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
766
774
|
...(done ? { done: true } : {}),
|
|
767
775
|
...(cutSaid ? { cut: true } : {}),
|
|
768
776
|
});
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
current = socket;
|
|
772
|
-
};
|
|
777
|
+
// On abort every exec of this command ends with it: start and follow get the signal (runScript),
|
|
778
|
+
// so one that is still connecting, or stalled, is not waited for. The cancel is what kills it.
|
|
773
779
|
const cancel = () => runScript(instance, namespace, pod, scripts.cancel, [directory], { timeout: KILL_TIMEOUT_MS });
|
|
774
780
|
const kill = async () => {
|
|
775
781
|
const killed = await cancel();
|
|
@@ -777,7 +783,6 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
777
783
|
task.status.write('debug', `the command could not be stopped in the runner, it goes: ${killed.message ?? 'the kill did not end'}`);
|
|
778
784
|
await deletePod(instance, namespace, pod).catch(() => undefined);
|
|
779
785
|
}
|
|
780
|
-
current?.close();
|
|
781
786
|
};
|
|
782
787
|
let killing;
|
|
783
788
|
const aborted = () => {
|
|
@@ -792,7 +797,7 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
792
797
|
try {
|
|
793
798
|
// a start again after its connection broke takes the command it started, by its nonce
|
|
794
799
|
const nonce = (0, crypto_1.randomBytes)(12).toString('hex');
|
|
795
|
-
const start = (mode) => runScript(instance, namespace, pod, scripts.start, [directory, mode, resumed ? '' : nonce, root, cwd, ...command], {
|
|
800
|
+
const start = (mode) => runScript(instance, namespace, pod, scripts.start, [directory, mode, resumed ? '' : nonce, root, cwd, ...command], { signal: abort, timeout: START_SESSION_MS });
|
|
796
801
|
let started = await start(resumed ? 'adopt' : 'fresh');
|
|
797
802
|
for (let attempt = 0; started.exitCode === undefined && attempt < RECONNECTS && !abort.aborted; attempt++) {
|
|
798
803
|
await (0, sleep_1.sleep)(RUNNER_POLL_MS * 2 ** attempt);
|
|
@@ -876,7 +881,7 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
876
881
|
const before = offsets.stdout + offsets.stderr;
|
|
877
882
|
const stdout = lines('stdout');
|
|
878
883
|
const stderr = lines('stderr');
|
|
879
|
-
const followed = await runScript(instance, namespace, pod, scripts.follow, [directory, String(offsets.stdout), String(offsets.stderr)], { stdout: stdout.writable, stderr: stderr.writable,
|
|
884
|
+
const followed = await runScript(instance, namespace, pod, scripts.follow, [directory, String(offsets.stdout), String(offsets.stderr)], { stdout: stdout.writable, stderr: stderr.writable, signal: abort, timeout: FOLLOW_SESSION_MS });
|
|
880
885
|
if (abort.aborted) {
|
|
881
886
|
return await stopped();
|
|
882
887
|
}
|
|
@@ -885,8 +890,9 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
885
890
|
}
|
|
886
891
|
// 0: all of it was said. Else what followed it ended before: the end of the command killed
|
|
887
892
|
// it (137), its connection broke, it failed. It is followed again, a few times in a row
|
|
888
|
-
// without getting further at most: a command that keeps killing what follows it too
|
|
889
|
-
|
|
893
|
+
// without getting further at most: a command that keeps killing what follows it too. A
|
|
894
|
+
// session that ran its time limit is opened again, as a command that runs on is followed.
|
|
895
|
+
if (followed.exitCode !== 0 && !followed.timedOut) {
|
|
890
896
|
failures = offsets.stdout + offsets.stderr > before ? 1 : failures + 1;
|
|
891
897
|
if (failures > RECONNECTS) {
|
|
892
898
|
throw new Error(`the command in the runner of the sandbox could not be followed: ${followed.message ?? `exit code ${followed.exitCode}`}`);
|
|
@@ -897,11 +903,10 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
897
903
|
return await stopped();
|
|
898
904
|
}
|
|
899
905
|
const now = parseCommandState(status.out);
|
|
900
|
-
if (!now) {
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
throw new Error('the command in the runner of the sandbox ended without an exit code: its runner went');
|
|
906
|
+
if (!now || now.type === 'none') {
|
|
907
|
+
// what the status said: the exec's error, or that the runner went
|
|
908
|
+
const said = now ? 'its runner went' : status.message ?? followed.message ?? 'the connection closed';
|
|
909
|
+
throw new Error(`the command in the runner of the sandbox ended without an exit code: ${said}; ${await describeRunner(instance, namespace, pod)}`);
|
|
905
910
|
}
|
|
906
911
|
if (followed.exitCode === 0) {
|
|
907
912
|
if (now.type === 'cancelled') {
|
|
@@ -931,6 +936,37 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
931
936
|
abort.removeEventListener('abort', aborted);
|
|
932
937
|
}
|
|
933
938
|
}
|
|
939
|
+
// What the cluster says of the runner's pod and container, for a command whose exit code can not
|
|
940
|
+
// be had: the pod is gone, or its container ended (how, as describeLastExit says) or waits
|
|
941
|
+
async function describeRunner(instance, namespace, pod) {
|
|
942
|
+
let runner;
|
|
943
|
+
try {
|
|
944
|
+
runner = await instance.coreApi.readNamespacedPod({ name: pod, namespace });
|
|
945
|
+
}
|
|
946
|
+
catch (e) {
|
|
947
|
+
if ((0, apply_1.statusCodeOf)(e) === 404) {
|
|
948
|
+
return 'its pod is gone';
|
|
949
|
+
}
|
|
950
|
+
// the detail of an API error can name the service account of the server: it goes to the
|
|
951
|
+
// server's own log, not to the run
|
|
952
|
+
process.stderr.write(`hammerkit: reading the runner ${pod} failed: ${(0, log_1.getErrorMessage)(e)}\n`);
|
|
953
|
+
return 'its pod could not be read';
|
|
954
|
+
}
|
|
955
|
+
if (runner.metadata?.deletionTimestamp) {
|
|
956
|
+
return 'its pod is being deleted';
|
|
957
|
+
}
|
|
958
|
+
const container = runner.status?.containerStatuses?.find((status) => status.name === RUNNER_CONTAINER);
|
|
959
|
+
if (!container) {
|
|
960
|
+
return `its pod is ${runner.status?.phase ?? 'unknown'} and has no status of its runner container`;
|
|
961
|
+
}
|
|
962
|
+
if (container.state?.waiting) {
|
|
963
|
+
return `the runner's container waits: ${container.state.waiting.reason ?? 'for no reason it names'}`;
|
|
964
|
+
}
|
|
965
|
+
if (container.state?.terminated || container.lastState?.terminated) {
|
|
966
|
+
return `the runner's container ended: ${(0, cluster_state_1.describeLastExit)(container, runner)}`;
|
|
967
|
+
}
|
|
968
|
+
return `the runner's container is ${container.state?.running ? 'running' : 'not running'}, its pod is ${runner.status?.phase ?? 'unknown'}`;
|
|
969
|
+
}
|
|
934
970
|
// Runs `fn` again while it answers no exit code (its connection broke), RECONNECTS times at most
|
|
935
971
|
async function reconnecting(abort, fn) {
|
|
936
972
|
let result = await fn();
|
|
@@ -940,6 +976,31 @@ async function reconnecting(abort, fn) {
|
|
|
940
976
|
}
|
|
941
977
|
return result;
|
|
942
978
|
}
|
|
979
|
+
// The value of `connecting` once it connects, or undefined when `ms` passed or `signal` aborted
|
|
980
|
+
// first. An exec that connects after that is closed, as nothing waits for it any more.
|
|
981
|
+
function connectWithin(connecting, ms, signal) {
|
|
982
|
+
return new Promise((resolve, reject) => {
|
|
983
|
+
let over = false;
|
|
984
|
+
const onAbort = () => end(() => resolve(undefined));
|
|
985
|
+
const end = (answer) => {
|
|
986
|
+
if (over) {
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
over = true;
|
|
990
|
+
clearTimeout(timer);
|
|
991
|
+
signal?.removeEventListener('abort', onAbort);
|
|
992
|
+
answer();
|
|
993
|
+
};
|
|
994
|
+
const timer = setTimeout(() => end(() => resolve(undefined)), ms);
|
|
995
|
+
if (signal?.aborted) {
|
|
996
|
+
onAbort();
|
|
997
|
+
}
|
|
998
|
+
else {
|
|
999
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1000
|
+
}
|
|
1001
|
+
connecting.then((socket) => (over ? socket.close() : end(() => resolve(socket))), (e) => end(() => reject(e)));
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
943
1004
|
// Runs a script of the runner's busybox with `args` as `$1`… in the runner
|
|
944
1005
|
async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
945
1006
|
let out = '';
|
|
@@ -952,34 +1013,48 @@ async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
|
952
1013
|
});
|
|
953
1014
|
let status;
|
|
954
1015
|
let broken;
|
|
1016
|
+
let timedOut = false;
|
|
955
1017
|
try {
|
|
956
|
-
const
|
|
1018
|
+
const connecting = instance.exec.exec(namespace, pod, RUNNER_CONTAINER, [BUSYBOX, 'sh', '-c', script, 'hammerkit', ...args], stdout, options.stderr ?? null, null, false, (received) => {
|
|
957
1019
|
status = received;
|
|
958
1020
|
});
|
|
959
|
-
options.
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
1021
|
+
const socket = await connectWithin(connecting, EXEC_CONNECT_MS, options.signal);
|
|
1022
|
+
if (socket) {
|
|
1023
|
+
// the end of the exec: its close, an error, the abort or the time limit, whichever comes first
|
|
1024
|
+
// (a close that never comes is not waited for)
|
|
1025
|
+
// resolves the wait for the exec: at its close, its error, the abort or the time limit
|
|
1026
|
+
let resolveClosed = () => undefined;
|
|
1027
|
+
const closed = new Promise((resolve) => {
|
|
1028
|
+
resolveClosed = resolve;
|
|
1029
|
+
socket.on('close', () => resolve());
|
|
1030
|
+
socket.on('error', (e) => {
|
|
1031
|
+
broken = e;
|
|
1032
|
+
resolve();
|
|
1033
|
+
});
|
|
965
1034
|
});
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
1035
|
+
const onAbort = () => {
|
|
1036
|
+
socket.close();
|
|
1037
|
+
resolveClosed();
|
|
1038
|
+
};
|
|
1039
|
+
if (options.signal?.aborted) {
|
|
1040
|
+
onAbort();
|
|
1041
|
+
}
|
|
1042
|
+
else {
|
|
1043
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
1044
|
+
}
|
|
1045
|
+
const limit = options.timeout && !options.signal?.aborted
|
|
1046
|
+
? setTimeout(() => {
|
|
1047
|
+
timedOut = true;
|
|
1048
|
+
broken ?? (broken = new Error('it did not answer'));
|
|
1049
|
+
onAbort();
|
|
1050
|
+
}, options.timeout)
|
|
1051
|
+
: undefined;
|
|
1052
|
+
await closed;
|
|
1053
|
+
clearTimeout(limit);
|
|
1054
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
980
1055
|
}
|
|
981
1056
|
else {
|
|
982
|
-
|
|
1057
|
+
broken = new Error(options.signal?.aborted ? 'the run was cancelled' : 'it did not connect');
|
|
983
1058
|
}
|
|
984
1059
|
}
|
|
985
1060
|
catch (e) {
|
|
@@ -992,6 +1067,7 @@ async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
|
992
1067
|
...(exitCode === undefined
|
|
993
1068
|
? { message: status?.message ?? (broken ? (0, log_1.getErrorMessage)(broken) : 'the connection closed') }
|
|
994
1069
|
: {}),
|
|
1070
|
+
...(timedOut ? { timedOut } : {}),
|
|
995
1071
|
};
|
|
996
1072
|
}
|
|
997
1073
|
//# sourceMappingURL=sandbox-runner.js.map
|
package/dist/server/executor.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.pushCacheNamespace = exports.cacheNamespace = exports.defaultWorker = void 0;
|
|
3
|
+
exports.HostExecutor = exports.killGroup = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.pushCacheNamespace = exports.cacheNamespace = exports.defaultWorker = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const checks_1 = require("./checks");
|
|
@@ -12,6 +12,7 @@ const resolve_git_source_1 = require("../includes/resolve-git-source");
|
|
|
12
12
|
const git_checkout_1 = require("./git-checkout");
|
|
13
13
|
const runs_1 = require("./runs");
|
|
14
14
|
const run_plan_1 = require("./run-plan");
|
|
15
|
+
const run_worker_1 = require("./run-worker");
|
|
15
16
|
const work_network_1 = require("../planner/work-network");
|
|
16
17
|
const execute_docker_1 = require("../executer/execute-docker");
|
|
17
18
|
const run_source_environment_1 = require("./run-source-environment");
|
|
@@ -29,6 +30,11 @@ const STOP_GRACE_MS = 15000;
|
|
|
29
30
|
// A run the server leaves to the next one gets this long to stop its tasks on this machine: the
|
|
30
31
|
// rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
|
|
31
32
|
const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
|
|
33
|
+
// The worker's output is read until its stdio closes. After its exit that comes at once, unless a
|
|
34
|
+
// process of the run keeps the stdio open: it gets this long, then the wait ends with what the
|
|
35
|
+
// worker said. A worker that said its result and does not exit gets killed after RESULT_EXIT_MS.
|
|
36
|
+
const STDIO_CLOSE_MS = 2000;
|
|
37
|
+
const RESULT_EXIT_MS = 10000;
|
|
32
38
|
// what is kept of the error output of a process that died without saying why
|
|
33
39
|
const MAX_STDERR = 2 * 1024;
|
|
34
40
|
/**
|
|
@@ -160,6 +166,24 @@ function relayWorkerLine(line, runId, relay) {
|
|
|
160
166
|
}
|
|
161
167
|
}
|
|
162
168
|
exports.relayWorkerLine = relayWorkerLine;
|
|
169
|
+
// Signals the process group of a worker, which is started as one (`detached` on POSIX): what the
|
|
170
|
+
// worker started, and what it left running, is signalled with it. On Windows, the process alone.
|
|
171
|
+
function killGroup(child, signal) {
|
|
172
|
+
if (child.pid === undefined || process.platform === 'win32') {
|
|
173
|
+
child.kill(signal);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
process.kill(-child.pid, signal);
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
// the group is gone already, or the process is not its leader any more: the process itself goes
|
|
181
|
+
if (e.code !== 'ESRCH') {
|
|
182
|
+
child.kill(signal);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
exports.killGroup = killGroup;
|
|
163
187
|
class HostExecutor {
|
|
164
188
|
constructor(options) {
|
|
165
189
|
this.options = options;
|
|
@@ -422,6 +446,8 @@ class HostExecutor {
|
|
|
422
446
|
options: run.options,
|
|
423
447
|
...(push ? { cachePush: push } : {}),
|
|
424
448
|
cacheRegistries: this.options.cacheRegistries ?? [],
|
|
449
|
+
// how long a cancel's cleanup of the run's commands may take, from the server's environment
|
|
450
|
+
cleanupTimeoutMs: (0, run_worker_1.cleanupTimeoutMs)(process.env.HAMMERKIT_CLEANUP_TIMEOUT_MS),
|
|
425
451
|
accounts: run.accounts,
|
|
426
452
|
volumeScope: volumeScope(run, this.options.directory),
|
|
427
453
|
...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
|
|
@@ -533,6 +559,8 @@ class HostExecutor {
|
|
|
533
559
|
env,
|
|
534
560
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
535
561
|
windowsHide: true,
|
|
562
|
+
// its own process group on POSIX, so a kill reaches the children of the worker too
|
|
563
|
+
detached: process.platform !== 'win32',
|
|
536
564
|
});
|
|
537
565
|
child.stdin.on('error', () => undefined);
|
|
538
566
|
// the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
|
|
@@ -541,10 +569,13 @@ class HostExecutor {
|
|
|
541
569
|
let result;
|
|
542
570
|
let stderr = '';
|
|
543
571
|
let killTimer;
|
|
572
|
+
let resultTimer;
|
|
573
|
+
let stdioTimer;
|
|
574
|
+
let finished = false;
|
|
544
575
|
const stop = () => {
|
|
545
576
|
const detaching = (0, runs_1.isDetached)(context);
|
|
546
577
|
if (detaching && onCluster) {
|
|
547
|
-
child
|
|
578
|
+
killGroup(child, 'SIGKILL');
|
|
548
579
|
return;
|
|
549
580
|
}
|
|
550
581
|
child.stdin.write('cancel\n', (e) => {
|
|
@@ -553,7 +584,7 @@ class HostExecutor {
|
|
|
553
584
|
}
|
|
554
585
|
});
|
|
555
586
|
const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
|
|
556
|
-
killTimer = setTimeout(() => child
|
|
587
|
+
killTimer = setTimeout(() => killGroup(child, 'SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
|
|
557
588
|
killTimer.unref();
|
|
558
589
|
};
|
|
559
590
|
if (signal.aborted) {
|
|
@@ -562,17 +593,27 @@ class HostExecutor {
|
|
|
562
593
|
else {
|
|
563
594
|
signal.addEventListener('abort', stop, { once: true });
|
|
564
595
|
}
|
|
565
|
-
(0, readline_1.createInterface)({ input: child.stdout })
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
596
|
+
const lines = (0, readline_1.createInterface)({ input: child.stdout });
|
|
597
|
+
lines.on('line', (line) => {
|
|
598
|
+
// nothing is emitted for a run that has settled
|
|
599
|
+
if (finished) {
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
relayWorkerLine(line, runId, {
|
|
603
|
+
emit: (event) => context.emit(event),
|
|
604
|
+
up: (targets) => context.up?.(targets),
|
|
605
|
+
syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
|
|
606
|
+
result: (message) => {
|
|
607
|
+
result = message;
|
|
608
|
+
// nothing left to tell the process
|
|
609
|
+
this.children.delete(runId);
|
|
610
|
+
child.stdin.end();
|
|
611
|
+
// the worker says nothing more: it should exit now, and its group is killed if it does not
|
|
612
|
+
resultTimer = setTimeout(() => killGroup(child, 'SIGKILL'), RESULT_EXIT_MS);
|
|
613
|
+
resultTimer.unref();
|
|
614
|
+
},
|
|
615
|
+
});
|
|
616
|
+
});
|
|
576
617
|
child.stderr.on('data', (chunk) => {
|
|
577
618
|
stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
|
|
578
619
|
});
|
|
@@ -581,9 +622,18 @@ class HostExecutor {
|
|
|
581
622
|
clearTimeout(killTimer);
|
|
582
623
|
reject(new Error(`the process of the run could not start: ${e.message}`));
|
|
583
624
|
});
|
|
584
|
-
|
|
625
|
+
// The wait ends on the worker's exit. Its stdio may stay open after it (a process of the run
|
|
626
|
+
// the cluster or the worker left holds it), so after the exit the wait ends at the close, or
|
|
627
|
+
// when STDIO_CLOSE_MS passed, with what the worker said.
|
|
628
|
+
const finish = (code, killed) => {
|
|
629
|
+
if (finished) {
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
finished = true;
|
|
585
633
|
signal.removeEventListener('abort', stop);
|
|
586
634
|
clearTimeout(killTimer);
|
|
635
|
+
clearTimeout(resultTimer);
|
|
636
|
+
clearTimeout(stdioTimer);
|
|
587
637
|
if (this.children.get(runId) === child) {
|
|
588
638
|
this.children.delete(runId);
|
|
589
639
|
}
|
|
@@ -600,7 +650,25 @@ class HostExecutor {
|
|
|
600
650
|
const reason = stderr.trim().split('\n').pop() ?? '';
|
|
601
651
|
reject(new Error(`the process of the run stopped (${killed ? `signal ${killed}` : `code ${code}`})${reason ? `: ${reason}` : ''}`));
|
|
602
652
|
}
|
|
653
|
+
};
|
|
654
|
+
// After the worker's exit the stdio may stay open, a process of the run holds it. Then the
|
|
655
|
+
// group is killed, the pipes are closed, and the wait ends with what the worker said.
|
|
656
|
+
const settleOpen = (code, killed) => {
|
|
657
|
+
if (finished) {
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
killGroup(child, 'SIGKILL');
|
|
661
|
+
lines.close();
|
|
662
|
+
child.stdout.destroy();
|
|
663
|
+
child.stderr.destroy();
|
|
664
|
+
child.stdin.destroy();
|
|
665
|
+
finish(code, killed);
|
|
666
|
+
};
|
|
667
|
+
child.on('exit', (code, killed) => {
|
|
668
|
+
stdioTimer = setTimeout(() => settleOpen(code, killed), STDIO_CLOSE_MS);
|
|
669
|
+
stdioTimer.unref();
|
|
603
670
|
});
|
|
671
|
+
child.on('close', (code, killed) => finish(code, killed));
|
|
604
672
|
});
|
|
605
673
|
}
|
|
606
674
|
// The published files go over the checkout; nothing may land outside of it or in
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AnswerReader = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
|
|
3
|
+
exports.AnswerReader = exports.ConnectionClosedError = exports.getPushRefusal = exports.KubernetesSandboxStorage = exports.getSandboxNames = void 0;
|
|
4
4
|
const crypto_1 = require("crypto");
|
|
5
5
|
const promises_1 = require("fs/promises");
|
|
6
6
|
const path_1 = require("path");
|
|
@@ -514,7 +514,11 @@ class KubernetesSandboxStorage {
|
|
|
514
514
|
await (0, git_checkout_1.git)([`--git-dir=${repository}`, 'fetch', '--quiet', '--depth', '1', '--', fetch.url, fetch.ref], fetch.env, fetch.signal, what);
|
|
515
515
|
await (0, git_checkout_1.git)([`--git-dir=${repository}`, 'update-ref', `refs/heads/${sandbox_pod_1.INCOMING_REF}`, 'FETCH_HEAD'], fetch.env, fetch.signal, what, op);
|
|
516
516
|
const incoming = `${CLAIM_PATH}/${sandbox_pod_1.INCOMING}`;
|
|
517
|
-
|
|
517
|
+
const upload = () => this.withPod(key, (pod) => this.exec(pod, ['sh', '-c', 'rm -rf "$1" && mkdir -p "$1" && tar xf - -C "$1"', 'sh', incoming], stream_1.Readable.from((0, tar_2.packArchive)({ cwd: repository, portable: true }, ['.'])), null, fetch.signal));
|
|
518
|
+
// a connection that closed in the middle of the upload is tried once more, with the whole
|
|
519
|
+
// archive: the pod unpacks it into a directory it empties first. Not once the fetch was
|
|
520
|
+
// cancelled: the cancel is the answer, not a retry.
|
|
521
|
+
await upload().catch((e) => e instanceof ConnectionClosedError && !fetch.signal.aborted ? upload() : Promise.reject(e));
|
|
518
522
|
return (await this.request(key, { op, id: key.id }, fetch.signal)).result;
|
|
519
523
|
}
|
|
520
524
|
finally {
|
|
@@ -867,37 +871,59 @@ class KubernetesSandboxStorage {
|
|
|
867
871
|
let status;
|
|
868
872
|
// the stdin of the command waits on the connection, which is there once it started
|
|
869
873
|
const connection = {};
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
if (signal.aborted) {
|
|
883
|
-
abort();
|
|
884
|
-
return;
|
|
885
|
-
}
|
|
886
|
-
signal.addEventListener('abort', abort, { once: true });
|
|
887
|
-
socket.on('error', (e) => {
|
|
888
|
-
signal.removeEventListener('abort', abort);
|
|
889
|
-
reject(e);
|
|
874
|
+
// whether all of stdin was handed to an open connection: the client drops what it is given
|
|
875
|
+
// once the connection closed, so a stdin that did not end while it was open is an upload
|
|
876
|
+
// cut short (ConnectionClosedError)
|
|
877
|
+
let stdinSent = stdin === null;
|
|
878
|
+
const settled = new AbortController();
|
|
879
|
+
const sent = stdin && throttle(stdin, () => connection.socket, settled.signal);
|
|
880
|
+
// a chunk that the connection did not take ends the stream with an error, read below
|
|
881
|
+
sent?.on('error', () => undefined);
|
|
882
|
+
sent?.on('end', () => (stdinSent = connection.socket?.readyState === WS_OPEN));
|
|
883
|
+
try {
|
|
884
|
+
const socket = await this.instance.exec.exec(pod.namespace, pod.name, 'files', command, stdout ?? new stream_1.Writable({ write: (_chunk, _encoding, callback) => callback() }), errors, sent ?? null, false, (received) => {
|
|
885
|
+
status = received;
|
|
890
886
|
});
|
|
891
|
-
socket
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
887
|
+
connection.socket = socket;
|
|
888
|
+
if (stdout) {
|
|
889
|
+
holdBack(socket, stdout);
|
|
890
|
+
}
|
|
891
|
+
await new Promise((resolve, reject) => {
|
|
892
|
+
const abort = () => {
|
|
893
|
+
socket.close();
|
|
894
|
+
reject(new Error(`${command[0]} in the pod of the sandbox was cancelled`));
|
|
895
|
+
};
|
|
896
|
+
if (signal.aborted) {
|
|
897
|
+
abort();
|
|
895
898
|
return;
|
|
896
899
|
}
|
|
897
|
-
|
|
898
|
-
|
|
900
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
901
|
+
socket.on('error', (e) => {
|
|
902
|
+
signal.removeEventListener('abort', abort);
|
|
903
|
+
reject(stdinSent ? e : new ConnectionClosedError(e));
|
|
904
|
+
});
|
|
905
|
+
socket.on('close', () => {
|
|
906
|
+
signal.removeEventListener('abort', abort);
|
|
907
|
+
if (!stdinSent) {
|
|
908
|
+
reject(new ConnectionClosedError());
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
if (status?.status === 'Success') {
|
|
912
|
+
resolve();
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
const reason = stderr.trim().split('\n').pop() || status?.message || 'the connection to the pod closed';
|
|
916
|
+
reject(new Error(`${command[0]} in the pod of the sandbox failed: ${reason}`));
|
|
917
|
+
});
|
|
899
918
|
});
|
|
900
|
-
}
|
|
919
|
+
}
|
|
920
|
+
finally {
|
|
921
|
+
// what a failed attempt left of its archive and of the throttle that reads it: the throttle
|
|
922
|
+
// stops waiting, and its stream is destroyed
|
|
923
|
+
settled.abort();
|
|
924
|
+
sent?.destroy();
|
|
925
|
+
stdin?.destroy();
|
|
926
|
+
}
|
|
901
927
|
}
|
|
902
928
|
}
|
|
903
929
|
exports.KubernetesSandboxStorage = KubernetesSandboxStorage;
|
|
@@ -932,13 +958,39 @@ function defined(env) {
|
|
|
932
958
|
}
|
|
933
959
|
return result;
|
|
934
960
|
}
|
|
961
|
+
// The readyState values of a websocket (ws), which is only a type in this file
|
|
962
|
+
const WS_CONNECTING = 0;
|
|
963
|
+
const WS_OPEN = 1;
|
|
964
|
+
// A command's connection to the files pod closed before all of its stdin was sent: what the
|
|
965
|
+
// client sends after the close is dropped, so the command could only have read its input short
|
|
966
|
+
class ConnectionClosedError extends Error {
|
|
967
|
+
constructor(cause) {
|
|
968
|
+
super('the connection to the files pod closed during the upload', { cause });
|
|
969
|
+
this.name = 'ConnectionClosedError';
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
exports.ConnectionClosedError = ConnectionClosedError;
|
|
935
973
|
// The client of the cluster sends what stdin has as fast as it comes: this waits while the
|
|
936
|
-
// connection has more than MAX_STDIN_BUFFERED not sent yet
|
|
937
|
-
|
|
974
|
+
// connection has more than MAX_STDIN_BUFFERED not sent yet, and hands a chunk on only while the
|
|
975
|
+
// connection is open, else it fails with ConnectionClosedError (the client would drop it).
|
|
976
|
+
// `settled` ends the wait: once the exec is over, no connection comes for the chunk, and the
|
|
977
|
+
// stream returns instead of polling for one.
|
|
978
|
+
function throttle(stdin, connection, settled) {
|
|
938
979
|
return stream_1.Readable.from((async function* () {
|
|
939
980
|
for await (const chunk of stdin) {
|
|
940
|
-
|
|
981
|
+
let socket = connection();
|
|
982
|
+
while (!settled.aborted && (socket === undefined || socket.readyState === WS_CONNECTING)) {
|
|
941
983
|
await (0, sleep_1.sleep)(10);
|
|
984
|
+
socket = connection();
|
|
985
|
+
}
|
|
986
|
+
while (!settled.aborted && socket?.readyState === WS_OPEN && socket.bufferedAmount > MAX_STDIN_BUFFERED) {
|
|
987
|
+
await (0, sleep_1.sleep)(10);
|
|
988
|
+
}
|
|
989
|
+
if (settled.aborted) {
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
if (socket?.readyState !== WS_OPEN) {
|
|
993
|
+
throw new ConnectionClosedError();
|
|
942
994
|
}
|
|
943
995
|
yield chunk;
|
|
944
996
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.parseChanges = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.getRunHosted = exports.createRunSecrets = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
|
|
3
|
+
exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.parseChanges = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.getRunHosted = exports.createRunSecrets = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = exports.cleanupTimeoutMs = void 0;
|
|
4
4
|
const readline_1 = require("readline");
|
|
5
5
|
const zod_1 = require("zod");
|
|
6
6
|
const cli_1 = require("../cli");
|
|
@@ -40,6 +40,18 @@ const MAX_LOG_TEXT = 8 * 1024;
|
|
|
40
40
|
* engine reads of its process (the home directory, the docker host, the cache directory)
|
|
41
41
|
* is the run's and not the server's.
|
|
42
42
|
*/
|
|
43
|
+
// The cleanup of the commands of a run after a cancel, bounded (ms): HAMMERKIT_CLEANUP_TIMEOUT_MS
|
|
44
|
+
// sets it when it is a plain integer in this range, else the default
|
|
45
|
+
const REMOVE_COMMANDS_MS = 60000;
|
|
46
|
+
const CLEANUP_LIMITS_MS = { min: 1000, max: 600000 };
|
|
47
|
+
function cleanupTimeoutMs(value) {
|
|
48
|
+
if (value === undefined || !/^\d+$/.test(value.trim())) {
|
|
49
|
+
return REMOVE_COMMANDS_MS;
|
|
50
|
+
}
|
|
51
|
+
const ms = Number(value.trim());
|
|
52
|
+
return ms >= CLEANUP_LIMITS_MS.min && ms <= CLEANUP_LIMITS_MS.max ? ms : REMOVE_COMMANDS_MS;
|
|
53
|
+
}
|
|
54
|
+
exports.cleanupTimeoutMs = cleanupTimeoutMs;
|
|
43
55
|
exports.workerInputSchema = zod_1.z
|
|
44
56
|
.object({
|
|
45
57
|
// the build file to start from, in the checkout
|
|
@@ -63,6 +75,8 @@ exports.workerInputSchema = zod_1.z
|
|
|
63
75
|
// on the server's docker host, the runtime a container that adds capabilities runs in
|
|
64
76
|
// (`backend.capabilities.runtime`)
|
|
65
77
|
capabilityRuntime: zod_1.z.string().min(1).optional(),
|
|
78
|
+
// how long the cleanup of the commands of a run after a cancel may take (ms), see cleanupTimeoutMs
|
|
79
|
+
cleanupTimeoutMs: zod_1.z.number().int().min(CLEANUP_LIMITS_MS.min).max(CLEANUP_LIMITS_MS.max).optional(),
|
|
66
80
|
// the server's credential to write a registry cache with, for a trusted run only (`cache.push`,
|
|
67
81
|
// see cache-push.ts); left out for any other run, which may only read the caches
|
|
68
82
|
cachePush: zod_1.z
|
|
@@ -227,10 +241,28 @@ async function removeCommandsOfRun(input, commands, emit) {
|
|
|
227
241
|
if (!kubernetes || !workspace?.runner || commands.executions.size === 0) {
|
|
228
242
|
return;
|
|
229
243
|
}
|
|
244
|
+
// The cluster may not answer: the cleanup ends after its limit, so the result is not held up by a
|
|
245
|
+
// removal that never settles. The command directories of the run may then stay in the runner; the
|
|
246
|
+
// cancel has killed their processes already.
|
|
247
|
+
const limit = input.cleanupTimeoutMs ?? REMOVE_COMMANDS_MS;
|
|
248
|
+
let timer;
|
|
249
|
+
const expired = new Promise((resolve) => {
|
|
250
|
+
timer = setTimeout(() => resolve('expired'), limit);
|
|
251
|
+
});
|
|
230
252
|
try {
|
|
231
|
-
|
|
253
|
+
// inside the try: a synchronous throw of the removal is logged like any other failure
|
|
254
|
+
const removal = Promise.resolve().then(() => (0, sandbox_runner_1.removeRunCommands)((0, kubernetes_instance_1.createKubernetesInstances)(kubernetes), kubernetes.namespace, workspace.label, kubernetes.server.run, {
|
|
232
255
|
clean: true,
|
|
233
|
-
});
|
|
256
|
+
}));
|
|
257
|
+
const outcome = await Promise.race([removal.then(() => 'removed'), expired]);
|
|
258
|
+
if (outcome === 'expired') {
|
|
259
|
+
emit({
|
|
260
|
+
type: 'log',
|
|
261
|
+
task: 'hammerkit',
|
|
262
|
+
stream: 'stderr',
|
|
263
|
+
text: `what the commands of the run left in the sandbox could not be removed: the cluster did not answer in ${limit} ms`,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
234
266
|
}
|
|
235
267
|
catch (e) {
|
|
236
268
|
emit({
|
|
@@ -240,6 +272,9 @@ async function removeCommandsOfRun(input, commands, emit) {
|
|
|
240
272
|
text: `what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
|
|
241
273
|
});
|
|
242
274
|
}
|
|
275
|
+
finally {
|
|
276
|
+
clearTimeout(timer);
|
|
277
|
+
}
|
|
243
278
|
}
|
|
244
279
|
exports.removeCommandsOfRun = removeCommandsOfRun;
|
|
245
280
|
// The secrets of a run, masked in what it logs: the password of its cache push, as a secret of a
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.MAX_PATH_LENGTH = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
3
|
+
exports.HostSandboxFiles = exports.ripgrepBinary = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.MAX_PATH_LENGTH = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const fs_1 = require("fs");
|
|
@@ -199,6 +199,13 @@ function fileType(stats) {
|
|
|
199
199
|
*/
|
|
200
200
|
// the ignore files ripgrep reads in the folders above the path it searches
|
|
201
201
|
const IGNORE_FILES = ['.gitignore', '.ignore', '.rgignore'];
|
|
202
|
+
// The ripgrep a search runs: HAMMERKIT_RG_PATH, rg on the PATH when it is not set. It is the
|
|
203
|
+
// operator's setting, read from the server's own environment, never from a run's: a run's
|
|
204
|
+
// variables reach ripgrep as its environment (this.env), not here.
|
|
205
|
+
function ripgrepBinary(env) {
|
|
206
|
+
return env.HAMMERKIT_RG_PATH || 'rg';
|
|
207
|
+
}
|
|
208
|
+
exports.ripgrepBinary = ripgrepBinary;
|
|
202
209
|
class HostSandboxFiles {
|
|
203
210
|
constructor(root, git,
|
|
204
211
|
// the environment of ripgrep: the variables runs see
|
|
@@ -719,7 +726,7 @@ class HostSandboxFiles {
|
|
|
719
726
|
}
|
|
720
727
|
}
|
|
721
728
|
return new Promise((resolve, reject) => {
|
|
722
|
-
const child = (0, child_process_1.spawn)(
|
|
729
|
+
const child = (0, child_process_1.spawn)(ripgrepBinary(process.env), args, {
|
|
723
730
|
cwd: target.cwd,
|
|
724
731
|
env,
|
|
725
732
|
stdio: ['pipe', 'pipe', 'pipe'],
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hammerkit",
|
|
3
3
|
"description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
|
|
4
|
-
"version": "2.2.0-next.
|
|
4
|
+
"version": "2.2.0-next.8",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"build",
|
|
7
7
|
"build-tool",
|
|
@@ -80,6 +80,7 @@
|
|
|
80
80
|
"@typescript-eslint/eslint-plugin": "^6.16.0",
|
|
81
81
|
"@typescript-eslint/parser": "^6.16.0",
|
|
82
82
|
"@vitest/coverage-istanbul": "^2.1.8",
|
|
83
|
+
"@vscode/ripgrep": "1.18.0",
|
|
83
84
|
"@yao-pkg/pkg": "^6.20.0",
|
|
84
85
|
"eslint": "^8.56.0",
|
|
85
86
|
"fast-check": "^4.10.2",
|