hammerkit 2.1.0-next.1 → 2.1.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build.schema.json CHANGED
@@ -776,19 +776,96 @@
776
776
  "type": "boolean"
777
777
  },
778
778
  "healthcheck": {
779
- "type": "object",
780
- "properties": {
781
- "cmd": {
782
- "type": "string"
779
+ "anyOf": [
780
+ {
781
+ "type": "object",
782
+ "properties": {
783
+ "cmd": {
784
+ "type": "string"
785
+ },
786
+ "timeout": {
787
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/timeout"
788
+ }
789
+ },
790
+ "required": [
791
+ "cmd"
792
+ ],
793
+ "additionalProperties": false
794
+ },
795
+ {
796
+ "type": "object",
797
+ "properties": {
798
+ "http": {
799
+ "type": "object",
800
+ "properties": {
801
+ "port": {
802
+ "type": "integer",
803
+ "minimum": 1,
804
+ "maximum": 65535
805
+ },
806
+ "path": {
807
+ "type": "string",
808
+ "pattern": "^\\/"
809
+ },
810
+ "scheme": {
811
+ "type": "string",
812
+ "enum": [
813
+ "http",
814
+ "https"
815
+ ]
816
+ },
817
+ "status": {
818
+ "type": "array",
819
+ "items": {
820
+ "type": "integer",
821
+ "minimum": 100,
822
+ "maximum": 599
823
+ },
824
+ "minItems": 1
825
+ }
826
+ },
827
+ "required": [
828
+ "port"
829
+ ],
830
+ "additionalProperties": false,
831
+ "description": "GET <scheme>://<service>:<port><path>, healthy on one of status (default any 2xx or 3xx)"
832
+ },
833
+ "timeout": {
834
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/0/properties/timeout"
835
+ }
836
+ },
837
+ "required": [
838
+ "http"
839
+ ],
840
+ "additionalProperties": false
783
841
  },
784
- "timeout": {
785
- "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/timeout"
842
+ {
843
+ "type": "object",
844
+ "properties": {
845
+ "tcp": {
846
+ "type": "object",
847
+ "properties": {
848
+ "port": {
849
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/1/properties/http/properties/port"
850
+ }
851
+ },
852
+ "required": [
853
+ "port"
854
+ ],
855
+ "additionalProperties": false,
856
+ "description": "healthy once <port> takes a connection"
857
+ },
858
+ "timeout": {
859
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/0/properties/timeout"
860
+ }
861
+ },
862
+ "required": [
863
+ "tcp"
864
+ ],
865
+ "additionalProperties": false
786
866
  }
787
- },
788
- "required": [
789
- "cmd"
790
867
  ],
791
- "additionalProperties": false
868
+ "description": "exactly one of cmd, http or tcp, and how long it may take to pass"
792
869
  },
793
870
  "init": {
794
871
  "type": "string",
@@ -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.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.HELPER_HOST_CONFIG = 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,8 +154,9 @@ async function createInternalNetwork(docker, name, labels) {
154
154
  }
155
155
  }
156
156
  exports.createInternalNetwork = createInternalNetwork;
157
- // What the proxy and relay may do: serve, nothing else.
158
- const HELPER_HOST_CONFIG = {
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 = {
159
160
  CapDrop: ['ALL'],
160
161
  SecurityOpt: ['no-new-privileges'],
161
162
  ReadonlyRootfs: true,
@@ -340,7 +341,7 @@ async function startEgressProxy(docker, item, environment, networkName, network,
340
341
  Env: Object.entries((0, egress_proxy_1.getItemProxyEnvironment)(item, egress_proxy_1.EGRESS_PROXY_HOST)).map(([key, value]) => `${key}=${value}`),
341
342
  Labels: getHelperLabels(networkName, options),
342
343
  // unprivileged, it still listens on the port of a TCP forward below 1024
343
- HostConfig: { ...HELPER_HOST_CONFIG, Sysctls: { 'net.ipv4.ip_unprivileged_port_start': '0' } },
344
+ HostConfig: { ...exports.HELPER_HOST_CONFIG, Sysctls: { 'net.ipv4.ip_unprivileged_port_start': '0' } },
344
345
  };
345
346
  const container = await docker.createContainer(createOptions);
346
347
  await docker.getNetwork(getProxyNetworkName(networkName)).connect({
@@ -402,7 +403,7 @@ async function startPortRelay(docker, item, environment, networkName, service, p
402
403
  Labels: getHelperLabels(networkName, options),
403
404
  ExposedPorts: Object.fromEntries(ports.map((port) => [`${port.containerPort}/tcp`, {}])),
404
405
  HostConfig: {
405
- ...HELPER_HOST_CONFIG,
406
+ ...exports.HELPER_HOST_CONFIG,
406
407
  PortBindings: Object.fromEntries(ports.map((port) => [`${port.containerPort}/tcp`, [getPortBinding(port)]])),
407
408
  },
408
409
  });
@@ -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 or an egress proxy of a run that is
8
- // gone, started by a hammerkit process of this machine that no longer exists,
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,
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,8 +14,9 @@ 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
18
- if (type !== 'task' && type !== 'service' && type !== 'proxy') {
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') {
19
20
  return false;
20
21
  }
21
22
  return isOfStoppedRun(labels, isProcessAlive);
@@ -2,8 +2,12 @@
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
- const result = await (0, execute_docker_1.execCommand)(status, environment, container, undefined, command, user, 2000, abort, env);
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);
7
11
  if (result.type === 'timeout') {
8
12
  return false;
9
13
  }
@@ -12,11 +16,11 @@ async function checkReadiness(status, command, environment, container, user, abo
12
16
  }
13
17
  else {
14
18
  if (result.result.ExitCode === 0) {
15
- status.write('debug', `healthcheck ${command.join(' ')} succeeded`);
19
+ status.write('debug', `healthcheck ${name} succeeded`);
16
20
  return true;
17
21
  }
18
22
  else {
19
- status.write('debug', `healthcheck ${command.join(' ')} failed with ${result.result.ExitCode}`);
23
+ status.write('debug', `healthcheck ${name} failed with ${result.result.ExitCode}`);
20
24
  return false;
21
25
  }
22
26
  }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareDockerHealthcheck = void 0;
4
+ const work_service_1 = require("../planner/work-service");
5
+ const work_healthcheck_1 = require("../planner/work-healthcheck");
6
+ const check_readiness_1 = require("./check-readiness");
7
+ const main_process_user_1 = require("./main-process-user");
8
+ const pull_1 = require("../docker/pull");
9
+ const transfer_tools_1 = require("../kubernetes/transfer-tools");
10
+ const item_network_1 = require("../docker/item-network");
11
+ const run_labels_1 = require("../docker/run-labels");
12
+ const work_instance_id_1 = require("../planner/work-instance-id");
13
+ const remove_container_1 = require("../docker/remove-container");
14
+ const healthcheck_request_1 = require("../network/healthcheck-request");
15
+ // how long docker may take to run one check of a request: its own bound, and the exec around it
16
+ const REQUEST_EXEC_TIMEOUT_MS = (healthcheck_request_1.HEALTHCHECK_REQUEST_SECONDS + 3) * 1000;
17
+ /**
18
+ * The checks of a service's healthcheck on Docker. A `cmd` runs in the service's container,
19
+ * as the user of its main process. An `http` or `tcp` check runs in a container of the pinned
20
+ * busybox that shares the service's network namespace: it needs no tool of the image and no
21
+ * published port, and reaches the service whatever network it is on. That container lives
22
+ * while the service is waited for.
23
+ */
24
+ async function prepareDockerHealthcheck(docker, item, healthcheck, container, environment, abort,
25
+ // the variables of a `cmd` on top of the container's
26
+ env) {
27
+ if ('cmd' in healthcheck) {
28
+ const command = (0, work_service_1.getHealthcheckCommand)(item.data) ?? [];
29
+ return {
30
+ async check() {
31
+ const user = await (0, main_process_user_1.getMainProcessUser)(container);
32
+ return (0, check_readiness_1.checkReadiness)(item.status, command, environment, container, user, abort, env);
33
+ },
34
+ async remove() { },
35
+ };
36
+ }
37
+ await (0, pull_1.pull)(item.status, docker, transfer_tools_1.HELPER_TOOLS_IMAGE, environment);
38
+ const helper = await docker.createContainer({
39
+ Image: transfer_tools_1.HELPER_TOOLS_IMAGE,
40
+ Cmd: ['sleep', '86400'],
41
+ User: '65534:65534',
42
+ Labels: {
43
+ app: 'hammerkit',
44
+ 'hammerkit-type': 'healthcheck',
45
+ 'hammerkit-healthcheck-of': (0, work_instance_id_1.getWorkInstanceId)(item),
46
+ ...(0, run_labels_1.getRunLabels)(),
47
+ // gone once the service is up, also of `up --daemon`
48
+ 'hammerkit-daemon': 'false',
49
+ },
50
+ HostConfig: { ...item_network_1.HELPER_HOST_CONFIG, NetworkMode: `container:${container.id}` },
51
+ });
52
+ try {
53
+ await helper.start();
54
+ }
55
+ catch (e) {
56
+ await (0, remove_container_1.removeContainer)(helper).catch(() => undefined);
57
+ throw e;
58
+ }
59
+ const command = (0, healthcheck_request_1.getHealthcheckRequestCommand)('/bin/busybox', healthcheck);
60
+ return {
61
+ check() {
62
+ return (0, check_readiness_1.checkReadiness)(item.status, command, environment, helper, null, abort, undefined, {
63
+ timeout: REQUEST_EXEC_TIMEOUT_MS,
64
+ name: (0, work_healthcheck_1.describeHealthcheck)(healthcheck),
65
+ });
66
+ },
67
+ remove() {
68
+ return (0, remove_container_1.removeContainer)(helper);
69
+ },
70
+ };
71
+ }
72
+ exports.prepareDockerHealthcheck = prepareDockerHealthcheck;
73
+ //# sourceMappingURL=docker-healthcheck.js.map
@@ -11,8 +11,7 @@ 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 check_readiness_1 = require("./check-readiness");
15
- const main_process_user_1 = require("./main-process-user");
14
+ const docker_healthcheck_1 = require("./docker-healthcheck");
16
15
  const execution_steps_1 = require("./execution-steps");
17
16
  const check_container_binds_1 = require("./check-container-binds");
18
17
  const server_tools_1 = require("../docker/server-tools");
@@ -164,21 +163,28 @@ async function dockerService(docker, item, options, environment) {
164
163
  }
165
164
  else {
166
165
  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
- 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);
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
+ }
182
188
  if (ready) {
183
189
  options.state.set({
184
190
  type: 'running',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
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;
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,6 +18,8 @@ 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");
21
23
  // what the service was created from, to tell a changed one
22
24
  exports.DEFINITION_LABEL = 'hammerkit.dev/definition';
23
25
  // how often a starting container is checked: as the liveness probe
@@ -34,18 +36,15 @@ network,
34
36
  rollout = {}) {
35
37
  const envs = (0, replace_env_variables_1.getEnvironmentVariables)(service.data.envs);
36
38
  const name = (0, resources_1.getResourceName)(service, env);
37
- const healthcheckCommand = (0, work_service_1.getHealthcheckCommand)(service.data);
38
39
  const serviceCommand = (0, work_service_1.getServiceCommand)(service.data, { kubernetes: true });
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,
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`);
47
46
  }
48
- : undefined;
47
+ }
49
48
  // the healthcheck's `timeout` for each start: until it passed once, the liveness probe
50
49
  // doesn't kill a container that starts slowly, and the wait fails it with the timeout
51
50
  const startupProbe = probe && service.data.healthcheck
@@ -96,7 +95,7 @@ rollout = {}) {
96
95
  // the pod resolves its own service name, as with Docker's Hostname
97
96
  hostname: (0, service_hostname_1.getServiceHostname)(service.name),
98
97
  hostAliases: network.hostAliases,
99
- initContainers: network.initContainers,
98
+ initContainers: [...network.initContainers, ...(probeTools ? [(0, transfer_tools_1.getTransferToolsInitContainer)()] : [])],
100
99
  // on a server the pod is the build's: no token of the namespace, and the
101
100
  // nodes of the first pool
102
101
  ...(placement
@@ -127,7 +126,11 @@ rollout = {}) {
127
126
  livenessProbe: probe,
128
127
  startupProbe,
129
128
  ...(0, container_resources_1.getKubernetesResources)(service.data.resources),
130
- volumeMounts: [...persistence.mounts.map((m) => m.mount), ...secrets.mounts],
129
+ volumeMounts: [
130
+ ...persistence.mounts.map((m) => m.mount),
131
+ ...secrets.mounts,
132
+ ...(probeTools ? [transfer_tools_1.TRANSFER_TOOLS_MOUNT] : []),
133
+ ],
131
134
  ...(0, job_placement_1.getContainerSecurity)(env),
132
135
  },
133
136
  {
@@ -142,7 +145,12 @@ rollout = {}) {
142
145
  ...(0, job_placement_1.getContainerSecurity)(env),
143
146
  },
144
147
  ],
145
- volumes: [...persistence.volumes, ...persistence.workspace, ...secrets.volumes],
148
+ volumes: [
149
+ ...persistence.volumes,
150
+ ...persistence.workspace,
151
+ ...secrets.volumes,
152
+ ...(probeTools ? transfer_tools_1.TRANSFER_TOOLS_VOLUMES : []),
153
+ ],
146
154
  },
147
155
  },
148
156
  },
@@ -276,6 +284,46 @@ function getKubernetesCommand(command) {
276
284
  }
277
285
  return {};
278
286
  }
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
+ }
279
327
  // A probe runs with the container's variables, so it empties the proxy ones
280
328
  // through `env`, as a Docker healthcheck does with the exec's own variables.
281
329
  function withoutProxy(command, env) {
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHealthcheckRequestCommand = exports.HEALTHCHECK_REQUEST_SECONDS = void 0;
4
+ // how long the request or connection of one check may take
5
+ exports.HEALTHCHECK_REQUEST_SECONDS = 2;
6
+ /**
7
+ * An `http` or `tcp` healthcheck, run by a static busybox in the network namespace of the
8
+ * service: no tool of the image does it. It connects to the address the service's hostname
9
+ * names, the one its dependents reach (as the kubelet connects to the pod's), else to
10
+ * 127.0.0.1. Of a request, the status of the first response counts: a redirect is not
11
+ * followed, and a certificate is not checked. Without status codes, any 2xx or 3xx is
12
+ * healthy. Exits 0 when the service is healthy.
13
+ */
14
+ const SCRIPT = `b=$1; kind=$2; port=$3; shift 3
15
+ addr=127.0.0.1
16
+ for a in $($b hostname -i 2>/dev/null); do case $a in *:*) ;; *) addr=$a; break ;; esac; done
17
+ if [ "$kind" = tcp ]; then exec $b nc -z -w ${exports.HEALTHCHECK_REQUEST_SECONDS} "$addr" "$port"; fi
18
+ scheme=$1; path=$2; shift 2
19
+ code=$($b timeout ${exports.HEALTHCHECK_REQUEST_SECONDS} $b wget -S -O /dev/null -Y off --no-check-certificate "$scheme://$addr:$port$path" 2>&1 | $b awk '/^ HTTP\\//{print $2; exit}') 2>/dev/null
20
+ [ -n "$code" ] || exit 1
21
+ if [ $# -eq 0 ]; then case $code in 2??|3??) exit 0 ;; esac; exit 1; fi
22
+ for s in "$@"; do [ "$code" = "$s" ] && exit 0; done
23
+ exit 1`;
24
+ // The check as a command of the busybox at `busybox`.
25
+ function getHealthcheckRequestCommand(busybox, healthcheck) {
26
+ const args = 'http' in healthcheck
27
+ ? [
28
+ 'http',
29
+ `${healthcheck.http.port}`,
30
+ healthcheck.http.scheme,
31
+ healthcheck.http.path,
32
+ ...(healthcheck.http.status ?? []).map((status) => `${status}`),
33
+ ]
34
+ : ['tcp', `${healthcheck.tcp.port}`];
35
+ return [busybox, 'sh', '-c', SCRIPT, 'hammerkit-healthcheck', busybox, ...args];
36
+ }
37
+ exports.getHealthcheckRequestCommand = getHealthcheckRequestCommand;
38
+ //# sourceMappingURL=healthcheck-request.js.map
@@ -10,6 +10,7 @@ const claim_layout_1 = require("../kubernetes/claim-layout");
10
10
  const work_service_1 = require("../planner/work-service");
11
11
  const work_service_id_1 = require("../planner/work-service-id");
12
12
  const work_cache_id_1 = require("../planner/work-cache-id");
13
+ const work_healthcheck_1 = require("../planner/work-healthcheck");
13
14
  // Every path is made project-relative (portablePath) so the description, and the
14
15
  // task id hashed from it, is identical wherever the project is checked out.
15
16
  //
@@ -94,7 +95,7 @@ function getWorkServiceCacheIdentity(item, visiting = new Set()) {
94
95
  ? {
95
96
  cmd: service.cmd?.cmd ?? null,
96
97
  envs: (0, replace_env_variables_1.getEnvironmentVariables)(service.envs),
97
- healthcheck: service.healthcheck?.cmd.cmd ?? null,
98
+ healthcheck: service.healthcheck ? (0, work_healthcheck_1.getHealthcheckDefinition)(service.healthcheck) : null,
98
99
  secrets: service.secrets
99
100
  .filter((secret) => secret.cache)
100
101
  .map((secret) => `${(0, work_secret_1.getPortableSecretName)(service.projectRoot, secret)}=${secret.digest()}`)
@@ -7,6 +7,7 @@ const work_service_1 = require("./work-service");
7
7
  const work_network_1 = require("./work-network");
8
8
  const work_cache_id_1 = require("./work-cache-id");
9
9
  const portable_path_1 = require("./utils/portable-path");
10
+ const work_healthcheck_1 = require("./work-healthcheck");
10
11
  // Everything a running container of the service was created from, plus the
11
12
  // definitions of the services it needs: a dependent links to the container it
12
13
  // started with, so a recreated need means a recreated dependent too. Stored as
@@ -32,7 +33,7 @@ function getServiceDefinitionHash(item) {
32
33
  // the volume of a dep's output is named by where it is, which its path says already
33
34
  volumes: service.volumes.map((v) => `${v.inherited ? '' : v.name}:${portable(v.containerPath)}:${v.readOnly ? 'ro' : 'rw'}`),
34
35
  src: service.src.map((s) => portable(s.absolutePath)),
35
- healthcheck: service.healthcheck?.cmd.cmd ?? null,
36
+ healthcheck: service.healthcheck ? (0, work_healthcheck_1.getHealthcheckDefinition)(service.healthcheck) : null,
36
37
  // where secrets go, never their values: a rotated value needs a `down`
37
38
  secrets: service.secrets.map((s) => s.source.type === 'provider'
38
39
  ? `provider:${(0, work_secret_1.getSecretName)(s)}:${(0, work_secret_1.describeSecretSource)(s)}`
@@ -98,10 +98,7 @@ function parseService(workTree, service, environment, context) {
98
98
  type: 'container-service',
99
99
  continuous: service.schema.continuous ?? false,
100
100
  healthcheck: service.schema.healthcheck
101
- ? {
102
- cmd: (0, parse_work_command_1.parseWorkCommand)(service.cwd, service.schema.healthcheck.cmd, envs),
103
- timeout: getHealthcheckTimeout(service.schema.healthcheck.timeout, environment),
104
- }
101
+ ? parseWorkHealthcheck(service.cwd, service.schema.healthcheck, envs, environment)
105
102
  : null,
106
103
  envs: (0, replace_env_variables_1.buildEnvironmentVariables)(service.envs, environment, context),
107
104
  image: (0, template_value_1.templateValue)(service.schema.image, envs),
@@ -201,6 +198,17 @@ function getInitTimeout(timeout, environment) {
201
198
  return (0, units_1.parseDuration)(exports.DEFAULT_INIT_TIMEOUT);
202
199
  }
203
200
  exports.getInitTimeout = getInitTimeout;
201
+ function parseWorkHealthcheck(cwd, healthcheck, envs, environment) {
202
+ const timeout = getHealthcheckTimeout(healthcheck.timeout, environment);
203
+ if ('cmd' in healthcheck) {
204
+ return { cmd: (0, parse_work_command_1.parseWorkCommand)(cwd, healthcheck.cmd, envs), timeout };
205
+ }
206
+ if ('http' in healthcheck) {
207
+ const { port, path, scheme, status } = healthcheck.http;
208
+ return { http: { port, path: path ?? '/', scheme: scheme ?? 'http', status: status ?? null }, timeout };
209
+ }
210
+ return { tcp: { port: healthcheck.tcp.port }, timeout };
211
+ }
204
212
  exports.DEFAULT_HEALTHCHECK_TIMEOUT = '20s';
205
213
  // A service's own `healthcheck.timeout`, else HAMMERKIT_HEALTHCHECK_TIMEOUT,
206
214
  // else 20s: a check that never passes fails the run instead of hanging it.
@@ -1,9 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHealthcheckTimeoutMessage = void 0;
3
+ exports.getHealthcheckTimeoutMessage = exports.describeHealthcheck = exports.getHealthcheckDefinition = void 0;
4
4
  const units_1 = require("../utils/units");
5
+ // What the check is, in the definition of the service and its cache identity: a command as
6
+ // it is written, so those of a service with one stay what they were. Not its timeout.
7
+ function getHealthcheckDefinition(healthcheck) {
8
+ if ('cmd' in healthcheck) {
9
+ return healthcheck.cmd.cmd;
10
+ }
11
+ return 'http' in healthcheck ? { http: healthcheck.http } : { tcp: healthcheck.tcp };
12
+ }
13
+ exports.getHealthcheckDefinition = getHealthcheckDefinition;
14
+ // what the check is, for a message
15
+ function describeHealthcheck(healthcheck) {
16
+ if ('cmd' in healthcheck) {
17
+ return healthcheck.cmd.cmd;
18
+ }
19
+ if ('http' in healthcheck) {
20
+ const { scheme, port, path, status } = healthcheck.http;
21
+ return `GET ${scheme}://:${port}${path}${status ? ` (${status.join(', ')})` : ''}`;
22
+ }
23
+ return `tcp :${healthcheck.tcp.port}`;
24
+ }
25
+ exports.describeHealthcheck = describeHealthcheck;
5
26
  function getHealthcheckTimeoutMessage(serviceName, healthcheck) {
6
- return (`service ${serviceName} did not pass its healthcheck "${healthcheck.cmd.cmd}" within ` +
27
+ return (`service ${serviceName} did not pass its healthcheck "${describeHealthcheck(healthcheck)}" within ` +
7
28
  `${(0, units_1.formatDuration)(healthcheck.timeout)} of starting (see its log above; raise healthcheck.timeout ` +
8
29
  `or HAMMERKIT_HEALTHCHECK_TIMEOUT if it is just slow)`);
9
30
  }
@@ -24,9 +24,9 @@ function getServiceCommand(service, options = {}) {
24
24
  return { entrypoint: null, cmd: [service.cmd.parsed.command, ...args] };
25
25
  }
26
26
  exports.getServiceCommand = getServiceCommand;
27
- // The healthcheck as an exec command, through the service's `shell` if it has one.
27
+ // The `cmd` of the healthcheck as an exec command, through the service's `shell` if it has one.
28
28
  function getHealthcheckCommand(service) {
29
- if (!service.healthcheck) {
29
+ if (!service.healthcheck || !('cmd' in service.healthcheck)) {
30
30
  return null;
31
31
  }
32
32
  const cmd = service.healthcheck.cmd;
@@ -1,12 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildFileServiceContainerHealthcheck = void 0;
3
+ exports.buildFileServiceContainerHealthcheck = exports.buildFileServiceTcpHealthcheck = exports.buildFileServiceHttpHealthcheck = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const duration_schema_1 = require("./duration-schema");
6
- exports.buildFileServiceContainerHealthcheck = (0, zod_1.object)({
7
- cmd: (0, zod_1.string)(),
8
- // How long the service may take to pass `cmd` once its container runs
9
- // (default 20s, HAMMERKIT_HEALTHCHECK_TIMEOUT changes the default).
10
- timeout: duration_schema_1.durationSchema.optional(),
11
- });
6
+ // How long the service may take to pass its check once its container runs
7
+ // (default 20s, HAMMERKIT_HEALTHCHECK_TIMEOUT changes the default).
8
+ const timeout = duration_schema_1.durationSchema.optional();
9
+ const port = (0, zod_1.number)().int().min(1).max(65535);
10
+ // A request to a port of the service, from its own network: no tool of the image runs it.
11
+ exports.buildFileServiceHttpHealthcheck = (0, zod_1.object)({
12
+ port,
13
+ path: (0, zod_1.string)().startsWith('/', 'path must start with /').optional(),
14
+ scheme: (0, zod_1.enum)(['http', 'https']).optional(),
15
+ // the status codes that count as healthy, any 2xx or 3xx without
16
+ status: (0, zod_1.array)((0, zod_1.number)().int().min(100).max(599)).min(1).optional(),
17
+ })
18
+ .strict()
19
+ .describe('GET <scheme>://<service>:<port><path>, healthy on one of status (default any 2xx or 3xx)');
20
+ // a connection to a port of the service
21
+ exports.buildFileServiceTcpHealthcheck = (0, zod_1.object)({ port })
22
+ .strict()
23
+ .describe('healthy once <port> takes a connection');
24
+ // Exactly one of `cmd`, `http` or `tcp`.
25
+ exports.buildFileServiceContainerHealthcheck = (0, zod_1.union)([
26
+ (0, zod_1.object)({ cmd: (0, zod_1.string)(), timeout }).strict(),
27
+ (0, zod_1.object)({ http: exports.buildFileServiceHttpHealthcheck, timeout }).strict(),
28
+ (0, zod_1.object)({ tcp: exports.buildFileServiceTcpHealthcheck, timeout }).strict(),
29
+ ]).describe('exactly one of cmd, http or tcp, and how long it may take to pass');
12
30
  //# sourceMappingURL=build-file-service-container-healthcheck.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.1.0-next.1",
4
+ "version": "2.1.0-next.2",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",