hammerkit 2.1.0-next.14 → 2.1.0-next.16

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.
@@ -6,6 +6,7 @@ const path_1 = require("path");
6
6
  const crypto_1 = require("crypto");
7
7
  const promises_1 = require("fs/promises");
8
8
  const limit_1 = require("../utils/limit");
9
+ const runner_commands_1 = require("../executer/runner-commands");
9
10
  function isExcluded(path, excluded) {
10
11
  return excluded.some((excludedPath) => path === excludedPath || path.startsWith(excludedPath + path_1.sep));
11
12
  }
@@ -31,6 +32,12 @@ async function addWorkCacheStats(result, cwd, path, matcher, context, root, excl
31
32
  }
32
33
  async function visitPath(cwd, path, matcher, context, root) {
33
34
  const key = (0, path_1.relative)(cwd, path).split(path_1.sep).join(path_1.posix.sep);
35
+ // On a server, what the commands of runs in a sandbox's runner keep at the root of its files
36
+ // is their output: no source of a task, which would key it by the runs before
37
+ const workspace = context.hosted?.kubernetes?.server?.workspace;
38
+ if (workspace?.runner && (0, runner_commands_1.isRunnerCommandsPath)(path, workspace.root)) {
39
+ return { type: 'none' };
40
+ }
34
41
  // On a server the files were written by a commit or a task: a link is a source as it is,
35
42
  // its target, and never followed. A `**` would walk `x -> /` through the server's disk.
36
43
  if (context.hosted) {
@@ -15,6 +15,15 @@ function logContext(type, item) {
15
15
  };
16
16
  }
17
17
  exports.logContext = logContext;
18
+ // what a message says to its readers: the cursor of a line is for a server that resumes a run
19
+ function withoutCursor(message) {
20
+ if (message.type !== 'console') {
21
+ return message;
22
+ }
23
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- left out on purpose
24
+ const { cursor, ...rest } = message;
25
+ return rest;
26
+ }
18
27
  // `secrets` is the registry of the run (its Environment) whose output this console shows.
19
28
  function statusConsole(writable, secrets = (0, redact_1.createSecretRegistry)()) {
20
29
  const statusBuffer = new buffer_context_1.BufferContext(StatusBufferMax);
@@ -23,7 +32,7 @@ function statusConsole(writable, secrets = (0, redact_1.createSecretRegistry)())
23
32
  function addMessage(context, unredacted) {
24
33
  const message = { ...unredacted, message: secrets.redact(unredacted.message) };
25
34
  emit.emit(message);
26
- writable.write(JSON.stringify({ context, message }) + '\n');
35
+ writable.write(JSON.stringify({ context, message: withoutCursor(message) }) + '\n');
27
36
  if (message.type === 'console') {
28
37
  consoleBuffer.add(context.name, message);
29
38
  }
@@ -58,13 +67,14 @@ function statusConsole(writable, secrets = (0, redact_1.createSecretRegistry)())
58
67
  yield log;
59
68
  }
60
69
  },
61
- console(type, message) {
70
+ console(type, message, cursor) {
62
71
  addMessage(context, {
63
72
  type: 'console',
64
73
  console: type,
65
74
  message,
66
75
  date: new Date(),
67
76
  context,
77
+ ...(cursor ? { cursor } : {}),
68
78
  });
69
79
  },
70
80
  write(level, message) {
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.removeLegacyKubernetesService = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = exports.recordJobExecution = void 0;
6
+ exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.removeLegacyKubernetesService = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = exports.recordJobExecution = exports.getResumedLogs = void 0;
7
7
  const abort_1 = require("../executer/abort");
8
8
  const kubernetes_service_1 = require("../executer/kubernetes-service");
9
9
  const kubernetes_instance_1 = require("../kubernetes/kubernetes-instance");
@@ -47,6 +47,125 @@ async function listJobNames(instance, kubernetes, task) {
47
47
  });
48
48
  return jobs.items.flatMap((job) => (job.metadata?.name ? [job.metadata.name] : []));
49
49
  }
50
+ // The command of the task a Job runs (from 1), by the name of its container
51
+ function getJobCommand(job) {
52
+ const match = /^cmd-(\d+)$/.exec(job.spec?.template.spec?.containers[0]?.name ?? '');
53
+ return match ? Number(match[1]) : undefined;
54
+ }
55
+ // Whether the container runs the command as the task would make it now
56
+ function runsCommand(container, expected) {
57
+ if (!container) {
58
+ return false;
59
+ }
60
+ return (container.image === expected.image &&
61
+ JSON.stringify(container.command ?? []) === JSON.stringify(expected.command ?? []) &&
62
+ JSON.stringify(container.args ?? []) === JSON.stringify(expected.args ?? []) &&
63
+ expected.env.every((variable) => container.env?.some((has) => has.name === variable.name && has.value === variable.value && !has.valueFrom)));
64
+ }
65
+ // Whether the pod of a Job mounts the claim
66
+ function mountsClaim(job, claim) {
67
+ return (job.spec?.template.spec?.volumes ?? []).some((volume) => volume.persistentVolumeClaim?.claimName === claim);
68
+ }
69
+ // Where the log of an item got to before a restart of the server, by instance of its container:
70
+ // an own entry of the record only, an item may be named as a property of any object
71
+ function getResumedLogs(kubernetes, item) {
72
+ const logs = kubernetes.server?.resumed?.logs;
73
+ const cursors = logs && Object.prototype.hasOwnProperty.call(logs, item) ? logs[item] : undefined;
74
+ return Array.isArray(cursors) ? cursors : undefined;
75
+ }
76
+ exports.getResumedLogs = getResumedLogs;
77
+ function isJobFinished(job) {
78
+ return (!!job.status?.succeeded ||
79
+ !!job.status?.conditions?.some((c) => (c.type === 'Complete' || c.type === 'Failed') && c.status === 'True'));
80
+ }
81
+ // The Secrets the pod of a Job reads: the values the server handed over and the credentials
82
+ // of its init containers
83
+ function getJobSecretNames(job) {
84
+ const pod = job.spec?.template.spec;
85
+ const names = new Set();
86
+ for (const volume of pod?.volumes ?? []) {
87
+ if (volume.secret?.secretName) {
88
+ names.add(volume.secret.secretName);
89
+ }
90
+ }
91
+ for (const container of [...(pod?.initContainers ?? []), ...(pod?.containers ?? [])]) {
92
+ for (const env of container.env ?? []) {
93
+ if (env.valueFrom?.secretKeyRef?.name) {
94
+ names.add(env.valueFrom.secretKeyRef.name);
95
+ }
96
+ }
97
+ for (const from of container.envFrom ?? []) {
98
+ if (from.secretRef?.name) {
99
+ names.add(from.secretRef.name);
100
+ }
101
+ }
102
+ }
103
+ return [...names];
104
+ }
105
+ async function secretExists(instance, namespace, name) {
106
+ try {
107
+ const secret = await instance.coreApi.readNamespacedSecret({ name, namespace });
108
+ return !secret.metadata?.deletionTimestamp;
109
+ }
110
+ catch (e) {
111
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
112
+ return false;
113
+ }
114
+ throw e;
115
+ }
116
+ }
117
+ /**
118
+ * The Job a run that resumes after a restart of the server left for the task at this state,
119
+ * and the command it runs (from 1): the one of its deterministic name, labelled with the run
120
+ * and the state, whose container is the one of that command (`expected`). A Job of another
121
+ * run, state or command, or one that goes, is not the task's to take. Nor is one whose files
122
+ * may not be what it wrote: a claim that another run wrote to since (`claim`, the marker the
123
+ * Job's execution left on it), or the Secrets it reads that are gone while it may still need
124
+ * them (it did not finish, or a command comes after it).
125
+ */
126
+ async function findLeftJob(instance, kubernetes, task, options) {
127
+ let job;
128
+ try {
129
+ job = await instance.batchApi.readNamespacedJob({
130
+ name: (0, resources_1.getResourceName)(task, kubernetes, '-job'),
131
+ namespace: kubernetes.namespace,
132
+ });
133
+ }
134
+ catch (e) {
135
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
136
+ return undefined;
137
+ }
138
+ throw e;
139
+ }
140
+ const labels = job.metadata?.labels ?? {};
141
+ const command = getJobCommand(job);
142
+ if (job.metadata?.deletionTimestamp ||
143
+ labels[network_policy_1.RUN_LABEL] !== options.run ||
144
+ labels['hammerkit.dev/state'] !== options.stateKey ||
145
+ command === undefined ||
146
+ command < 1 ||
147
+ command > task.data.cmds.length) {
148
+ return undefined;
149
+ }
150
+ const expected = options.expected(task.data.cmds[command - 1]);
151
+ if (!expected || !runsCommand(job.spec?.template.spec?.containers[0], expected)) {
152
+ return undefined;
153
+ }
154
+ // a claim it does not mount holds nothing of it
155
+ if (options.claim &&
156
+ mountsClaim(job, options.claim.name) &&
157
+ !(await (0, kept_claims_1.isClaimWrittenBy)(instance, kubernetes, options.claim.name, options.claim.writer))) {
158
+ return undefined;
159
+ }
160
+ if (!isJobFinished(job) || command < task.data.cmds.length) {
161
+ for (const name of getJobSecretNames(job)) {
162
+ if (!(await secretExists(instance, kubernetes.namespace, name))) {
163
+ return undefined;
164
+ }
165
+ }
166
+ }
167
+ return { job, command };
168
+ }
50
169
  // The Secret of the values the server hands over and the one of the credentials the
51
170
  // pod reads its own secrets with
52
171
  async function removeTaskSecrets(instance, kubernetes, task) {
@@ -209,7 +328,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
209
328
  // a shell of a sandbox: its commands go into the sandbox's runner, when it has one now
210
329
  if ((0, sandbox_runner_1.canUseRunner)(task, kubernetes, persistence)) {
211
330
  try {
212
- const result = await (0, sandbox_runner_1.executeInRunner)(instance, task, kubernetes, persistence, options.abort);
331
+ const result = await (0, sandbox_runner_1.executeInRunner)(instance, task, kubernetes, persistence, options.abort, environment.hosted?.runnerCommands);
213
332
  if (result.type === 'crash') {
214
333
  options.state.set({ stateKey: options.stateKey, type: 'crash', exitCode: result.exitCode });
215
334
  return;
@@ -228,30 +347,84 @@ function kubernetesTaskRuntime(task, kubernetes) {
228
347
  return;
229
348
  }
230
349
  }
350
+ const server = kubernetes.server;
351
+ // the run label of its pods: on a server, the server's run; on a sandbox, its proxy
352
+ // stays with the sandbox for the next runs
353
+ const run = server ? (0, job_placement_1.getRunLabelValue)(server.run) : (0, run_id_1.getRunId)();
354
+ const { delivered, inJob } = (0, job_secrets_1.splitJobSecrets)(task.data.secrets, server);
355
+ // the Job of a run and state writes to a claim other runs mount too (see WRITER_ANNOTATION)
356
+ const writer = `${run}/${options.stateKey}`;
357
+ // a run that resumes after a restart of the server: the Job the task left goes on, from
358
+ // the command it ran, and its files are the ones it works on
359
+ let adopted;
360
+ if (server?.resumed) {
361
+ try {
362
+ adopted = await findLeftJob(instance, kubernetes, task, {
363
+ run,
364
+ stateKey: options.stateKey,
365
+ expected: (cmd) => {
366
+ try {
367
+ // the wrapper of the command depends on the secrets it reads, not on the
368
+ // credentials minted for them nor the proxy (those go to init containers)
369
+ const command = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, {}, environment).command(task.data.shell, (0, task_arguments_1.getKubernetesCommandText)(cmd));
370
+ // the image of the container of a Job (getTaskJobContainers)
371
+ return { image: task.data.image, command: command.command, args: command.args, env: command.env };
372
+ }
373
+ catch (e) {
374
+ // a Job of the task can't be made now (the Job it starts says why): none is taken over
375
+ task.status.write('debug', `${task.name}: its job is not taken over: ${(0, log_1.getErrorMessage)(e)}`);
376
+ return undefined;
377
+ }
378
+ },
379
+ ...(remembers ? { claim: { name: claim, writer } } : {}),
380
+ });
381
+ }
382
+ catch (e) {
383
+ options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
384
+ return;
385
+ }
386
+ }
231
387
  await (0, ensure_namespace_1.ensureNamespace)(instance, kubernetes.namespace);
232
388
  // a service run writes the outputs of each state into a folder of their own (see
233
389
  // getStateFilesDir), which pods of its services may mount: of the commit before during
234
390
  // a move, or of this state after a move that went back
235
391
  const files = kubernetes.server?.serviceRun ? { dir: (0, volumes_1.getStateFilesDir)(options.stateKey) } : undefined;
236
392
  try {
237
- if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
393
+ if (adopted) {
394
+ task.status.write('info', `${task.name}: takes over its job from before the restart of the server`);
395
+ }
396
+ else if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
238
397
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
239
398
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
240
399
  return;
241
400
  }
242
- // the task writes to it now: what it holds stops being the outputs of a state, and
243
- // goes, as a new claim would hold nothing (on a service run, the folders of other
244
- // states that no pod mounts go)
245
- const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
246
- const reset = kept && forgotten;
247
- await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
401
+ else {
402
+ // The last job of a run stays: its state label is what currentStateKey reads. Jobs
403
+ // from an earlier run of this task go before this one starts, and before its files
404
+ // change: one left is never taken over over files written since.
405
+ for (const name of await listJobNames(instance, kubernetes, task)) {
406
+ await (0, await_running_state_1.deleteJobAndWait)(instance, kubernetes, name, options.abort);
407
+ }
408
+ // the task writes to it now: what it holds stops being the outputs of a state, and
409
+ // goes, as a new claim would hold nothing (on a service run, the folders of other
410
+ // states that no pod mounts go)
411
+ const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
412
+ const reset = kept && forgotten;
413
+ await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
414
+ if (remembers) {
415
+ // the claim is there now, also on the first run of a source: the Job of this run
416
+ // and state is the one that writes to it
417
+ await (0, kept_claims_1.markClaimWriter)(instance, kubernetes, claim, writer);
418
+ }
419
+ }
248
420
  }
249
421
  catch (e) {
422
+ if (e instanceof abort_1.AbortError) {
423
+ throw e;
424
+ }
250
425
  options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
251
426
  return;
252
427
  }
253
- const server = kubernetes.server;
254
- const { delivered, inJob } = (0, job_secrets_1.splitJobSecrets)(task.data.secrets, server);
255
428
  const secrets = (0, secrets_1.getKubernetesSecretRefs)(task, kubernetes, delivered);
256
429
  const admitted = environment.hosted?.accounts;
257
430
  let secretHosts;
@@ -260,7 +433,10 @@ function kubernetesTaskRuntime(task, kubernetes) {
260
433
  if (server) {
261
434
  (0, job_secrets_1.assertJobAccounts)(inJob, server, admitted);
262
435
  }
263
- await (0, secrets_1.ensureKubernetesSecret)(instance, kubernetes, task, delivered, environment);
436
+ // the values a Job it took over reads are in the Secret it was started with
437
+ if (!adopted) {
438
+ await (0, secrets_1.ensureKubernetesSecret)(instance, kubernetes, task, delivered, environment);
439
+ }
264
440
  }
265
441
  catch (e) {
266
442
  await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
@@ -270,7 +446,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
270
446
  // the run its pods and limits belong to: on a server, the server's run; on a
271
447
  // sandbox, its proxy stays with the sandbox for the next runs
272
448
  const scope = {
273
- run: server ? (0, job_placement_1.getRunLabelValue)(server.run) : (0, run_id_1.getRunId)(),
449
+ run,
274
450
  ...(server?.workspace
275
451
  ? {
276
452
  sandbox: {
@@ -288,11 +464,6 @@ function kubernetesTaskRuntime(task, kubernetes) {
288
464
  ...(0, network_policy_1.getNetworkLabels)(kubernetes, task),
289
465
  };
290
466
  const placement = server ? (0, job_placement_1.getPodPlacement)(server, task.data.pool) : null;
291
- // The last job of a run stays: its state label is what currentStateKey
292
- // reads. Jobs from an earlier run of this task go before this one starts.
293
- for (const name of await listJobNames(instance, kubernetes, task)) {
294
- await (0, await_running_state_1.deleteJobAndWait)(instance, kubernetes, name, options.abort);
295
- }
296
467
  // the services the task needs by the names it lists them under, and the
297
468
  // NetworkPolicy and proxy of a limited network, both of this run
298
469
  let network;
@@ -313,18 +484,26 @@ function kubernetesTaskRuntime(task, kubernetes) {
313
484
  let i = 0;
314
485
  for (const cmd of task.data.cmds) {
315
486
  const container = `cmd-${++i}`;
316
- let secretSpec;
317
- try {
318
- // made for each Job right before it, so a later command's token is as fresh
319
- const credentials = await (0, job_secrets_1.ensureJobCredentials)(instance, kubernetes, task, inJob, admitted);
320
- secretSpec = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, credentials, environment, network.secretEnv);
487
+ // the commands before the one of a Job it took over ran before the restart
488
+ if (adopted && i < adopted.command) {
489
+ continue;
321
490
  }
322
- catch (e) {
323
- await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
324
- options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
325
- return;
491
+ // a Job it took over keeps the pod and the credentials it was started with
492
+ const left = adopted?.command === i ? adopted.job : undefined;
493
+ let secretSpec;
494
+ if (!left) {
495
+ try {
496
+ // made for each Job right before it, so a later command's token is as fresh
497
+ const credentials = await (0, job_secrets_1.ensureJobCredentials)(instance, kubernetes, task, inJob, admitted);
498
+ secretSpec = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, credentials, environment, network.secretEnv);
499
+ }
500
+ catch (e) {
501
+ await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
502
+ options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
503
+ return;
504
+ }
326
505
  }
327
- const spec = {
506
+ const spec = secretSpec && {
328
507
  kind: 'Job',
329
508
  apiVersion: 'batch/v1',
330
509
  metadata: {
@@ -380,13 +559,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
380
559
  },
381
560
  };
382
561
  try {
383
- const pod = await (0, apply_1.apply)(instance, spec);
384
- // what the command prints, while it prints it; the last lines once the pod ended
385
- const logs = (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, `job-name=${podName}`, container, (line) => task.status.console('stdout', line), { onError: (text) => task.status.write('debug', text) });
562
+ const pod = left ?? (await (0, apply_1.apply)(instance, spec));
563
+ // what the command prints, while it prints it; the last lines once the pod ended.
564
+ // Of a Job it took over, from where the run's log got to.
565
+ const from = left ? getResumedLogs(kubernetes, task.name) : undefined;
566
+ const logs = (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, `job-name=${podName}`, container, (line, cursor) => task.status.console('stdout', line, cursor), { onError: (text) => task.status.write('debug', text), ...(from ? { from } : {}) });
386
567
  try {
387
568
  if (!pod.status?.succeeded) {
388
569
  try {
389
- await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
570
+ await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, podName, options.abort, 1000, {
390
571
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
391
572
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
392
573
  onRefused: options.onQuotaRefused,
@@ -505,7 +686,14 @@ function kubernetesTaskRuntime(task, kubernetes) {
505
686
  namespace: kubernetes.namespace,
506
687
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),
507
688
  });
689
+ // the Job of an earlier command that succeeded (a server stopped before it went) is not
690
+ // the task's. A Job whose container names no command still counts: one of an older
691
+ // version, whose state a run before the update recorded so.
508
692
  const completedStates = jobs.items
693
+ .filter((j) => {
694
+ const command = getJobCommand(j);
695
+ return command === undefined || command >= task.data.cmds.length;
696
+ })
509
697
  .filter((j) => j.status?.succeeded && j.metadata?.labels?.['hammerkit.dev/state'])
510
698
  .map((j) => j.metadata.labels['hammerkit.dev/state']);
511
699
  const stateKey = completedStates[completedStates.length - 1] ?? null;
@@ -607,13 +795,39 @@ function kubernetesServiceRuntime(service, kubernetes) {
607
795
  },
608
796
  async execute(environment, options) {
609
797
  const name = (0, resources_1.getResourceName)(service, kubernetes);
610
- // a service run that moves to another commit: a service of the same definition and
611
- // state is left running, another one is rolled from the Deployment it has now
798
+ // its output, as on Docker: while it starts, and while it runs unless it runs on
799
+ // without hammerkit (`up --daemon`)
800
+ const followLogs = (from) => (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, (0, resources_1.getItemSelector)(service, kubernetes), (0, ensure_kubernetes_deployment_exists_1.getServiceContainerName)(service), (line, cursor) => service.status.console('stdout', line, cursor), { onError: (text) => service.status.write('debug', text), ...(from ? { from } : {}) });
801
+ const followWhileUp = (logs) => {
802
+ if (options.daemon || options.abort.aborted || environment.abortCtrl.signal.aborted) {
803
+ logs.stop();
804
+ return;
805
+ }
806
+ // either ends it, and takes the other listener with it
807
+ const listening = new AbortController();
808
+ const stop = () => {
809
+ logs.stop();
810
+ listening.abort();
811
+ };
812
+ options.abort.addEventListener('abort', stop, { once: true, signal: listening.signal });
813
+ environment.abortCtrl.signal.addEventListener('abort', stop, { once: true, signal: listening.signal });
814
+ };
815
+ // a service run that moves to another commit, or that resumes after a restart of the
816
+ // server: a service of the same definition and state is left running, another one is
817
+ // rolled from the Deployment it has now
612
818
  let previous;
613
819
  if (kubernetes.server?.serviceRun) {
614
820
  previous = await readDeployment(instance, kubernetes.namespace, name);
615
- if (previous && isRolledOut(previous, (0, service_definition_1.getServiceDefinitionHash)(service), options.stateKey)) {
821
+ const resumed = kubernetes.server.resumed;
822
+ // after a restart, only a Deployment the run started stays (a move's are the run's anyway)
823
+ const ours = !resumed || previous?.metadata?.labels?.[network_policy_1.RUN_LABEL] === (0, job_placement_1.getRunLabelValue)(kubernetes.server.run);
824
+ if (previous && ours && isRolledOut(previous, (0, service_definition_1.getServiceDefinitionHash)(service), options.stateKey)) {
616
825
  service.status.write('info', `${service.name} did not change, it stays up`);
826
+ if (resumed) {
827
+ // the execution before the restart followed its log, a move leaves that to the
828
+ // execution it takes the services over from
829
+ followWhileUp(followLogs(getResumedLogs(kubernetes, service.name)));
830
+ }
617
831
  options.state.set({ type: 'running', dns: { containerId: name }, stateKey: options.stateKey, remote: null });
618
832
  return;
619
833
  }
@@ -645,9 +859,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
645
859
  followLog: false,
646
860
  run: kubernetes.server ? (0, job_placement_1.getRunLabelValue)(kubernetes.server.run) : null,
647
861
  });
648
- // its output, as on Docker: while it starts, and while it runs unless it runs on
649
- // without hammerkit (`up --daemon`)
650
- const logs = (0, follow_pod_logs_1.followPodLogs)(instance, kubernetes.namespace, (0, resources_1.getItemSelector)(service, kubernetes), (0, ensure_kubernetes_deployment_exists_1.getServiceContainerName)(service), (line) => service.status.console('stdout', line), { onError: (text) => service.status.write('debug', text) });
862
+ const logs = followLogs();
651
863
  try {
652
864
  await (0, ensure_kubernetes_deployment_exists_1.ensureKubernetesDeploymentExists)(instance, kubernetes, service, persistence, (0, secrets_1.getKubernetesSecretRefs)(service, kubernetes, service.data.secrets), options.stateKey, network, { previous, signal: options.abort });
653
865
  }
@@ -657,19 +869,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
657
869
  logs.stop();
658
870
  throw e;
659
871
  }
660
- if (options.daemon || options.abort.aborted || environment.abortCtrl.signal.aborted) {
661
- logs.stop();
662
- }
663
- else {
664
- // either ends it, and takes the other listener with it
665
- const listening = new AbortController();
666
- const stop = () => {
667
- logs.stop();
668
- listening.abort();
669
- };
670
- options.abort.addEventListener('abort', stop, { once: true, signal: listening.signal });
671
- environment.abortCtrl.signal.addEventListener('abort', stop, { once: true, signal: listening.signal });
672
- }
872
+ followWhileUp(logs);
673
873
  options.state.set({
674
874
  type: 'running',
675
875
  dns: { containerId: name },
@@ -363,6 +363,9 @@ class HostExecutor {
363
363
  volumeScope: volumeScope(run, this.options.directory),
364
364
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
365
365
  ...(context.durations ? { durations: context.durations } : {}),
366
+ // the commands it started in a sandbox's runner; the logs of its pods go in the
367
+ // cluster's environment (KubernetesExecutor)
368
+ ...(context.resumed?.outputs ? { resumed: { outputs: context.resumed.outputs } } : {}),
366
369
  ...(artifacts ? { artifacts } : {}),
367
370
  catalog: planning.environment.hosted?.catalog,
368
371
  ...(run.up
@@ -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
@@ -580,7 +599,7 @@ class KubernetesExecutor {
580
599
  // its pods take room the callers can't borrow
581
600
  await this.quotas?.serviceRun(namespace, this.config.runs.up.quota ?? this.config.backend.quota);
582
601
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
583
- return { kubernetes: this.environmentOf(run, namespace), env: this.access.env };
602
+ return { kubernetes: this.environmentOf(run, namespace, context), env: this.access.env };
584
603
  }
585
604
  const label = (0, job_placement_1.getRunLabelValue)(run.id);
586
605
  let capabilitiesProblem;
@@ -617,7 +636,7 @@ class KubernetesExecutor {
617
636
  context.emit({ type: 'log', task: 'hammerkit', stream: 'stdout', text: `runs in the namespace ${namespace}` });
618
637
  this.placed.add(run.id);
619
638
  return {
620
- kubernetes: this.environmentOf(run, namespace, work, capabilitiesProblem),
639
+ kubernetes: this.environmentOf(run, namespace, context, work, capabilitiesProblem),
621
640
  env: this.access.env,
622
641
  };
623
642
  },
@@ -686,7 +705,7 @@ class KubernetesExecutor {
686
705
  }
687
706
  }
688
707
  // The cluster as the process of a run sees it: the namespace its tasks and services go in.
689
- environmentOf(run, namespace, work, capabilitiesProblem) {
708
+ environmentOf(run, namespace, context, work, capabilitiesProblem) {
690
709
  const backend = this.config.backend;
691
710
  const openGate = (0, network_gate_1.getOpenNetworkGate)(backend);
692
711
  return {
@@ -710,6 +729,8 @@ class KubernetesExecutor {
710
729
  ...(this.keep > 0 && !run.up ? { volumeScope: getVolumeScope(run) } : {}),
711
730
  ...(run.up ? { serviceRun: true } : {}),
712
731
  ...(openGate ? { openGate } : {}),
732
+ // what the execution before a restart left, its tasks and services take over
733
+ ...(context.resumed ? { resumed: { logs: context.resumed.logs } } : {}),
713
734
  ...(backend.capabilities
714
735
  ? {
715
736
  capabilities: {