hammerkit 2.0.0-next.9 → 2.0.0

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 (89) hide show
  1. package/build.schema.json +228 -63
  2. package/dist/cache/backends/registry/registry-client.js +8 -2
  3. package/dist/cache/explain.js +5 -0
  4. package/dist/cache/last-resolved.js +11 -0
  5. package/dist/cli.js +4 -1
  6. package/dist/dashboard/assets/{graph-canvas-HmkW_-XJ.js → graph-canvas-DtJSpova.js} +1 -1
  7. package/dist/dashboard/assets/index-BndChMep.css +2 -0
  8. package/dist/dashboard/assets/{index-vE22S5E_.js → index-DRSwIRXd.js} +9 -9
  9. package/dist/dashboard/index.html +2 -2
  10. package/dist/docker/item-network.js +51 -18
  11. package/dist/docker/package.js +85 -76
  12. package/dist/docker/server-tools.js +96 -0
  13. package/dist/docker/stream.js +15 -7
  14. package/dist/environment/replace-env-variables.js +1 -1
  15. package/dist/environment/run-source-envs.js +18 -0
  16. package/dist/executer/check-container-binds.js +158 -0
  17. package/dist/executer/docker-service.js +42 -3
  18. package/dist/executer/docker-task.js +33 -6
  19. package/dist/executer/execute-command.js +9 -15
  20. package/dist/executer/execute-work-task.js +11 -1
  21. package/dist/executer/execute-work-tree.js +2 -1
  22. package/dist/executer/execution-steps.js +6 -2
  23. package/dist/executer/get-container-binds.js +2 -0
  24. package/dist/executer/print-container-options.js +10 -10
  25. package/dist/executer/process-manager.js +84 -5
  26. package/dist/executer/scheduler/state-key.js +19 -1
  27. package/dist/executer/task-priority.js +131 -0
  28. package/dist/file/stat-beneath.js +66 -0
  29. package/dist/file/within-root.js +13 -4
  30. package/dist/harness/connect.js +1 -6
  31. package/dist/harness/mcp-command.js +1 -1
  32. package/dist/harness/sandbox-client.js +39 -4
  33. package/dist/harness/service-tools.js +2 -2
  34. package/dist/kubernetes/await-running-state.js +42 -26
  35. package/dist/kubernetes/ensure-persistent-data.js +22 -7
  36. package/dist/kubernetes/network-gate.js +74 -11
  37. package/dist/kubernetes/network-policy.js +32 -10
  38. package/dist/kubernetes/remove-stale-items.js +15 -2
  39. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  40. package/dist/kubernetes/sandbox-runner.js +3 -4
  41. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  42. package/dist/kubernetes/transfer-tools.js +66 -0
  43. package/dist/kubernetes/volumes.js +52 -10
  44. package/dist/optimizer/check-key.js +7 -0
  45. package/dist/optimizer/check-keys.js +19 -5
  46. package/dist/optimizer/get-work-cache-stats.js +19 -7
  47. package/dist/optimizer/work-task-cache-description.js +42 -8
  48. package/dist/planner/image-build.js +172 -0
  49. package/dist/planner/utils/append-work-dependencies.js +14 -1
  50. package/dist/planner/utils/append-work-service.js +1 -1
  51. package/dist/planner/utils/append-work-task.js +51 -1
  52. package/dist/planner/utils/assert-item-paths.js +6 -7
  53. package/dist/planner/utils/dependency-outputs.js +18 -0
  54. package/dist/planner/work-runtime-docker.js +48 -50
  55. package/dist/planner/work-runtime-kubernetes.js +1 -0
  56. package/dist/planner/work-runtime-local.js +3 -7
  57. package/dist/planner/work-secret.js +135 -13
  58. package/dist/planner/work-tree.js +10 -0
  59. package/dist/remote/collect-bundle.js +9 -1
  60. package/dist/remote/host-config.js +49 -3
  61. package/dist/remote/location.js +5 -5
  62. package/dist/remote/remote-commands.js +12 -14
  63. package/dist/remote/remote-work-commands.js +20 -8
  64. package/dist/schema/build-file-image-build-schema.js +77 -0
  65. package/dist/schema/build-file-task-schema.js +9 -2
  66. package/dist/schema/reference-parser.js +10 -1
  67. package/dist/schema/work-scope-parser.js +16 -1
  68. package/dist/secrets/secret-catalog.js +8 -1
  69. package/dist/server/dashboard.js +8 -5
  70. package/dist/server/executor.js +58 -35
  71. package/dist/server/kubernetes-backend.js +29 -4
  72. package/dist/server/overview.js +20 -2
  73. package/dist/server/plan.js +31 -3
  74. package/dist/server/policy.js +14 -7
  75. package/dist/server/repo-access.js +4 -3
  76. package/dist/server/run-environment.js +5 -2
  77. package/dist/server/run-plan.js +18 -6
  78. package/dist/server/run-retry.js +57 -0
  79. package/dist/server/run-source-environment.js +39 -0
  80. package/dist/server/run-worker.js +38 -9
  81. package/dist/server/runs.js +59 -1
  82. package/dist/server/sandbox-files.js +232 -39
  83. package/dist/server/server-config.js +24 -4
  84. package/dist/server/server.js +107 -12
  85. package/dist/server/service-runs.js +42 -4
  86. package/dist/utils/line-splitter.js +52 -0
  87. package/dist/utils/tar.js +51 -1
  88. package/package.json +1 -1
  89. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getImageName = exports.getImageBuildCommand = exports.getBuildKitVolumeName = exports.getImageBuildGenerates = exports.getImageBuildSources = exports.getImageBuildSecrets = exports.checkImageBuildEnvs = exports.parseWorkImageBuild = exports.BUILDKIT_STATE = exports.BUILDKIT_IMAGE = void 0;
4
+ const path_1 = require("path");
5
+ const template_value_1 = require("./utils/template-value");
6
+ const plan_work_volume_1 = require("./utils/plan-work-volume");
7
+ const egress_proxy_1 = require("../network/egress-proxy");
8
+ // A task with `build` is a container task hammerkit writes itself: BuildKit, without a
9
+ // daemon, in this image. BuildKit mounts the layers it builds, which needs SYS_ADMIN: a
10
+ // server adds it only in a sandboxed runtime (backend.capabilities), and on a dev machine the
11
+ // container runs privileged, as `docker buildx` runs its own BuildKit. Pinned, so a build
12
+ // file builds with the same BuildKit everywhere; bumping it changes the id of every such task.
13
+ exports.BUILDKIT_IMAGE = 'moby/buildkit:v0.25.1';
14
+ // Where BuildKit keeps its layers. On a server it is a tmpfs the command mounts (gVisor
15
+ // can't mount the layers on the container's own file system); on a dev machine a volume of
16
+ // the task, so the layers are there for the next build.
17
+ exports.BUILDKIT_STATE = '/var/lib/buildkit';
18
+ // The variable the password of each login is in, as an env secret of the task. Not a file: a
19
+ // file secret is a subPath mount of the volume the secrets are written to, and a sandbox such
20
+ // as gVisor keeps that volume (in memory) inside the sandbox, where the host's mount doesn't see
21
+ // the file and makes a folder of it.
22
+ const LOGIN_ENV = 'HAMMERKIT_REGISTRY_PASSWORD_';
23
+ // BuildKit's report of the build, where the digest of the image is
24
+ const METADATA_FILE = '/tmp/hammerkit-build.json';
25
+ const IMAGE = /^[a-z0-9][a-z0-9._/:@-]*$/i;
26
+ // The build of a task, with the values of its envs in place
27
+ function parseWorkImageBuild(cwd, build, envs, taskName) {
28
+ const context = (0, path_1.join)(cwd, (0, template_value_1.templateValue)(build.context ?? '.', envs));
29
+ const dockerfile = build.dockerfile ? (0, path_1.join)(cwd, (0, template_value_1.templateValue)(build.dockerfile, envs)) : (0, path_1.join)(context, 'Dockerfile');
30
+ 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));
31
+ return {
32
+ context,
33
+ dockerfile,
34
+ tags,
35
+ push: build.push ?? false,
36
+ cache: build.cache ? checkImage((0, template_value_1.templateValue)(build.cache, envs), 'cache', taskName) : null,
37
+ digest: build.digest ? (0, path_1.join)(cwd, (0, template_value_1.templateValue)(build.digest, envs)) : null,
38
+ logins: (build.login ?? []).map((login, index) => ({
39
+ registry: (0, template_value_1.templateValue)(login.registry, envs),
40
+ user: checkUser((0, template_value_1.templateValue)(login.user, envs), taskName),
41
+ passwordEnv: `${LOGIN_ENV}${index}`,
42
+ })),
43
+ insecure: build.insecure ?? false,
44
+ platforms: build.platforms === undefined ? [] : Array.isArray(build.platforms) ? build.platforms : [build.platforms],
45
+ };
46
+ }
47
+ exports.parseWorkImageBuild = parseWorkImageBuild;
48
+ // a user of basic auth, as the schema checks the build file's own value
49
+ function checkUser(value, taskName) {
50
+ if (!/^[^:"\\\s]+$/.test(value)) {
51
+ throw new Error(`task ${taskName}: build login user ${JSON.stringify(value)} holds a colon, a quote, a backslash or a space`);
52
+ }
53
+ return value;
54
+ }
55
+ // a value put in with $NAME is checked as the build file's own value is
56
+ function checkImage(value, field, taskName) {
57
+ if (!IMAGE.test(value)) {
58
+ throw new Error(`task ${taskName}: build ${field} ${JSON.stringify(value)} is no image name`);
59
+ }
60
+ return value;
61
+ }
62
+ // Names the task can't set: BuildKit's own script runs the programs and flags these name, and
63
+ // the command runs from PATH, in a container that is privileged on a dev machine. Hammerkit
64
+ // writes the command of the build, not the build file.
65
+ const RESERVED_ENV = /^(PATH|LD_[A-Z0-9_]*|BUILDKIT[A-Z0-9_]*|BUILDCTL[A-Z0-9_]*|HAMMERKIT_REGISTRY_[A-Z0-9_]*)$/;
66
+ function checkImageBuildEnvs(names, taskName) {
67
+ const reserved = names.filter((name) => RESERVED_ENV.test(name));
68
+ if (reserved.length > 0) {
69
+ throw new Error(`task ${taskName}: ${reserved.join(', ')} can't be set on a task with build, which runs BuildKit as hammerkit writes it`);
70
+ }
71
+ }
72
+ exports.checkImageBuildEnvs = checkImageBuildEnvs;
73
+ // The passwords of the logins, as env secrets of the task
74
+ function getImageBuildSecrets(build) {
75
+ return (build.login ?? []).map((login, index) => ({
76
+ from: login.password.from,
77
+ ...(login.password.account ? { account: login.password.account } : {}),
78
+ env: `${LOGIN_ENV}${index}`,
79
+ }));
80
+ }
81
+ exports.getImageBuildSecrets = getImageBuildSecrets;
82
+ // What the build reads when the task doesn't list `src`: its context, as `docker build` sends
83
+ // it, and the Dockerfile where that is outside of it.
84
+ function getImageBuildSources(cwd, build) {
85
+ const context = toPosix((0, path_1.relative)(cwd, build.context)) || '.';
86
+ return isInside(build.context, build.dockerfile) ? [context] : [context, toPosix((0, path_1.relative)(cwd, build.dockerfile))];
87
+ }
88
+ exports.getImageBuildSources = getImageBuildSources;
89
+ // The file the digest is written to is an output of the task. It is a file whatever its name
90
+ // (see parseWorkGenerate): without an extension it would be taken for a folder.
91
+ function getImageBuildGenerates(cwd, build) {
92
+ return build.digest ? [toPosix((0, path_1.relative)(cwd, build.digest))] : [];
93
+ }
94
+ exports.getImageBuildGenerates = getImageBuildGenerates;
95
+ // The volume a build keeps its layers in on a dev machine, one per task, as two BuildKits
96
+ // can't share one
97
+ function getBuildKitVolumeName(task) {
98
+ return (0, plan_work_volume_1.getVolumeName)((0, path_1.join)(task.cwd, '.hammerkit', 'buildkit', task.name));
99
+ }
100
+ exports.getBuildKitVolumeName = getBuildKitVolumeName;
101
+ // The command of the task: BuildKit's own `buildctl`, without a daemon. Every value of the
102
+ // build file is a quoted word of it, never shell to run.
103
+ function getImageBuildCommand(cwd, build) {
104
+ const context = toPosix((0, path_1.relative)(cwd, build.context)) || '.';
105
+ const dockerfileDir = toPosix((0, path_1.relative)(cwd, (0, path_1.dirname)(build.dockerfile))) || '.';
106
+ const dockerfileName = path_1.posix.basename(toPosix(build.dockerfile));
107
+ const lines = [
108
+ 'set -e',
109
+ // on a dev machine the volume of the task is mounted there already
110
+ `grep -qs ${quote(` ${exports.BUILDKIT_STATE} `)} /proc/mounts || mount -t tmpfs tmpfs ${exports.BUILDKIT_STATE}`,
111
+ 'export DOCKER_CONFIG="$(mktemp -d)"',
112
+ ];
113
+ if (build.logins.length > 0) {
114
+ // the password of each, in a docker config.json, which BuildKit reads for the push and the cache
115
+ lines.push('auth() { printf \'"%s":{"auth":"%s"}\' "$1" "$(printf \'%s:%s\' "$2" "$(printf \'%s\' "$3" | tr -d \'\\r\\n\')" | base64 | tr -d \'\\n\')"; }', `{ printf '{"auths":{'; ${build.logins
116
+ .map((login) => `auth ${quote(getAuthKey(login.registry))} ${quote(login.user)} "$${login.passwordEnv}"`)
117
+ .join("; printf ','; ")}; printf '}}'; } > "$DOCKER_CONFIG/config.json"`);
118
+ }
119
+ lines.push('set --',
120
+ // A task with a `network` reaches the internet through hammerkit's egress proxy. BuildKit
121
+ // pulls and pushes through it with the task's variables, but its RUN steps see neither them
122
+ // nor the task's /etc/hosts: they get the proxy as build args and its address as a host.
123
+ 'for name in HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy; do', ' eval "value=\\${$name:-}"', ' if [ -n "$value" ]; then set -- "$@" --opt "build-arg:$name=$value"; fi', 'done', `proxy="$(getent hosts ${egress_proxy_1.EGRESS_PROXY_HOST} | awk '{print $1; exit}' || true)"`, `if [ -n "$proxy" ]; then set -- "$@" --opt "add-hosts=${egress_proxy_1.EGRESS_PROXY_HOST}=$proxy"; fi`);
124
+ const insecure = build.insecure ? ',registry.insecure=true' : '';
125
+ if (build.platforms.length > 0) {
126
+ // one image for each under one name; BuildKit runs a RUN step of another platform in the
127
+ // QEMU of its image (buildkit-qemu-*), so the machine needs no emulator of its own
128
+ lines.push(`set -- "$@" --opt ${quote(`platform=${build.platforms.join(',')}`)}`);
129
+ }
130
+ if (build.cache) {
131
+ lines.push(`set -- "$@" --import-cache ${quote(`type=registry,ref=${build.cache}${insecure}`)} --export-cache ${quote(`type=registry,ref=${build.cache},mode=max${insecure}`)}`);
132
+ }
133
+ if (build.tags.length > 0) {
134
+ const names = build.tags.length === 1 ? `name=${build.tags[0]}` : `"name=${build.tags.join(',')}"`;
135
+ lines.push(`set -- "$@" --output ${quote(`type=image,${names},push=${build.push}${insecure}`)}`);
136
+ }
137
+ lines.push(
138
+ // buildctl-daemonless.sh runs $BUILDCTL, $BUILDKITD and $BUILDKITD_FLAGS: BuildKit's own
139
+ `BUILDCTL=buildctl BUILDKITD=buildkitd BUILDKITD_FLAGS= buildctl-daemonless.sh build --progress plain --frontend dockerfile.v0 --local context=${quote(context)} --local dockerfile=${quote(dockerfileDir)} --opt filename=${quote(dockerfileName)} "$@" --metadata-file ${METADATA_FILE}`);
140
+ if (build.digest) {
141
+ const digestFile = toPosix((0, path_1.relative)(cwd, build.digest));
142
+ lines.push(`digest="$(grep -o '"containerimage.digest": *"[^"]*"' ${METADATA_FILE} | cut -d '"' -f 4)"`, `if [ -z "$digest" ]; then echo 'hammerkit: BuildKit reported no digest of the image' >&2; exit 1; fi`, `mkdir -p ${quote(path_1.posix.dirname(digestFile))}`, `printf '%s@%s\\n' ${quote(getImageName(build.tags[0]))} "$digest" > ${quote(digestFile)}`, `echo "${getImageName(build.tags[0])}@$digest"`);
143
+ }
144
+ return lines.join('\n');
145
+ }
146
+ exports.getImageBuildCommand = getImageBuildCommand;
147
+ // The name of an image without its tag or digest: ghcr.io/acme/app:1 is ghcr.io/acme/app,
148
+ // localhost:5000/app is itself
149
+ function getImageName(image) {
150
+ const withoutDigest = image.split('@')[0];
151
+ const slash = withoutDigest.lastIndexOf('/');
152
+ const colon = withoutDigest.lastIndexOf(':');
153
+ return colon > slash ? withoutDigest.substring(0, colon) : withoutDigest;
154
+ }
155
+ exports.getImageName = getImageName;
156
+ // The key of a registry in a docker config.json: Docker Hub's is its old index URL
157
+ function getAuthKey(registry) {
158
+ return ['docker.io', 'index.docker.io', 'registry-1.docker.io'].includes(registry.toLowerCase())
159
+ ? 'https://index.docker.io/v1/'
160
+ : registry;
161
+ }
162
+ function quote(value) {
163
+ return `'${value.split("'").join("'\\''")}'`;
164
+ }
165
+ function toPosix(value) {
166
+ return path_1.sep === path_1.posix.sep ? value : value.split(path_1.sep).join(path_1.posix.sep);
167
+ }
168
+ function isInside(folder, path) {
169
+ const rel = (0, path_1.relative)(folder, path);
170
+ return rel.length > 0 && rel !== '..' && !rel.startsWith(`..${path_1.sep}`) && !(0, path_1.isAbsolute)(rel);
171
+ }
172
+ //# sourceMappingURL=image-build.js.map
@@ -26,7 +26,20 @@ function appendWorkDependencies(workTree, referenced, item, environment, context
26
26
  for (const generate of depNode.data.generates) {
27
27
  const inherited = generate.inherited ?? depNode;
28
28
  if (generate.isFile) {
29
- // TODO check if thats correct
29
+ // a file the dep generates (the digest of an image it built) is bound into the
30
+ // container of a task, from the host on docker and from the dep's claim on a cluster;
31
+ // a service has no generates to put it in
32
+ if ((0, work_task_1.isWorkTask)(item.data) && !item.data.generates.some((g) => g.path === generate.path)) {
33
+ item.data.generates.push({
34
+ volumeName: generate.volumeName,
35
+ export: false,
36
+ exportAlways: false,
37
+ resetOnChange: false,
38
+ path: generate.path,
39
+ inherited,
40
+ isFile: true,
41
+ });
42
+ }
30
43
  continue;
31
44
  }
32
45
  if (item.data.type === 'container-service') {
@@ -115,7 +115,7 @@ function parseService(workTree, service, environment, context) {
115
115
  caching,
116
116
  // set once the service is planned, see appendServiceInit
117
117
  init: null,
118
- secrets: (0, work_secret_1.parseWorkSecrets)(service.cwd, context.projectRoot, service.schema.secrets, envs, environment, context.secrets, service.schema.account),
118
+ secrets: (0, work_secret_1.parseWorkSecrets)(service.cwd, context.projectRoot, service.schema.secrets, envs, environment, context.secrets, `service ${service.relativeName}`, service.schema.account),
119
119
  resources: (0, work_resources_1.parseWorkResources)(service.schema.resources),
120
120
  volumeSize: service.schema.volumeSize ?? null,
121
121
  restarts: service.schema.restarts ?? null,
@@ -22,6 +22,7 @@ const units_1 = require("../../utils/units");
22
22
  const work_resources_1 = require("../work-resources");
23
23
  const job_placement_1 = require("../../kubernetes/job-placement");
24
24
  const work_network_1 = require("../work-network");
25
+ const image_build_1 = require("../image-build");
25
26
  function appendWorkTask(workTree, cwd, referenceTask, environment, context) {
26
27
  const parsed = parseTask(cwd, referenceTask, environment, context);
27
28
  // on a server's cluster a local task runs in a tool image like a container task
@@ -64,6 +65,9 @@ function appendWorkTask(workTree, cwd, referenceTask, environment, context) {
64
65
  }
65
66
  exports.appendWorkTask = appendWorkTask;
66
67
  function parseTask(cwd, task, environment, context) {
68
+ if ((0, build_file_task_schema_1.isBuildFileImageBuildTaskSchema)(task.schema)) {
69
+ return parseImageBuildTask(cwd, task, task.schema, environment, context);
70
+ }
67
71
  const envs = (0, replace_env_variables_1.buildEnvironmentVariables)(task.envs, environment, context);
68
72
  const baseWorkNode = {
69
73
  envs,
@@ -80,7 +84,7 @@ function parseTask(cwd, task, environment, context) {
80
84
  caching: (0, resolve_cache_1.resolveCache)(task.schema.cache ?? null, context.caches, task.relativeName),
81
85
  shell: task.schema.shell ? (0, template_value_1.templateValue)(task.schema.shell, envs) : '/bin/sh',
82
86
  timeout: task.schema.timeout ? (0, units_1.parseDuration)(task.schema.timeout) : null,
83
- secrets: (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, task.schema.secrets, envs, environment, context.secrets, task.schema.account),
87
+ secrets: (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, task.schema.secrets, envs, environment, context.secrets, `task ${task.relativeName}`, task.schema.account),
84
88
  resources: (0, work_resources_1.parseWorkResources)(task.schema.resources),
85
89
  network: (0, work_network_1.parseWorkNetwork)(task.schema.network),
86
90
  networkCeiling: null,
@@ -123,6 +127,52 @@ function parseTask(cwd, task, environment, context) {
123
127
  };
124
128
  }
125
129
  }
130
+ // A task that builds an image is the container task of BuildKit, with the command, sources,
131
+ // output and secrets of its `build` (see image-build.ts). It takes no arguments: they would go
132
+ // to buildctl, whose command line is hammerkit's.
133
+ function parseImageBuildTask(cwd, task, schema, environment, context) {
134
+ const envs = (0, replace_env_variables_1.buildEnvironmentVariables)(task.envs, environment, context);
135
+ const build = (0, image_build_1.parseWorkImageBuild)(cwd, schema.build, envs, task.relativeName);
136
+ const digest = (0, image_build_1.getImageBuildGenerates)(cwd, build);
137
+ const generates = (0, parse_work_generate_1.parseWorkGenerate)(cwd, { ...schema, generates: [...(schema.generates ?? []), ...digest] }, envs);
138
+ const secrets = (0, work_secret_1.parseWorkSecrets)(cwd, context.projectRoot, [...(schema.secrets ?? []), ...(0, image_build_1.getImageBuildSecrets)(schema.build)], envs, environment, context.secrets, `task ${task.relativeName}`, schema.account);
139
+ (0, image_build_1.checkImageBuildEnvs)([
140
+ ...Object.keys(envs.variables),
141
+ // the build file's own: those of the logins are hammerkit's
142
+ ...(schema.secrets ?? []).flatMap((secret) => (secret.env ? [secret.env] : [])),
143
+ ], task.relativeName);
144
+ return {
145
+ envs,
146
+ envOrigins: getEnvOrigins(task),
147
+ description: (0, template_value_1.templateValue)(schema.description || '', envs).trim(),
148
+ name: task.relativeName,
149
+ cwd,
150
+ projectRoot: context.projectRoot,
151
+ cmds: [{ cwd, cmd: (0, image_build_1.getImageBuildCommand)(cwd, build), parsed: { command: 'set', args: ['-e'] } }],
152
+ src: (0, parse_work_source_1.parseWorkSource)(cwd, schema.src ?? (0, image_build_1.getImageBuildSources)(cwd, build), envs),
153
+ // the digest is a file whatever its name, which parseWorkGenerate goes by
154
+ generates: generates.map((generate) => (generate.path === build.digest ? { ...generate, isFile: true } : generate)),
155
+ scope: task.scope,
156
+ labels: task.labels,
157
+ caching: (0, resolve_cache_1.resolveCache)(schema.cache ?? null, context.caches, task.relativeName),
158
+ shell: '/bin/sh',
159
+ timeout: schema.timeout ? (0, units_1.parseDuration)(schema.timeout) : null,
160
+ secrets,
161
+ resources: (0, work_resources_1.parseWorkResources)(schema.resources),
162
+ network: (0, work_network_1.parseWorkNetwork)(schema.network),
163
+ networkCeiling: null,
164
+ args: false,
165
+ runner: schema.runner ?? task.scope.schema.runner ?? null,
166
+ type: 'container-task',
167
+ // BuildKit runs as root: SYS_ADMIN holds for root only
168
+ user: null,
169
+ image: image_build_1.BUILDKIT_IMAGE,
170
+ mounts: [],
171
+ volumeSize: schema.volumeSize ?? null,
172
+ capAdd: ['SYS_ADMIN'],
173
+ build,
174
+ };
175
+ }
126
176
  function getEnvOrigins(task) {
127
177
  const origins = {};
128
178
  for (const key of Object.keys(task.envs)) {
@@ -11,14 +11,14 @@ const hosted_volumes_1 = require("./hosted-volumes");
11
11
  * checkout it did not write either: a `src: ../..` or a link in the checkout would
12
12
  * have the server mount or upload its own files (its credentials, other callers'
13
13
  * caches) into a task. Checked when the run is planned and again before each item
14
- * runs, since an earlier task may have left a link behind.
14
+ * runs, since an earlier task may have left a link behind: the sources and outputs it
15
+ * inherits from its dependencies too, which a task after them may have swapped for a link.
15
16
  */
16
17
  async function assertItemPathsWithinRoot(item, root) {
17
18
  const data = item.data;
18
19
  for (const source of 'src' in data ? data.src : []) {
19
- if (!source.inherited) {
20
- await (0, within_root_1.assertWithinRoot)(root, source.absolutePath, `${item.name}: src ${source.source}`);
21
- }
20
+ const of = source.inherited ? ` of ${source.inherited.name}` : '';
21
+ await (0, within_root_1.assertWithinRoot)(root, source.absolutePath, `${item.name}: src ${source.source}${of}`);
22
22
  }
23
23
  if ((0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)) {
24
24
  for (const mount of data.mounts) {
@@ -34,9 +34,8 @@ async function assertItemPathsWithinRoot(item, root) {
34
34
  }
35
35
  if ((0, work_task_1.isWorkTask)(data)) {
36
36
  for (const generate of data.generates) {
37
- if (!generate.inherited) {
38
- await (0, within_root_1.assertWithinRoot)(root, generate.path, `${item.name}: generates ${generate.path}`);
39
- }
37
+ const of = generate.inherited ? ` of ${generate.inherited.name}` : '';
38
+ await (0, within_root_1.assertWithinRoot)(root, generate.path, `${item.name}: generates ${generate.path}${of}`);
40
39
  }
41
40
  }
42
41
  }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isDependencyOutput = void 0;
4
+ const path_1 = require("path");
5
+ // Whether a path is, or is inside, a folder a dependency of the task generates. The task sees
6
+ // what the dependency made there: a src at such a path stays a src of the task (its id and its
7
+ // cache key are as they were), but isn't bound or mounted over the output, as docker would bind
8
+ // the host's folder (empty where the dependency ran in a container) and a pod would mount the
9
+ // same path twice. A `build` whose context a dependency writes reads it so.
10
+ function isDependencyOutput(task, path) {
11
+ return task.generates.some((generate) => generate.inherited && !generate.isFile && (generate.path === path || isInside(generate.path, path)));
12
+ }
13
+ exports.isDependencyOutput = isDependencyOutput;
14
+ function isInside(folder, path) {
15
+ const rel = (0, path_1.relative)(folder, path);
16
+ return rel.length > 0 && rel !== '..' && !rel.startsWith(`..${path_1.sep}`) && !(0, path_1.isAbsolute)(rel);
17
+ }
18
+ //# sourceMappingURL=dependency-outputs.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dockerServiceRuntime = exports.dockerTaskRuntime = void 0;
3
+ exports.dockerServiceRuntime = exports.getCacheHelperOptions = exports.dockerTaskRuntime = void 0;
4
4
  const run_labels_1 = require("../docker/run-labels");
5
5
  const execute_docker_1 = require("../executer/execute-docker");
6
6
  const remove_container_1 = require("../docker/remove-container");
@@ -11,12 +11,12 @@ const using_container_1 = require("../docker/using-container");
11
11
  const event_cache_1 = require("../executer/event-cache");
12
12
  const get_docker_executor_1 = require("../executer/get-docker-executor");
13
13
  const path_1 = require("path");
14
- const tar_1 = require("tar");
15
- const tar_2 = require("../utils/tar");
14
+ const tar_1 = require("../utils/tar");
16
15
  const plan_work_volume_1 = require("./utils/plan-work-volume");
17
16
  const work_instance_id_1 = require("./work-instance-id");
18
17
  const stream_1 = require("stream");
19
18
  const service_definition_1 = require("./service-definition");
19
+ const image_build_1 = require("./image-build");
20
20
  const container_task_state_1 = require("../executer/container-task-state");
21
21
  const item_network_1 = require("../docker/item-network");
22
22
  const execution_steps_1 = require("../executer/execution-steps");
@@ -78,6 +78,13 @@ function dockerTaskRuntime(task, workEnvironment) {
78
78
  async remove(environment) {
79
79
  await this.stop();
80
80
  await (0, container_task_state_1.removeContainerTaskState)(environment, task);
81
+ // the layers BuildKit kept for the task's builds (see getBuildKitBinds)
82
+ if (task.data.build && !environment.hosted) {
83
+ const buildKitVolume = (0, image_build_1.getBuildKitVolumeName)(task.data);
84
+ if (await (0, get_docker_executor_1.existsVolume)(docker, buildKitVolume)) {
85
+ await (0, get_docker_executor_1.removeVolume)(docker, task.status, buildKitVolume);
86
+ }
87
+ }
81
88
  for (const generate of task.data.generates) {
82
89
  if (generate.inherited) {
83
90
  continue;
@@ -117,20 +124,11 @@ exports.dockerTaskRuntime = dockerTaskRuntime;
117
124
  function isOnHost(generate) {
118
125
  return generate.isFile || generate.export;
119
126
  }
120
- async function restoreContainer(docker, environment, item, path) {
121
- await (0, execution_steps_1.refuseHostLinks)(item, environment);
122
- // on a server the volumes the outputs are restored into carry the run's files, so they
123
- // are removed with a sandbox
124
- const root = (0, execution_steps_1.hostedRoot)(environment);
125
- if (root) {
126
- const names = item.data.type === 'container-service'
127
- ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
128
- : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
129
- for (const name of names) {
130
- await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
131
- }
132
- }
133
- await (0, using_container_1.usingContainer)(docker, item, {
127
+ // The container that copies an item's outputs into and out of its volumes for the cache:
128
+ // the item's image with those volumes mounted, kept running while archives go in or out.
129
+ // The image is the item's, so whatever its network, this step has none.
130
+ function getCacheHelperOptions(item, environment) {
131
+ return {
134
132
  abortSignal: environment.abortCtrl.signal,
135
133
  Image: item.data.image,
136
134
  Tty: true,
@@ -145,19 +143,41 @@ async function restoreContainer(docker, environment, item, path) {
145
143
  },
146
144
  HostConfig: {
147
145
  AutoRemove: true,
148
- // mount the same volumes archiveContainer reads from, so the restored
149
- // archives land in the task's output volumes rather than in this
150
- // throwaway container's filesystem
146
+ NetworkMode: 'none',
147
+ // the item's own output volumes, so restored archives land there rather than in
148
+ // this throwaway container's filesystem
151
149
  Binds: item.data.type === 'container-service'
152
- ? item.data.volumes
153
- .filter((v) => !v.inherited)
154
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
150
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
155
151
  : item.data.generates
156
152
  .filter((v) => !v.inherited && !v.isFile)
157
153
  .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
158
154
  },
159
- }, async (container) => {
155
+ };
156
+ }
157
+ exports.getCacheHelperOptions = getCacheHelperOptions;
158
+ async function restoreContainer(docker, environment, item, path) {
159
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
160
+ // on a server the volumes the outputs are restored into carry the run's files, so they
161
+ // are removed with a sandbox
162
+ const root = (0, execution_steps_1.hostedRoot)(environment);
163
+ if (root) {
164
+ const names = item.data.type === 'container-service'
165
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
166
+ : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
167
+ for (const name of names) {
168
+ await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
169
+ }
170
+ }
171
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
172
+ // a file output is a bind of a host file, restored on the host below; its folder (as
173
+ // `.images` of `.images/app`) is not in this container
174
+ const files = new Set(item.data.type === 'container-task'
175
+ ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
176
+ : []);
160
177
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
178
+ if (files.has(generate.path)) {
179
+ continue;
180
+ }
161
181
  if (await environment.file.exists(generate.filename)) {
162
182
  // a cache hit means exactly the stored outputs: whatever a failed or
163
183
  // older run left in the volume goes first
@@ -174,7 +194,8 @@ async function restoreContainer(docker, environment, item, path) {
174
194
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
175
195
  if (onHost.has(generate.path) && (await environment.file.exists(generate.filename))) {
176
196
  await environment.file.remove(generate.path);
177
- await (0, tar_1.extract)({ file: generate.filename, cwd: (0, path_1.dirname)(generate.path) });
197
+ await environment.file.createDirectory((0, path_1.dirname)(generate.path));
198
+ await (0, tar_1.extractOutput)(generate.filename, (0, path_1.dirname)(generate.path), (0, path_1.basename)(generate.path), !!environment.hosted);
178
199
  }
179
200
  }
180
201
  }
@@ -273,37 +294,14 @@ function dockerServiceRuntime(service, workEnvironment) {
273
294
  exports.dockerServiceRuntime = dockerServiceRuntime;
274
295
  async function archiveContainer(docker, environment, item, path) {
275
296
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
276
- await (0, using_container_1.usingContainer)(docker, item, {
277
- abortSignal: environment.abortCtrl.signal,
278
- Image: item.data.image,
279
- Tty: true,
280
- Entrypoint: ['sh'],
281
- Cmd: ['-c', 'sleep 3600'],
282
- WorkingDir: (0, execute_docker_1.convertToPosixPath)(item.data.cwd),
283
- Labels: {
284
- app: 'hammerkit',
285
- 'hammerkit-id': (0, work_instance_id_1.getWorkInstanceId)(item),
286
- ...(0, run_labels_1.getRunLabels)(),
287
- 'hammerkit-type': 'task',
288
- },
289
- HostConfig: {
290
- AutoRemove: true,
291
- Binds: item.data.type === 'container-service'
292
- ? item.data.volumes
293
- .filter((v) => !v.inherited)
294
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
295
- : item.data.generates
296
- .filter((v) => !v.inherited && !v.isFile)
297
- .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
298
- },
299
- }, async (container) => {
297
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
300
298
  const hostFiles = new Set(item.data.type === 'container-task'
301
299
  ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
302
300
  : []);
303
301
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
304
302
  // a file output is a bind mount of a host file, so archive it from the host
305
303
  const readable = hostFiles.has(generatedArchive.path)
306
- ? stream_1.Readable.from((0, tar_2.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
304
+ ? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
307
305
  : await container.getArchive({
308
306
  path: generatedArchive.path,
309
307
  });
@@ -388,6 +388,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
388
388
  await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
389
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
390
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ onRefused: options.onQuotaRefused,
391
392
  });
392
393
  }
393
394
  catch (e) {
@@ -4,8 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getLocalWorkRuntime = exports.getStateFilename = void 0;
7
- const tar_1 = require("tar");
8
- const tar_2 = require("../utils/tar");
7
+ const tar_1 = require("../utils/tar");
9
8
  const path_1 = require("path");
10
9
  const local_task_1 = require("../executer/local-task");
11
10
  const event_cache_1 = require("../executer/event-cache");
@@ -122,7 +121,7 @@ async function archiveLocal(environment, task, path) {
122
121
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
123
122
  await environment.file.writeStream(generatedArchive.filename,
124
123
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
125
- stream_1.Readable.from((0, tar_2.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
124
+ stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
125
  }
127
126
  }
128
127
  async function restoreLocal(environment, task, path) {
@@ -131,10 +130,7 @@ async function restoreLocal(environment, task, path) {
131
130
  // a cache hit means exactly the stored outputs: whatever a failed or
132
131
  // older run left in the folder goes first
133
132
  await environment.file.remove(generate.path);
134
- await (0, tar_1.extract)({
135
- file: generate.filename,
136
- cwd: task.cwd,
137
- });
133
+ await (0, tar_1.extractOutput)(generate.filename, task.cwd, (0, path_1.relative)(task.cwd, generate.path), !!environment.hosted);
138
134
  }
139
135
  }
140
136
  }