hammerkit 1.27.0-next.9 → 2.0.0-next.10

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 (141) hide show
  1. package/build.schema.json +176 -6
  2. package/dist/cache/backends/local-cache-backend.js +6 -0
  3. package/dist/cache/backends/registry/registry-client.js +1 -0
  4. package/dist/cache/cache-sync.js +1 -1
  5. package/dist/cache/explain.js +23 -4
  6. package/dist/cli.js +2 -0
  7. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  8. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  9. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  10. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  11. package/dist/dashboard/index.html +15 -0
  12. package/dist/dashboard/logo.png +0 -0
  13. package/dist/docker/item-network.js +13 -5
  14. package/dist/executer/archive-task-entry.js +4 -2
  15. package/dist/executer/deadline.js +17 -3
  16. package/dist/executer/deferred-restore.js +36 -0
  17. package/dist/executer/docker-service.js +30 -8
  18. package/dist/executer/docker-task.js +24 -1
  19. package/dist/executer/execute-work-service.js +2 -0
  20. package/dist/executer/execute-work-task.js +14 -5
  21. package/dist/executer/execution-steps.js +25 -4
  22. package/dist/executer/local-task.js +3 -0
  23. package/dist/executer/reset-work-tree.js +4 -0
  24. package/dist/executer/scheduler/enqueue-next.js +63 -7
  25. package/dist/executer/scheduler/state-key.js +89 -15
  26. package/dist/executer/watch-loop.js +22 -6
  27. package/dist/file/get-file-context.js +5 -1
  28. package/dist/harness/connect.js +20 -6
  29. package/dist/harness/mcp-command.js +22 -6
  30. package/dist/harness/mcp.js +63 -114
  31. package/dist/harness/opencode.js +158 -50
  32. package/dist/harness/pi.js +29 -0
  33. package/dist/harness/sandbox-client.js +194 -23
  34. package/dist/harness/service-tools.js +141 -0
  35. package/dist/harness/task-tools.js +221 -0
  36. package/dist/kubernetes/apply.js +49 -1
  37. package/dist/kubernetes/await-running-state.js +241 -18
  38. package/dist/kubernetes/claim-layout.js +10 -1
  39. package/dist/kubernetes/cluster-state.js +245 -0
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +142 -9
  41. package/dist/kubernetes/ensure-kubernetes-service-exists.js +2 -0
  42. package/dist/kubernetes/ensure-persistent-data.js +305 -12
  43. package/dist/kubernetes/follow-pod-logs.js +281 -0
  44. package/dist/kubernetes/job-placement.js +36 -12
  45. package/dist/kubernetes/kept-claims.js +16 -1
  46. package/dist/kubernetes/kubernetes-instance.js +1 -0
  47. package/dist/kubernetes/network-policy.js +6 -5
  48. package/dist/kubernetes/quota-wait.js +97 -0
  49. package/dist/kubernetes/remove-stale-items.js +46 -0
  50. package/dist/kubernetes/restore-kubernetes-data.js +35 -8
  51. package/dist/kubernetes/sandbox-runner.js +628 -0
  52. package/dist/kubernetes/service-rollouts.js +74 -0
  53. package/dist/kubernetes/store-kubernetes-data.js +18 -4
  54. package/dist/kubernetes/volumes.js +124 -12
  55. package/dist/main.js +2 -0
  56. package/dist/optimizer/calculate-checksum.js +49 -5
  57. package/dist/optimizer/check-key.js +94 -0
  58. package/dist/optimizer/check-keys.js +66 -0
  59. package/dist/optimizer/get-work-cache-stats.js +53 -27
  60. package/dist/optimizer/work-task-cache-description.js +49 -1
  61. package/dist/parser/read-build-file.js +8 -3
  62. package/dist/planner/service-definition.js +9 -4
  63. package/dist/planner/utils/append-work-dependencies.js +5 -3
  64. package/dist/planner/utils/append-work-service.js +18 -1
  65. package/dist/planner/utils/append-work-task.js +13 -3
  66. package/dist/planner/utils/get-work-runtime.js +6 -1
  67. package/dist/planner/utils/normalize-path.js +19 -1
  68. package/dist/planner/utils/parse-work-mount.js +7 -1
  69. package/dist/planner/utils/parse-work-port.js +4 -1
  70. package/dist/planner/utils/template-value.js +20 -4
  71. package/dist/planner/validate.js +22 -0
  72. package/dist/planner/work-item-executions.js +27 -0
  73. package/dist/planner/work-network.js +3 -1
  74. package/dist/planner/work-runtime-aggregate.js +32 -0
  75. package/dist/planner/work-runtime-kubernetes.js +204 -53
  76. package/dist/planner/work-task.js +6 -1
  77. package/dist/program.js +27 -9
  78. package/dist/remote/device-login.js +7 -2
  79. package/dist/remote/host-config.js +69 -3
  80. package/dist/remote/remote-commands.js +33 -7
  81. package/dist/remote/remote-status.js +112 -0
  82. package/dist/remote/remote-work-commands.js +571 -45
  83. package/dist/remote/server-client.js +15 -2
  84. package/dist/remote/token-source.js +64 -26
  85. package/dist/run-program.js +9 -0
  86. package/dist/schema/build-file-base-task-schema.js +3 -3
  87. package/dist/schema/build-file-container-service-schema.js +10 -0
  88. package/dist/schema/build-file-container-task-schema.js +16 -1
  89. package/dist/schema/build-file-include-schema.js +18 -4
  90. package/dist/schema/build-file-kubernetes-service-schema.js +2 -0
  91. package/dist/schema/build-file-task-schema.js +5 -1
  92. package/dist/schema/capabilities-schema.js +56 -0
  93. package/dist/schema/reference-parser.js +119 -11
  94. package/dist/schema/removed-properties.js +20 -0
  95. package/dist/schema/schema-parser.js +140 -43
  96. package/dist/schema/work-scope-parser.js +33 -10
  97. package/dist/secrets/command-secret-provider.js +3 -1
  98. package/dist/secrets/github-app-token-command.js +3 -1
  99. package/dist/secrets/secret-catalog.js +43 -19
  100. package/dist/server/accounts-api.js +4 -1
  101. package/dist/server/approvals-api.js +1 -1
  102. package/dist/server/capacity-format.js +36 -0
  103. package/dist/server/capacity.js +330 -0
  104. package/dist/server/checks-api.js +83 -0
  105. package/dist/server/checks.js +116 -0
  106. package/dist/server/dashboard.js +214 -0
  107. package/dist/server/definitions-api.js +66 -3
  108. package/dist/server/endpoints.js +803 -0
  109. package/dist/server/executor.js +216 -30
  110. package/dist/server/kubernetes-backend.js +415 -48
  111. package/dist/server/kubernetes-sandbox-storage.js +60 -6
  112. package/dist/server/oauth.js +16 -1
  113. package/dist/server/overview.js +340 -0
  114. package/dist/server/plan.js +186 -124
  115. package/dist/server/policy.js +42 -4
  116. package/dist/server/proposals-api.js +17 -8
  117. package/dist/server/repo-access.js +5 -0
  118. package/dist/server/run-logs.js +4 -0
  119. package/dist/server/run-plan.js +38 -4
  120. package/dist/server/run-request.js +58 -3
  121. package/dist/server/run-worker.js +307 -17
  122. package/dist/server/runs.js +1036 -42
  123. package/dist/server/sandbox-files.js +107 -16
  124. package/dist/server/sandbox-patch.js +43 -17
  125. package/dist/server/sandbox-pod.js +28 -0
  126. package/dist/server/sandbox-storage.js +23 -0
  127. package/dist/server/sandboxes.js +65 -23
  128. package/dist/server/server-config.js +250 -11
  129. package/dist/server/server.js +465 -33
  130. package/dist/server/service-runs.js +89 -0
  131. package/dist/server/sources.js +68 -11
  132. package/dist/server/timings.js +152 -0
  133. package/dist/server/wait-reason.js +21 -0
  134. package/dist/utils/buffer-context.js +30 -20
  135. package/dist/utils/limit.js +30 -0
  136. package/dist/utils/read-lines.js +65 -0
  137. package/dist/utils/tar.js +28 -1
  138. package/dist/utils/terminal-prompt.js +53 -0
  139. package/dist/utils/units.js +36 -1
  140. package/dist/utils/web-links.js +34 -0
  141. package/package.json +8 -2
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.aggregateWorkRuntime = void 0;
4
+ // An aggregate runs nothing, so it touches nothing: no pid or state file in its
5
+ // directory (on a server that is a checkout it doesn't trust), no outputs.
6
+ function aggregateWorkRuntime() {
7
+ return {
8
+ async initialize() {
9
+ // nothing to prepare
10
+ },
11
+ async remove() {
12
+ // it has no outputs of its own
13
+ },
14
+ async execute() {
15
+ // its state stays running, and executeWorkTask completes it
16
+ },
17
+ async stop() {
18
+ // nothing is running
19
+ },
20
+ async archive() {
21
+ // never pushed, see pushToBackend
22
+ },
23
+ async restore() {
24
+ // never a hit, see checkCacheState
25
+ },
26
+ async currentStateKey() {
27
+ return null;
28
+ },
29
+ };
30
+ }
31
+ exports.aggregateWorkRuntime = aggregateWorkRuntime;
32
+ //# sourceMappingURL=work-runtime-aggregate.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.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = void 0;
6
+ exports.kubernetesForwardRuntime = exports.isRolledOut = exports.kubernetesServiceRuntime = exports.kubernetesTaskRuntime = exports.getTaskJobContainers = exports.describeFailedJob = exports.recordJobExecution = 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");
@@ -11,12 +11,15 @@ const replace_env_variables_1 = require("../environment/replace-env-variables");
11
11
  const apply_1 = require("../kubernetes/apply");
12
12
  const ensure_kubernetes_service_exists_1 = require("../kubernetes/ensure-kubernetes-service-exists");
13
13
  const ensure_kubernetes_deployment_exists_1 = require("../kubernetes/ensure-kubernetes-deployment-exists");
14
+ const follow_pod_logs_1 = require("../kubernetes/follow-pod-logs");
15
+ const work_item_executions_1 = require("./work-item-executions");
14
16
  const service_definition_1 = require("./service-definition");
15
17
  const ensure_namespace_1 = require("../kubernetes/ensure-namespace");
16
18
  const ensure_persistent_data_1 = require("../kubernetes/ensure-persistent-data");
17
19
  const network_gate_1 = require("../kubernetes/network-gate");
18
20
  const await_running_state_1 = require("../kubernetes/await-running-state");
19
21
  const volumes_1 = require("../kubernetes/volumes");
22
+ const service_rollouts_1 = require("../kubernetes/service-rollouts");
20
23
  const resources_1 = require("../kubernetes/resources");
21
24
  const ensure_http_route_1 = require("../kubernetes/ensure-http-route");
22
25
  const find_process_1 = __importDefault(require("find-process"));
@@ -34,6 +37,7 @@ const job_placement_1 = require("../kubernetes/job-placement");
34
37
  const network_policy_1 = require("../kubernetes/network-policy");
35
38
  const run_id_1 = require("../utils/run-id");
36
39
  const work_network_1 = require("./work-network");
40
+ const sandbox_runner_1 = require("../kubernetes/sandbox-runner");
37
41
  const work_secret_1 = require("./work-secret");
38
42
  async function listJobNames(instance, kubernetes, task) {
39
43
  const jobs = await instance.batchApi.listNamespacedJob({
@@ -59,32 +63,17 @@ async function getJobPod(instance, kubernetes, job) {
59
63
  .sort((a, b) => (a.metadata?.creationTimestamp?.toISOString() ?? '').localeCompare(b.metadata?.creationTimestamp?.toISOString() ?? ''))
60
64
  .pop();
61
65
  }
62
- // a task's log is kept to this, the run's own cap is smaller
63
- const MAX_JOB_LOG_BYTES = 4 * 1024 * 1024;
64
- // What the command printed, as the task's output: read from the cluster once the Job
65
- // has ended. Without a pod (it never started) there is nothing to say.
66
- async function writeJobLogs(instance, kubernetes, task, job, container) {
67
- try {
68
- const pod = await getJobPod(instance, kubernetes, job);
69
- if (!pod?.metadata?.name) {
70
- return;
71
- }
72
- const log = await instance.coreApi.readNamespacedPodLog({
73
- name: pod.metadata.name,
74
- namespace: kubernetes.namespace,
75
- container,
76
- limitBytes: MAX_JOB_LOG_BYTES,
77
- });
78
- for (const line of String(log ?? '').split(/\r?\n/)) {
79
- if (line.length > 0) {
80
- task.status.console('stdout', line);
81
- }
82
- }
83
- }
84
- catch (e) {
85
- task.status.write('debug', `the log of ${job} could not be read: ${(0, log_1.getErrorMessage)(e)}`);
66
+ // When the command of a Job ran, as its container says: what the task spent before it (the
67
+ // pod scheduled, the image pulled, the init containers) and after it is not the command's.
68
+ async function recordJobExecution(instance, kubernetes, task, job, container) {
69
+ const pod = await getJobPod(instance, kubernetes, job).catch(() => undefined);
70
+ const status = pod?.status?.containerStatuses?.find((s) => s.name === container);
71
+ const terminated = status?.state?.terminated ?? status?.lastState?.terminated;
72
+ if (terminated?.startedAt && terminated.finishedAt) {
73
+ (0, work_item_executions_1.recordExecution)(task, new Date(terminated.startedAt), new Date(terminated.finishedAt));
86
74
  }
87
75
  }
76
+ exports.recordJobExecution = recordJobExecution;
88
77
  // the command of a Job exited with this code, as a crash on docker or a host
89
78
  class JobCrash extends Error {
90
79
  constructor(exitCode) {
@@ -129,7 +118,8 @@ exports.describeFailedJob = describeFailedJob;
129
118
  * The containers of the Job of a command: the network gate first, nothing runs before the
130
119
  * item's policy holds, then the init containers that read its secrets, then the command. The
131
120
  * proxy's token (`network.secretEnv`) reaches the init containers through `secretSpec` only:
132
- * the command's container gets the proxy variables of a limited network without it.
121
+ * the command's container gets the proxy variables of a limited network without it. A task that
122
+ * adds capabilities gets them in the sandbox's RuntimeClass only.
133
123
  */
134
124
  function getTaskJobContainers(options) {
135
125
  const { task, cmd, envs, secrets, network, secretSpec, kubernetes } = options;
@@ -154,9 +144,10 @@ function getTaskJobContainers(options) {
154
144
  name: options.container,
155
145
  volumeMounts: [...options.mounts, ...secrets.mounts, ...secretSpec.mounts],
156
146
  ...(0, container_resources_1.getKubernetesResources)(task.data.resources),
157
- ...(0, job_placement_1.getContainerSecurity)(kubernetes),
147
+ ...(0, job_placement_1.getContainerSecurity)(kubernetes, task.data.capAdd),
158
148
  },
159
149
  ],
150
+ ...(0, job_placement_1.getPodRuntimeClass)({ name: task.name, capAdd: task.data.capAdd }, kubernetes),
160
151
  };
161
152
  }
162
153
  exports.getTaskJobContainers = getTaskJobContainers;
@@ -165,35 +156,94 @@ function kubernetesTaskRuntime(task, kubernetes) {
165
156
  // on a server that keeps them, the task's claim stays after the run with the state of its
166
157
  // outputs, and the next run of the same source mounts them as they are (see kept-claims)
167
158
  const kept = (0, kept_claims_1.isKeptClaim)(task, kubernetes);
159
+ // on a service run, the claim names the last state whose folder is whole (see
160
+ // rememberedClaimState): a wake or a move at that state mounts it without an upload
161
+ const remembers = kept || !!kubernetes.server?.serviceRun;
168
162
  const claim = (0, volumes_1.getVolumeName)(task, kubernetes);
169
163
  return {
170
164
  initialize() {
171
165
  return Promise.resolve();
172
166
  },
173
167
  async restore(environment, path, stateKey) {
168
+ // a cache hit of a service run at the state that services of the run mount (a move whose
169
+ // dep did not change): its outputs are there, and stay as they are while pods read them
170
+ if (kubernetes.server?.serviceRun &&
171
+ stateKey &&
172
+ (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has((0, volumes_1.getStateFilesDir)(stateKey))) {
173
+ task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
174
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
175
+ return;
176
+ }
177
+ if (remembers && !kept) {
178
+ // the folder of the state is written now: until it is whole, the claim names no state
179
+ // (a restore without a state key says none, and the next run uploads again)
180
+ await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim);
181
+ await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, {
182
+ stateKey,
183
+ // the folders of other states no pod of the run mounts go, as before a Job
184
+ ...(stateKey ? { otherStates: await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim) } : {}),
185
+ });
186
+ if (stateKey) {
187
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
188
+ }
189
+ return;
190
+ }
174
191
  if (!kept) {
175
- await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path);
192
+ await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, { stateKey });
176
193
  return;
177
194
  }
178
195
  const reset = await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim);
179
- await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, { reset });
196
+ await (0, restore_kubernetes_data_1.restoreKubernetesData)(task, kubernetes, instance, environment, path, { reset, stateKey });
180
197
  if (stateKey) {
181
198
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, stateKey);
182
199
  }
183
200
  },
184
- async archive(environment, path) {
185
- await (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path);
201
+ async archive(environment, path, stateKey) {
202
+ await (0, store_kubernetes_data_1.storeKubernetesData)(task, kubernetes, instance, environment, path, stateKey);
186
203
  },
187
204
  async execute(environment, options) {
188
205
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(task.data.envs);
189
- const persistence = await (0, volumes_1.getKubernetesPersistence)(task, kubernetes);
206
+ const persistence = await (0, volumes_1.getKubernetesPersistence)(task, kubernetes, options.stateKey);
190
207
  const workspace = (0, volumes_1.getWorkspacePodSpec)(kubernetes, persistence, { name: task.name, pool: task.data.pool });
208
+ // a shell of a sandbox: its commands go into the sandbox's runner, when it has one now
209
+ if ((0, sandbox_runner_1.canUseRunner)(task, kubernetes, persistence)) {
210
+ try {
211
+ const result = await (0, sandbox_runner_1.executeInRunner)(instance, task, kubernetes, persistence, options.abort);
212
+ if (result.type === 'crash') {
213
+ options.state.set({ stateKey: options.stateKey, type: 'crash', exitCode: result.exitCode });
214
+ return;
215
+ }
216
+ // stopped while the runner started: no Job for it either
217
+ if (result.type === 'canceled' || options.abort.aborted) {
218
+ options.state.set({ stateKey: options.stateKey, type: 'canceled' });
219
+ return;
220
+ }
221
+ if (result.type === 'done') {
222
+ return;
223
+ }
224
+ }
225
+ catch (e) {
226
+ options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
227
+ return;
228
+ }
229
+ }
191
230
  await (0, ensure_namespace_1.ensureNamespace)(instance, kubernetes.namespace);
231
+ // a service run writes the outputs of each state into a folder of their own (see
232
+ // getStateFilesDir), which pods of its services may mount: of the commit before during
233
+ // a move, or of this state after a move that went back
234
+ const files = kubernetes.server?.serviceRun ? { dir: (0, volumes_1.getStateFilesDir)(options.stateKey) } : undefined;
192
235
  try {
236
+ if (files && (await (0, ensure_persistent_data_1.getStateDirsInUse)(instance, kubernetes.namespace, claim)).has(files.dir)) {
237
+ task.status.write('info', `${task.name}: services of the run use its outputs of this state, they stay`);
238
+ await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
239
+ return;
240
+ }
193
241
  // the task writes to it now: what it holds stops being the outputs of a state, and
194
- // goes, as a new claim would hold nothing
195
- const reset = kept && (await (0, kept_claims_1.forgetClaimState)(instance, kubernetes, claim));
196
- await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, task, persistence, { reset });
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 });
197
247
  }
198
248
  catch (e) {
199
249
  options.state.set({ stateKey: options.stateKey, type: 'error', errorMessage: (0, log_1.getErrorMessage)(e) });
@@ -330,24 +380,36 @@ function kubernetesTaskRuntime(task, kubernetes) {
330
380
  };
331
381
  try {
332
382
  const pod = await (0, apply_1.apply)(instance, spec);
333
- if (!pod.status?.succeeded) {
334
- try {
335
- await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort);
336
- }
337
- catch (e) {
338
- if (!(e instanceof abort_1.AbortError)) {
339
- await writeJobLogs(instance, kubernetes, task, podName, container);
340
- const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
341
- if (failure?.type === 'crash') {
342
- throw new JobCrash(failure.exitCode);
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) });
385
+ try {
386
+ if (!pod.status?.succeeded) {
387
+ try {
388
+ await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
+ onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
+ timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ });
392
+ }
393
+ catch (e) {
394
+ if (!(e instanceof abort_1.AbortError)) {
395
+ await logs.settle();
396
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
397
+ const failure = await describeFailedJob(instance, kubernetes, task.name, podName, container, inJob);
398
+ if (failure?.type === 'crash') {
399
+ throw new JobCrash(failure.exitCode);
400
+ }
401
+ throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
343
402
  }
344
- throw new Error(failure?.message ?? (0, log_1.getErrorMessage)(e));
403
+ throw e;
345
404
  }
346
- throw e;
347
405
  }
406
+ await logs.settle();
407
+ }
408
+ finally {
409
+ logs.stop();
348
410
  }
349
- await writeJobLogs(instance, kubernetes, task, podName, container);
350
411
  task.status.write('debug', 'pod completed');
412
+ await recordJobExecution(instance, kubernetes, task.data, podName, container);
351
413
  // its init containers are done with the credentials
352
414
  await (0, job_secrets_1.removeJobCredentials)(instance, kubernetes, task);
353
415
  if (i < task.data.cmds.length) {
@@ -372,7 +434,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
372
434
  }
373
435
  // the finished job stays for its state, the values it read need not
374
436
  await removeTaskSecrets(instance, kubernetes, task);
375
- if (kept) {
437
+ if (remembers) {
376
438
  await (0, kept_claims_1.recordClaimState)(instance, kubernetes, claim, options.stateKey);
377
439
  }
378
440
  }
@@ -428,6 +490,15 @@ function kubernetesTaskRuntime(task, kubernetes) {
428
490
  // the server removes the Jobs of a run at its end, the claim says
429
491
  return (0, kept_claims_1.useClaimState)(instance, kubernetes, claim);
430
492
  }
493
+ if (remembers) {
494
+ // a service run that sleeps loses its Jobs but keeps its claims, the claim says. One
495
+ // that names no state is being written (or was, and that failed): the folder of the
496
+ // state of an earlier Job may be gone. Only a task without a claim goes by its Jobs.
497
+ const remembered = await (0, kept_claims_1.rememberedClaimState)(instance, kubernetes, claim);
498
+ if (remembered !== undefined) {
499
+ return remembered;
500
+ }
501
+ }
431
502
  const jobs = await instance.batchApi.listNamespacedJob({
432
503
  namespace: kubernetes.namespace,
433
504
  labelSelector: (0, resources_1.getItemSelector)(task, kubernetes),
@@ -465,6 +536,10 @@ function kubernetesServiceRuntime(service, kubernetes) {
465
536
  // stops it and a run reuses it, as with a container on Docker. One whose
466
537
  // definition changed goes, with its limits, and is created anew.
467
538
  async initialize(state) {
539
+ if (kubernetes.server?.serviceRun) {
540
+ // a service run starts every service: one that did not change stays as it is (execute)
541
+ return;
542
+ }
468
543
  const deployments = await instance.appsApi.listNamespacedDeployment({
469
544
  namespace: kubernetes.namespace,
470
545
  labelSelector: (0, resources_1.getItemSelector)(service, kubernetes),
@@ -509,18 +584,70 @@ function kubernetesServiceRuntime(service, kubernetes) {
509
584
  await (0, network_policy_1.removeAllKubernetesItemNetworks)(instance, kubernetes, service);
510
585
  },
511
586
  async execute(environment, options) {
512
- const persistence = await (0, volumes_1.getKubernetesPersistence)(service, kubernetes);
587
+ const name = (0, resources_1.getResourceName)(service, kubernetes);
588
+ // a service run that moves to another commit: a service of the same definition and
589
+ // state is left running, another one is rolled from the Deployment it has now
590
+ let previous;
591
+ if (kubernetes.server?.serviceRun) {
592
+ previous = await readDeployment(instance, kubernetes.namespace, name);
593
+ if (previous && isRolledOut(previous, (0, service_definition_1.getServiceDefinitionHash)(service), options.stateKey)) {
594
+ service.status.write('info', `${service.name} did not change, it stays up`);
595
+ options.state.set({ type: 'running', dns: { containerId: name }, stateKey: options.stateKey, remote: null });
596
+ return;
597
+ }
598
+ }
599
+ const persistence = await (0, volumes_1.getKubernetesPersistence)(service, kubernetes, options.stateKey);
600
+ // the files of a service run's service go into a folder of their state, so the pod that
601
+ // runs keeps its own until the new one is up. One that watches its files (`continuous`)
602
+ // gets them synced into the folder its pod mounts: the pod that runs sees the changes.
603
+ const live = (0, volumes_1.isLiveService)(service, kubernetes);
604
+ // the files of the state it runs at now, to put back when the move does not get up
605
+ const before = live ? previous?.metadata?.labels?.['hammerkit.dev/state'] : undefined;
606
+ const files = kubernetes.server?.serviceRun
607
+ ? {
608
+ dir: (0, volumes_1.getStateFilesDir)(options.stateKey),
609
+ live,
610
+ keep: before ? [(0, volumes_1.getStateFilesDir)(before)] : [],
611
+ }
612
+ : undefined;
613
+ if (live && previous && before) {
614
+ const from = (0, volumes_1.getStateFilesDir)(before);
615
+ service_rollouts_1.serviceRollouts.add(kubernetes.namespace, name, previous, () => (0, ensure_persistent_data_1.restoreLiveFiles)(instance, kubernetes, service, persistence, from));
616
+ }
513
617
  await (0, ensure_namespace_1.ensureNamespace)(instance, kubernetes.namespace);
514
618
  await (0, ensure_kubernetes_service_exists_1.ensureKubernetesServiceExists)(instance, kubernetes, service);
515
- await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, service, persistence);
619
+ await (0, ensure_persistent_data_1.ensurePersistentData)(instance, kubernetes, environment, service, persistence, { files });
516
620
  await (0, secrets_1.ensureKubernetesSecret)(instance, kubernetes, service, service.data.secrets, environment);
517
621
  // on a server, the run's: its runs share the namespace, and the service goes with the run
518
622
  const network = await (0, network_policy_1.ensureKubernetesItemNetwork)(instance, kubernetes, service, {
519
623
  followLog: false,
520
624
  run: kubernetes.server ? (0, job_placement_1.getRunLabelValue)(kubernetes.server.run) : null,
521
625
  });
522
- await (0, ensure_kubernetes_deployment_exists_1.ensureKubernetesDeploymentExists)(instance, kubernetes, service, persistence, (0, secrets_1.getKubernetesSecretRefs)(service, kubernetes, service.data.secrets), options.stateKey, network);
523
- const name = (0, resources_1.getResourceName)(service, kubernetes);
626
+ // its output, as on Docker: while it starts, and while it runs unless it runs on
627
+ // without hammerkit (`up --daemon`)
628
+ 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) });
629
+ try {
630
+ 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 });
631
+ }
632
+ catch (e) {
633
+ // the last words of a container that crashed, before why it failed
634
+ await logs.settle().catch(() => undefined);
635
+ logs.stop();
636
+ throw e;
637
+ }
638
+ if (options.daemon || options.abort.aborted || environment.abortCtrl.signal.aborted) {
639
+ logs.stop();
640
+ }
641
+ else {
642
+ // either ends it, and takes the other listener with it
643
+ const listening = new AbortController();
644
+ const stop = () => {
645
+ logs.stop();
646
+ listening.abort();
647
+ };
648
+ options.abort.addEventListener('abort', stop, { once: true, signal: listening.signal });
649
+ environment.abortCtrl.signal.addEventListener('abort', stop, { once: true, signal: listening.signal });
650
+ }
524
651
  options.state.set({
525
652
  type: 'running',
526
653
  dns: { containerId: name },
@@ -576,6 +703,30 @@ function kubernetesServiceRuntime(service, kubernetes) {
576
703
  };
577
704
  }
578
705
  exports.kubernetesServiceRuntime = kubernetesServiceRuntime;
706
+ async function readDeployment(instance, namespace, name) {
707
+ try {
708
+ return await instance.appsApi.readNamespacedDeployment({ name, namespace });
709
+ }
710
+ catch (e) {
711
+ if ((0, apply_1.statusCodeOf)(e) === 404) {
712
+ return undefined;
713
+ }
714
+ throw e;
715
+ }
716
+ }
717
+ // A Deployment of this definition and state whose pods are all of it and ready
718
+ function isRolledOut(deployment, definition, stateKey) {
719
+ const labels = deployment.metadata?.labels ?? {};
720
+ const status = deployment.status;
721
+ return (!deployment.metadata?.deletionTimestamp &&
722
+ labels[ensure_kubernetes_deployment_exists_1.DEFINITION_LABEL] === definition &&
723
+ labels['hammerkit.dev/state'] === stateKey &&
724
+ (status?.observedGeneration ?? 0) >= (deployment.metadata?.generation ?? 0) &&
725
+ (status?.updatedReplicas ?? 0) >= 1 &&
726
+ (status?.availableReplicas ?? 0) >= 1 &&
727
+ (status?.replicas ?? 0) === (status?.updatedReplicas ?? 0));
728
+ }
729
+ exports.isRolledOut = isRolledOut;
579
730
  function kubernetesForwardRuntime(service) {
580
731
  return {
581
732
  async initialize(item) {
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isWorkTask = exports.isContainerWorkTask = void 0;
3
+ exports.isAggregateTask = exports.isWorkTask = exports.isContainerWorkTask = void 0;
4
4
  const isContainerWorkTask = (val) => val.type === 'container-task';
5
5
  exports.isContainerWorkTask = isContainerWorkTask;
6
6
  const isWorkTask = (val) => val.type === 'container-task' || val.type === 'local-task';
7
7
  exports.isWorkTask = isWorkTask;
8
+ // A task that only groups its dependencies: `deps`, and no `image`, `cmds`, `src`,
9
+ // `generates`, `secrets` or `needs`. It needs no runtime, hands on what its dependencies generate to what
10
+ // depends on it, and is up to date (or verified) when all its dependencies are.
11
+ const isAggregateTask = (val) => val.type === 'local-task' && val.aggregate === true;
12
+ exports.isAggregateTask = isAggregateTask;
8
13
  //# sourceMappingURL=work-task.js.map
package/dist/program.js CHANGED
@@ -111,6 +111,18 @@ function getListJson(tasks, services) {
111
111
  })),
112
112
  };
113
113
  }
114
+ // `up` and `down` select by name or by label, not both: a name outside the labels would
115
+ // silently select nothing
116
+ function parseWorkNameScope(names, options) {
117
+ const scope = parseWorkLabelScope(options);
118
+ if (names.length === 0) {
119
+ return scope;
120
+ }
121
+ if (scope.filterLabels || scope.excludeLabels) {
122
+ throw new Error('name tasks and services or select them with --filter/--exclude, not both');
123
+ }
124
+ return { ...scope, names };
125
+ }
114
126
  function parseWorkLabelScope(options) {
115
127
  const scope = {
116
128
  environmentName: null,
@@ -587,9 +599,9 @@ async function getProgram(environment, argv) {
587
599
  }
588
600
  });
589
601
  program
590
- .command('up')
591
- .description("start services(s), with the arguments after -- appended to the selected service's cmd")
592
- .usage('[options] [-- args...]')
602
+ .command('up [names...]')
603
+ .description("start services(s), all or the named tasks and services, with the arguments after -- appended to the selected service's cmd")
604
+ .usage('[options] [names...] [-- args...]')
593
605
  .addOption(new commander_1.Option('-f, --filter <labels...>', 'filter task and services with labels'))
594
606
  .addOption(new commander_1.Option('-e, --exclude <labels...>', 'exclude task and services with labels'))
595
607
  .addOption(new commander_1.Option('-c, --concurrency <number>', 'parallel worker count (default 4, unbounded when every task and service requests cpus and memory)').argParser(parseInt))
@@ -608,11 +620,12 @@ async function getProgram(environment, argv) {
608
620
  .choices(['checksum', 'modify-date', 'none']))
609
621
  .addOption(new commander_1.Option('--cache-read-only', `restore from cache backends but never push to them (or set ${read_only_1.CACHE_READ_ONLY_ENV}=1)`).default(false))
610
622
  .addOption(new commander_1.Option('--timeout <duration>', 'fail tasks without their own timeout after this long (e.g. 10m)').argParser(units_1.parseDuration))
623
+ .addOption(new commander_1.Option('--max-timeout <duration>', 'fail any task after this long, also one with a longer timeout of its own (e.g. 2m)').argParser(units_1.parseDuration))
611
624
  .addOption(new commander_1.Option('--network <level>', 'the most any task or service reaches besides its needs: none, open or allow:<host>,<host>').argParser(parseNetworkArgument))
612
- .action(async (options, command) => {
625
+ .action(async (names, options, command) => {
613
626
  try {
614
627
  const scope = {
615
- ...parseWorkLabelScope(options),
628
+ ...parseWorkNameScope(names, options),
616
629
  args: { values: passthrough, services: true, cache: keepsCache(command) },
617
630
  };
618
631
  const cli = await createCli(fileName, environment, scope);
@@ -626,6 +639,7 @@ async function getProgram(environment, argv) {
626
639
  wait: options.wait,
627
640
  cacheReadOnly: (0, read_only_1.isCacheReadOnly)(options.cacheReadOnly, environment.processEnvs),
628
641
  timeout: options.timeout ?? null,
642
+ maxTimeout: options.maxTimeout ?? null,
629
643
  network: options.network ?? null,
630
644
  });
631
645
  if (!result.success) {
@@ -644,14 +658,14 @@ async function getProgram(environment, argv) {
644
658
  }
645
659
  });
646
660
  program
647
- .command('down')
648
- .description('stop services(s)')
661
+ .command('down [names...]')
662
+ .description('stop services(s), all or the named services and the services the named tasks need')
649
663
  .addOption(new commander_1.Option('-f, --filter <labels...>', 'filter task and services with labels'))
650
664
  .addOption(new commander_1.Option('-e, --exclude <labels...>', 'exclude task and services with labels'))
651
665
  .addOption(new commander_1.Option('--env <name>', 'environment'))
652
- .action(async (options) => {
666
+ .action(async (names, options) => {
653
667
  try {
654
- const scope = parseWorkLabelScope(options);
668
+ const scope = { ...parseWorkNameScope(names, options), stop: true };
655
669
  const cli = await createCli(fileName, environment, scope);
656
670
  const result = await cli.runDown();
657
671
  if (!result.success) {
@@ -688,8 +702,10 @@ async function getProgram(environment, argv) {
688
702
  .addOption(new commander_1.Option('--dry-run', 'print the execution plan with predicted cache hits/misses without running').default(false))
689
703
  .addOption(new commander_1.Option('--cache-read-only', `restore from cache backends but never push to them (or set ${read_only_1.CACHE_READ_ONLY_ENV}=1)`).default(false))
690
704
  .addOption(new commander_1.Option('--timeout <duration>', 'fail tasks without their own timeout after this long (e.g. 10m)').argParser(units_1.parseDuration))
705
+ .addOption(new commander_1.Option('--max-timeout <duration>', 'fail any task after this long, also one with a longer timeout of its own (e.g. 2m)').argParser(units_1.parseDuration))
691
706
  .addOption(new commander_1.Option('--network <level>', 'the most any task or service reaches besides its needs: none, open or allow:<host>,<host>').argParser(parseNetworkArgument))
692
707
  .addOption(new commander_1.Option('--no-skip-deps', 'run dependencies even when nothing needing them has to run'))
708
+ .addOption(new commander_1.Option('--no-restore', 'only look cache hits up, download their outputs only when a task that runs needs them'))
693
709
  .action(async (task, options, command) => {
694
710
  try {
695
711
  // For machine-readable JSON, suppress the human progress logger (which
@@ -722,8 +738,10 @@ async function getProgram(environment, argv) {
722
738
  explain: options.explain,
723
739
  cacheReadOnly: (0, read_only_1.isCacheReadOnly)(options.cacheReadOnly, environment.processEnvs),
724
740
  timeout: options.timeout ?? null,
741
+ maxTimeout: options.maxTimeout ?? null,
725
742
  network: options.network ?? null,
726
743
  skipDeps: options.skipDeps !== false,
744
+ restore: options.restore !== false,
727
745
  });
728
746
  // Reporting only: the summary never changes the exit code or behavior.
729
747
  if (!options.watch) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deviceLogin = void 0;
3
+ exports.deviceLogin = exports.NoSignInError = void 0;
4
4
  const server_client_1 = require("./server-client");
5
5
  const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
6
6
  const DEFAULT_INTERVAL_SECONDS = 5;
@@ -8,6 +8,11 @@ const SLOW_DOWN_SECONDS = 5;
8
8
  const FETCH_TIMEOUT_MS = 10000;
9
9
  const MIN_INTERVAL_SECONDS = 1;
10
10
  const MAX_LIFETIME_SECONDS = 30 * 60;
11
+ // The server takes tokens of this issuer but offers no device sign-in for it: the token has
12
+ // to come from elsewhere, such as a token command.
13
+ class NoSignInError extends server_client_1.ServerError {
14
+ }
15
+ exports.NoSignInError = NoSignInError;
11
16
  const isLoopbackHost = (hostname) => ['localhost', '127.0.0.1', '[::1]'].includes(hostname);
12
17
  // An endpoint must use the scheme of the issuer: loopback http is for a test
13
18
  // identity provider on this machine only, never beside an https issuer.
@@ -89,7 +94,7 @@ async function deviceLogin(server, options) {
89
94
  throw new server_client_1.ServerError(`${server.url} does not accept tokens from ${server.issuer} (it accepts ${accepted})`);
90
95
  }
91
96
  if (!offered.clientId) {
92
- throw new server_client_1.ServerError(`${server.url} offers no sign-in for ${server.issuer}, it needs a token obtained elsewhere`);
97
+ throw new NoSignInError(`${server.url} offers no sign-in for ${server.issuer}, it needs a token obtained elsewhere`);
93
98
  }
94
99
  // What was pinned (by `remote add` or an earlier login) wins; the server can
95
100
  // only offer the same, never something else to sign in with.