hammerkit 2.1.0-next.15 → 2.1.0-next.17

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.
@@ -15,6 +15,8 @@ const log_1 = require("../log");
15
15
  const network_policy_1 = require("../kubernetes/network-policy");
16
16
  const network_gate_1 = require("../kubernetes/network-gate");
17
17
  const sleep_1 = require("../utils/sleep");
18
+ const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
19
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
18
20
  const version_1 = require("../version");
19
21
  const executor_1 = require("./executor");
20
22
  const kept_claims_1 = require("../kubernetes/kept-claims");
@@ -362,17 +364,22 @@ class KubernetesExecutor {
362
364
  finally {
363
365
  const placed = this.placed.delete(run.id);
364
366
  if (left && !placed && !(0, runs_1.isDetached)(context)) {
365
- await this.removeLeft(run);
367
+ // the run executed: its process removed its commands when it ended
368
+ await this.removeLeft(run, false);
366
369
  }
367
370
  }
368
371
  }
369
372
  // What a run left on the cluster, that no release removes
370
- async removeLeft(run) {
373
+ async removeLeft(run, commands = true) {
371
374
  const say = (text) => this.log?.(`run=${run.id} ${text}`);
372
375
  this.resuming.forget(run);
373
376
  try {
374
377
  if (!run.up) {
375
- await this.removeRun(run, getCallerNamespace(this.config.backend.namespacePrefix, run.owner), say);
378
+ const namespace = getCallerNamespace(this.config.backend.namespacePrefix, run.owner);
379
+ if (commands) {
380
+ await this.removeRunCommands(run, namespace, say);
381
+ }
382
+ await this.removeRun(run, namespace, say);
376
383
  return;
377
384
  }
378
385
  // a namespace is kept only for a run that has one from start to end
@@ -384,6 +391,17 @@ class KubernetesExecutor {
384
391
  say(`what the run left could not be removed: ${(0, log_1.getErrorMessage)(e)}`);
385
392
  }
386
393
  }
394
+ // What the commands of a run on a sandbox left in its runner: they ran on over the restart
395
+ // for the run to take them up again, which it no longer does. Another run may be on the
396
+ // sandbox by now, so only the run's own commands are killed.
397
+ async removeRunCommands(run, namespace, say) {
398
+ if (run.source.type !== 'sandbox' || !this.config.backend.sandboxes.runner) {
399
+ return;
400
+ }
401
+ await (0, sandbox_runner_1.removeRunCommands)(this.instance, namespace, (0, kubernetes_sandbox_storage_1.getSandboxNames)(run.source.id).label, run.id, {
402
+ clean: false,
403
+ }).catch((e) => say(`what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`));
404
+ }
387
405
  async executeOn(run, context) {
388
406
  if (run.up) {
389
407
  if (run.source.type === 'sandbox') {
@@ -437,7 +455,8 @@ class KubernetesExecutor {
437
455
  * restart left goes, as no execution may have removed it (one cancelled in the queue).
438
456
  */
439
457
  async forget(run) {
440
- await this.removeLeft(run);
458
+ // the commands of a run are left only when it was restored and never executed again
459
+ await this.removeLeft(run, this.resuming.has(run));
441
460
  }
442
461
  /**
443
462
  * The runs of a previous start that are not over: the service runs that sleep with their
@@ -711,7 +730,7 @@ class KubernetesExecutor {
711
730
  ...(run.up ? { serviceRun: true } : {}),
712
731
  ...(openGate ? { openGate } : {}),
713
732
  // what the execution before a restart left, its tasks and services take over
714
- ...(context.resumed ? { resumed: context.resumed } : {}),
733
+ ...(context.resumed ? { resumed: { logs: context.resumed.logs } } : {}),
715
734
  ...(backend.capabilities
716
735
  ? {
717
736
  capabilities: {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
3
+ exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -30,6 +30,8 @@ const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
30
30
  const check_keys_1 = require("../optimizer/check-keys");
31
31
  const units_2 = require("../utils/units");
32
32
  const keep_artifacts_1 = require("./keep-artifacts");
33
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
34
+ const runner_commands_1 = require("../executer/runner-commands");
33
35
  // one log line of a task is cut here, the registry caps how many events a run keeps
34
36
  const MAX_LOG_TEXT = 8 * 1024;
35
37
  /**
@@ -90,6 +92,26 @@ exports.workerInputSchema = zod_1.z
90
92
  .object({ directory: zod_1.z.string().min(1), maxBytes: zod_1.z.number().int().positive() })
91
93
  .strict()
92
94
  .optional(),
95
+ // the run executed before a restart of the server: how far its log holds the output of
96
+ // each command in a sandbox's runner (RunContext.resumed)
97
+ resumed: zod_1.z
98
+ .object({
99
+ outputs: zod_1.z
100
+ .record(zod_1.z.string().regex(runner_commands_1.COMMAND_ID_PATTERN), zod_1.z
101
+ .object({
102
+ task: zod_1.z.string().max(1024),
103
+ step: zod_1.z.number().int().nonnegative(),
104
+ execution: zod_1.z.number().int().nonnegative(),
105
+ stdout: zod_1.z.number().int().nonnegative(),
106
+ stderr: zod_1.z.number().int().nonnegative(),
107
+ done: zod_1.z.literal(true).optional(),
108
+ cut: zod_1.z.literal(true).optional(),
109
+ })
110
+ .strict())
111
+ .refine((outputs) => Object.keys(outputs).length <= runner_commands_1.MAX_OUTPUT_COMMANDS, 'too many commands'),
112
+ })
113
+ .strict()
114
+ .optional(),
93
115
  })
94
116
  .strict();
95
117
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -171,6 +193,54 @@ function getLogEvent(message) {
171
193
  return undefined;
172
194
  }
173
195
  exports.getLogEvent = getLogEvent;
196
+ // What the commands of the run in a sandbox's runner know of it: the ones it started before a
197
+ // restart and how far its log held their output, and the `output` events that say how far it
198
+ // holds it now. They go out through `emit` after the log lines they count, so the registry
199
+ // never keeps an offset ahead of its log.
200
+ function getRunnerCommands(input, emit) {
201
+ return (0, runner_commands_1.createRunnerCommands)({
202
+ ...(input.resumed ? { resumed: input.resumed.outputs } : {}),
203
+ reached: (command, record) => emit({ type: 'output', command, ...record }),
204
+ });
205
+ }
206
+ exports.getRunnerCommands = getRunnerCommands;
207
+ // What the commands of a run that ended left in the sandbox goes: they are killed and their
208
+ // directory removed. Not when the server went (it stops, or died): the run resumes with the
209
+ // next one, which takes its commands up again. A server that stops kills this process before.
210
+ async function removeCommandsOfRun(input, commands, emit) {
211
+ const kubernetes = input.kubernetes;
212
+ const workspace = kubernetes?.server?.workspace;
213
+ if (!kubernetes || !workspace?.runner || commands.executions.size === 0) {
214
+ return;
215
+ }
216
+ try {
217
+ await (0, sandbox_runner_1.removeRunCommands)((0, kubernetes_instance_1.createKubernetesInstances)(kubernetes), kubernetes.namespace, workspace.label, kubernetes.server.run, {
218
+ clean: true,
219
+ });
220
+ }
221
+ catch (e) {
222
+ emit({
223
+ type: 'log',
224
+ task: 'hammerkit',
225
+ stream: 'stderr',
226
+ text: `what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
227
+ });
228
+ }
229
+ }
230
+ exports.removeCommandsOfRun = removeCommandsOfRun;
231
+ // What a task says in the process of a run, as events: the lines it prints (with where the log
232
+ // of its pod got to) and its warnings and errors, in the order they come. The `output` events
233
+ // of the commands in a runner are emitted after the lines they count, on the same way (see
234
+ // getRunnerCommands).
235
+ function relayStatus(status, emit) {
236
+ return status.on((message) => {
237
+ const event = getLogEvent(message);
238
+ if (event) {
239
+ emit(event);
240
+ }
241
+ });
242
+ }
243
+ exports.relayStatus = relayStatus;
174
244
  /**
175
245
  * Executes the tasks of a run with the engine of `hammerkit run`. The caller says which
176
246
  * process this is in: it reports what happens through `emit` and stops when `abortCtrl`
@@ -180,7 +250,9 @@ async function runTasks(input, cwd, processEnvs, abortCtrl,
180
250
  // whether the run was stopped from outside; the engine aborts too when a task fails
181
251
  cancelled, emit,
182
252
  // a service run: its services are ready, at these addresses
183
- up) {
253
+ up,
254
+ // its commands in a sandbox's runner
255
+ commands = getRunnerCommands(input, emit)) {
184
256
  const secrets = (0, redact_1.createSecretRegistry)();
185
257
  const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
186
258
  // the process starts in a directory of the server, the tasks work on the run's files
@@ -194,6 +266,7 @@ up) {
194
266
  accounts: input.accounts,
195
267
  kubernetes: input.kubernetes,
196
268
  capabilityRuntime: input.capabilityRuntime,
269
+ runnerCommands: commands,
197
270
  },
198
271
  abortCtrl,
199
272
  cwd: work,
@@ -205,12 +278,7 @@ up) {
205
278
  stderr: (0, empty_writable_1.emptyWritable)(),
206
279
  stdoutColumns: 120,
207
280
  };
208
- const listener = status.on((message) => {
209
- const event = getLogEvent(message);
210
- if (event) {
211
- emit(event);
212
- }
213
- });
281
+ const listener = relayStatus(status, emit);
214
282
  try {
215
283
  const options = input.options;
216
284
  const execOptions = {
@@ -601,17 +669,31 @@ async function workerMain(stdin, stdout, processEnvs, cwd, abortCtrl) {
601
669
  say({ kind: 'result', ok: false, error: `the run could not be read: ${e instanceof Error ? e.message : e}` });
602
670
  return;
603
671
  }
604
- if (input.up) {
605
- // services stay until they are stopped: without the server that would stop them, at
606
- // their ttl or on a cancel, nothing would
607
- reader.onEnd(stop);
608
- }
672
+ // the input ends before the run does: the server is gone
673
+ let gone = false;
674
+ reader.onEnd(() => {
675
+ gone = true;
676
+ if (input.up) {
677
+ // services stay until they are stopped: without the server that would stop them, at
678
+ // their ttl or on a cancel, nothing would
679
+ stop();
680
+ }
681
+ });
682
+ const emit = (event) => say({ kind: 'event', event });
683
+ const commands = getRunnerCommands(input, emit);
609
684
  try {
610
- await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, (event) => say({ kind: 'event', event }), (targets) => say({ kind: 'up', targets }));
611
- say({ kind: 'result', ok: true });
612
- }
613
- catch (e) {
614
- say({ kind: 'result', ok: false, error: e instanceof Error ? e.message : String(e) });
685
+ let result;
686
+ try {
687
+ await runTasks(input, cwd, processEnvs, abortCtrl, () => cancelled, emit, (targets) => say({ kind: 'up', targets }), commands);
688
+ result = { kind: 'result', ok: true };
689
+ }
690
+ catch (e) {
691
+ result = { kind: 'result', ok: false, error: e instanceof Error ? e.message : String(e) };
692
+ }
693
+ if (!gone) {
694
+ await removeCommandsOfRun(input, commands, emit);
695
+ }
696
+ say(result);
615
697
  }
616
698
  finally {
617
699
  reader.close();
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.unavailableExecutor = exports.RunRegistry = exports.isLogCursor = exports.logCursors = exports.MAX_CURSORS_PER_ITEM = exports.MAX_COMMANDS = exports.MAX_TASK_ERROR = exports.MAX_CAUSES = exports.MAX_RESUMES = exports.CLOSE_TIMEOUT = exports.SANDBOX_ID_PATTERN = exports.RUN_ID_PATTERN = exports.QuotaError = exports.ShuttingDownError = exports.RunError = exports.isDetached = exports.RUN_PHASES = exports.isFinal = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const oauth_1 = require("./oauth");
6
+ const runner_commands_1 = require("../executer/runner-commands");
6
7
  const run_logs_1 = require("./run-logs");
7
8
  const units_1 = require("../utils/units");
8
9
  const FINAL_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
@@ -220,6 +221,39 @@ function checkKeys(keys) {
220
221
  .filter(([, key]) => key === null || typeof key === 'string')
221
222
  .slice(0, MAX_KEYED_TASKS));
222
223
  }
224
+ // The commands of a record, as the registry keeps them (`output` events)
225
+ function commandRecords(outputs) {
226
+ if (!outputs || typeof outputs !== 'object' || Array.isArray(outputs)) {
227
+ return {};
228
+ }
229
+ return Object.fromEntries(Object.entries(outputs)
230
+ .flatMap(([command, record]) => {
231
+ const kept = toCommandRecord({ ...record, command });
232
+ return kept ? [[command, kept]] : [];
233
+ })
234
+ .slice(0, runner_commands_1.MAX_OUTPUT_COMMANDS));
235
+ }
236
+ // What an `output` event says of its command, when it is one
237
+ function toCommandRecord(event) {
238
+ const count = (value) => Number.isSafeInteger(value) && value >= 0;
239
+ if (typeof event?.command !== 'string' ||
240
+ !runner_commands_1.COMMAND_ID_PATTERN.test(event.command) ||
241
+ typeof event.task !== 'string' ||
242
+ event.task.length > 1024 ||
243
+ ![event.step, event.execution, event.stdout, event.stderr].every(count)) {
244
+ return undefined;
245
+ }
246
+ const { task, step, execution, stdout, stderr } = event;
247
+ return {
248
+ task,
249
+ step,
250
+ execution,
251
+ stdout,
252
+ stderr,
253
+ ...(event.done === true ? { done: true } : {}),
254
+ ...(event.cut === true ? { cut: true } : {}),
255
+ };
256
+ }
223
257
  // What keeps the run of a record from executing again: what it runs, from where, is not in it
224
258
  function unresumable(run) {
225
259
  if (typeof run.id !== 'string' || !exports.RUN_ID_PATTERN.test(run.id)) {
@@ -292,7 +326,7 @@ class RunRegistry {
292
326
  // the queue as it was: the runs that executed first, then the others as they were queued
293
327
  const resuming = [];
294
328
  skipped.forEach((name) => this.options.log?.(`skip run record ${name}: it can not be read`));
295
- for (const { run, events, keys, cursors, clean } of records) {
329
+ for (const { run, events, keys, cursors, outputs, clean } of records) {
296
330
  // a move that executed went with the server
297
331
  delete run.moving;
298
332
  const entry = {
@@ -306,6 +340,7 @@ class RunRegistry {
306
340
  saving: Promise.resolve(),
307
341
  keys: checkKeys(keys),
308
342
  cursors: logCursors(cursors),
343
+ outputs: commandRecords(outputs),
309
344
  };
310
345
  this.entries.set(run.id, entry);
311
346
  if (run.state === 'awaiting-approval') {
@@ -1052,14 +1087,18 @@ class RunRegistry {
1052
1087
  runningOf(owner) {
1053
1088
  return this.usage(owner).running.length;
1054
1089
  }
1055
- // The run on the same sandbox that executes: a sandbox runs one at a time.
1090
+ // The run on the same sandbox that executes: a sandbox runs one at a time. One that executed
1091
+ // before a restart and resumes holds it from the queue too: what it runs on in the sandbox's
1092
+ // runner is not another run's to clean up.
1056
1093
  sandboxBusy(run) {
1057
1094
  const source = run.source;
1058
1095
  if (source.type !== 'sandbox') {
1059
1096
  return undefined;
1060
1097
  }
1061
- return [...this.entries.values()].find((entry) => entry.run.state === 'running' && onSandbox(entry.run, source.id))
1062
- ?.run.id;
1098
+ const resuming = this.entries.get(run.id)?.resumed;
1099
+ return [...this.entries.values()].find((entry) => onSandbox(entry.run, source.id) &&
1100
+ (entry.run.state === 'running' ||
1101
+ (entry.run.state === 'queued' && entry.resumed && !resuming && entry.run.id !== run.id)))?.run.id;
1063
1102
  }
1064
1103
  // The run that executes and holds what the run would (RunExecutor.excludes)
1065
1104
  held(run) {
@@ -1156,7 +1195,16 @@ class RunRegistry {
1156
1195
  emit: (event) => this.record(entry, event),
1157
1196
  signal: entry.abort.signal,
1158
1197
  detached: () => !!entry.detached,
1159
- ...(resumed ? { resumed: { logs: cursorsOf(entry.cursors) } } : {}),
1198
+ ...(resumed
1199
+ ? {
1200
+ resumed: {
1201
+ logs: cursorsOf(entry.cursors),
1202
+ // the commands it started in a sandbox's runner, which a run that went on
1203
+ // takes up again
1204
+ ...(continues ? { outputs: { ...entry.outputs } } : {}),
1205
+ },
1206
+ }
1207
+ : {}),
1160
1208
  ...(Object.keys(durations).length > 0 ? { durations } : {}),
1161
1209
  ...(this.options.artifacts && !entry.run.up
1162
1210
  ? {
@@ -1839,6 +1887,10 @@ class RunRegistry {
1839
1887
  }
1840
1888
  recorded = line;
1841
1889
  }
1890
+ if (recorded.type === 'output') {
1891
+ this.keepCommand(entry, recorded);
1892
+ return;
1893
+ }
1842
1894
  const event = recorded.type === 'task' ? bounded(recorded) : recorded;
1843
1895
  if (event.type === 'log') {
1844
1896
  this.keepTail(entry, event.task, event.text);
@@ -1865,6 +1917,29 @@ class RunRegistry {
1865
1917
  }
1866
1918
  this.push(entry, event);
1867
1919
  }
1920
+ // the newest of each command; past MAX_OUTPUT_COMMANDS one that ended makes way for a new one,
1921
+ // which a run that resumes would start again
1922
+ keepCommand(entry, event) {
1923
+ const record = toCommandRecord(event);
1924
+ if (!record) {
1925
+ return;
1926
+ }
1927
+ const outputs = (entry.outputs ?? (entry.outputs = {}));
1928
+ const started = !(event.command in outputs);
1929
+ if (started && Object.keys(outputs).length >= runner_commands_1.MAX_OUTPUT_COMMANDS) {
1930
+ const ended = Object.keys(outputs).find((command) => outputs[command].done);
1931
+ if (!ended) {
1932
+ return;
1933
+ }
1934
+ delete outputs[ended];
1935
+ }
1936
+ outputs[event.command] = record;
1937
+ if (started && !this.closed) {
1938
+ // written down at once: a server killed before its next write would have the run resume
1939
+ // without it, start the command again and kill the one that runs
1940
+ this.persist(entry);
1941
+ }
1942
+ }
1868
1943
  // once each, from the executor: a phase it reports again (a service run that wakes) is the
1869
1944
  // newest
1870
1945
  keepPhase(entry, event) {
@@ -1958,11 +2033,14 @@ class RunRegistry {
1958
2033
  const keys = isFinal(entry.run.state) || Object.keys(entry.keys).length === 0 ? {} : { keys: { ...entry.keys } };
1959
2034
  // where the logs of its pods got to, for the next server that resumes it
1960
2035
  const cursors = isFinal(entry.run.state) || entry.cursors.size === 0 ? {} : { cursors: cursorsOf(entry.cursors) };
2036
+ // what the log of a run that resumes holds of the output of its commands, as far as `events` go
2037
+ const outputs = isFinal(entry.run.state) || Object.keys(entry.outputs ?? {}).length === 0 ? {} : { outputs: { ...entry.outputs } };
1961
2038
  const record = {
1962
2039
  run: this.copy(entry.run),
1963
2040
  events: [...entry.events],
1964
2041
  ...keys,
1965
2042
  ...cursors,
2043
+ ...outputs,
1966
2044
  ...(clean || this.written ? { clean: true } : {}),
1967
2045
  };
1968
2046
  entry.saving = entry.saving
@@ -11,6 +11,7 @@ const path_1 = require("path");
11
11
  const minimatch_1 = require("minimatch");
12
12
  const source_manifest_1 = require("../remote/source-manifest");
13
13
  const sandbox_patch_1 = require("./sandbox-patch");
14
+ const runner_commands_1 = require("../executer/runner-commands");
14
15
  // The largest file the API reads into memory, edits or writes: the limit of an upload.
15
16
  exports.MAX_FILE_BYTES = source_manifest_1.MAX_SOURCE_FILE_BYTES;
16
17
  // what one typed read answers at most
@@ -66,8 +67,13 @@ function checkPath(path) {
66
67
  }
67
68
  exports.checkPath = checkPath;
68
69
  // The deny list of uploads, with the last name taken as a directory too, so `.git` itself
69
- // is as denied as what is in it.
70
+ // is as denied as what is in it. The output of the commands of runs in the sandbox's runner
71
+ // is denied too: it is the runs' to read (their logs), not a file of the sandbox, and a file
72
+ // written there could pass for how a command ended.
70
73
  function deniedPath(path) {
74
+ if (path === runner_commands_1.RUNNER_COMMANDS_DIRECTORY || path.startsWith(`${runner_commands_1.RUNNER_COMMANDS_DIRECTORY}/`)) {
75
+ return 'the commands of runs keep their output there';
76
+ }
71
77
  return (0, source_manifest_1.deniedSourcePath)(path) ?? (0, source_manifest_1.deniedSourcePath)(`${path}/-`);
72
78
  }
73
79
  exports.deniedPath = deniedPath;
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.1.0-next.15",
4
+ "version": "2.1.0-next.17",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",