hammerkit 2.1.0-next.1 → 2.1.0-next.3

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
@@ -56,6 +56,31 @@
56
56
  "description": {
57
57
  "type": "string"
58
58
  },
59
+ "extend": {
60
+ "type": "string"
61
+ },
62
+ "abstract": {
63
+ "type": "boolean"
64
+ },
65
+ "reset": {
66
+ "type": "array",
67
+ "items": {
68
+ "type": "string",
69
+ "enum": [
70
+ "deps",
71
+ "needs",
72
+ "src",
73
+ "generates",
74
+ "cmds",
75
+ "mounts",
76
+ "envs",
77
+ "labels",
78
+ "build",
79
+ "secrets",
80
+ "capAdd"
81
+ ]
82
+ }
83
+ },
59
84
  "envs": {
60
85
  "$ref": "#/definitions/hammerkit/properties/envs",
61
86
  "description": "Environment values for the current build task\nhttps://hammerkit.dev/docs/build-file/environment-variables"
@@ -376,23 +401,13 @@
376
401
  "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/description"
377
402
  },
378
403
  "extend": {
379
- "type": "string"
404
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/extend"
405
+ },
406
+ "abstract": {
407
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/abstract"
380
408
  },
381
409
  "reset": {
382
- "type": "array",
383
- "items": {
384
- "type": "string",
385
- "enum": [
386
- "deps",
387
- "needs",
388
- "src",
389
- "generates",
390
- "cmds",
391
- "mounts",
392
- "envs",
393
- "labels"
394
- ]
395
- }
410
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/reset"
396
411
  },
397
412
  "envs": {
398
413
  "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/envs"
@@ -544,10 +559,13 @@
544
559
  "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/description"
545
560
  },
546
561
  "extend": {
547
- "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/1/properties/extend"
562
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/extend"
563
+ },
564
+ "abstract": {
565
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/abstract"
548
566
  },
549
567
  "reset": {
550
- "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/1/properties/reset"
568
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/reset"
551
569
  },
552
570
  "envs": {
553
571
  "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/envs"
@@ -634,8 +652,11 @@
634
652
  "extend": {
635
653
  "type": "string"
636
654
  },
655
+ "abstract": {
656
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/abstract"
657
+ },
637
658
  "reset": {
638
- "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/1/properties/reset"
659
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/reset"
639
660
  },
640
661
  "envs": {
641
662
  "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/envs"
@@ -776,19 +797,96 @@
776
797
  "type": "boolean"
777
798
  },
778
799
  "healthcheck": {
779
- "type": "object",
780
- "properties": {
781
- "cmd": {
782
- "type": "string"
800
+ "anyOf": [
801
+ {
802
+ "type": "object",
803
+ "properties": {
804
+ "cmd": {
805
+ "type": "string"
806
+ },
807
+ "timeout": {
808
+ "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/timeout"
809
+ }
810
+ },
811
+ "required": [
812
+ "cmd"
813
+ ],
814
+ "additionalProperties": false
783
815
  },
784
- "timeout": {
785
- "$ref": "#/definitions/hammerkit/properties/tasks/additionalProperties/anyOf/0/properties/timeout"
816
+ {
817
+ "type": "object",
818
+ "properties": {
819
+ "http": {
820
+ "type": "object",
821
+ "properties": {
822
+ "port": {
823
+ "type": "integer",
824
+ "minimum": 1,
825
+ "maximum": 65535
826
+ },
827
+ "path": {
828
+ "type": "string",
829
+ "pattern": "^\\/"
830
+ },
831
+ "scheme": {
832
+ "type": "string",
833
+ "enum": [
834
+ "http",
835
+ "https"
836
+ ]
837
+ },
838
+ "status": {
839
+ "type": "array",
840
+ "items": {
841
+ "type": "integer",
842
+ "minimum": 100,
843
+ "maximum": 599
844
+ },
845
+ "minItems": 1
846
+ }
847
+ },
848
+ "required": [
849
+ "port"
850
+ ],
851
+ "additionalProperties": false,
852
+ "description": "GET <scheme>://<service>:<port><path>, healthy on one of status (default any 2xx or 3xx)"
853
+ },
854
+ "timeout": {
855
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/0/properties/timeout"
856
+ }
857
+ },
858
+ "required": [
859
+ "http"
860
+ ],
861
+ "additionalProperties": false
862
+ },
863
+ {
864
+ "type": "object",
865
+ "properties": {
866
+ "tcp": {
867
+ "type": "object",
868
+ "properties": {
869
+ "port": {
870
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/1/properties/http/properties/port"
871
+ }
872
+ },
873
+ "required": [
874
+ "port"
875
+ ],
876
+ "additionalProperties": false,
877
+ "description": "healthy once <port> takes a connection"
878
+ },
879
+ "timeout": {
880
+ "$ref": "#/definitions/hammerkit/properties/services/additionalProperties/anyOf/0/properties/healthcheck/anyOf/0/properties/timeout"
881
+ }
882
+ },
883
+ "required": [
884
+ "tcp"
885
+ ],
886
+ "additionalProperties": false
786
887
  }
787
- },
788
- "required": [
789
- "cmd"
790
888
  ],
791
- "additionalProperties": false
889
+ "description": "exactly one of cmd, http or tcp, and how long it may take to pass"
792
890
  },
793
891
  "init": {
794
892
  "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()}`)
@@ -25,6 +25,11 @@ const METADATA_FILE = '/tmp/hammerkit-build.json';
25
25
  const IMAGE = /^[a-z0-9][a-z0-9._/:@-]*$/i;
26
26
  // The build of a task, with the values of its envs in place
27
27
  function parseWorkImageBuild(cwd, build, envs, taskName) {
28
+ // checked here, not in the schema: a base of `extend` may set push for tasks that set their tags
29
+ const needsTags = build.push ? 'push' : build.digest !== undefined ? 'digest' : null;
30
+ if (needsTags && build.tags === undefined) {
31
+ throw new Error(`task ${taskName}: build ${needsTags} needs tags, the names of the image`);
32
+ }
28
33
  const context = (0, path_1.join)(cwd, (0, template_value_1.templateValue)(build.context ?? '.', envs));
29
34
  const dockerfile = build.dockerfile ? (0, path_1.join)(cwd, (0, template_value_1.templateValue)(build.dockerfile, envs)) : (0, path_1.join)(context, 'Dockerfile');
30
35
  const tags = (build.tags === undefined ? [] : Array.isArray(build.tags) ? build.tags : [build.tags]).map((tag) => checkImage((0, template_value_1.templateValue)(tag, envs), 'tag', taskName));
@@ -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.
@@ -13,6 +13,7 @@ async function* validate(workTree, context) {
13
13
  yield { type: 'warn', message: `missing description`, item: service };
14
14
  }
15
15
  if (service.type === 'container-service') {
16
+ yield* warnUnsetEnvs(service.envs, service);
16
17
  if (!service.healthcheck) {
17
18
  yield { type: 'warn', message: 'missing healthcheck', item: service };
18
19
  }
@@ -52,6 +53,7 @@ async function* validate(workTree, context) {
52
53
  if (!task.description) {
53
54
  yield { type: 'warn', message: `missing description`, item: task };
54
55
  }
56
+ yield* warnUnsetEnvs(task.envs, task);
55
57
  if (task.type === 'local-task' && task.resources) {
56
58
  yield { type: 'warn', message: 'resources are not enforced for a local task', item: task };
57
59
  }
@@ -103,6 +105,20 @@ async function* validate(workTree, context) {
103
105
  }
104
106
  }
105
107
  exports.validate = validate;
108
+ // An env that reads a variable set nowhere, such as an input of an included file run on its
109
+ // own: the task fails when it starts, and until then `$NAME` stays in what it templates
110
+ function* warnUnsetEnvs(envs, item) {
111
+ for (const replacement of envs.replacements) {
112
+ if (!replacement.available) {
113
+ yield {
114
+ type: 'warn',
115
+ message: `env ${replacement.key} reads $${replacement.name}, which neither the environment nor a .env file sets: ` +
116
+ `it can't start, and $${replacement.key} stays as it is written in its build file`,
117
+ item,
118
+ };
119
+ }
120
+ }
121
+ }
106
122
  function hasMixedCycle(item, currentPath) {
107
123
  if (currentPath.indexOf(item) >= 0) {
108
124
  return [...currentPath, item];
@@ -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;
@@ -14,12 +14,27 @@ const resources_schema_1 = require("./resources-schema");
14
14
  const runner_schema_1 = require("./runner-schema");
15
15
  const network_schema_1 = require("./network-schema");
16
16
  // what `extend` adds to (the rest, e.g. `image` or `shell`, the task just overrides)
17
- exports.RESET_PROPERTIES = ['deps', 'needs', 'src', 'generates', 'cmds', 'mounts', 'envs', 'labels'];
17
+ exports.RESET_PROPERTIES = [
18
+ 'deps',
19
+ 'needs',
20
+ 'src',
21
+ 'generates',
22
+ 'cmds',
23
+ 'mounts',
24
+ 'envs',
25
+ 'labels',
26
+ 'build',
27
+ 'secrets',
28
+ 'capAdd',
29
+ ];
18
30
  exports.buildFileBaseTaskSchema = (0, zod_1.object)({
19
31
  deps: (0, zod_1.array)((0, zod_1.string)()).optional(),
20
32
  needs: (0, zod_1.array)(build_file_need_schema_1.buildFileNeedSchema).optional(),
21
33
  description: (0, zod_1.string)().optional(),
22
34
  extend: (0, zod_1.string)().optional(),
35
+ // true: a base other tasks extend, which doesn't run itself: not listed, no dependency, not
36
+ // published by a server. Unlike a task, it passes on its secrets, resources and claim too.
37
+ abstract: (0, zod_1.boolean)().optional(),
23
38
  // properties of the `extend` base this task does not inherit
24
39
  reset: (0, zod_1.array)((0, zod_1.enum)(exports.RESET_PROPERTIES)).optional(),
25
40
  envs: envs_schema_1.envsSchema.optional(),
@@ -57,17 +57,14 @@ exports.buildFileImageBuildSchema = (0, zod_1.object)({
57
57
  .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
58
  })
59
59
  .strict()
60
- .refine((build) => !build.push || build.tags !== undefined, {
61
- message: 'push needs tags, the names of the image to push',
62
- })
63
- .refine((build) => build.digest === undefined || build.tags !== undefined, {
64
- message: 'digest needs tags, the name the digest is written with',
65
- })
60
+ // that push and digest need tags is checked once `extend` has merged in the base's
61
+ // (parseWorkImageBuild): a base may set push for tasks that set their tags
66
62
  .describe('builds a Dockerfile with BuildKit, as docker build does');
67
63
  // A task that builds an image: hammerkit runs BuildKit for it, so it names no image, commands or
68
- // shell of its own, and doesn't extend another task or take arguments.
64
+ // shell of its own and takes no arguments. It may extend another task, which merges `build` key
65
+ // by key (applySchemaExtension).
69
66
  exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
- .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
67
+ .omit({ cmds: true, shell: true, args: true })
71
68
  .extend({
72
69
  build: exports.buildFileImageBuildSchema,
73
70
  volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
@@ -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
@@ -29,8 +29,15 @@ class UnpublishedError extends Error {
29
29
  this.reason = reason;
30
30
  }
31
31
  }
32
- // The task or service `user` names another one by, which a server left out: the error says
33
- // which published one still needs it, as an error elsewhere is left as it is
32
+ // What a task or service names that is a base (`abstract: true`), which only `extend` names
33
+ class AbstractError extends Error {
34
+ constructor(name) {
35
+ super(`${name} is abstract`);
36
+ this.name = name;
37
+ }
38
+ }
39
+ // The task or service `user` names another one by, which a server left out or which is a base:
40
+ // the error says which one names it, as an error elsewhere is left as it is
34
41
  function findPublished(user, verb, find) {
35
42
  try {
36
43
  return find();
@@ -39,6 +46,9 @@ function findPublished(user, verb, find) {
39
46
  if (e instanceof UnpublishedError) {
40
47
  throw new Error(`${user} ${verb} ${e.name}, which is not published (${e.reason})`);
41
48
  }
49
+ if (e instanceof AbstractError) {
50
+ throw new Error(`${user} ${verb} ${e.name}, which is abstract: a base that only extend names, it doesn't run`);
51
+ }
42
52
  throw e;
43
53
  }
44
54
  }
@@ -67,6 +77,7 @@ async function parseReferences(ctx, mainScope, environment) {
67
77
  const reference = {
68
78
  files: {},
69
79
  tasks: {},
80
+ bases: {},
70
81
  services: {},
71
82
  envFiles: {},
72
83
  environments: {},
@@ -109,7 +120,8 @@ async function parseReferences(ctx, mainScope, environment) {
109
120
  if (isLeftOut(file, relativeName, task)) {
110
121
  continue;
111
122
  }
112
- reference.tasks[relativeName] = {
123
+ const tasks = task.abstract ? reference.bases : reference.tasks;
124
+ tasks[relativeName] = {
113
125
  type: 'task',
114
126
  schema: task,
115
127
  cwd: file.cwd,
@@ -159,7 +171,8 @@ async function parseReferences(ctx, mainScope, environment) {
159
171
  }
160
172
  }
161
173
  }
162
- for (const task of Object.values(reference.tasks)) {
174
+ // a base is checked as a task is, though only the tasks extending it run
175
+ for (const task of [...Object.values(reference.tasks), ...Object.values(reference.bases)]) {
163
176
  applySchemaExtension(reference, task);
164
177
  resolveDeps(reference, task, task.scope, task.schema);
165
178
  resolveNeeds(reference, task, task.scope, task.schema);
@@ -188,57 +201,67 @@ function applySchemaExtension(reference, task) {
188
201
  task.extension = 'applying';
189
202
  task.depBases = [];
190
203
  task.needBases = [];
191
- // a task that builds an image extends nothing (its schema has no `extend`)
192
- if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
193
- task.extension = 'applied';
194
- return;
195
- }
196
- const reset = new Set(task.schema.reset ?? []);
197
- if (!task.schema.extend) {
204
+ // every property of every kind of task, as a task may take its kind from its base
205
+ const schema = task.schema;
206
+ const reset = new Set(schema.reset ?? []);
207
+ if (!schema.extend) {
198
208
  if (reset.size > 0) {
199
209
  throw new Error(`task ${task.relativeName} sets reset without extend`);
200
210
  }
201
211
  task.extension = 'applied';
202
212
  return;
203
213
  }
204
- const name = task.schema.extend;
205
- const extend = findPublished(task.relativeName, 'extends', () => findTask(reference, task.scope, name, null)).task;
206
- // hammerkit makes the commands of a task that builds an image (see image-build.ts)
207
- if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(extend.schema)) {
208
- throw new Error(`task ${task.relativeName} extends ${name}, which builds an image: such a task can't be extended`);
209
- }
214
+ const name = schema.extend;
215
+ const extend = findPublished(task.relativeName, 'extends', () => findBase(reference, task, name));
210
216
  applySchemaExtension(reference, extend);
211
- task.schema.shell = task.schema.shell ?? extend.schema.shell;
212
- task.schema.cache = task.schema.cache ?? extend.schema.cache;
213
- task.schema.timeout = task.schema.timeout ?? extend.schema.timeout;
214
- task.schema.runner = task.schema.runner ?? extend.schema.runner;
215
- task.schema.network = task.schema.network ?? extend.schema.network;
216
- task.schema.args = task.schema.args ?? extend.schema.args;
217
+ const base = extend.schema;
218
+ // only a value the base has: `image` and `build` in a schema decide the kind of task
219
+ for (const key of ['shell', 'cache', 'timeout', 'runner', 'network', 'args', 'image']) {
220
+ if (schema[key] === undefined && base[key] !== undefined) {
221
+ Object.assign(schema, { [key]: base[key] });
222
+ }
223
+ }
217
224
  if (!reset.has('cmds'))
218
- task.schema.cmds = extendArray(task.schema.cmds, extend.schema.cmds);
225
+ schema.cmds = extendArray(schema.cmds, base.cmds);
219
226
  if (!reset.has('src'))
220
- task.schema.src = extendArray(task.schema.src, extend.schema.src);
227
+ schema.src = extendArray(schema.src, base.src);
221
228
  if (!reset.has('generates'))
222
- task.schema.generates = extendArray(task.schema.generates, extend.schema.generates);
229
+ schema.generates = extendArray(schema.generates, base.generates);
230
+ if (!reset.has('mounts'))
231
+ schema.mounts = extendArray(schema.mounts, base.mounts);
232
+ // key by key, the task's own value winning, as envs and labels: a base sets push and login
233
+ // for the tasks that set their own tags
234
+ if (!reset.has('build') && base.build)
235
+ schema.build = { ...base.build, ...schema.build };
236
+ // what is a task's own, for its own run, a base that only is extended declares for the tasks
237
+ // extending it: its credentials, limits and claim
238
+ if (base.abstract) {
239
+ for (const key of ['account', 'resources', 'volumeSize', 'platform']) {
240
+ if (schema[key] === undefined && base[key] !== undefined) {
241
+ Object.assign(schema, { [key]: base[key] });
242
+ }
243
+ }
244
+ if (!reset.has('secrets'))
245
+ schema.secrets = extendArray(schema.secrets, base.secrets);
246
+ if (!reset.has('capAdd'))
247
+ schema.capAdd = extendArray(schema.capAdd, base.capAdd);
248
+ }
223
249
  if (!reset.has('labels'))
224
- task.schema.labels = extendObject(task.schema.labels, extend.schema.labels);
250
+ schema.labels = extendObject(schema.labels, base.labels);
251
+ // the labels a task is filtered by: those of its build file with its own, now with its base's
252
+ task.labels = (0, label_values_1.mergeLabels)(task.scope.schema.labels, schema.labels);
225
253
  // the base's resolved envs: its own plus the top-level envs of its build file
226
254
  // (and the inputs an include passed), which carry the defaults it relies on
227
255
  if (!reset.has('envs'))
228
256
  task.envs = (0, merge_environment_variables_1.mergeEnvironmentVariables)(task.envs, extend.envs);
229
- if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(extend.schema)) {
230
- const taskSchema = task.schema;
231
- taskSchema.image = taskSchema.image ?? extend.schema.image;
232
- if (!reset.has('mounts'))
233
- taskSchema.mounts = extendArray(taskSchema.mounts, extend.schema.mounts);
234
- }
235
257
  rejectContainerPropertiesWithoutImage(task);
258
+ rejectCommandsOfImageBuild(task);
236
259
  // deps and needs resolve in the file that declares them, so every base up the
237
260
  // chain contributes its own, not only the nearest; what a task resets is not
238
261
  // passed on to the tasks extending it either
239
- const base = { scope: extend.scope, schema: extend.schema };
240
- task.needBases = reset.has('needs') ? [] : [...(extend.needBases ?? []), base];
241
- task.depBases = reset.has('deps') ? [] : [...(extend.depBases ?? []), base];
262
+ const declared = { scope: extend.scope, schema: extend.schema };
263
+ task.needBases = reset.has('needs') ? [] : [...(extend.needBases ?? []), declared];
264
+ task.depBases = reset.has('deps') ? [] : [...(extend.depBases ?? []), declared];
242
265
  for (const needBase of task.needBases) {
243
266
  resolveNeeds(reference, task, needBase.scope, needBase.schema);
244
267
  }
@@ -247,6 +270,20 @@ function applySchemaExtension(reference, task) {
247
270
  }
248
271
  task.extension = 'applied';
249
272
  }
273
+ // The task `extend` names, a base or a task, with what a build file is missing when there is none
274
+ function findBase(reference, task, name) {
275
+ try {
276
+ return findTask(reference, task.scope, name, null, true).task;
277
+ }
278
+ catch (e) {
279
+ if (!(e instanceof NotFoundError)) {
280
+ throw e;
281
+ }
282
+ const prefix = (0, split_name_1.splitName)(e.name).prefix;
283
+ const missing = prefix && !e.scope.references[prefix] ? `include or reference ${prefix}` : `task ${(0, split_name_1.splitName)(e.name).name}`;
284
+ throw new Error(`task ${task.relativeName} extends ${name}, but ${e.scope.fileName} has no ${missing}`);
285
+ }
286
+ }
250
287
  function rejectContainerPropertiesWithoutImage(task) {
251
288
  if ((0, build_file_task_schema_1.isBuildFileContainerTaskSchema)(task.schema) || (0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
252
289
  return;
@@ -257,6 +294,22 @@ function rejectContainerPropertiesWithoutImage(task) {
257
294
  throw new Error(`task ${task.relativeName} sets ${property}, but neither it nor its base has an image`);
258
295
  }
259
296
  }
297
+ // hammerkit makes the image and the command of a task that builds one (see image-build.ts)
298
+ const IMAGE_BUILD_EXCLUDED = ['image', 'cmds', 'shell', 'args', 'mounts', 'capAdd', 'platform'];
299
+ function rejectCommandsOfImageBuild(task) {
300
+ const schema = task.schema;
301
+ if (!schema.build) {
302
+ return;
303
+ }
304
+ const property = IMAGE_BUILD_EXCLUDED.find((key) => {
305
+ const value = schema[key];
306
+ return value !== undefined && !(Array.isArray(value) && value.length === 0);
307
+ });
308
+ if (property) {
309
+ throw new Error(`task ${task.relativeName} has build and ${property}, from it or the task it extends: ` +
310
+ `a task that builds an image takes no ${property}`);
311
+ }
312
+ }
260
313
  function extendArray(base, extend) {
261
314
  if (!extend) {
262
315
  return base;
@@ -325,21 +378,30 @@ function resolveNeeds(reference, taskOrService, scope, schema) {
325
378
  throw new Error(`${taskOrService.relativeName} needs two services as ${twice}, give one another name with name:`);
326
379
  }
327
380
  }
328
- function findTask(ctx, scope, name, type) {
381
+ // A name no task of a build file has
382
+ class NotFoundError extends Error {
383
+ constructor(scope, name) {
384
+ super('unable to find ' + name);
385
+ this.scope = scope;
386
+ this.name = name;
387
+ }
388
+ }
389
+ // The task a name stands for in a build file; a base (`abstract`) only for `extend`
390
+ function findTask(ctx, scope, name, type, base = false) {
329
391
  refuseNotFetched(scope, name);
330
392
  const ref = (0, split_name_1.splitName)(name);
331
393
  if (ref.prefix) {
332
394
  if (scope.references[ref.prefix]) {
333
- return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type);
395
+ return findTask(ctx, scope.references[ref.prefix].scope, ref.name, scope.references[ref.prefix].type, base);
334
396
  }
335
397
  else if (scope.schema.tasks && scope.schema.tasks[name]) {
336
- return resolveTask(ctx, scope, name, type ?? 'build-file');
398
+ return resolveTask(ctx, scope, name, type ?? 'build-file', base);
337
399
  }
338
400
  }
339
401
  else if (scope.schema.tasks && scope.schema.tasks[ref.name]) {
340
- return resolveTask(ctx, scope, ref.name, type ?? 'build-file');
402
+ return resolveTask(ctx, scope, ref.name, type ?? 'build-file', base);
341
403
  }
342
- throw new Error('unable to find ' + name); // TODO improve
404
+ throw new NotFoundError(scope, name);
343
405
  }
344
406
  exports.findTask = findTask;
345
407
  // A name in a git source a server did not fetch, since it is left out
@@ -348,9 +410,12 @@ function refuseNotFetched(scope, name) {
348
410
  throw new UnpublishedError(combinePath(scope.namePrefix, name), 'its build file is included with publish: false');
349
411
  }
350
412
  }
351
- function resolveTask(ctx, scope, name, type) {
413
+ function resolveTask(ctx, scope, name, type, base) {
352
414
  const fullName = combinePath(scope.namePrefix, name);
353
- const buildFileTask = ctx.tasks[fullName];
415
+ if (!base && ctx.bases[fullName]) {
416
+ throw new AbstractError(fullName);
417
+ }
418
+ const buildFileTask = ctx.tasks[fullName] ?? (base ? ctx.bases[fullName] : undefined);
354
419
  if (!buildFileTask && ctx.unpublished?.[fullName]) {
355
420
  throw new UnpublishedError(fullName, ctx.unpublished[fullName]);
356
421
  }
@@ -48,6 +48,7 @@ function getWorkContext(context, scope, environment) {
48
48
  // its init task's need on it, which narrowing follows
49
49
  const tasks = Object.values(context.tasks).map((task) => (0, append_work_task_1.appendWorkTask)(workTree, task.cwd, task, environment, context));
50
50
  const services = Object.values(context.services).map((service) => (0, append_work_service_1.appendWorkService)(workTree, service, environment, context));
51
+ refuseBases(context, (0, work_scope_1.isContextTaskFilter)(scope) ? [scope.taskName] : [...(scope.names ?? []), ...(scope.taskNames ?? [])]);
51
52
  const apply = { servicesAlone: !(0, work_scope_1.isContextTaskFilter)(scope) && !!scope.names && !!scope.stop };
52
53
  const selectedTasks = [];
53
54
  const selectedServices = [];
@@ -86,6 +87,13 @@ function getWorkContext(context, scope, environment) {
86
87
  return filteredWorkTree;
87
88
  }
88
89
  exports.getWorkContext = getWorkContext;
90
+ // A base (`abstract: true`) is not run by its name, as it is not listed
91
+ function refuseBases(context, names) {
92
+ const base = names.find((name) => name in context.bases);
93
+ if (base) {
94
+ throw new Error(`${base} is abstract, a base for extend that doesn't run: run a task that extends it`);
95
+ }
96
+ }
89
97
  // The whole build file is planned first, so a shared service lists every task
90
98
  // and service that needs it. Those outside this run never start or end, and a
91
99
  // service waiting for them to finish would keep the run open forever.
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.3",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",