hammerkit 2.0.0-next.8 → 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 (99) 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/follow-pod-logs.js +5 -3
  37. package/dist/kubernetes/network-gate.js +74 -11
  38. package/dist/kubernetes/network-policy.js +32 -10
  39. package/dist/kubernetes/remove-stale-items.js +15 -2
  40. package/dist/kubernetes/restore-kubernetes-data.js +3 -2
  41. package/dist/kubernetes/sandbox-runner.js +3 -4
  42. package/dist/kubernetes/store-kubernetes-data.js +3 -2
  43. package/dist/kubernetes/transfer-tools.js +66 -0
  44. package/dist/kubernetes/volumes.js +52 -10
  45. package/dist/optimizer/check-key.js +7 -0
  46. package/dist/optimizer/check-keys.js +19 -5
  47. package/dist/optimizer/get-work-cache-stats.js +19 -7
  48. package/dist/optimizer/work-task-cache-description.js +42 -8
  49. package/dist/parser/read-build-file.js +8 -3
  50. package/dist/planner/image-build.js +172 -0
  51. package/dist/planner/utils/append-work-dependencies.js +14 -1
  52. package/dist/planner/utils/append-work-service.js +1 -1
  53. package/dist/planner/utils/append-work-task.js +51 -1
  54. package/dist/planner/utils/assert-item-paths.js +6 -7
  55. package/dist/planner/utils/dependency-outputs.js +18 -0
  56. package/dist/planner/utils/template-value.js +20 -4
  57. package/dist/planner/work-runtime-docker.js +48 -50
  58. package/dist/planner/work-runtime-kubernetes.js +1 -0
  59. package/dist/planner/work-runtime-local.js +3 -7
  60. package/dist/planner/work-secret.js +135 -13
  61. package/dist/planner/work-tree.js +10 -0
  62. package/dist/remote/collect-bundle.js +9 -1
  63. package/dist/remote/host-config.js +49 -3
  64. package/dist/remote/location.js +5 -5
  65. package/dist/remote/remote-commands.js +12 -14
  66. package/dist/remote/remote-work-commands.js +20 -8
  67. package/dist/schema/build-file-image-build-schema.js +77 -0
  68. package/dist/schema/build-file-task-schema.js +9 -2
  69. package/dist/schema/reference-parser.js +10 -1
  70. package/dist/schema/schema-parser.js +46 -2
  71. package/dist/schema/work-scope-parser.js +16 -1
  72. package/dist/secrets/secret-catalog.js +8 -1
  73. package/dist/server/dashboard.js +8 -5
  74. package/dist/server/executor.js +58 -35
  75. package/dist/server/kubernetes-backend.js +29 -4
  76. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  77. package/dist/server/overview.js +20 -2
  78. package/dist/server/plan.js +31 -3
  79. package/dist/server/policy.js +14 -7
  80. package/dist/server/repo-access.js +4 -3
  81. package/dist/server/run-environment.js +5 -2
  82. package/dist/server/run-plan.js +18 -6
  83. package/dist/server/run-retry.js +57 -0
  84. package/dist/server/run-source-environment.js +39 -0
  85. package/dist/server/run-worker.js +38 -9
  86. package/dist/server/runs.js +59 -1
  87. package/dist/server/sandbox-files.js +339 -55
  88. package/dist/server/sandbox-patch.js +43 -17
  89. package/dist/server/sandboxes.js +57 -23
  90. package/dist/server/server-config.js +24 -4
  91. package/dist/server/server.js +107 -12
  92. package/dist/server/service-runs.js +42 -4
  93. package/dist/server/sources.js +68 -11
  94. package/dist/utils/buffer-context.js +30 -20
  95. package/dist/utils/line-splitter.js +52 -0
  96. package/dist/utils/read-lines.js +65 -0
  97. package/dist/utils/tar.js +51 -1
  98. package/package.json +1 -1
  99. package/dist/dashboard/assets/index-gIBDC_m8.css +0 -2
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stateKeyDigest = exports.getStateKey = exports.getWorkItemCheckoutStats = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
3
+ exports.stateKeyDigest = exports.encodeStateEntries = exports.getStateKey = exports.getWorkItemCheckoutStats = exports.getWorkItemCacheStats = exports.getWorkCacheStats = void 0;
4
4
  const calculate_checksum_1 = require("./calculate-checksum");
5
5
  const path_1 = require("path");
6
6
  const crypto_1 = require("crypto");
@@ -39,9 +39,11 @@ async function visitPath(cwd, path, matcher, context, root) {
39
39
  if (!matcher(path)) {
40
40
  return { type: 'none' };
41
41
  }
42
- const checksum = (0, crypto_1.createHash)('sha256')
42
+ // `l` and the digest of its target, a kind of entry of its own: no checksum of a file
43
+ // starts with a letter past `f`
44
+ const checksum = `l${(0, crypto_1.createHash)('sha256')
43
45
  .update(`link:${await (0, promises_1.readlink)(path)}`)
44
- .digest('hex');
46
+ .digest('hex')}`;
45
47
  return { type: 'file', key, lastModified: link.mtimeMs, checksum };
46
48
  }
47
49
  }
@@ -121,20 +123,30 @@ function dependencyOutputs(item) {
121
123
  return [...outputs];
122
124
  }
123
125
  function getStateKey(stats, cacheMethod) {
124
- const contents = [];
126
+ const entries = [];
125
127
  // Sorted: the walk follows the filesystem's listing order, which differs
126
128
  // between machines (ext4 and overlayfs list in hash order).
127
129
  for (const key of Object.keys(stats.files).sort()) {
128
130
  if (cacheMethod === 'checksum') {
129
- contents.push(`${key}:${stats.files[key].checksum}`);
131
+ entries.push([key, stats.files[key].checksum]);
130
132
  }
131
133
  else if (cacheMethod === 'modify-date') {
132
- contents.push(`${key}:${stats.files[key].lastModified}`);
134
+ entries.push([key, `${stats.files[key].lastModified}`]);
133
135
  }
134
136
  }
135
- return stateKeyDigest(contents.join(','));
137
+ return stateKeyDigest(encodeStateEntries(entries));
136
138
  }
137
139
  exports.getStateKey = getStateKey;
140
+ // The paths and values of a tree as one text that names no other tree. `path:value,...` as
141
+ // before while no path holds `:` or `,` (a value is hex digits or a date), so those keys stay
142
+ // what they were; else JSON after a NUL, which no path holds.
143
+ function encodeStateEntries(entries) {
144
+ if (entries.some(([path]) => /[:,]/.test(path))) {
145
+ return `\0${JSON.stringify(entries)}`;
146
+ }
147
+ return entries.map(([path, value]) => `${path}:${value}`).join(',');
148
+ }
149
+ exports.encodeStateEntries = encodeStateEntries;
138
150
  // A state key is also the value of the `hammerkit.dev/state` label on Kubernetes, which
139
151
  // takes at most 63 characters: the sha256 in base 36 has 50.
140
152
  function stateKeyDigest(content) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.storedCacheDescription = exports.getWorkServiceCacheIdentity = exports.getWorkTaskCacheDescription = void 0;
3
+ exports.storedCacheDescription = exports.getWorkServiceCacheIdentity = exports.getSecretSources = exports.getWorkTaskCacheDescription = void 0;
4
4
  const os_1 = require("os");
5
5
  const crypto_1 = require("crypto");
6
6
  const replace_env_variables_1 = require("../environment/replace-env-variables");
@@ -24,6 +24,7 @@ function getWorkTaskCacheDescription(item) {
24
24
  .filter((secret) => secret.cache)
25
25
  .map((secret) => `${(0, work_secret_1.getPortableSecretName)(task.projectRoot, secret)}=${secret.digest()}`)
26
26
  .sort();
27
+ const secretSources = getSecretSources(task.projectRoot, task.secrets);
27
28
  return {
28
29
  shell: task.shell ?? undefined,
29
30
  platform: task.type === 'container-task' ? task.image : (0, os_1.platform)(),
@@ -31,7 +32,12 @@ function getWorkTaskCacheDescription(item) {
31
32
  // architecture, so container tasks are keyed by it too; on a cluster it is the
32
33
  // one of the nodes the task runs on
33
34
  arch: (task.type === 'container-task' && task.arch) || process.arch,
34
- 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,
35
41
  src: task.src.map((s) => s.source).sort() ?? undefined,
36
42
  envs: Object.keys(envs)
37
43
  .sort()
@@ -44,11 +50,26 @@ function getWorkTaskCacheDescription(item) {
44
50
  cwd: portable(task.cwd),
45
51
  deps: item.deps.length > 0 ? item.deps.map((dep) => dep.id()).sort() : undefined,
46
52
  secrets: cachedSecrets.length > 0 ? cachedSecrets : undefined,
53
+ secretSources: secretSources.length > 0 ? secretSources : undefined,
47
54
  claimLayout: (0, claim_layout_1.hasPathsEndingAlike)(item) || (0, claim_layout_1.hasOutputsFlatteningAlike)(item) ? 2 : undefined,
48
55
  needs: item.needs.length > 0 ? getNeedsIdentities(item) : undefined,
49
56
  };
50
57
  }
51
58
  exports.getWorkTaskCacheDescription = getWorkTaskCacheDescription;
59
+ // The secrets without `cache: true`, by name and source: `NAME<env:VAR`, `NAME<gcp:ref as
60
+ // account`, `NAME<file` (a path of the machine, which differs between machines). Their values
61
+ // stay out of the key, as before: what a provider returns may change on every read.
62
+ function getSecretSources(projectRoot, secrets) {
63
+ return secrets
64
+ .filter((secret) => !secret.cache)
65
+ .map((secret) => {
66
+ const source = secret.source;
67
+ const from = source.type === 'file' ? 'file' : (0, work_secret_1.describeSecretSource)(secret);
68
+ return `${(0, work_secret_1.getPortableSecretName)(projectRoot, secret)}<${from}`;
69
+ })
70
+ .sort();
71
+ }
72
+ exports.getSecretSources = getSecretSources;
52
73
  // `visiting` holds the services on the way here: services that need each other in a loop
53
74
  // fail to plan (checkForLoop), the identity only has to come back to say so
54
75
  function getNeedsIdentities(item, visiting = new Set()) {
@@ -78,6 +99,10 @@ function getWorkServiceCacheIdentity(item, visiting = new Set()) {
78
99
  .filter((secret) => secret.cache)
79
100
  .map((secret) => `${(0, work_secret_1.getPortableSecretName)(service.projectRoot, secret)}=${secret.digest()}`)
80
101
  .sort(),
102
+ // left out when it reads none, so the identity of such a service stays what it was
103
+ ...(service.secrets.some((secret) => !secret.cache)
104
+ ? { secretSources: getSecretSources(service.projectRoot, service.secrets) }
105
+ : {}),
81
106
  // as declared: arguments after -- of a run of the init leave the service as it is
82
107
  init: service.init ? (0, work_cache_id_1.getDeclaredWorkTaskId)(service.init.task) : null,
83
108
  }
@@ -96,16 +121,25 @@ exports.getWorkServiceCacheIdentity = getWorkServiceCacheIdentity;
96
121
  // The form written to disk: description.json in a cache entry (pushed to remote
97
122
  // backends, readable by everyone who can pull) and the local explain record.
98
123
  // Env is where tokens get passed, so each value is stored as a digest; the task
99
- // id is still hashed from the values themselves.
124
+ // id is still hashed from the values themselves. So are where its secrets come from: who may
125
+ // pull an entry need not know which secrets of which provider a task reads.
100
126
  function storedCacheDescription(description) {
101
- if (!description.envs) {
127
+ if (!description.envs && !description.secretSources) {
102
128
  return description;
103
129
  }
104
- const envs = {};
105
- for (const [key, value] of Object.entries(description.envs)) {
106
- envs[key] = `sha256:${(0, crypto_1.createHash)('sha256').update(value).digest('hex')}`;
130
+ const digest = (value) => `sha256:${(0, crypto_1.createHash)('sha256').update(value).digest('hex')}`;
131
+ const stored = { ...description };
132
+ if (description.envs) {
133
+ const envs = {};
134
+ for (const [key, value] of Object.entries(description.envs)) {
135
+ envs[key] = digest(value);
136
+ }
137
+ stored.envs = envs;
138
+ }
139
+ if (description.secretSources) {
140
+ stored.secretSources = description.secretSources.map(digest);
107
141
  }
108
- return { ...description, envs };
142
+ return stored;
109
143
  }
110
144
  exports.storedCacheDescription = storedCacheDescription;
111
145
  //# sourceMappingURL=work-task-cache-description.js.map
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.read = exports.write = void 0;
3
+ exports.readSized = exports.read = exports.write = void 0;
4
4
  const yaml_1 = require("yaml");
5
5
  async function write(filename, content, context) {
6
6
  await context.file.writeFile(filename, (0, yaml_1.stringify)(content));
7
7
  }
8
8
  exports.write = write;
9
9
  async function read(fileName, context) {
10
+ return (await readSized(fileName, context)).value;
11
+ }
12
+ exports.read = read;
13
+ // The parsed file and the bytes it took.
14
+ async function readSized(fileName, context) {
10
15
  context.status.context({ type: 'cli', name: 'hammerkit' }).write('debug', `read ${fileName} build file`);
11
16
  let content;
12
17
  try {
@@ -16,7 +21,7 @@ async function read(fileName, context) {
16
21
  throw new Error(`unable to read ${fileName}`);
17
22
  }
18
23
  try {
19
- return (0, yaml_1.parse)(content);
24
+ return { value: (0, yaml_1.parse)(content), bytes: Buffer.byteLength(content, 'utf8') };
20
25
  }
21
26
  catch (e) {
22
27
  if (e instanceof Error) {
@@ -27,5 +32,5 @@ async function read(fileName, context) {
27
32
  }
28
33
  }
29
34
  }
30
- exports.read = read;
35
+ exports.readSized = readSized;
31
36
  //# sourceMappingURL=read-build-file.js.map
@@ -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
@@ -5,11 +5,27 @@ function templateValue(value, envs) {
5
5
  if (!value || !envs) {
6
6
  return value;
7
7
  }
8
- let result = value;
9
- for (const [key, envValue] of Object.entries(envs.variables)) {
10
- result = result.replace(new RegExp(`\\$\\{${key}\\}|\\$${key}`, 'gi'), envValue);
8
+ // A name is matched as the text it is, in any case; when two names match the same `$`, the
9
+ // one listed first wins. One pass over the value: a value put in is not read again.
10
+ const names = Object.keys(envs.variables).filter((name) => name.length > 0);
11
+ if (names.length === 0) {
12
+ return value;
13
+ }
14
+ const values = new Map();
15
+ for (const name of names) {
16
+ const key = name.toLowerCase();
17
+ if (!values.has(key)) {
18
+ values.set(key, envs.variables[name]);
19
+ }
11
20
  }
12
- return result;
21
+ const alternatives = names.map(escapeRegExp).join('|');
22
+ const pattern = new RegExp(`\\$\\{(${alternatives})\\}|\\$(${alternatives})`, 'gi');
23
+ return value.replace(pattern, (match, braced, bare) => {
24
+ return values.get((braced ?? bare ?? '').toLowerCase()) ?? match;
25
+ });
13
26
  }
14
27
  exports.templateValue = templateValue;
28
+ function escapeRegExp(text) {
29
+ return text.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
30
+ }
15
31
  //# sourceMappingURL=template-value.js.map