hammerkit 2.1.0 → 2.2.0-next.2

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.
Files changed (103) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cache/backends/registry/push-credentials.js +50 -0
  3. package/dist/cache/backends/registry/registry-client.js +41 -10
  4. package/dist/cache/backends/registry-cache-backend.js +6 -1
  5. package/dist/cache/cache-inventory.js +3 -0
  6. package/dist/cli.js +5 -0
  7. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  8. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  9. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/docker/item-network.js +6 -5
  12. package/dist/docker/remove-orphaned-containers.js +5 -4
  13. package/dist/environment/replace-env-variables.js +8 -5
  14. package/dist/environment/run-source-envs.js +2 -1
  15. package/dist/executer/archive-task-entry.js +1 -1
  16. package/dist/executer/check-readiness.js +8 -4
  17. package/dist/executer/docker-healthcheck.js +73 -0
  18. package/dist/executer/docker-service.js +21 -15
  19. package/dist/executer/event-cache.js +7 -1
  20. package/dist/executer/execute-work-task.js +8 -0
  21. package/dist/executer/runner-commands.js +36 -0
  22. package/dist/file/get-file-context.js +4 -7
  23. package/dist/harness/connect.js +12 -8
  24. package/dist/harness/reconnect.js +141 -0
  25. package/dist/harness/sandbox-client.js +241 -33
  26. package/dist/harness/service-tools.js +11 -2
  27. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  28. package/dist/kubernetes/ensure-persistent-data.js +1 -1
  29. package/dist/kubernetes/follow-pod-logs.js +8 -5
  30. package/dist/kubernetes/kept-claims.js +38 -14
  31. package/dist/kubernetes/sandbox-runner.js +526 -156
  32. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  33. package/dist/kubernetes/sync-changes.js +463 -0
  34. package/dist/kubernetes/volumes.js +23 -1
  35. package/dist/network/healthcheck-request.js +38 -0
  36. package/dist/optimizer/get-work-cache-stats.js +7 -0
  37. package/dist/optimizer/work-task-cache-description.js +5 -3
  38. package/dist/planner/image-build.js +5 -0
  39. package/dist/planner/service-definition.js +2 -1
  40. package/dist/planner/utils/append-work-service.js +12 -4
  41. package/dist/planner/utils/dependency-outputs.js +7 -6
  42. package/dist/planner/validate.js +41 -0
  43. package/dist/planner/work-healthcheck.js +23 -2
  44. package/dist/planner/work-item-status.js +12 -2
  45. package/dist/planner/work-runtime-aggregate.js +1 -0
  46. package/dist/planner/work-runtime-docker.js +33 -6
  47. package/dist/planner/work-runtime-kubernetes.js +313 -70
  48. package/dist/planner/work-runtime-local.js +8 -4
  49. package/dist/planner/work-secret.js +33 -11
  50. package/dist/planner/work-service-id.js +30 -6
  51. package/dist/planner/work-service.js +2 -2
  52. package/dist/program.js +19 -1
  53. package/dist/remote/annotations.js +8 -2
  54. package/dist/remote/bundle.js +6 -8
  55. package/dist/remote/device-login.js +4 -1
  56. package/dist/remote/remote-commands.js +16 -7
  57. package/dist/remote/remote-status.js +1 -1
  58. package/dist/remote/remote-work-commands.js +220 -68
  59. package/dist/remote/server-client.js +38 -40
  60. package/dist/schema/build-file-base-task-schema.js +16 -1
  61. package/dist/schema/build-file-image-build-schema.js +5 -8
  62. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  63. package/dist/schema/reference-parser.js +108 -43
  64. package/dist/schema/work-scope-parser.js +8 -0
  65. package/dist/secrets/prefetch-secrets.js +20 -1
  66. package/dist/server/artifacts-api.js +56 -0
  67. package/dist/server/borrowed-quota.js +216 -0
  68. package/dist/server/cache-push.js +50 -0
  69. package/dist/server/capacity.js +18 -6
  70. package/dist/server/definitions-api.js +62 -8
  71. package/dist/server/executor.js +131 -31
  72. package/dist/server/http.js +4 -1
  73. package/dist/server/keep-artifacts.js +230 -0
  74. package/dist/server/kubernetes-backend.js +292 -79
  75. package/dist/server/kubernetes-sandbox-storage.js +86 -24
  76. package/dist/server/overview.js +73 -9
  77. package/dist/server/paging.js +167 -0
  78. package/dist/server/plan.js +54 -8
  79. package/dist/server/run-access.js +24 -0
  80. package/dist/server/run-artifacts.js +171 -0
  81. package/dist/server/run-logs.js +25 -1
  82. package/dist/server/run-request.js +11 -0
  83. package/dist/server/run-source-environment.js +1 -1
  84. package/dist/server/run-worker.js +305 -40
  85. package/dist/server/runs.js +531 -105
  86. package/dist/server/sandbox-files-api.js +27 -12
  87. package/dist/server/sandbox-files.js +12 -10
  88. package/dist/server/sandbox-follow.js +54 -0
  89. package/dist/server/sandbox-pod.js +1 -1
  90. package/dist/server/sandbox-storage.js +38 -1
  91. package/dist/server/sandbox-sync.js +392 -0
  92. package/dist/server/sandboxes-api.js +116 -19
  93. package/dist/server/sandboxes.js +38 -3
  94. package/dist/server/server-config.js +133 -2
  95. package/dist/server/server.js +189 -39
  96. package/dist/server/task-order.js +56 -0
  97. package/dist/utils/project-path.js +20 -0
  98. package/dist/utils/tar-files.js +52 -0
  99. package/dist/utils/tar.js +37 -1
  100. package/package.json +1 -1
  101. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  102. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  103. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -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.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");
@@ -14,11 +14,13 @@ const ensure_kubernetes_deployment_exists_1 = require("../kubernetes/ensure-kube
14
14
  const follow_pod_logs_1 = require("../kubernetes/follow-pod-logs");
15
15
  const work_item_executions_1 = require("./work-item-executions");
16
16
  const service_definition_1 = require("./service-definition");
17
+ const work_service_id_1 = require("./work-service-id");
17
18
  const ensure_namespace_1 = require("../kubernetes/ensure-namespace");
18
19
  const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data");
19
20
  const network_gate_1 = require("../kubernetes/network-gate");
20
21
  const await_running_state_1 = require("../kubernetes/await-running-state");
21
22
  const volumes_1 = require("../kubernetes/volumes");
23
+ const sync_changes_1 = require("../kubernetes/sync-changes");
22
24
  const service_rollouts_1 = require("../kubernetes/service-rollouts");
23
25
  const resources_1 = require("../kubernetes/resources");
24
26
  const ensure_http_route_1 = require("../kubernetes/ensure-http-route");
@@ -46,6 +48,125 @@ async function listJobNames(instance, kubernetes, task) {
46
48
  });
47
49
  return jobs.items.flatMap((job) => (job.metadata?.name ? [job.metadata.name] : []));
48
50
  }
51
+ // The command of the task a Job runs (from 1), by the name of its container
52
+ function getJobCommand(job) {
53
+ const match = /^cmd-(\d+)$/.exec(job.spec?.template.spec?.containers[0]?.name ?? '');
54
+ return match ? Number(match[1]) : undefined;
55
+ }
56
+ // Whether the container runs the command as the task would make it now
57
+ function runsCommand(container, expected) {
58
+ if (!container) {
59
+ return false;
60
+ }
61
+ return (container.image === expected.image &&
62
+ JSON.stringify(container.command ?? []) === JSON.stringify(expected.command ?? []) &&
63
+ JSON.stringify(container.args ?? []) === JSON.stringify(expected.args ?? []) &&
64
+ expected.env.every((variable) => container.env?.some((has) => has.name === variable.name && has.value === variable.value && !has.valueFrom)));
65
+ }
66
+ // Whether the pod of a Job mounts the claim
67
+ function mountsClaim(job, claim) {
68
+ return (job.spec?.template.spec?.volumes ?? []).some((volume) => volume.persistentVolumeClaim?.claimName === claim);
69
+ }
70
+ // Where the log of an item got to before a restart of the server, by instance of its container:
71
+ // an own entry of the record only, an item may be named as a property of any object
72
+ function getResumedLogs(kubernetes, item) {
73
+ const logs = kubernetes.server?.resumed?.logs;
74
+ const cursors = logs && Object.prototype.hasOwnProperty.call(logs, item) ? logs[item] : undefined;
75
+ return Array.isArray(cursors) ? cursors : undefined;
76
+ }
77
+ exports.getResumedLogs = getResumedLogs;
78
+ function isJobFinished(job) {
79
+ return (!!job.status?.succeeded ||
80
+ !!job.status?.conditions?.some((c) => (c.type === 'Complete' || c.type === 'Failed') && c.status === 'True'));
81
+ }
82
+ // The Secrets the pod of a Job reads: the values the server handed over and the credentials
83
+ // of its init containers
84
+ function getJobSecretNames(job) {
85
+ const pod = job.spec?.template.spec;
86
+ const names = new Set();
87
+ for (const volume of pod?.volumes ?? []) {
88
+ if (volume.secret?.secretName) {
89
+ names.add(volume.secret.secretName);
90
+ }
91
+ }
92
+ for (const container of [...(pod?.initContainers ?? []), ...(pod?.containers ?? [])]) {
93
+ for (const env of container.env ?? []) {
94
+ if (env.valueFrom?.secretKeyRef?.name) {
95
+ names.add(env.valueFrom.secretKeyRef.name);
96
+ }
97
+ }
98
+ for (const from of container.envFrom ?? []) {
99
+ if (from.secretRef?.name) {
100
+ names.add(from.secretRef.name);
101
+ }
102
+ }
103
+ }
104
+ return [...names];
105
+ }
106
+ async function secretExists(instance, namespace, name) {
107
+ try {
108
+ const secret = await instance.coreApi.readNamespacedSecret({ name, namespace });
109
+ return !secret.metadata?.deletionTimestamp;
110
+ }
111
+ catch (e) {
112
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
113
+ return false;
114
+ }
115
+ throw e;
116
+ }
117
+ }
118
+ /**
119
+ * The Job a run that resumes after a restart of the server left for the task at this state,
120
+ * and the command it runs (from 1): the one of its deterministic name, labelled with the run
121
+ * and the state, whose container is the one of that command (`expected`). A Job of another
122
+ * run, state or command, or one that goes, is not the task's to take. Nor is one whose files
123
+ * may not be what it wrote: a claim that another run wrote to since (`claim`, the marker the
124
+ * Job's execution left on it), or the Secrets it reads that are gone while it may still need
125
+ * them (it did not finish, or a command comes after it).
126
+ */
127
+ async function findLeftJob(instance, kubernetes, task, options) {
128
+ let job;
129
+ try {
130
+ job = await instance.batchApi.readNamespacedJob({
131
+ name: (0, resources_1.getResourceName)(task, kubernetes, '-job'),
132
+ namespace: kubernetes.namespace,
133
+ });
134
+ }
135
+ catch (e) {
136
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
137
+ return undefined;
138
+ }
139
+ throw e;
140
+ }
141
+ const labels = job.metadata?.labels ?? {};
142
+ const command = getJobCommand(job);
143
+ if (job.metadata?.deletionTimestamp ||
144
+ labels[network_policy_1.RUN_LABEL] !== options.run ||
145
+ labels['hammerkit.dev/state'] !== options.stateKey ||
146
+ command === undefined ||
147
+ command < 1 ||
148
+ command > task.data.cmds.length) {
149
+ return undefined;
150
+ }
151
+ const expected = options.expected(task.data.cmds[command - 1]);
152
+ if (!expected || !runsCommand(job.spec?.template.spec?.containers[0], expected)) {
153
+ return undefined;
154
+ }
155
+ // a claim it does not mount holds nothing of it
156
+ if (options.claim &&
157
+ mountsClaim(job, options.claim.name) &&
158
+ !(await (0, kept_claims_1.isClaimWrittenBy)(instance, kubernetes, options.claim.name, options.claim.writer))) {
159
+ return undefined;
160
+ }
161
+ if (!isJobFinished(job) || command < task.data.cmds.length) {
162
+ for (const name of getJobSecretNames(job)) {
163
+ if (!(await secretExists(instance, kubernetes.namespace, name))) {
164
+ return undefined;
165
+ }
166
+ }
167
+ }
168
+ return { job, command };
169
+ }
49
170
  // The Secret of the values the server hands over and the one of the credentials the
50
171
  // pod reads its own secrets with
51
172
  async function removeTaskSecrets(instance, kubernetes, task) {
@@ -198,8 +319,8 @@ function kubernetesTaskRuntime(task, kubernetes) {
198
319
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
199
320
  }
200
321
  },
201
- async archive(environment, path, stateKey) {
202
- await (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path, stateKey);
322
+ async archive(environment, path, options = {}) {
323
+ return (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path, options.stateKey, options.only);
203
324
  },
204
325
  async execute(environment, options) {
205
326
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(task.data.envs);
@@ -208,7 +329,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
208
329
  // a shell of a sandbox: its commands go into the sandbox's runner, when it has one now
209
330
  if ((0, sandbox_runner_1.canUseRunner)(task, kubernetes, persistence)) {
210
331
  try {
211
- const result = await (0, sandbox_runner_1.executeInRunner)(instance, task, kubernetes, persistence, options.abort);
332
+ const result = await (0, sandbox_runner_1.executeInRunner)(instance, task, kubernetes, persistence, options.abort, environment.hosted?.runnerCommands);
212
333
  if (result.type === 'crash') {
213
334
  options.state.set({ stateKey: options.stateKey, type: 'crash', exitCode: result.exitCode });
214
335
  return;
@@ -227,30 +348,84 @@ function kubernetesTaskRuntime(task, kubernetes) {
227
348
  return;
228
349
  }
229
350
  }
351
+ const server = kubernetes.server;
352
+ // the run label of its pods: on a server, the server's run; on a sandbox, its proxy
353
+ // stays with the sandbox for the next runs
354
+ const run = server ? (0, job_placement_1.getRunLabelValue)(server.run) : (0, run_id_1.getRunId)();
355
+ const { delivered, inJob } = (0, job_secrets_1.splitJobSecrets)(task.data.secrets, server);
356
+ // the Job of a run and state writes to a claim other runs mount too (see WRITER_ANNOTATION)
357
+ const writer = `${run}/${options.stateKey}`;
358
+ // a run that resumes after a restart of the server: the Job the task left goes on, from
359
+ // the command it ran, and its files are the ones it works on
360
+ let adopted;
361
+ if (server?.resumed) {
362
+ try {
363
+ adopted = await findLeftJob(instance, kubernetes, task, {
364
+ run,
365
+ stateKey: options.stateKey,
366
+ expected: (cmd) => {
367
+ try {
368
+ // the wrapper of the command depends on the secrets it reads, not on the
369
+ // credentials minted for them nor the proxy (those go to init containers)
370
+ const command = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, {}, environment).command(task.data.shell, (0, task_arguments_1.getKubernetesCommandText)(cmd));
371
+ // the image of the container of a Job (getTaskJobContainers)
372
+ return { image: task.data.image, command: command.command, args: command.args, env: command.env };
373
+ }
374
+ catch (e) {
375
+ // a Job of the task can't be made now (the Job it starts says why): none is taken over
376
+ task.status.write('debug', `${task.name}: its job is not taken over: ${(0, log_1.getErrorMessage)(e)}`);
377
+ return undefined;
378
+ }
379
+ },
380
+ ...(remembers ? { claim: { name: claim, writer } } : {}),
381
+ });
382
+ }
383
+ catch (e) {
384
+ options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
385
+ return;
386
+ }
387
+ }
230
388
  await (0, ensure_namespace_1.ensureNamespace)(instance, kubernetes.namespace);
231
389
  // a service run writes the outputs of each state into a folder of their own (see
232
390
  // getStateFilesDir), which pods of its services may mount: of the commit before during
233
391
  // a move, or of this state after a move that went back
234
392
  const files = kubernetes.server?.serviceRun ? { dir: (0, volumes_1.getStateFilesDir)(options.stateKey) } : undefined;
235
393
  try {
236
- if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
394
+ if (adopted) {
395
+ task.status.write('info', `${task.name}: takes over its job from before the restart of the server`);
396
+ }
397
+ else if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
237
398
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
238
399
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
239
400
  return;
240
401
  }
241
- // the task writes to it now: what it holds stops being the outputs of a state, and
242
- // goes, as a new claim would hold nothing (on a service run, the folders of other
243
- // states that no pod mounts go)
244
- const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
245
- const reset = kept && forgotten;
246
- await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
402
+ else {
403
+ // The last job of a run stays: its state label is what currentStateKey reads. Jobs
404
+ // from an earlier run of this task go before this one starts, and before its files
405
+ // change: one left is never taken over over files written since.
406
+ for (const name of await listJobNames(instance, kubernetes, task)) {
407
+ await (0, await_running_state_1.deleteJobAndWait)(instance, kubernetes, name, options.abort);
408
+ }
409
+ // the task writes to it now: what it holds stops being the outputs of a state, and
410
+ // goes, as a new claim would hold nothing (on a service run, the folders of other
411
+ // states that no pod mounts go)
412
+ const forgotten = remembers && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
413
+ const reset = kept && forgotten;
414
+ await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset, files });
415
+ if (remembers) {
416
+ // the claim is there now, also on the first run of a source: the Job of this run
417
+ // and state is the one that writes to it
418
+ await (0, kept_claims_1.markClaimWriter)(instance, kubernetes, claim, writer);
419
+ }
420
+ }
247
421
  }
248
422
  catch (e) {
423
+ if (e instanceof abort_1.AbortError) {
424
+ throw e;
425
+ }
249
426
  options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
250
427
  return;
251
428
  }
252
- const server = kubernetes.server;
253
- const { delivered, inJob } = (0, job_secrets_1.splitJobSecrets)(task.data.secrets, server);
254
429
  const secrets = (0, secrets_1.getKubernetesSecretRefs)(task, kubernetes, delivered);
255
430
  const admitted = environment.hosted?.accounts;
256
431
  let secretHosts;
@@ -259,7 +434,10 @@ function kubernetesTaskRuntime(task, kubernetes) {
259
434
  if (server) {
260
435
  (0, job_secrets_1.assertJobAccounts)(inJob, server, admitted);
261
436
  }
262
- await (0, secrets_1.ensureKubernetesSecret)(instance, kubernetes, task, delivered, environment);
437
+ // the values a Job it took over reads are in the Secret it was started with
438
+ if (!adopted) {
439
+ await (0, secrets_1.ensureKubernetesSecret)(instance, kubernetes, task, delivered, environment);
440
+ }
263
441
  }
264
442
  catch (e) {
265
443
  await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
@@ -269,7 +447,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
269
447
  // the run its pods and limits belong to: on a server, the server's run; on a
270
448
  // sandbox, its proxy stays with the sandbox for the next runs
271
449
  const scope = {
272
- run: server ? (0, job_placement_1.getRunLabelValue)(server.run) : (0, run_id_1.getRunId)(),
450
+ run,
273
451
  ...(server?.workspace
274
452
  ? {
275
453
  sandbox: {
@@ -287,11 +465,6 @@ function kubernetesTaskRuntime(task, kubernetes) {
287
465
  ...(0, network_policy_1.getNetworkLabels)(kubernetes, task),
288
466
  };
289
467
  const placement = server ? (0, job_placement_1.getPodPlacement)(server, task.data.pool) : null;
290
- // The last job of a run stays: its state label is what currentStateKey
291
- // reads. Jobs from an earlier run of this task go before this one starts.
292
- for (const name of await listJobNames(instance, kubernetes, task)) {
293
- await (0, await_running_state_1.deleteJobAndWait)(instance, kubernetes, name, options.abort);
294
- }
295
468
  // the services the task needs by the names it lists them under, and the
296
469
  // NetworkPolicy and proxy of a limited network, both of this run
297
470
  let network;
@@ -312,18 +485,26 @@ function kubernetesTaskRuntime(task, kubernetes) {
312
485
  let i = 0;
313
486
  for (const cmd of task.data.cmds) {
314
487
  const container = `cmd-${++i}`;
315
- let secretSpec;
316
- try {
317
- // made for each Job right before it, so a later command's token is as fresh
318
- const credentials = await (0, job_secrets_1.ensureJobCredentials)(instance, kubernetes, task, inJob, admitted);
319
- secretSpec = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, credentials, environment, network.secretEnv);
488
+ // the commands before the one of a Job it took over ran before the restart
489
+ if (adopted && i < adopted.command) {
490
+ continue;
320
491
  }
321
- catch (e) {
322
- await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
323
- options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
324
- return;
492
+ // a Job it took over keeps the pod and the credentials it was started with
493
+ const left = adopted?.command === i ? adopted.job : undefined;
494
+ let secretSpec;
495
+ if (!left) {
496
+ try {
497
+ // made for each Job right before it, so a later command's token is as fresh
498
+ const credentials = await (0, job_secrets_1.ensureJobCredentials)(instance, kubernetes, task, inJob, admitted);
499
+ secretSpec = (0, job_secrets_1.getJobSecretSpec)(task, inJob, server, credentials, environment, network.secretEnv);
500
+ }
501
+ catch (e) {
502
+ await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
503
+ options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
504
+ return;
505
+ }
325
506
  }
326
- const spec = {
507
+ const spec = secretSpec && {
327
508
  kind: 'Job',
328
509
  apiVersion: 'batch/v1',
329
510
  metadata: {
@@ -379,13 +560,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
379
560
  },
380
561
  };
381
562
  try {
382
- const pod = await (0, apply_1.apply)(instance, spec);
383
- // what the command prints, while it prints it; the last lines once the pod ended
384
- 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) });
563
+ const pod = left ?? (await (0, apply_1.apply)(instance, spec));
564
+ // what the command prints, while it prints it; the last lines once the pod ended.
565
+ // Of a Job it took over, from where the run's log got to.
566
+ const from = left ? getResumedLogs(kubernetes, task.name) : undefined;
567
+ 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 } : {}) });
385
568
  try {
386
569
  if (!pod.status?.succeeded) {
387
570
  try {
388
- await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
571
+ await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, podName, options.abort, 1000, {
389
572
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
573
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
574
  onRefused: options.onQuotaRefused,
@@ -504,7 +687,14 @@ function kubernetesTaskRuntime(task, kubernetes) {
504
687
  namespace: kubernetes.namespace,
505
688
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),
506
689
  });
690
+ // the Job of an earlier command that succeeded (a server stopped before it went) is not
691
+ // the task's. A Job whose container names no command still counts: one of an older
692
+ // version, whose state a run before the update recorded so.
507
693
  const completedStates = jobs.items
694
+ .filter((j) => {
695
+ const command = getJobCommand(j);
696
+ return command === undefined || command >= task.data.cmds.length;
697
+ })
508
698
  .filter((j) => j.status?.succeeded && j.metadata?.labels?.['hammerkit.dev/state'])
509
699
  .map((j) => j.metadata.labels['hammerkit.dev/state']);
510
700
  const stateKey = completedStates[completedStates.length - 1] ?? null;
@@ -530,6 +720,35 @@ function kubernetesTaskRuntime(task, kubernetes) {
530
720
  };
531
721
  }
532
722
  exports.kubernetesTaskRuntime = kubernetesTaskRuntime;
723
+ async function stopKubernetesService(instance, kubernetes, service) {
724
+ const deployments = await instance.appsApi.listNamespacedDeployment({
725
+ namespace: kubernetes.namespace,
726
+ labelSelector: (0, resources_1.getItemSelector)(service, kubernetes),
727
+ });
728
+ for (const deployment of deployments.items) {
729
+ if (deployment.metadata?.name) {
730
+ await instance.appsApi.deleteNamespacedDeployment({
731
+ name: deployment.metadata.name,
732
+ namespace: kubernetes.namespace,
733
+ });
734
+ }
735
+ }
736
+ await (0, secrets_1.removeKubernetesSecret)(instance, kubernetes, service);
737
+ // the limits go last, once the service's pods ended
738
+ await (0, network_policy_1.removeAllKubernetesItemNetworks)(instance, kubernetes, service);
739
+ }
740
+ async function removeLegacyKubernetesService(instance, kubernetes, service) {
741
+ const legacy = (0, work_service_id_1.getLegacyServiceItem)(service);
742
+ const deployments = await instance.appsApi.listNamespacedDeployment({
743
+ namespace: kubernetes.namespace,
744
+ labelSelector: (0, resources_1.getItemSelector)(legacy, kubernetes),
745
+ });
746
+ if (deployments.items.length > 0) {
747
+ service.status.write('info', `${service.name} was started by an earlier version of hammerkit, recreating it`);
748
+ await stopKubernetesService(instance, kubernetes, legacy);
749
+ }
750
+ }
751
+ exports.removeLegacyKubernetesService = removeLegacyKubernetesService;
533
752
  function kubernetesServiceRuntime(service, kubernetes) {
534
753
  const instance = (0, kubernetes_instance_1.createKubernetesInstances)(kubernetes);
535
754
  return {
@@ -541,6 +760,11 @@ function kubernetesServiceRuntime(service, kubernetes) {
541
760
  // a service run starts every service: one that did not change stays as it is (execute)
542
761
  return;
543
762
  }
763
+ // one an earlier version started, under the id it had then (getLegacyServiceItem); on a
764
+ // server a run finds only objects of its own
765
+ if (!kubernetes.server) {
766
+ await removeLegacyKubernetesService(instance, kubernetes, service);
767
+ }
544
768
  const deployments = await instance.appsApi.listNamespacedDeployment({
545
769
  namespace: kubernetes.namespace,
546
770
  labelSelector: (0, resources_1.getItemSelector)(service, kubernetes),
@@ -561,38 +785,69 @@ function kubernetesServiceRuntime(service, kubernetes) {
561
785
  remote: null,
562
786
  });
563
787
  },
788
+ // The files of the sandbox changed while the service of a service run is up (FileChanges):
789
+ // synced into the folder its pod mounts, which the service sees, and its pods start again
790
+ // when it restarts. A service that keeps its files takes nothing.
791
+ async syncFiles(changes) {
792
+ const stateDir = kubernetes.server?.serviceRun ? (0, volumes_1.getItemFilesDir)(service, undefined) : undefined;
793
+ const target = stateDir
794
+ ? (0, sync_changes_1.getChangeTarget)((0, volumes_1.isLiveService)(service, kubernetes), changes.restart, stateDir)
795
+ : undefined;
796
+ if (!target) {
797
+ return;
798
+ }
799
+ const persistence = await (0, volumes_1.getKubernetesPersistence)(service, kubernetes);
800
+ for (const line of await (0, sync_changes_1.syncChangedFiles)(instance, kubernetes, service, persistence, target.dir, changes)) {
801
+ service.status.write('info', line);
802
+ }
803
+ if (target.rollout) {
804
+ await (0, sync_changes_1.restartPods)(instance, kubernetes, service);
805
+ }
806
+ },
564
807
  async restore(environment, path) {
565
808
  await (0, restore_kubernetes_data_1.restoreKubernetesData)(service, kubernetes, instance, environment, path);
566
809
  },
567
810
  async archive(environment, path) {
568
- await (0, store_kubernetes_data_1.storeKubernetesData)(service, kubernetes, instance, environment, path);
811
+ return (0, store_kubernetes_data_1.storeKubernetesData)(service, kubernetes, instance, environment, path);
569
812
  },
570
813
  async stop() {
571
- const deployments = await instance.appsApi.listNamespacedDeployment({
572
- namespace: kubernetes.namespace,
573
- labelSelector: (0, resources_1.getItemSelector)(service, kubernetes),
574
- });
575
- for (const deployment of deployments.items) {
576
- if (deployment.metadata?.name) {
577
- await instance.appsApi.deleteNamespacedDeployment({
578
- name: deployment.metadata.name,
579
- namespace: kubernetes.namespace,
580
- });
581
- }
582
- }
583
- await (0, secrets_1.removeKubernetesSecret)(instance, kubernetes, service);
584
- // the limits go last, once the service's pods ended
585
- await (0, network_policy_1.removeAllKubernetesItemNetworks)(instance, kubernetes, service);
814
+ await stopKubernetesService(instance, kubernetes, service);
586
815
  },
587
816
  async execute(environment, options) {
588
817
  const name = (0, resources_1.getResourceName)(service, kubernetes);
589
- // a service run that moves to another commit: a service of the same definition and
590
- // state is left running, another one is rolled from the Deployment it has now
818
+ // its output, as on Docker: while it starts, and while it runs unless it runs on
819
+ // without hammerkit (`up --daemon`)
820
+ 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 } : {}) });
821
+ const followWhileUp = (logs) => {
822
+ if (options.daemon || options.abort.aborted || environment.abortCtrl.signal.aborted) {
823
+ logs.stop();
824
+ return;
825
+ }
826
+ // either ends it, and takes the other listener with it
827
+ const listening = new AbortController();
828
+ const stop = () => {
829
+ logs.stop();
830
+ listening.abort();
831
+ };
832
+ options.abort.addEventListener('abort', stop, { once: true, signal: listening.signal });
833
+ environment.abortCtrl.signal.addEventListener('abort', stop, { once: true, signal: listening.signal });
834
+ };
835
+ // a service run that moves to another commit, or that resumes after a restart of the
836
+ // server: a service of the same definition and state is left running, another one is
837
+ // rolled from the Deployment it has now
591
838
  let previous;
592
839
  if (kubernetes.server?.serviceRun) {
593
840
  previous = await readDeployment(instance, kubernetes.namespace, name);
594
- if (previous && isRolledOut(previous, (0, service_definition_1.getServiceDefinitionHash)(service), options.stateKey)) {
841
+ const resumed = kubernetes.server.resumed;
842
+ // after a restart, only a Deployment the run started stays (a move's are the run's anyway)
843
+ const ours = !resumed || previous?.metadata?.labels?.[network_policy_1.RUN_LABEL] === (0, job_placement_1.getRunLabelValue)(kubernetes.server.run);
844
+ if (previous && ours && isRolledOut(previous, (0, service_definition_1.getServiceDefinitionHash)(service), options.stateKey)) {
595
845
  service.status.write('info', `${service.name} did not change, it stays up`);
846
+ if (resumed) {
847
+ // the execution before the restart followed its log, a move leaves that to the
848
+ // execution it takes the services over from
849
+ followWhileUp(followLogs(getResumedLogs(kubernetes, service.name)));
850
+ }
596
851
  options.state.set({ type: 'running', dns: { containerId: name }, stateKey: options.stateKey, remote: null });
597
852
  return;
598
853
  }
@@ -624,9 +879,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
624
879
  followLog: false,
625
880
  run: kubernetes.server ? (0, job_placement_1.getRunLabelValue)(kubernetes.server.run) : null,
626
881
  });
627
- // its output, as on Docker: while it starts, and while it runs unless it runs on
628
- // without hammerkit (`up --daemon`)
629
- 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) });
882
+ const logs = followLogs();
630
883
  try {
631
884
  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 });
632
885
  }
@@ -636,19 +889,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
636
889
  logs.stop();
637
890
  throw e;
638
891
  }
639
- if (options.daemon || options.abort.aborted || environment.abortCtrl.signal.aborted) {
640
- logs.stop();
641
- }
642
- else {
643
- // either ends it, and takes the other listener with it
644
- const listening = new AbortController();
645
- const stop = () => {
646
- logs.stop();
647
- listening.abort();
648
- };
649
- options.abort.addEventListener('abort', stop, { once: true, signal: listening.signal });
650
- environment.abortCtrl.signal.addEventListener('abort', stop, { once: true, signal: listening.signal });
651
- }
892
+ followWhileUp(logs);
652
893
  options.state.set({
653
894
  type: 'running',
654
895
  dns: { containerId: name },
@@ -747,7 +988,9 @@ function kubernetesForwardRuntime(service) {
747
988
  }
748
989
  },
749
990
  async restore() { },
750
- async archive() { },
991
+ async archive() {
992
+ return [];
993
+ },
751
994
  async remove() { },
752
995
  async execute(_environment, options) {
753
996
  await (0, kubernetes_service_1.kubernetesService)(service, options);
@@ -45,8 +45,8 @@ function getLocalWorkRuntime(task) {
45
45
  await removeStateFile(environment, task);
46
46
  await restoreLocal(environment, task.data, path);
47
47
  },
48
- async archive(environment, path) {
49
- await archiveLocal(environment, task, path);
48
+ async archive(environment, path, options = {}) {
49
+ return archiveLocal(environment, task, path, options.only);
50
50
  },
51
51
  async execute(environment, options) {
52
52
  const activePid = await readActivePid(task, environment);
@@ -117,12 +117,16 @@ async function removeStateFile(environment, task) {
117
117
  await environment.file.remove(stateFile);
118
118
  }
119
119
  }
120
- async function archiveLocal(environment, task, path) {
121
- for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
120
+ async function archiveLocal(environment, task, path, only) {
121
+ const written = [];
122
+ for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path, only)) {
122
123
  await environment.file.writeStream(generatedArchive.filename,
123
124
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
124
125
  stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
+ // the entries are relative to the directory of the task
127
+ written.push({ filename: generatedArchive.filename, root: task.data.cwd });
125
128
  }
129
+ return written;
126
130
  }
127
131
  async function restoreLocal(environment, task, path) {
128
132
  for (const generate of (0, event_cache_1.getArchivePaths)(task, path)) {