hammerkit 2.1.0-next.9 → 2.2.0-next.1

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 (70) hide show
  1. package/dist/dashboard/assets/{graph-canvas-BFnEN5i0.js → graph-canvas-D6GMgkoe.js} +1 -1
  2. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  3. package/dist/dashboard/assets/{index-Dt3ITvRO.css → index-DP3_hKOe.css} +1 -1
  4. package/dist/dashboard/index.html +2 -2
  5. package/dist/executer/archive-task-entry.js +1 -1
  6. package/dist/executer/deadline.js +63 -10
  7. package/dist/executer/event-cache.js +5 -1
  8. package/dist/executer/execute-work-task.js +15 -3
  9. package/dist/executer/runner-commands.js +36 -0
  10. package/dist/file/get-file-context.js +4 -7
  11. package/dist/harness/connect.js +12 -8
  12. package/dist/harness/reconnect.js +141 -0
  13. package/dist/harness/sandbox-client.js +242 -33
  14. package/dist/harness/service-tools.js +36 -3
  15. package/dist/kubernetes/cluster-state.js +48 -14
  16. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  17. package/dist/kubernetes/follow-pod-logs.js +8 -5
  18. package/dist/kubernetes/kept-claims.js +26 -5
  19. package/dist/kubernetes/resources.js +5 -1
  20. package/dist/kubernetes/sandbox-runner.js +526 -156
  21. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  22. package/dist/kubernetes/sync-changes.js +463 -0
  23. package/dist/kubernetes/volumes.js +23 -1
  24. package/dist/optimizer/get-work-cache-stats.js +7 -0
  25. package/dist/planner/work-item-status.js +12 -2
  26. package/dist/planner/work-runtime-aggregate.js +1 -0
  27. package/dist/planner/work-runtime-docker.js +9 -5
  28. package/dist/planner/work-runtime-kubernetes.js +277 -55
  29. package/dist/planner/work-runtime-local.js +8 -4
  30. package/dist/remote/annotations.js +29 -3
  31. package/dist/remote/bundle.js +6 -8
  32. package/dist/remote/collect-bundle.js +3 -2
  33. package/dist/remote/device-login.js +4 -1
  34. package/dist/remote/remote-commands.js +16 -7
  35. package/dist/remote/remote-work-commands.js +265 -72
  36. package/dist/remote/server-client.js +38 -40
  37. package/dist/server/artifacts-api.js +56 -0
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/endpoints.js +52 -32
  40. package/dist/server/executor.js +117 -30
  41. package/dist/server/http.js +4 -1
  42. package/dist/server/keep-artifacts.js +230 -0
  43. package/dist/server/kubernetes-backend.js +186 -59
  44. package/dist/server/kubernetes-sandbox-storage.js +83 -22
  45. package/dist/server/overview.js +67 -9
  46. package/dist/server/paging.js +167 -0
  47. package/dist/server/plan.js +8 -1
  48. package/dist/server/public-paths.js +52 -0
  49. package/dist/server/run-access.js +24 -0
  50. package/dist/server/run-artifacts.js +171 -0
  51. package/dist/server/run-logs.js +25 -1
  52. package/dist/server/run-request.js +63 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-worker.js +267 -33
  55. package/dist/server/runs.js +527 -99
  56. package/dist/server/sandbox-files.js +9 -8
  57. package/dist/server/sandbox-follow.js +54 -0
  58. package/dist/server/sandbox-storage.js +38 -1
  59. package/dist/server/sandbox-sync.js +392 -0
  60. package/dist/server/sandboxes-api.js +54 -8
  61. package/dist/server/sandboxes.js +19 -0
  62. package/dist/server/server-config.js +14 -0
  63. package/dist/server/server.js +189 -46
  64. package/dist/server/service-runs.js +41 -8
  65. package/dist/server/task-order.js +56 -0
  66. package/dist/utils/project-path.js +20 -0
  67. package/dist/utils/tar-files.js +52 -0
  68. package/dist/utils/tar.js +37 -1
  69. package/package.json +1 -1
  70. package/dist/dashboard/assets/index-CE5PSB3y.js +0 -23
@@ -49,8 +49,8 @@ function dockerTaskRuntime(task, workEnvironment) {
49
49
  await (0, container_task_state_1.removeContainerTaskState)(environment, task);
50
50
  await restoreContainer(docker, environment, task, path);
51
51
  },
52
- async archive(environment, path) {
53
- await archiveContainer(docker, environment, task, path);
52
+ async archive(environment, path, options = {}) {
53
+ return archiveContainer(docker, environment, task, path, options.only);
54
54
  },
55
55
  async stop() {
56
56
  const containers = await docker.listContainers({
@@ -273,7 +273,7 @@ function dockerServiceRuntime(service, workEnvironment) {
273
273
  await restoreContainer(docker, environment, service, path);
274
274
  },
275
275
  async archive(environment, path) {
276
- await archiveContainer(docker, environment, service, path);
276
+ return archiveContainer(docker, environment, service, path);
277
277
  },
278
278
  async currentStateKey() {
279
279
  const containers = await docker.listContainers({
@@ -315,13 +315,14 @@ async function removeLegacyService(docker, service) {
315
315
  await (0, container_secrets_1.removeContainerSecrets)((0, work_instance_id_1.getWorkInstanceId)(legacy));
316
316
  }
317
317
  exports.removeLegacyService = removeLegacyService;
318
- async function archiveContainer(docker, environment, item, path) {
318
+ async function archiveContainer(docker, environment, item, path, only) {
319
319
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
320
+ const written = [];
320
321
  await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
321
322
  const hostFiles = new Set(item.data.type === 'container-task'
322
323
  ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
323
324
  : []);
324
- for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
325
+ for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path, only)) {
325
326
  // a file output is a bind mount of a host file, so archive it from the host
326
327
  const readable = hostFiles.has(generatedArchive.path)
327
328
  ? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
@@ -329,7 +330,10 @@ async function archiveContainer(docker, environment, item, path) {
329
330
  path: generatedArchive.path,
330
331
  });
331
332
  await environment.file.writeStream(generatedArchive.filename, readable);
333
+ // what the container archives at a path is the entries of the path's folder, by its name
334
+ written.push({ filename: generatedArchive.filename, root: (0, path_1.dirname)(generatedArchive.path) });
332
335
  }
333
336
  });
337
+ return written;
334
338
  }
335
339
  //# sourceMappingURL=work-runtime-docker.js.map
@@ -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");
@@ -20,6 +20,7 @@ const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data")
20
20
  const network_gate_1 = require("../kubernetes/network-gate");
21
21
  const await_running_state_1 = require("../kubernetes/await-running-state");
22
22
  const volumes_1 = require("../kubernetes/volumes");
23
+ const sync_changes_1 = require("../kubernetes/sync-changes");
23
24
  const service_rollouts_1 = require("../kubernetes/service-rollouts");
24
25
  const resources_1 = require("../kubernetes/resources");
25
26
  const ensure_http_route_1 = require("../kubernetes/ensure-http-route");
@@ -47,6 +48,125 @@ async function listJobNames(instance, kubernetes, task) {
47
48
  });
48
49
  return jobs.items.flatMap((job) => (job.metadata?.name ? [job.metadata.name] : []));
49
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
+ }
50
170
  // The Secret of the values the server hands over and the one of the credentials the
51
171
  // pod reads its own secrets with
52
172
  async function removeTaskSecrets(instance, kubernetes, task) {
@@ -199,8 +319,8 @@ function kubernetesTaskRuntime(task, kubernetes) {
199
319
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
200
320
  }
201
321
  },
202
- async archive(environment, path, stateKey) {
203
- 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);
204
324
  },
205
325
  async execute(environment, options) {
206
326
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(task.data.envs);
@@ -209,7 +329,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
209
329
  // a shell of a sandbox: its commands go into the sandbox's runner, when it has one now
210
330
  if ((0, sandbox_runner_1.canUseRunner)(task, kubernetes, persistence)) {
211
331
  try {
212
- 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);
213
333
  if (result.type === 'crash') {
214
334
  options.state.set({ stateKey: options.stateKey, type: 'crash', exitCode: result.exitCode });
215
335
  return;
@@ -228,30 +348,84 @@ function kubernetesTaskRuntime(task, kubernetes) {
228
348
  return;
229
349
  }
230
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
+ }
231
388
  await (0, ensure_namespace_1.ensureNamespace)(instance, kubernetes.namespace);
232
389
  // a service run writes the outputs of each state into a folder of their own (see
233
390
  // getStateFilesDir), which pods of its services may mount: of the commit before during
234
391
  // a move, or of this state after a move that went back
235
392
  const files = kubernetes.server?.serviceRun ? { dir: (0, volumes_1.getStateFilesDir)(options.stateKey) } : undefined;
236
393
  try {
237
- 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)) {
238
398
  task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
239
399
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
240
400
  return;
241
401
  }
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 });
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
+ }
248
421
  }
249
422
  catch (e) {
423
+ if (e instanceof abort_1.AbortError) {
424
+ throw e;
425
+ }
250
426
  options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
251
427
  return;
252
428
  }
253
- const server = kubernetes.server;
254
- const { delivered, inJob } = (0, job_secrets_1.splitJobSecrets)(task.data.secrets, server);
255
429
  const secrets = (0, secrets_1.getKubernetesSecretRefs)(task, kubernetes, delivered);
256
430
  const admitted = environment.hosted?.accounts;
257
431
  let secretHosts;
@@ -260,7 +434,10 @@ function kubernetesTaskRuntime(task, kubernetes) {
260
434
  if (server) {
261
435
  (0, job_secrets_1.assertJobAccounts)(inJob, server, admitted);
262
436
  }
263
- 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
+ }
264
441
  }
265
442
  catch (e) {
266
443
  await removeTaskSecrets(instance, kubernetes, task).catch(() => undefined);
@@ -270,7 +447,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
270
447
  // the run its pods and limits belong to: on a server, the server's run; on a
271
448
  // sandbox, its proxy stays with the sandbox for the next runs
272
449
  const scope = {
273
- run: server ? (0, job_placement_1.getRunLabelValue)(server.run) : (0, run_id_1.getRunId)(),
450
+ run,
274
451
  ...(server?.workspace
275
452
  ? {
276
453
  sandbox: {
@@ -288,11 +465,6 @@ function kubernetesTaskRuntime(task, kubernetes) {
288
465
  ...(0, network_policy_1.getNetworkLabels)(kubernetes, task),
289
466
  };
290
467
  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
468
  // the services the task needs by the names it lists them under, and the
297
469
  // NetworkPolicy and proxy of a limited network, both of this run
298
470
  let network;
@@ -313,18 +485,26 @@ function kubernetesTaskRuntime(task, kubernetes) {
313
485
  let i = 0;
314
486
  for (const cmd of task.data.cmds) {
315
487
  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);
488
+ // the commands before the one of a Job it took over ran before the restart
489
+ if (adopted && i < adopted.command) {
490
+ continue;
321
491
  }
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;
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
+ }
326
506
  }
327
- const spec = {
507
+ const spec = secretSpec && {
328
508
  kind: 'Job',
329
509
  apiVersion: 'batch/v1',
330
510
  metadata: {
@@ -380,13 +560,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
380
560
  },
381
561
  };
382
562
  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) });
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 } : {}) });
386
568
  try {
387
569
  if (!pod.status?.succeeded) {
388
570
  try {
389
- 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, {
390
572
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
391
573
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
392
574
  onRefused: options.onQuotaRefused,
@@ -505,7 +687,14 @@ function kubernetesTaskRuntime(task, kubernetes) {
505
687
  namespace: kubernetes.namespace,
506
688
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),
507
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.
508
693
  const completedStates = jobs.items
694
+ .filter((j) => {
695
+ const command = getJobCommand(j);
696
+ return command === undefined || command >= task.data.cmds.length;
697
+ })
509
698
  .filter((j) => j.status?.succeeded && j.metadata?.labels?.['hammerkit.dev/state'])
510
699
  .map((j) => j.metadata.labels['hammerkit.dev/state']);
511
700
  const stateKey = completedStates[completedStates.length - 1] ?? null;
@@ -596,24 +785,69 @@ function kubernetesServiceRuntime(service, kubernetes) {
596
785
  remote: null,
597
786
  });
598
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
+ },
599
807
  async restore(environment, path) {
600
808
  await (0, restore_kubernetes_data_1.restoreKubernetesData)(service, kubernetes, instance, environment, path);
601
809
  },
602
810
  async archive(environment, path) {
603
- 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);
604
812
  },
605
813
  async stop() {
606
814
  await stopKubernetesService(instance, kubernetes, service);
607
815
  },
608
816
  async execute(environment, options) {
609
817
  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
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
612
838
  let previous;
613
839
  if (kubernetes.server?.serviceRun) {
614
840
  previous = await readDeployment(instance, kubernetes.namespace, name);
615
- 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)) {
616
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
+ }
617
851
  options.state.set({ type: 'running', dns: { containerId: name }, stateKey: options.stateKey, remote: null });
618
852
  return;
619
853
  }
@@ -645,9 +879,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
645
879
  followLog: false,
646
880
  run: kubernetes.server ? (0, job_placement_1.getRunLabelValue)(kubernetes.server.run) : null,
647
881
  });
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) });
882
+ const logs = followLogs();
651
883
  try {
652
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 });
653
885
  }
@@ -657,19 +889,7 @@ function kubernetesServiceRuntime(service, kubernetes) {
657
889
  logs.stop();
658
890
  throw e;
659
891
  }
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
- }
892
+ followWhileUp(logs);
673
893
  options.state.set({
674
894
  type: 'running',
675
895
  dns: { containerId: name },
@@ -768,7 +988,9 @@ function kubernetesForwardRuntime(service) {
768
988
  }
769
989
  },
770
990
  async restore() { },
771
- async archive() { },
991
+ async archive() {
992
+ return [];
993
+ },
772
994
  async remove() { },
773
995
  async execute(_environment, options) {
774
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)) {
@@ -36,16 +36,42 @@ function remoteRepo(url) {
36
36
  }
37
37
  }
38
38
  exports.remoteRepo = remoteRepo;
39
+ // what the server takes for a commit, not for the name of a branch or tag
40
+ const COMMIT_NAME = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
41
+ const ORIGIN_BRANCHES = 'refs/remotes/origin/';
42
+ const TAGS = 'refs/tags/';
39
43
  // The checkout a directory is in: the repository of its `origin`, the branch it is on and
40
- // its commit, what can be found of them.
44
+ // its commit, what can be found of them. A detached HEAD is on no branch: `heads` are then the
45
+ // branches of origin (as the last fetch or push left them) and the tags whose head is its
46
+ // commit, branches first, as git sorts them.
41
47
  async function readCheckout(cwd) {
42
48
  if ((await git(cwd, 'rev-parse', '--is-inside-work-tree')) !== 'true') {
43
49
  return {};
44
50
  }
45
51
  const remote = await git(cwd, 'remote', 'get-url', 'origin');
46
- // a detached HEAD is on no branch
52
+ const repo = remote ? remoteRepo(remote) : undefined;
47
53
  const branch = await git(cwd, 'symbolic-ref', '--quiet', '--short', 'HEAD');
48
- return { repo: remote ? remoteRepo(remote) : undefined, branch, commit: await git(cwd, 'rev-parse', 'HEAD') };
54
+ const commit = await git(cwd, 'rev-parse', 'HEAD');
55
+ if (branch || !commit) {
56
+ return { repo, branch, commit };
57
+ }
58
+ const refs = await git(cwd, 'for-each-ref', `--points-at=${commit}`, '--format=%(refname)%09%(symref)', ORIGIN_BRANCHES, TAGS);
59
+ const heads = [];
60
+ for (const line of refs?.split('\n') ?? []) {
61
+ const [ref, symref] = line.split('\t');
62
+ // origin/HEAD names the default branch of origin, it is no branch of its own
63
+ if (symref || ref === `${ORIGIN_BRANCHES}HEAD`) {
64
+ continue;
65
+ }
66
+ const head = ref.startsWith(ORIGIN_BRANCHES)
67
+ ? { name: ref.slice(ORIGIN_BRANCHES.length), kind: 'branch' }
68
+ : { name: ref.slice(TAGS.length), kind: 'tag' };
69
+ // a name that looks like a commit would be run as that commit
70
+ if (head.name && !COMMIT_NAME.test(head.name)) {
71
+ heads.push(head);
72
+ }
73
+ }
74
+ return { repo, commit, heads };
49
75
  }
50
76
  exports.readCheckout = readCheckout;
51
77
  // Where a build file is published from: its path in its repository (or on this
@@ -1,26 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HASH_PATTERN = exports.hashBundle = exports.bundleSchema = exports.annotationsSchema = exports.MAX_ANNOTATIONS = exports.isBundlePath = exports.MAX_BUNDLE_BYTES = exports.MAX_BUNDLE_FILES = exports.DEFAULT_ENTRY = void 0;
3
+ exports.HASH_PATTERN = exports.hashBundle = exports.bundleSchema = exports.annotationsSchema = exports.ANNOTATION_KEY_PATTERN = exports.MAX_ANNOTATIONS = exports.isBundlePath = exports.MAX_BUNDLE_BYTES = exports.MAX_BUNDLE_FILES = exports.DEFAULT_ENTRY = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const zod_1 = require("zod");
6
+ const project_path_1 = require("../utils/project-path");
6
7
  exports.DEFAULT_ENTRY = '.hammerkit.yaml';
7
8
  exports.MAX_BUNDLE_FILES = 200;
8
9
  exports.MAX_BUNDLE_BYTES = 1024 * 1024;
9
10
  // A path inside the bundle: relative, forward slashes, nothing that climbs out.
10
11
  function isBundlePath(path) {
11
- return (path.length > 0 &&
12
- path.length <= 200 &&
13
- !path.startsWith('/') &&
14
- !path.includes('\\') &&
15
- !path.includes('\0') &&
16
- !path.split('/').some((part) => part === '' || part === '.' || part === '..'));
12
+ return (0, project_path_1.isRelativePath)(path, 200);
17
13
  }
18
14
  exports.isBundlePath = isBundlePath;
19
15
  exports.MAX_ANNOTATIONS = 20;
16
+ // the key of an annotation
17
+ exports.ANNOTATION_KEY_PATTERN = /^[a-z][a-z0-9._-]{0,63}$/;
20
18
  exports.annotationsSchema = zod_1.z
21
19
  .record(zod_1.z
22
20
  .string()
23
- .regex(/^[a-z][a-z0-9._-]{0,63}$/, 'use lower case letters, digits, ".", "_" and "-", starting with a letter'), zod_1.z.string().min(1).max(500))
21
+ .regex(exports.ANNOTATION_KEY_PATTERN, 'use lower case letters, digits, ".", "_" and "-", starting with a letter'), zod_1.z.string().min(1).max(500))
24
22
  .refine((annotations) => Object.keys(annotations).length <= exports.MAX_ANNOTATIONS, {
25
23
  message: `at most ${exports.MAX_ANNOTATIONS} annotations`,
26
24
  });