hammerkit 2.1.0-next.9 → 2.1.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 (69) hide show
  1. package/build.schema.json +28 -126
  2. package/dist/cli.js +0 -5
  3. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +8 -0
  4. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  5. package/dist/dashboard/assets/{index-CE5PSB3y.js → index-DRSwIRXd.js} +9 -15
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +5 -6
  8. package/dist/docker/remove-orphaned-containers.js +4 -5
  9. package/dist/environment/replace-env-variables.js +5 -8
  10. package/dist/environment/run-source-envs.js +1 -2
  11. package/dist/executer/check-readiness.js +4 -8
  12. package/dist/executer/deadline.js +63 -10
  13. package/dist/executer/docker-service.js +15 -21
  14. package/dist/executer/execute-work-task.js +15 -3
  15. package/dist/harness/sandbox-client.js +1 -0
  16. package/dist/harness/service-tools.js +25 -1
  17. package/dist/kubernetes/cluster-state.js +48 -14
  18. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +14 -62
  19. package/dist/kubernetes/ensure-persistent-data.js +14 -3
  20. package/dist/kubernetes/kept-claims.js +9 -12
  21. package/dist/kubernetes/resources.js +5 -1
  22. package/dist/optimizer/work-task-cache-description.js +3 -5
  23. package/dist/planner/image-build.js +0 -5
  24. package/dist/planner/service-definition.js +1 -2
  25. package/dist/planner/utils/append-work-service.js +4 -12
  26. package/dist/planner/utils/dependency-outputs.js +6 -7
  27. package/dist/planner/validate.js +0 -41
  28. package/dist/planner/work-healthcheck.js +2 -23
  29. package/dist/planner/work-runtime-docker.js +1 -24
  30. package/dist/planner/work-runtime-kubernetes.js +16 -37
  31. package/dist/planner/work-secret.js +11 -33
  32. package/dist/planner/work-service-id.js +6 -30
  33. package/dist/planner/work-service.js +2 -2
  34. package/dist/program.js +1 -19
  35. package/dist/remote/annotations.js +31 -11
  36. package/dist/remote/collect-bundle.js +3 -2
  37. package/dist/remote/remote-status.js +1 -1
  38. package/dist/remote/remote-work-commands.js +53 -12
  39. package/dist/schema/build-file-base-task-schema.js +1 -16
  40. package/dist/schema/build-file-image-build-schema.js +8 -5
  41. package/dist/schema/build-file-service-container-healthcheck.js +7 -25
  42. package/dist/schema/reference-parser.js +43 -108
  43. package/dist/schema/work-scope-parser.js +0 -8
  44. package/dist/secrets/prefetch-secrets.js +1 -20
  45. package/dist/server/capacity.js +6 -18
  46. package/dist/server/endpoints.js +52 -32
  47. package/dist/server/kubernetes-backend.js +28 -114
  48. package/dist/server/kubernetes-sandbox-storage.js +2 -3
  49. package/dist/server/overview.js +1 -7
  50. package/dist/server/plan.js +0 -8
  51. package/dist/server/public-paths.js +52 -0
  52. package/dist/server/run-request.js +52 -1
  53. package/dist/server/run-retry.js +6 -0
  54. package/dist/server/run-source-environment.js +1 -1
  55. package/dist/server/runs.js +6 -4
  56. package/dist/server/sandbox-files-api.js +12 -27
  57. package/dist/server/sandbox-files.js +2 -3
  58. package/dist/server/sandbox-pod.js +1 -1
  59. package/dist/server/sandboxes-api.js +14 -65
  60. package/dist/server/sandboxes.js +3 -19
  61. package/dist/server/server-config.js +2 -59
  62. package/dist/server/server.js +20 -8
  63. package/dist/server/service-runs.js +41 -8
  64. package/package.json +1 -1
  65. package/dist/dashboard/assets/graph-canvas-BFnEN5i0.js +0 -8
  66. package/dist/dashboard/assets/index-Dt3ITvRO.css +0 -2
  67. package/dist/executer/docker-healthcheck.js +0 -73
  68. package/dist/network/healthcheck-request.js +0 -38
  69. package/dist/server/borrowed-quota.js +0 -216
@@ -6,8 +6,8 @@
6
6
  <meta name="robots" content="noindex" />
7
7
  <link rel="icon" href="/logo.png" type="image/png" />
8
8
  <title>hammerkit</title>
9
- <script type="module" crossorigin src="/assets/index-CE5PSB3y.js"></script>
10
- <link rel="stylesheet" crossorigin href="/assets/index-Dt3ITvRO.css">
9
+ <script type="module" crossorigin src="/assets/index-DRSwIRXd.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-BndChMep.css">
11
11
  </head>
12
12
  <body>
13
13
  <div id="root"></div>
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeOrphanedNetworks = exports.removeItemNetworks = exports.getNetworkHostConfig = exports.getPortBinding = exports.removeItemNetwork = exports.prepareItemNetwork = exports.HELPER_HOST_CONFIG = exports.createInternalNetwork = exports.checkNetworkLimitSupport = exports.getNeedNetworkName = exports.getProxyNetworkName = exports.getRunNetworkName = exports.getItemNetworkName = void 0;
3
+ exports.removeOrphanedNetworks = exports.removeItemNetworks = exports.getNetworkHostConfig = exports.getPortBinding = exports.removeItemNetwork = exports.prepareItemNetwork = exports.createInternalNetwork = exports.checkNetworkLimitSupport = exports.getNeedNetworkName = exports.getProxyNetworkName = exports.getRunNetworkName = exports.getItemNetworkName = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const stream_1 = require("stream");
6
6
  const work_service_1 = require("../planner/work-service");
@@ -154,9 +154,8 @@ async function createInternalNetwork(docker, name, labels) {
154
154
  }
155
155
  }
156
156
  exports.createInternalNetwork = createInternalNetwork;
157
- // What the proxy, the relay and the container of a healthcheck may do: serve or connect,
158
- // nothing else.
159
- exports.HELPER_HOST_CONFIG = {
157
+ // What the proxy and relay may do: serve, nothing else.
158
+ const HELPER_HOST_CONFIG = {
160
159
  CapDrop: ['ALL'],
161
160
  SecurityOpt: ['no-new-privileges'],
162
161
  ReadonlyRootfs: true,
@@ -341,7 +340,7 @@ async function startEgressProxy(docker, item, environment, networkName, network,
341
340
  Env: Object.entries((0, egress_proxy_1.getItemProxyEnvironment)(item, egress_proxy_1.EGRESS_PROXY_HOST)).map(([key, value]) => `${key}=${value}`),
342
341
  Labels: getHelperLabels(networkName, options),
343
342
  // unprivileged, it still listens on the port of a TCP forward below 1024
344
- HostConfig: { ...exports.HELPER_HOST_CONFIG, Sysctls: { 'net.ipv4.ip_unprivileged_port_start': '0' } },
343
+ HostConfig: { ...HELPER_HOST_CONFIG, Sysctls: { 'net.ipv4.ip_unprivileged_port_start': '0' } },
345
344
  };
346
345
  const container = await docker.createContainer(createOptions);
347
346
  await docker.getNetwork(getProxyNetworkName(networkName)).connect({
@@ -403,7 +402,7 @@ async function startPortRelay(docker, item, environment, networkName, service, p
403
402
  Labels: getHelperLabels(networkName, options),
404
403
  ExposedPorts: Object.fromEntries(ports.map((port) => [`${port.containerPort}/tcp`, {}])),
405
404
  HostConfig: {
406
- ...exports.HELPER_HOST_CONFIG,
405
+ ...HELPER_HOST_CONFIG,
407
406
  PortBindings: Object.fromEntries(ports.map((port) => [`${port.containerPort}/tcp`, [getPortBinding(port)]])),
408
407
  },
409
408
  });
@@ -4,8 +4,8 @@ exports.removeOrphanedContainers = exports.isDockerUnreachable = exports.isProce
4
4
  const os_1 = require("os");
5
5
  const remove_container_1 = require("./remove-container");
6
6
  // A hammerkit container nothing will remove any more: a task container (they
7
- // never outlive their run), a service, an egress proxy or the container of a
8
- // healthcheck of a run that is gone, started by a hammerkit process of this machine that no longer exists,
7
+ // never outlive their run), a service or an egress proxy of a run that is
8
+ // gone, started by a hammerkit process of this machine that no longer exists,
9
9
  // and the paused state records hammerkit kept before 1.9. Services of `up --daemon` and
10
10
  // containers of other machines or of running processes stay.
11
11
  function isOrphanedContainer(container, isProcessAlive) {
@@ -14,9 +14,8 @@ function isOrphanedContainer(container, isProcessAlive) {
14
14
  if (type === 'task' && container.State === 'paused') {
15
15
  return true;
16
16
  }
17
- // a proxy goes with the task or service it serves, the container of a healthcheck with
18
- // the wait for its service
19
- if (type !== 'task' && type !== 'service' && type !== 'proxy' && type !== 'healthcheck') {
17
+ // a proxy goes with the task or service it serves
18
+ if (type !== 'task' && type !== 'service' && type !== 'proxy') {
20
19
  return false;
21
20
  }
22
21
  return isOfStoppedRun(labels, isProcessAlive);
@@ -37,9 +37,8 @@ function buildEnvironmentVariables(envs, environment, context) {
37
37
  }
38
38
  else if (value.includes('${')) {
39
39
  const interpolated = interpolate(value, envs, environment, context, fromProcess);
40
- if (interpolated.missing.length > 0) {
41
- const [name] = interpolated.missing;
42
- replacements.push({ key, name, available: false, value: null, missing: interpolated.missing });
40
+ if (interpolated.missing) {
41
+ replacements.push({ key, name: interpolated.missing, available: false, value: null });
43
42
  }
44
43
  else {
45
44
  variables[key] = interpolated.value;
@@ -54,15 +53,13 @@ function buildEnvironmentVariables(envs, environment, context) {
54
53
  exports.buildEnvironmentVariables = buildEnvironmentVariables;
55
54
  // Each `${NAME}` comes from the process environment or a .env file, else from a
56
55
  // literal value of the same build file / task `envs`, else from its
57
- // `:-default`. A reference without any of them is missing; each is listed once.
56
+ // `:-default`. A reference without any of them is missing.
58
57
  function interpolate(value, envs, environment, context, fromProcess) {
59
- const missing = [];
58
+ let missing = null;
60
59
  const result = value.replace(INTERPOLATION, (match, name, fallback) => {
61
60
  const resolved = resolveReference(name, environment, context, fromProcess) ?? getLiteral(envs, name) ?? fallback ?? null;
62
61
  if (resolved === null) {
63
- if (!missing.includes(name)) {
64
- missing.push(name);
65
- }
62
+ missing = missing ?? name;
66
63
  return match;
67
64
  }
68
65
  return resolved;
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isRunSourceEnv = exports.RUN_SOURCE_ENVS = void 0;
4
4
  // The variables a server sets for the process of a run, from what the run is from (see
5
5
  // src/server/run-source-environment.ts). Nothing else sets them: the operator's `runs.env`
6
- // can't name them, and a run that isn't from that source has none of them. `validate` reads
7
- // this list too, so an env that reads one of them isn't a variable set nowhere.
6
+ // can't name them, and a run that isn't from that source has none of them.
8
7
  exports.RUN_SOURCE_ENVS = [
9
8
  'HAMMERKIT_RUN_REPO',
10
9
  'HAMMERKIT_RUN_REF',
@@ -2,12 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.checkReadiness = void 0;
4
4
  const execute_docker_1 = require("./execute-docker");
5
- async function checkReadiness(status, command, environment, container, user, abort, env,
6
- // `timeout`: how long one check may take; `name`: the check in the log, else its command
7
- options = {}) {
8
- const timeout = options.timeout ?? 2000;
9
- const name = options.name ?? command.join(' ');
10
- const result = await (0, execute_docker_1.execCommand)(status, environment, container, undefined, command, user, timeout, abort, env);
5
+ async function checkReadiness(status, command, environment, container, user, abort, env) {
6
+ const result = await (0, execute_docker_1.execCommand)(status, environment, container, undefined, command, user, 2000, abort, env);
11
7
  if (result.type === 'timeout') {
12
8
  return false;
13
9
  }
@@ -16,11 +12,11 @@ options = {}) {
16
12
  }
17
13
  else {
18
14
  if (result.result.ExitCode === 0) {
19
- status.write('debug', `healthcheck ${name} succeeded`);
15
+ status.write('debug', `healthcheck ${command.join(' ')} succeeded`);
20
16
  return true;
21
17
  }
22
18
  else {
23
- status.write('debug', `healthcheck ${name} failed with ${result.result.ExitCode}`);
19
+ status.write('debug', `healthcheck ${command.join(' ')} failed with ${result.result.ExitCode}`);
24
20
  return false;
25
21
  }
26
22
  }
@@ -18,23 +18,76 @@ const MAX_TIMER_MS = 2 ** 31 - 1;
18
18
  // An abort signal that follows `parent` and additionally fires after `timeout`
19
19
  // ms, so a task deadline reuses the runtimes' existing abort/cleanup path. A
20
20
  // timeout beyond what a timer can wait (about 24.8 days) sets no deadline.
21
+ // `pause` stops the clock and `resume` starts it again with what was left, so a
22
+ // wait that is not the task's to count (its pod refused by the quota) does not use it.
23
+ // The pauses together may last `timeout` as well: then it fires and `waitedOut` says so.
21
24
  function withDeadline(parent, timeout) {
22
25
  const controller = new AbortController();
23
- let expired = false;
24
26
  const parentListener = (0, abort_event_1.listenOnAbort)(parent, () => controller.abort());
25
- const timer = timeout === null || timeout > MAX_TIMER_MS
26
- ? null
27
- : setTimeout(() => {
28
- expired = true;
27
+ const limit = timeout !== null && timeout <= MAX_TIMER_MS ? timeout : null;
28
+ // what is left of the time to run, and of the time to wait in pauses
29
+ let left = limit ?? 0;
30
+ let pauseLeft = limit ?? 0;
31
+ let paused = false;
32
+ let closed = false;
33
+ let ended = null;
34
+ let since = performance.now();
35
+ let timer = null;
36
+ // ends the current stretch: what it took comes off its budget
37
+ const stopClock = () => {
38
+ if (timer) {
39
+ clearTimeout(timer);
40
+ timer = null;
41
+ }
42
+ if (limit === null || ended) {
43
+ return;
44
+ }
45
+ const took = performance.now() - since;
46
+ if (paused) {
47
+ pauseLeft = Math.min(limit, Math.max(0, pauseLeft - took));
48
+ }
49
+ else {
50
+ left = Math.min(limit, Math.max(0, left - took));
51
+ }
52
+ };
53
+ const startClock = () => {
54
+ since = performance.now();
55
+ if (limit === null || controller.signal.aborted) {
56
+ return;
57
+ }
58
+ const end = paused ? 'waited-out' : 'expired';
59
+ timer = setTimeout(() => {
60
+ timer = null;
61
+ ended = end;
29
62
  controller.abort();
30
- }, timeout);
63
+ }, paused ? pauseLeft : left);
64
+ };
65
+ startClock();
31
66
  return {
32
67
  signal: controller.signal,
33
- expired: () => expired,
34
- clear() {
35
- if (timer) {
36
- clearTimeout(timer);
68
+ // it ran for its timeout
69
+ expired: () => ended === 'expired',
70
+ // its pauses together lasted its timeout
71
+ waitedOut: () => ended === 'waited-out',
72
+ pause() {
73
+ if (closed || paused || ended) {
74
+ return;
37
75
  }
76
+ stopClock();
77
+ paused = true;
78
+ startClock();
79
+ },
80
+ resume() {
81
+ if (closed || !paused || ended) {
82
+ return;
83
+ }
84
+ stopClock();
85
+ paused = false;
86
+ startClock();
87
+ },
88
+ clear() {
89
+ stopClock();
90
+ closed = true;
38
91
  parentListener.close();
39
92
  },
40
93
  };
@@ -11,7 +11,8 @@ const stream_1 = require("../docker/stream");
11
11
  const abort_event_1 = require("../utils/abort-event");
12
12
  const log_1 = require("../log");
13
13
  const remove_container_1 = require("../docker/remove-container");
14
- const docker_healthcheck_1 = require("./docker-healthcheck");
14
+ const check_readiness_1 = require("./check-readiness");
15
+ const main_process_user_1 = require("./main-process-user");
15
16
  const execution_steps_1 = require("./execution-steps");
16
17
  const check_container_binds_1 = require("./check-container-binds");
17
18
  const server_tools_1 = require("../docker/server-tools");
@@ -163,28 +164,21 @@ async function dockerService(docker, item, options, environment) {
163
164
  }
164
165
  else {
165
166
  const healthcheck = item.data.healthcheck;
166
- const checks = await (0, docker_healthcheck_1.prepareDockerHealthcheck)(docker, item, healthcheck, container, environment, options.abort, (0, egress_proxy_1.getProxylessEnvironment)(network.options.env ?? {}));
167
167
  const deadline = Date.now() + healthcheck.timeout;
168
168
  let ready = false;
169
- try {
170
- do {
171
- // The first check waits one interval too, so an entrypoint that drops
172
- // privileges (`exec su-exec app …`) has done so before anything runs.
173
- await new Promise((resolve) => setTimeout(() => resolve(), HEALTHCHECK_INTERVAL_MS));
174
- if (options.abort.aborted) {
175
- break;
176
- }
177
- ready = await checks.check();
178
- if (!ready && Date.now() >= deadline) {
179
- throw new Error((0, work_healthcheck_1.getHealthcheckTimeoutMessage)(item.name, healthcheck));
180
- }
181
- } while (!ready && !options.abort.aborted);
182
- }
183
- finally {
184
- await checks
185
- .remove()
186
- .catch((e) => item.status.write('error', `remove of healthcheck container failed ${(0, log_1.getErrorMessage)(e)}`));
187
- }
169
+ do {
170
+ // The first check waits one interval too, so an entrypoint that drops
171
+ // privileges (`exec su-exec app …`) has done so before anything runs.
172
+ await new Promise((resolve) => setTimeout(() => resolve(), HEALTHCHECK_INTERVAL_MS));
173
+ if (options.abort.aborted) {
174
+ break;
175
+ }
176
+ const user = await (0, main_process_user_1.getMainProcessUser)(container);
177
+ ready = await (0, check_readiness_1.checkReadiness)(item.status, (0, work_service_1.getHealthcheckCommand)(item.data) ?? [], environment, container, user, options.abort, (0, egress_proxy_1.getProxylessEnvironment)(network.options.env ?? {}));
178
+ if (!ready && Date.now() >= deadline) {
179
+ throw new Error((0, work_healthcheck_1.getHealthcheckTimeoutMessage)(item.name, healthcheck));
180
+ }
181
+ } while (!ready && !options.abort.aborted);
188
182
  if (ready) {
189
183
  options.state.set({
190
184
  type: 'running',
@@ -117,19 +117,31 @@ dependents = null) {
117
117
  daemon: options.daemon,
118
118
  publishPorts: false,
119
119
  waitForReady: true,
120
- onQuotaRefused: (refused) => options.processManager.quotaRefused(work, refused),
120
+ onQuotaRefused: (refused) => {
121
+ // the timeout counts the time it runs, not its wait for room under the quota;
122
+ // that wait may last as long as the timeout in all, besides QUOTA_TIMEOUT
123
+ if (refused) {
124
+ deadline.pause();
125
+ }
126
+ else {
127
+ deadline.resume();
128
+ }
129
+ options.processManager.quotaRefused(work, refused);
130
+ },
121
131
  });
122
132
  }
123
133
  finally {
124
134
  deadline.clear();
125
135
  }
126
- if (deadline.expired() && timeout !== null) {
136
+ if ((deadline.expired() || deadline.waitedOut()) && timeout !== null) {
127
137
  // the runtime saw an abort and cleaned up; report it as a failure
128
138
  // (never a cancellation) and stop the run like any failing task
129
139
  work.state.set({
130
140
  type: 'error',
131
141
  stateKey: cacheState.stateKey,
132
- errorMessage: `timed out after ${(0, units_1.formatDuration)(timeout)}`,
142
+ errorMessage: deadline.waitedOut()
143
+ ? `gave up waiting for room under the quota of the namespace after ${(0, units_1.formatDuration)(timeout)}, its timeout`
144
+ : `timed out after ${(0, units_1.formatDuration)(timeout)}`,
133
145
  });
134
146
  if (!options.watch) {
135
147
  environment.abortCtrl.abort();
@@ -201,6 +201,7 @@ class SandboxClient {
201
201
  definition: this.build.hash,
202
202
  services: request.services,
203
203
  endpoints: request.endpoints ?? [],
204
+ ...(request.publicPaths?.length ? { publicPaths: request.publicPaths } : {}),
204
205
  ...(request.ttl ? { ttl: request.ttl } : {}),
205
206
  ...(request.sleepTtl ? { sleepTtl: request.sleepTtl } : {}),
206
207
  ...(request.name ? { name: request.name } : {}),
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SERVICE_TOOLS = exports.describeServiceRun = exports.parseEndpoint = exports.serviceToolArgs = exports.serviceToolSchema = void 0;
3
+ exports.SERVICE_TOOLS = exports.describeServiceRun = exports.parsePublicPath = exports.parseEndpoint = exports.serviceToolArgs = exports.serviceToolSchema = void 0;
4
4
  // the most of a page an agent gets back
5
5
  const MAX_PAGE_CHARS = 20000;
6
6
  // The parameters as a JSON schema, for MCP, pi and opencode 2.
@@ -35,6 +35,23 @@ function parseEndpoint(value) {
35
35
  return { service: value.slice(0, index), port };
36
36
  }
37
37
  exports.parseEndpoint = parseEndpoint;
38
+ // `preview:web:8080=/mcp,/.well-known` as the server takes a public path of an endpoint: the
39
+ // run it is for, the endpoint, and the paths that need no sign-in
40
+ function parsePublicPath(value) {
41
+ const equals = value.indexOf('=');
42
+ const [run, service, port, ...rest] = (equals < 0 ? value : value.slice(0, equals)).split(':');
43
+ const paths = equals < 0 ? [] : value.slice(equals + 1).split(',');
44
+ if (equals < 0 ||
45
+ !run ||
46
+ !service ||
47
+ rest.length > 0 ||
48
+ !/^\d+$/.test(port ?? '') ||
49
+ paths.some((path) => path === '')) {
50
+ throw new Error(`${value} is not a public path, write it as run:service:port=/path,/other, such as preview:web:8080=/mcp`);
51
+ }
52
+ return { run, service, port: Number(port), paths };
53
+ }
54
+ exports.parsePublicPath = parsePublicPath;
38
55
  // How a service run stands, for an agent: where its endpoints are and until when.
39
56
  function describeServiceRun(run) {
40
57
  const lines = [`run ${run.id}: ${run.state}${run.up ? ` (${run.up.name})` : ''}`];
@@ -76,6 +93,12 @@ exports.SERVICE_TOOLS = [
76
93
  parameters: {
77
94
  services: { type: 'string[]', description: 'The services to start, as the build file names them' },
78
95
  endpoints: { type: 'string[]', description: 'The ports to publish, as service:port, such as web:8080' },
96
+ publicPaths: {
97
+ type: 'string[]',
98
+ description: 'Paths of an endpoint that need no sign-in of the server, for an app that signs in on its own (an MCP ' +
99
+ 'client, for one), as run:service:port=/path,/other, such as preview:web:8080=/mcp,/.well-known; the run is ' +
100
+ 'the name of this run',
101
+ },
79
102
  ttl: {
80
103
  type: 'string',
81
104
  description: 'How long they stay once ready, such as 2h, then they are removed; the server default when left out',
@@ -99,6 +122,7 @@ exports.SERVICE_TOOLS = [
99
122
  const followed = await client.up({
100
123
  services: args.services,
101
124
  endpoints: (args.endpoints ?? []).map(parseEndpoint),
125
+ publicPaths: (args.publicPaths ?? []).map(parsePublicPath),
102
126
  ttl: args.ttl || undefined,
103
127
  sleepTtl: args.sleepTtl || undefined,
104
128
  name: args.name || undefined,
@@ -45,7 +45,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
45
45
  }
46
46
  }
47
47
  for (const status of mainStatuses(pod, container)) {
48
- const failure = getContainerFailure(status, restartsEnded(pod, status), restarts);
48
+ const failure = getContainerFailure(pod, status, restartsEnded(pod, status), restarts);
49
49
  if (failure) {
50
50
  return failure;
51
51
  }
@@ -53,7 +53,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
53
53
  return null;
54
54
  }
55
55
  exports.getPodFailure = getPodFailure;
56
- function getContainerFailure(status, restartsEnded, restarts) {
56
+ function getContainerFailure(pod, status, restartsEnded, restarts) {
57
57
  const waiting = status.state?.waiting;
58
58
  const reason = waiting?.reason;
59
59
  const said = waiting?.message ? `: ${cut(waiting.message)}` : '';
@@ -78,18 +78,33 @@ function getContainerFailure(status, restartsEnded, restarts) {
78
78
  return { text: `its container could not be started (${reason})${said}`, final: false };
79
79
  case 'CrashLoopBackOff':
80
80
  return status.restartCount >= restarts
81
- ? { text: `it keeps crashing: ${describeLastExit(status)}`, final: true }
81
+ ? { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true }
82
82
  : null;
83
83
  }
84
84
  // a kubelet may leave an instance that ended as it is until its back-off is over, and say
85
85
  // CrashLoopBackOff only when it looks at the pod again, a minute later: the same crash
86
86
  if (restartsEnded && status.state?.terminated && status.restartCount >= restarts) {
87
- return { text: `it keeps crashing: ${describeLastExit(status)}`, final: true };
87
+ return { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true };
88
88
  }
89
89
  return null;
90
90
  }
91
- // How the last instance of a container ended, as the cluster says it.
92
- function describeLastExit(status) {
91
+ // The signals a container is most often ended by, by their Linux numbers: containers here
92
+ // are Linux ones, and other systems number some signals differently.
93
+ const SIGNALS = {
94
+ 1: 'SIGHUP',
95
+ 2: 'SIGINT',
96
+ 6: 'SIGABRT',
97
+ 9: 'SIGKILL',
98
+ 11: 'SIGSEGV',
99
+ 15: 'SIGTERM',
100
+ };
101
+ /**
102
+ * How the last instance of a container ended, as the cluster says it: its exit code and
103
+ * reason, and the signal of an exit code above 128. The kubelet kills a container whose
104
+ * liveness probe (its healthcheck) keeps failing, so a container of `pod` with one that was
105
+ * killed says that it may be why; one without a healthcheck never does.
106
+ */
107
+ function describeLastExit(status, pod) {
93
108
  // the instance that ended now, else the one before the one that waits or runs
94
109
  const last = status.state?.terminated ?? status.lastState?.terminated;
95
110
  const restarts = `, restarted ${status.restartCount} time${status.restartCount === 1 ? '' : 's'}`;
@@ -99,8 +114,14 @@ function describeLastExit(status) {
99
114
  if (last.reason === 'OOMKilled') {
100
115
  return `it was killed for using more memory than its limit (OOMKilled)${restarts}`;
101
116
  }
102
- // the kubelet kills a container whose liveness probe (its healthcheck) keeps failing
103
- const killed = last.exitCode === 137 || last.exitCode === 143 ? ', killed as when its healthcheck kept failing' : '';
117
+ // A shell, and the runtime for process 1, exit with 128 plus the signal that ended a
118
+ // process: 129 to 159 are the signals 1 to 31, which Linux has; a higher code is the
119
+ // process's own.
120
+ const signal = last.exitCode >= 129 && last.exitCode <= 159 ? last.exitCode - 128 : undefined;
121
+ const probed = !!pod.spec?.containers?.find((container) => container.name === status.name)?.livenessProbe;
122
+ const killed = signal === undefined
123
+ ? ''
124
+ : `, killed by ${SIGNALS[signal] ?? `signal ${signal}`}${probed && (signal === 9 || signal === 15) ? ' as when its healthcheck keeps failing' : ''}`;
104
125
  return `it exited with code ${last.exitCode}${last.reason ? ` (${last.reason})` : ''}${killed}${restarts}`;
105
126
  }
106
127
  exports.describeLastExit = describeLastExit;
@@ -125,14 +146,14 @@ function getPodWaiting(pod, container) {
125
146
  case 'RunContainerError':
126
147
  return `can not start its container yet (${waiting.reason})${said}`;
127
148
  case 'CrashLoopBackOff':
128
- return `crashed and starts again: ${describeLastExit(status)}`;
149
+ return `crashed and starts again: ${describeLastExit(status, pod)}`;
129
150
  }
130
151
  const ended = status.state?.terminated;
131
152
  if (ended && restartsEnded(pod, status)) {
132
- return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status)}`;
153
+ return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status, pod)}`;
133
154
  }
134
155
  if (status.restartCount > 0 && status.state?.running && !status.ready) {
135
- return `restarted: ${describeLastExit(status)}`;
156
+ return `restarted: ${describeLastExit(status, pod)}`;
136
157
  }
137
158
  }
138
159
  return undefined;
@@ -167,16 +188,29 @@ function describePod(pod) {
167
188
  const said = failure ?? waiting;
168
189
  const parts = [phase, ...(said ? [said] : [])];
169
190
  for (const status of crashed) {
170
- if (!said?.includes(describeLastExit(status))) {
171
- parts.push(`${status.name}: ${describeLastExit(status)}`);
191
+ const exit = describeLastExit(status, pod);
192
+ if (!said?.includes(exit)) {
193
+ parts.push(`container ${status.name}: ${exit}`);
172
194
  }
173
195
  }
174
196
  if (!said && unready.length > 0) {
175
197
  parts.push(`not ready: ${unready.join(', ')}`);
176
198
  }
177
- return `pod ${name}: ${parts.join(', ')}`;
199
+ return `pod ${name}${describeHelper(pod)}: ${parts.join(', ')}`;
178
200
  }
179
201
  exports.describePod = describePod;
202
+ // what a pod hammerkit runs beside a task or service does, so it is not taken for the item
203
+ function describeHelper(pod) {
204
+ const item = pod.metadata?.annotations?.[resources_1.ITEM_ANNOTATION];
205
+ switch (item ? pod.metadata?.annotations?.[resources_1.HELPER_ANNOTATION] : undefined) {
206
+ case 'upload':
207
+ return ` (a helper that copies the files of ${item} into its volume, not ${item} itself)`;
208
+ case 'download':
209
+ return ` (a helper that copies the outputs of ${item} out of its volume, not ${item} itself)`;
210
+ default:
211
+ return '';
212
+ }
213
+ }
180
214
  /**
181
215
  * The message of a warning event, as far as it is the cluster's: a failed probe says the
182
216
  * output of the command, which is the service's, and is left out.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHealthcheckProbe = exports.getServiceContainerName = exports.MIN_READY_SECONDS = exports.getPodTemplateHash = exports.POD_ANNOTATION = exports.ROLLOUT_DEADLINE_SECONDS = exports.ensureKubernetesDeploymentExists = exports.DEBUG_CONTAINER_RESOURCES = exports.DEFINITION_LABEL = void 0;
3
+ exports.getServiceContainerName = exports.MIN_READY_SECONDS = exports.getPodTemplateHash = exports.POD_ANNOTATION = exports.ROLLOUT_DEADLINE_SECONDS = exports.ensureKubernetesDeploymentExists = exports.DEBUG_CONTAINER_RESOURCES = exports.DEFINITION_LABEL = void 0;
4
4
  const service_definition_1 = require("../planner/service-definition");
5
5
  const work_service_1 = require("../planner/work-service");
6
6
  const volumes_1 = require("./volumes");
@@ -18,8 +18,6 @@ const network_policy_1 = require("./network-policy");
18
18
  const egress_proxy_1 = require("../network/egress-proxy");
19
19
  const service_rollouts_1 = require("./service-rollouts");
20
20
  const quota_wait_1 = require("./quota-wait");
21
- const transfer_tools_1 = require("./transfer-tools");
22
- const healthcheck_request_1 = require("../network/healthcheck-request");
23
21
  // what the service was created from, to tell a changed one
24
22
  exports.DEFINITION_LABEL = 'hammerkit.dev/definition';
25
23
  // how often a starting container is checked: as the liveness probe
@@ -36,15 +34,18 @@ network,
36
34
  rollout = {}) {
37
35
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(service.data.envs);
38
36
  const name = (0, resources_1.getResourceName)(service, env);
37
+ const healthcheckCommand = (0, work_service_1.getHealthcheckCommand)(service.data);
39
38
  const serviceCommand = (0, work_service_1.getServiceCommand)(service.data, { kubernetes: true });
40
- const probe = getHealthcheckProbe(service.data, network.env);
41
- const probeTools = needsProbeTools(service.data);
42
- if (probeTools) {
43
- const over = [...persistence.mounts.map((m) => m.mount), ...secrets.mounts].find((mount) => (0, transfer_tools_1.isTransferToolsPath)(mount.mountPath));
44
- if (over) {
45
- throw new Error(`service ${service.name} mounts ${over.mountPath}, over ${transfer_tools_1.TRANSFER_TOOLS_PATH} where its healthcheck's tools are`);
39
+ const probe = healthcheckCommand
40
+ ? {
41
+ exec: {
42
+ // the service itself, not through the proxy (see getProxylessEnvironment)
43
+ command: withoutProxy(healthcheckCommand, network.env),
44
+ },
45
+ periodSeconds: 5,
46
+ failureThreshold: 3,
46
47
  }
47
- }
48
+ : undefined;
48
49
  // the healthcheck's `timeout` for each start: until it passed once, the liveness probe
49
50
  // doesn't kill a container that starts slowly, and the wait fails it with the timeout
50
51
  const startupProbe = probe && service.data.healthcheck
@@ -95,7 +96,7 @@ rollout = {}) {
95
96
  // the pod resolves its own service name, as with Docker's Hostname
96
97
  hostname: (0, service_hostname_1.getServiceHostname)(service.name),
97
98
  hostAliases: network.hostAliases,
98
- initContainers: [...network.initContainers, ...(probeTools ? [(0, transfer_tools_1.getTransferToolsInitContainer)()] : [])],
99
+ initContainers: network.initContainers,
99
100
  // on a server the pod is the build's: no token of the namespace, and the
100
101
  // nodes of the first pool
101
102
  ...(placement
@@ -126,11 +127,7 @@ rollout = {}) {
126
127
  livenessProbe: probe,
127
128
  startupProbe,
128
129
  ...(0, container_resources_1.getKubernetesResources)(service.data.resources),
129
- volumeMounts: [
130
- ...persistence.mounts.map((m) => m.mount),
131
- ...secrets.mounts,
132
- ...(probeTools ? [transfer_tools_1.TRANSFER_TOOLS_MOUNT] : []),
133
- ],
130
+ volumeMounts: [...persistence.mounts.map((m) => m.mount), ...secrets.mounts],
134
131
  ...(0, job_placement_1.getContainerSecurity)(env),
135
132
  },
136
133
  {
@@ -145,12 +142,7 @@ rollout = {}) {
145
142
  ...(0, job_placement_1.getContainerSecurity)(env),
146
143
  },
147
144
  ],
148
- volumes: [
149
- ...persistence.volumes,
150
- ...persistence.workspace,
151
- ...secrets.volumes,
152
- ...(probeTools ? transfer_tools_1.TRANSFER_TOOLS_VOLUMES : []),
153
- ],
145
+ volumes: [...persistence.volumes, ...persistence.workspace, ...secrets.volumes],
154
146
  },
155
147
  },
156
148
  },
@@ -284,46 +276,6 @@ function getKubernetesCommand(command) {
284
276
  }
285
277
  return {};
286
278
  }
287
- /**
288
- * The healthcheck as the probe of the service's container: a `cmd` as an exec probe, `tcp`
289
- * and `http` as the kubelet's own tcpSocket and httpGet, which no NetworkPolicy of a limited
290
- * service keeps out. httpGet counts 200 to 399 as healthy, so an `http` check with status
291
- * codes of its own is an exec probe of the busybox an init container copies into the pod
292
- * (needsProbeTools), the check a service on Docker runs (getHealthcheckRequestCommand).
293
- */
294
- function getHealthcheckProbe(service, env) {
295
- const healthcheck = service.healthcheck;
296
- if (!healthcheck) {
297
- return undefined;
298
- }
299
- const timing = { periodSeconds: STARTUP_PERIOD_SECONDS, failureThreshold: 3 };
300
- if ('cmd' in healthcheck) {
301
- // the service itself, not through the proxy (see getProxylessEnvironment)
302
- return { exec: { command: withoutProxy((0, work_service_1.getHealthcheckCommand)(service) ?? [], env) }, ...timing };
303
- }
304
- if ('tcp' in healthcheck) {
305
- return { tcpSocket: { port: healthcheck.tcp.port }, timeoutSeconds: healthcheck_request_1.HEALTHCHECK_REQUEST_SECONDS, ...timing };
306
- }
307
- if (needsProbeTools(service)) {
308
- return {
309
- exec: { command: (0, healthcheck_request_1.getHealthcheckRequestCommand)(transfer_tools_1.TRANSFER_BUSYBOX, healthcheck) },
310
- // its request's bound, and the start of the busybox
311
- timeoutSeconds: healthcheck_request_1.HEALTHCHECK_REQUEST_SECONDS + 1,
312
- ...timing,
313
- };
314
- }
315
- const { port, path, scheme } = healthcheck.http;
316
- return {
317
- httpGet: { port, path, scheme: scheme === 'https' ? 'HTTPS' : 'HTTP' },
318
- timeoutSeconds: healthcheck_request_1.HEALTHCHECK_REQUEST_SECONDS,
319
- ...timing,
320
- };
321
- }
322
- exports.getHealthcheckProbe = getHealthcheckProbe;
323
- // an `http` healthcheck with status codes of its own, which the kubelet's httpGet can't check
324
- function needsProbeTools(service) {
325
- return !!service.healthcheck && 'http' in service.healthcheck && service.healthcheck.http.status !== null;
326
- }
327
279
  // A probe runs with the container's variables, so it empties the proxy ones
328
280
  // through `env`, as a Docker healthcheck does with the exec's own variables.
329
281
  function withoutProxy(command, env) {