hammerkit 2.0.0-next.20 → 2.0.0-next.22

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.
@@ -6,8 +6,8 @@
6
6
  <meta name="robots" content="noindex" />
7
7
  <link rel="icon" href="/logo.png" type="image/png" />
8
8
  <title>hammerkit</title>
9
- <script type="module" crossorigin src="/assets/index-vE22S5E_.js"></script>
10
- <link rel="stylesheet" crossorigin href="/assets/index-gIBDC_m8.css">
9
+ <script type="module" crossorigin src="/assets/index-DRSwIRXd.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-BndChMep.css">
11
11
  </head>
12
12
  <body>
13
13
  <div id="root"></div>
@@ -20,6 +20,8 @@ const get_outputs_to_reset_1 = require("../planner/utils/get-outputs-to-reset");
20
20
  const container_secrets_1 = require("./container-secrets");
21
21
  const container_task_state_1 = require("./container-task-state");
22
22
  const docker_resources_1 = require("./docker-resources");
23
+ const image_build_1 = require("../planner/image-build");
24
+ const get_docker_executor_1 = require("./get-docker-executor");
23
25
  function buildCreateOptions(item, stateKey, network, environment, secrets, resources = {},
24
26
  // on a server: the server's tools, whose busybox is the container's first process
25
27
  tools) {
@@ -49,6 +51,7 @@ tools) {
49
51
  Binds: [
50
52
  ...binds.map((b) => `${b.localPath}:${(0, execute_docker_1.convertToPosixPath)(b.containerPath)}${b.readOnly ? ':ro' : ''}`),
51
53
  ...secrets.binds,
54
+ ...getBuildKitBinds(item, environment),
52
55
  ...(tools ? (0, server_tools_1.serverToolsBinds)(tools) : []),
53
56
  ],
54
57
  ...(0, item_network_1.getNetworkHostConfig)(network),
@@ -69,7 +72,10 @@ function getCapabilityHostConfig(item, environment) {
69
72
  return {};
70
73
  }
71
74
  if (!environment.hosted) {
72
- return { CapAdd: capAdd };
75
+ // BuildKit of a task that builds an image (`build`) needs more than SYS_ADMIN where the
76
+ // kernel is the container's own: AppArmor, the read-only cgroups and the masked /proc
77
+ // stop it. On a dev machine it runs privileged, as `docker buildx` runs its BuildKit.
78
+ return item.data.build ? { CapAdd: capAdd, Privileged: true } : { CapAdd: capAdd };
73
79
  }
74
80
  const runtime = environment.hosted.capabilityRuntime;
75
81
  if (!runtime) {
@@ -78,6 +84,11 @@ function getCapabilityHostConfig(item, environment) {
78
84
  return { CapAdd: capAdd, Runtime: runtime };
79
85
  }
80
86
  exports.getCapabilityHostConfig = getCapabilityHostConfig;
87
+ // On a dev machine BuildKit keeps its layers in a volume of the task, for the next build; on
88
+ // a server it has a tmpfs, which its command mounts (see getImageBuildCommand).
89
+ function getBuildKitBinds(item, environment) {
90
+ return item.data.build && !environment.hosted ? [`${(0, image_build_1.getBuildKitVolumeName)(item.data)}:${image_build_1.BUILDKIT_STATE}`] : [];
91
+ }
81
92
  async function dockerTask(docker, item, environment, options) {
82
93
  item.status.write('info', `execute ${item.name} in container`);
83
94
  let network = null;
@@ -95,6 +106,9 @@ async function dockerTask(docker, item, environment, options) {
95
106
  await (0, execution_steps_1.pullImage)(item, docker, environment);
96
107
  (0, abort_1.checkForAbort)(options.abort);
97
108
  await (0, execution_steps_1.prepareVolume)(item, docker, environment);
109
+ if (item.data.build && !environment.hosted) {
110
+ await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, (0, image_build_1.getBuildKitVolumeName)(item.data));
111
+ }
98
112
  (0, abort_1.checkForAbort)(options.abort);
99
113
  network = await (0, item_network_1.prepareItemNetwork)(docker, item, environment, { daemon: false });
100
114
  (0, abort_1.checkForAbort)(options.abort);
@@ -100,6 +100,9 @@ async function prepareMounts(item, environment) {
100
100
  if (exists) {
101
101
  continue;
102
102
  }
103
+ // a file in a folder that isn't there yet (`.images/app.ref`), which docker would bind
104
+ // as a directory
105
+ await environment.file.createDirectory((0, path_1.dirname)(gen.path));
103
106
  await environment.file.writeFile(gen.path, '');
104
107
  }
105
108
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getContainerBinds = void 0;
4
4
  const path_1 = require("path");
5
+ const dependency_outputs_1 = require("../planner/utils/dependency-outputs");
5
6
  function isInside(path, parent) {
6
7
  const rel = (0, path_1.relative)(parent, path);
7
8
  return rel !== '' && !rel.startsWith('..') && !(0, path_1.isAbsolute)(rel);
@@ -16,6 +17,7 @@ function getContainerBinds(item) {
16
17
  // host delete while the container exists.
17
18
  ...sources
18
19
  .filter((path) => !sources.some((other) => isInside(path, other)))
20
+ .filter((path) => !(0, dependency_outputs_1.isDependencyOutput)(item.data, path))
19
21
  .map((path) => ({ localPath: path, containerPath: path, readOnly: false })),
20
22
  ...item.data.generates
21
23
  .filter((g) => !g.isFile)
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeStateKey = exports.combineStateKeys = exports.getExecutionStateKeys = exports.isOwnProvable = exports.resolveEffective = void 0;
3
+ exports.computeStateKey = exports.combineStateKeys = exports.getExecutionStateKeys = exports.getUncachedFileSources = exports.isOwnProvable = exports.resolveEffective = void 0;
4
4
  const get_work_cache_stats_1 = require("../../optimizer/get-work-cache-stats");
5
5
  const work_task_1 = require("../../planner/work-task");
6
6
  // The state-key engine is shared by the scheduler's hit/miss decision
@@ -29,6 +29,23 @@ function isOwnProvable(item, unmatched) {
29
29
  return unmatched.length < item.data.src.filter((src) => !src.inherited).length;
30
30
  }
31
31
  exports.isOwnProvable = isOwnProvable;
32
+ // The tasks with `cache: none` whose file outputs the item reads, such as the digest of an
33
+ // image a `build` pushes. Such a task runs every time and its file can be new each time (a new
34
+ // build is a new digest), while the item's key holds only its sources: a cached item would
35
+ // restore what it made from an older file, so it runs too.
36
+ function getUncachedFileSources(item) {
37
+ if (!(0, work_task_1.isWorkTask)(item.data)) {
38
+ return [];
39
+ }
40
+ const makers = new Set();
41
+ for (const generate of item.data.generates) {
42
+ if (generate.isFile && generate.inherited && generate.inherited.data.caching.method === 'none') {
43
+ makers.add(generate.inherited);
44
+ }
45
+ }
46
+ return [...makers];
47
+ }
48
+ exports.getUncachedFileSources = getUncachedFileSources;
32
49
  // What an item on its own way down stands for. Items that depend on or need each other in a
33
50
  // loop fail to plan (checkForLoop) and never run: this only has to end. The loop is told by
34
51
  // the path of one computation, never by the shared memo, which tasks checked at the same time
@@ -114,6 +131,7 @@ parentPath = new Set()) {
114
131
  depKeys.push(effective.stateKey);
115
132
  provable = provable && effective.provable;
116
133
  }
134
+ provable = provable && getUncachedFileSources(item).length === 0;
117
135
  // what a task that needs a service passed against: the sources of the service and of the
118
136
  // tasks it depends on (its definition is in the task id, getWorkServiceCacheIdentity)
119
137
  for (const need of item.needs) {
@@ -5,6 +5,7 @@ const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const crypto_1 = require("crypto");
7
7
  const kept_claims_1 = require("./kept-claims");
8
+ const dependency_outputs_1 = require("../planner/utils/dependency-outputs");
8
9
  const claim_layout_1 = require("./claim-layout");
9
10
  function getVolumeName(service, kubernetes) {
10
11
  return (0, kept_claims_1.getClaimName)(service, kubernetes);
@@ -73,6 +74,10 @@ stateKey) {
73
74
  // its deps' src too, uploaded into its own claim: a container task sees them as it does on
74
75
  // docker (a tsc -b of a project that references another reads the other's tsconfig)
75
76
  for (const src of getMountedSources(work.data.src)) {
77
+ if (work.data.type === 'container-task' && (0, dependency_outputs_1.isDependencyOutput)(work.data, src.absolutePath)) {
78
+ // what the dependency generates there is mounted below
79
+ continue;
80
+ }
76
81
  const isFile = isLocalFile(src.absolutePath, src.isFile);
77
82
  if (workspace && appendWorkspaceMount(workspace, persistence, src.absolutePath, src.absolutePath, isFile, false)) {
78
83
  continue;
@@ -32,7 +32,12 @@ function getWorkTaskCacheDescription(item) {
32
32
  // architecture, so container tasks are keyed by it too; on a cluster it is the
33
33
  // one of the nodes the task runs on
34
34
  arch: (task.type === 'container-task' && task.arch) || process.arch,
35
- generates: task.generates.map((g) => portable(g.path)).sort() ?? undefined,
35
+ // a file a dep generates is in its task id already (`deps`), and was left out of the
36
+ // generates before it was handed on: ids stay as they were
37
+ generates: task.generates
38
+ .filter((g) => !(g.inherited && g.isFile))
39
+ .map((g) => portable(g.path))
40
+ .sort() ?? undefined,
36
41
  src: task.src.map((s) => s.source).sort() ?? undefined,
37
42
  envs: Object.keys(envs)
38
43
  .sort()
@@ -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') {
@@ -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,
@@ -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)) {
@@ -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
@@ -16,6 +16,7 @@ const plan_work_volume_1 = require("./utils/plan-work-volume");
16
16
  const work_instance_id_1 = require("./work-instance-id");
17
17
  const stream_1 = require("stream");
18
18
  const service_definition_1 = require("./service-definition");
19
+ const image_build_1 = require("./image-build");
19
20
  const container_task_state_1 = require("../executer/container-task-state");
20
21
  const item_network_1 = require("../docker/item-network");
21
22
  const execution_steps_1 = require("../executer/execution-steps");
@@ -77,6 +78,13 @@ function dockerTaskRuntime(task, workEnvironment) {
77
78
  async remove(environment) {
78
79
  await this.stop();
79
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
+ }
80
88
  for (const generate of task.data.generates) {
81
89
  if (generate.inherited) {
82
90
  continue;
@@ -161,7 +169,15 @@ async function restoreContainer(docker, environment, item, path) {
161
169
  }
162
170
  }
163
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
+ : []);
164
177
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
178
+ if (files.has(generate.path)) {
179
+ continue;
180
+ }
165
181
  if (await environment.file.exists(generate.filename)) {
166
182
  // a cache hit means exactly the stored outputs: whatever a failed or
167
183
  // older run left in the volume goes first
@@ -178,6 +194,7 @@ async function restoreContainer(docker, environment, item, path) {
178
194
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
179
195
  if (onHost.has(generate.path) && (await environment.file.exists(generate.filename))) {
180
196
  await environment.file.remove(generate.path);
197
+ await environment.file.createDirectory((0, path_1.dirname)(generate.path));
181
198
  await (0, tar_1.extractOutput)(generate.filename, (0, path_1.dirname)(generate.path), (0, path_1.basename)(generate.path), !!environment.hosted);
182
199
  }
183
200
  }
@@ -683,6 +683,18 @@ function registerWorkCommands(remote, context) {
683
683
  const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/cancel`)).body;
684
684
  environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName}: ${run.state === 'up' || run.state === 'running' ? 'stopping' : (0, server_client_1.printable)(run.state)}\n`);
685
685
  }));
686
+ remote
687
+ .command('retry <run> [server]')
688
+ .description('start a run that is over again, as a new run of yours: the same tasks or services, settings and commit')
689
+ .action(guarded('Remote retry was not successful', async (id, name) => {
690
+ if (!RUN_ID.test(id)) {
691
+ throw new Error(`${(0, server_client_1.printable)(id)} is not a run id (run_...)`);
692
+ }
693
+ const { name: serverName, server, token } = await connect(name);
694
+ const run = (await (0, server_client_1.callServer)(server, token, 'POST', `/v1/runs/${id}/retry`)).body;
695
+ environment.stdout.write(`${(0, server_client_1.printable)(run.id)} on ${serverName} retries ${(0, server_client_1.printable)(id)}: ${(0, server_client_1.printable)(run.state)}, ` +
696
+ `follow it with hammerkit remote logs ${(0, server_client_1.printable)(run.id)} --follow\n`);
697
+ }));
686
698
  remote
687
699
  .command('verify <tasks...>')
688
700
  .description('check that the server already passed tasks for the files checked out here, without running them; ' +
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFileImageBuildTaskSchema = exports.buildFileImageBuildSchema = exports.buildFileRegistryLoginSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const build_file_base_task_schema_1 = require("./build-file-base-task-schema");
6
+ const size_schema_1 = require("./size-schema");
7
+ // A registry host, with a port where it has one: europe-west4-docker.pkg.dev, ghcr.io, localhost:5000
8
+ const REGISTRY = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/i;
9
+ // The name of an image with its tag or digest, as `docker build --tag` takes it. A comma, a
10
+ // quote or a space would end it in BuildKit's `--output`, so none of them is in one. `$NAME`
11
+ // and `${NAME}` take the value of a variable, and the name is checked again with it.
12
+ const IMAGE = /^[a-z0-9$][a-z0-9._/:@${}-]*$/i;
13
+ // A platform as BuildKit takes it: os/arch, with a variant where it has one (linux/arm/v7)
14
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9_]+(\/[a-z0-9]+)?$/;
15
+ // the password of a registry login, read like a secret of the task, never written in the build file
16
+ const registryPasswordSchema = (0, zod_1.object)({
17
+ from: (0, zod_1.string)().regex(/^[A-Za-z][A-Za-z0-9_-]*:.+$/, 'from must be env:NAME, file:path or <provider>:<ref>'),
18
+ account: (0, zod_1.string)().optional(),
19
+ })
20
+ .strict()
21
+ .describe('the password, a secret from env:NAME, file:path or <provider>:<ref>');
22
+ exports.buildFileRegistryLoginSchema = (0, zod_1.object)({
23
+ registry: (0, zod_1.string)().regex(REGISTRY, 'registry must be a host, with a port where it has one (ghcr.io, localhost:5000)'),
24
+ // a user name of basic auth holds no colon; a quote or a backslash would end it in the JSON
25
+ user: (0, zod_1.string)().regex(/^[^:"\\\s]+$/, 'user must not hold a colon, a quote, a backslash or a space'),
26
+ password: registryPasswordSchema,
27
+ })
28
+ .strict()
29
+ .describe('a sign-in to a registry, for the push and the cache');
30
+ exports.buildFileImageBuildSchema = (0, zod_1.object)({
31
+ // the folder sent to the build, relative to the task's directory
32
+ context: (0, zod_1.string)().optional().describe('the build context, `.` when left out'),
33
+ // the Dockerfile, relative to the task's directory
34
+ dockerfile: (0, zod_1.string)().optional().describe('the Dockerfile, Dockerfile in the context when left out'),
35
+ tags: (0, zod_1.union)([(0, zod_1.string)().regex(IMAGE, 'a tag must be an image name'), (0, zod_1.array)((0, zod_1.string)().regex(IMAGE)).min(1)])
36
+ .optional()
37
+ .describe('the names of the image, with their tags, as docker build --tag'),
38
+ push: (0, zod_1.boolean)().optional().describe('push the image to its registry, as docker build --push'),
39
+ // an image the layers are read from before the build and written to after it
40
+ cache: (0, zod_1.string)()
41
+ .regex(IMAGE, 'cache must be an image name, such as ghcr.io/acme/app:buildcache')
42
+ .optional()
43
+ .describe('an image in a registry the build reads its layers from and writes them to'),
44
+ // a file the task writes <name>@<digest> of the image to, which another task deploys
45
+ digest: (0, zod_1.string)().optional().describe('a file the task writes <image>@<digest> to'),
46
+ login: (0, zod_1.array)(exports.buildFileRegistryLoginSchema).optional(),
47
+ // the registries of the tags and the cache speak plain HTTP, as a registry:2 on a network of
48
+ // your own does (docker's --insecure-registry)
49
+ insecure: (0, zod_1.boolean)().optional().describe('reach the registries over plain HTTP'),
50
+ // the platforms of the image, as docker build --platform: one image for each, under one name.
51
+ // A RUN step for a platform other than the machine's runs in BuildKit's own QEMU.
52
+ platforms: (0, zod_1.union)([
53
+ (0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64'),
54
+ (0, zod_1.array)((0, zod_1.string)().regex(PLATFORM, 'a platform is os/arch, such as linux/arm64')).min(1),
55
+ ])
56
+ .optional()
57
+ .describe('the platforms to build for, such as linux/amd64 and linux/arm64, as docker build --platform'),
58
+ })
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
+ })
66
+ .describe('builds a Dockerfile with BuildKit, as docker build does');
67
+ // 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.
69
+ exports.buildFileImageBuildTaskSchema = build_file_base_task_schema_1.buildFileBaseTaskSchema
70
+ .omit({ extend: true, reset: true, cmds: true, shell: true, args: true })
71
+ .extend({
72
+ build: exports.buildFileImageBuildSchema,
73
+ volumeSize: size_schema_1.sizeSchema.describe('size of its claim on Kubernetes, e.g. 10Gi').optional(),
74
+ })
75
+ .strict()
76
+ .describe('task that builds an image');
77
+ //# sourceMappingURL=build-file-image-build-schema.js.map
@@ -1,16 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBuildFileLocalTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
3
+ exports.isBuildFileLocalTaskSchema = exports.isBuildFileImageBuildTaskSchema = exports.isBuildFileContainerTaskSchema = exports.buildFileTaskSchema = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const build_file_container_task_schema_1 = require("./build-file-container-task-schema");
6
6
  const build_file_local_task_schema_1 = require("./build-file-local-task-schema");
7
+ const build_file_image_build_schema_1 = require("./build-file-image-build-schema");
8
+ // A task with `build` is tried first: it fails at once without one, and with one its own
9
+ // errors are reported, not that the other kinds don't know `build` (zod gives the first
10
+ // option's errors that aren't fatal).
7
11
  exports.buildFileTaskSchema = (0, zod_1.union)([
12
+ build_file_image_build_schema_1.buildFileImageBuildTaskSchema,
8
13
  build_file_container_task_schema_1.buildFileContainerTaskSchema,
9
14
  build_file_local_task_schema_1.buildFileLocalTaskSchema,
10
15
  build_file_container_task_schema_1.buildFileExtendingContainerTaskSchema,
11
16
  ]);
12
17
  const isBuildFileContainerTaskSchema = (val) => 'image' in val;
13
18
  exports.isBuildFileContainerTaskSchema = isBuildFileContainerTaskSchema;
14
- const isBuildFileLocalTaskSchema = (val) => !('image' in val);
19
+ const isBuildFileImageBuildTaskSchema = (val) => 'build' in val;
20
+ exports.isBuildFileImageBuildTaskSchema = isBuildFileImageBuildTaskSchema;
21
+ const isBuildFileLocalTaskSchema = (val) => !('image' in val) && !('build' in val);
15
22
  exports.isBuildFileLocalTaskSchema = isBuildFileLocalTaskSchema;
16
23
  //# sourceMappingURL=build-file-task-schema.js.map