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
@@ -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>
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeOrphanedNetworks = exports.removeItemNetworks = exports.getNetworkHostConfig = exports.getPortBinding = exports.removeItemNetwork = exports.prepareItemNetwork = exports.checkNetworkLimitSupport = exports.getProxyNetworkName = exports.getRunNetworkName = exports.getItemNetworkName = void 0;
3
+ exports.removeOrphanedNetworks = exports.removeItemNetworks = exports.getNetworkHostConfig = exports.getPortBinding = exports.removeItemNetwork = exports.prepareItemNetwork = exports.createInternalNetwork = exports.checkNetworkLimitSupport = exports.getNeedNetworkName = exports.getProxyNetworkName = exports.getRunNetworkName = exports.getItemNetworkName = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const stream_1 = require("stream");
6
6
  const work_service_1 = require("../planner/work-service");
@@ -100,6 +100,16 @@ function getProxyNetworkName(networkName) {
100
100
  return `${networkName}-proxy`;
101
101
  }
102
102
  exports.getProxyNetworkName = getProxyNetworkName;
103
+ // Where a limited item reaches the service it needs at `index` in its list of container
104
+ // needs: the first on the item's own network, each further one on a network of its own
105
+ // that only the item (and its proxy) join, so the services it needs don't reach each other
106
+ // through it.
107
+ function getNeedNetworkName(networkName, index) {
108
+ return index === 0 ? networkName : `${networkName}-need${index}`;
109
+ }
110
+ exports.getNeedNetworkName = getNeedNetworkName;
111
+ // on the networks of the further needs: the item network they belong to, which removes them
112
+ const NEED_NETWORK_OF_LABEL = 'hammerkit-need-network-of';
103
113
  const daemonVersions = new WeakMap();
104
114
  function getDaemonVersion(docker) {
105
115
  let version = daemonVersions.get(docker);
@@ -127,13 +137,23 @@ exports.checkNetworkLimitSupport = checkNetworkLimitSupport;
127
137
  // Internal (no route out) and without an address on the host, so the host's
128
138
  // services can't be reached through it either.
129
139
  async function createInternalNetwork(docker, name, labels) {
130
- await docker.createNetwork({
131
- Name: name,
132
- Internal: true,
133
- Options: { 'com.docker.network.bridge.inhibit_ipv4': 'true' },
134
- Labels: labels,
135
- });
140
+ try {
141
+ await docker.createNetwork({
142
+ Name: name,
143
+ Internal: true,
144
+ Options: { 'com.docker.network.bridge.inhibit_ipv4': 'true' },
145
+ Labels: labels,
146
+ });
147
+ }
148
+ catch (e) {
149
+ if (/available, non-overlapping/i.test((0, log_1.getErrorMessage)(e))) {
150
+ throw new Error(`${(0, log_1.getErrorMessage)(e)}: the docker daemon has no address range left for the network ${name}; ` +
151
+ 'smaller default-address-pools in its daemon.json make room for more networks');
152
+ }
153
+ throw e;
154
+ }
136
155
  }
156
+ exports.createInternalNetwork = createInternalNetwork;
137
157
  // What the proxy and relay may do: serve, nothing else.
138
158
  const HELPER_HOST_CONFIG = {
139
159
  CapDrop: ['ALL'],
@@ -238,16 +258,20 @@ options) {
238
258
  'hammerkit-daemon': options.daemon ? 'true' : 'false',
239
259
  };
240
260
  await createInternalNetwork(docker, name, labels);
261
+ const needNetworks = containers.map((_, index) => getNeedNetworkName(name, index));
241
262
  try {
242
- for (const target of containers) {
243
- await docker.getNetwork(name).connect({
263
+ for (const [index, target] of containers.entries()) {
264
+ if (index > 0) {
265
+ await createInternalNetwork(docker, needNetworks[index], { ...labels, [NEED_NETWORK_OF_LABEL]: name });
266
+ }
267
+ await docker.getNetwork(needNetworks[index]).connect({
244
268
  Container: target.containerId,
245
269
  EndpointConfig: { Aliases: [target.need.name] },
246
270
  });
247
271
  }
248
272
  if (network.type === 'allow') {
249
273
  await createInternalNetwork(docker, getProxyNetworkName(name), labels);
250
- const proxyIp = await startEgressProxy(docker, item, environment, name, network, options, containers.length > 0);
274
+ const proxyIp = await startEgressProxy(docker, item, environment, name, network, options, needNetworks);
251
275
  // the item reaches each TCP forward under its host's name, at the proxy
252
276
  for (const forward of (0, work_network_1.getTcpForwards)(network)) {
253
277
  hosts.push(`${forward.host}:${proxyIp}`);
@@ -268,6 +292,10 @@ options) {
268
292
  },
269
293
  async connect(container) {
270
294
  try {
295
+ // created on the first, the item's own
296
+ for (const needNetwork of needNetworks.slice(1)) {
297
+ await docker.getNetwork(needNetwork).connect({ Container: container.id });
298
+ }
271
299
  if (network.type === 'allow') {
272
300
  await docker.getNetwork(getProxyNetworkName(name)).connect({ Container: container.id });
273
301
  }
@@ -299,11 +327,11 @@ function getHelperLabels(networkName, options) {
299
327
  }
300
328
  // On the default bridge for the way out, and on the proxy network under
301
329
  // EGRESS_PROXY_HOST, the only address it listens on: neither the bridge nor
302
- // the services on the item's network reach it. It joins the item's network
303
- // to reach the needed services (for tools that ignore NO_PROXY), but doesn't
304
- // listen there. Refused hosts show up in the item's log. Returns its address
330
+ // the services on the item's network reach it. It joins the networks of the
331
+ // needed services (`needNetworks`) to reach them (for tools that ignore
332
+ // NO_PROXY), but doesn't listen there. Refused hosts show up in the item's log. Returns its address
305
333
  // on the proxy network, where it also listens for the TCP forwards.
306
- async function startEgressProxy(docker, item, environment, networkName, network, options, reachNeeds) {
334
+ async function startEgressProxy(docker, item, environment, networkName, network, options, needNetworks) {
307
335
  await (0, pull_1.pull)(item.status, docker, egress_proxy_1.EGRESS_PROXY_IMAGE, environment);
308
336
  const createOptions = {
309
337
  Image: egress_proxy_1.EGRESS_PROXY_IMAGE,
@@ -319,8 +347,8 @@ async function startEgressProxy(docker, item, environment, networkName, network,
319
347
  Container: container.id,
320
348
  EndpointConfig: { Aliases: [egress_proxy_1.EGRESS_PROXY_HOST] },
321
349
  });
322
- if (reachNeeds) {
323
- await docker.getNetwork(networkName).connect({ Container: container.id });
350
+ for (const needNetwork of needNetworks) {
351
+ await docker.getNetwork(needNetwork).connect({ Container: container.id });
324
352
  }
325
353
  const stream = await container.attach({ stream: true, stdout: true, stderr: true });
326
354
  const stdout = new stream_1.PassThrough();
@@ -383,14 +411,19 @@ async function startPortRelay(docker, item, environment, networkName, service, p
383
411
  item.status.write('debug', `ports ${ports.map((port) => port.hostPort || 'any').join(', ')} published by a relay`);
384
412
  return container;
385
413
  }
386
- // The network, its proxy network, its proxy and relay, and every endpoint on
387
- // them: what an earlier run left behind, or what the item used.
414
+ // The network, its proxy network and the networks of further needs, its proxy and
415
+ // relay, and every endpoint on them: what an earlier run left behind, or what the item
416
+ // used.
388
417
  async function removeItemNetwork(docker, name) {
389
418
  const helpers = await docker.listContainers({ all: true, filters: { label: [`hammerkit-network=${name}`] } });
390
419
  for (const helper of helpers) {
391
420
  await (0, remove_container_1.removeContainer)(docker.getContainer(helper.Id));
392
421
  }
393
422
  await removeNetwork(docker, getProxyNetworkName(name));
423
+ const needNetworks = await docker.listNetworks({ filters: { label: [`${NEED_NETWORK_OF_LABEL}=${name}`] } });
424
+ for (const needNetwork of needNetworks) {
425
+ await removeNetwork(docker, needNetwork.Name);
426
+ }
394
427
  await removeNetwork(docker, name);
395
428
  }
396
429
  exports.removeItemNetwork = removeItemNetwork;
@@ -6,6 +6,7 @@ const work_item_1 = require("../planner/work-item");
6
6
  const work_service_1 = require("../planner/work-service");
7
7
  const execute_docker_1 = require("../executer/execute-docker");
8
8
  const node_os_1 = require("node:os");
9
+ const promises_1 = require("node:fs/promises");
9
10
  const path_1 = require("path");
10
11
  const log_1 = require("../log");
11
12
  // Default the build platform to the host architecture so a packaged image runs
@@ -32,88 +33,96 @@ async function packageWorkTree(workTree, environment, options) {
32
33
  if ((0, work_item_1.isContainerWorkServiceItem)(service)) {
33
34
  environment.console.info(`preparing files for ${service.name}`);
34
35
  const definition = getServiceInstructions(service, options);
35
- const buildDir = (0, path_1.join)((0, node_os_1.tmpdir)(), service.id());
36
- const dockerFileName = (0, path_1.join)(buildDir, 'Dockerfile');
37
- const dockerFileContent = definition.instructions.join('\n');
38
- await environment.file.createDirectory(buildDir);
39
- await environment.file.writeFile(dockerFileName, dockerFileContent);
40
- environment.console.debug(`create dockerfile ${dockerFileName}`);
41
- environment.console.debug(`with cwd ${definition.cwd}`);
42
- const src = ['Dockerfile'];
43
- for (const source of definition.sources) {
44
- const path = (0, path_1.relative)(definition.cwd, source.absolutePath);
45
- environment.console.debug(`copying ${source.absolutePath} to ${(0, path_1.join)(buildDir, path)}`);
46
- await environment.file.copy(source.absolutePath, (0, path_1.join)(buildDir, path));
47
- src.push(path);
36
+ // a new private directory for each build, removed afterwards
37
+ const buildDir = await (0, promises_1.mkdtemp)((0, path_1.join)((0, node_os_1.tmpdir)(), 'hammerkit-package-'));
38
+ try {
39
+ await packageService(docker, service, definition, buildDir, environment, options, platform, tag);
48
40
  }
49
- const imageName = `${options.registry}/${service.name}:${tag}`;
50
- environment.console.info(`building image ${imageName} for ${service.name} (${platform})`);
51
- const buildStream = await docker.buildImage({
52
- src,
53
- context: buildDir,
54
- }, {
55
- t: imageName,
56
- platform,
57
- abortSignal: environment.abortCtrl.signal,
58
- });
59
- await new Promise((resolve, reject) => {
60
- docker.modem.followProgress(buildStream, (err, res) => {
61
- if (err) {
62
- environment.console.error((0, log_1.getErrorMessage)(err));
63
- reject(err);
64
- return;
65
- }
66
- // followProgress returns every build message in `res`, so a
67
- // non-empty array is normal on success. Only fail when an entry
68
- // actually carries an error.
69
- const failure = (res ?? []).find((i) => 'error' in i && !!i.error);
70
- if (failure && 'error' in failure) {
71
- const detail = failure.errorDetail?.message ?? failure.error ?? 'unknown error';
72
- environment.console.error(detail);
73
- reject(new Error(`build failed: ${detail}`));
74
- }
75
- else {
76
- resolve();
77
- }
78
- }, (res) => {
79
- if (res.stream) {
80
- if (res.stream === '\n') {
81
- return;
82
- }
83
- if (res.stream.endsWith('\n')) {
84
- environment.console.info(res.stream.substr(0, res.stream.length - 1));
85
- }
86
- else {
87
- environment.console.info(res.stream);
88
- }
89
- }
90
- });
91
- });
92
- environment.console.info(`generated image ${imageName} for ${service.name}`);
93
- if (options.push) {
94
- environment.console.info(`pushing image ${imageName} to ${options.registry}`);
95
- const img = docker.getImage(imageName);
96
- const pushStream = await img.push({
97
- abortSignal: environment.abortCtrl.signal,
98
- authconfig: {
99
- username: options.username || '',
100
- password: options.password || '',
101
- serveraddress: options.registry,
102
- },
103
- });
104
- await new Promise((resolve, reject) => {
105
- docker.modem.followProgress(pushStream, (err, res) => (err ? reject(err) : resolve(res)), (res) => {
106
- if (res.stream) {
107
- environment.console.info(res.stream);
108
- }
109
- });
110
- });
111
- environment.console.info(`pushed image ${imageName} to ${options.registry}`);
41
+ finally {
42
+ await (0, promises_1.rm)(buildDir, { recursive: true, force: true });
112
43
  }
113
44
  }
114
45
  }
115
46
  }
116
47
  exports.packageWorkTree = packageWorkTree;
48
+ async function packageService(docker, service, definition, buildDir, environment, options, platform, tag) {
49
+ const dockerFileName = (0, path_1.join)(buildDir, 'Dockerfile');
50
+ const dockerFileContent = definition.instructions.join('\n');
51
+ await environment.file.writeFile(dockerFileName, dockerFileContent);
52
+ environment.console.debug(`create dockerfile ${dockerFileName}`);
53
+ environment.console.debug(`with cwd ${definition.cwd}`);
54
+ const src = ['Dockerfile'];
55
+ for (const source of definition.sources) {
56
+ const path = (0, path_1.relative)(definition.cwd, source.absolutePath);
57
+ environment.console.debug(`copying ${source.absolutePath} to ${(0, path_1.join)(buildDir, path)}`);
58
+ await environment.file.copy(source.absolutePath, (0, path_1.join)(buildDir, path));
59
+ src.push(path);
60
+ }
61
+ const imageName = `${options.registry}/${service.name}:${tag}`;
62
+ environment.console.info(`building image ${imageName} for ${service.name} (${platform})`);
63
+ const buildStream = await docker.buildImage({
64
+ src,
65
+ context: buildDir,
66
+ }, {
67
+ t: imageName,
68
+ platform,
69
+ abortSignal: environment.abortCtrl.signal,
70
+ });
71
+ await new Promise((resolve, reject) => {
72
+ docker.modem.followProgress(buildStream, (err, res) => {
73
+ if (err) {
74
+ environment.console.error((0, log_1.getErrorMessage)(err));
75
+ reject(err);
76
+ return;
77
+ }
78
+ // followProgress returns every build message in `res`, so a
79
+ // non-empty array is normal on success. Only fail when an entry
80
+ // actually carries an error.
81
+ const failure = (res ?? []).find((i) => 'error' in i && !!i.error);
82
+ if (failure && 'error' in failure) {
83
+ const detail = failure.errorDetail?.message ?? failure.error ?? 'unknown error';
84
+ environment.console.error(detail);
85
+ reject(new Error(`build failed: ${detail}`));
86
+ }
87
+ else {
88
+ resolve();
89
+ }
90
+ }, (res) => {
91
+ if (res.stream) {
92
+ if (res.stream === '\n') {
93
+ return;
94
+ }
95
+ if (res.stream.endsWith('\n')) {
96
+ environment.console.info(res.stream.substr(0, res.stream.length - 1));
97
+ }
98
+ else {
99
+ environment.console.info(res.stream);
100
+ }
101
+ }
102
+ });
103
+ });
104
+ environment.console.info(`generated image ${imageName} for ${service.name}`);
105
+ if (options.push) {
106
+ environment.console.info(`pushing image ${imageName} to ${options.registry}`);
107
+ const img = docker.getImage(imageName);
108
+ const pushStream = await img.push({
109
+ abortSignal: environment.abortCtrl.signal,
110
+ authconfig: {
111
+ username: options.username || '',
112
+ password: options.password || '',
113
+ serveraddress: options.registry,
114
+ },
115
+ });
116
+ await new Promise((resolve, reject) => {
117
+ docker.modem.followProgress(pushStream, (err, res) => (err ? reject(err) : resolve(res)), (res) => {
118
+ if (res.stream) {
119
+ environment.console.info(res.stream);
120
+ }
121
+ });
122
+ });
123
+ environment.console.info(`pushed image ${imageName} to ${options.registry}`);
124
+ }
125
+ }
117
126
  function getDependencySources(service, taskIds) {
118
127
  const result = [...service.data.src.filter((s) => !s.inherited)];
119
128
  taskIds.push(service.id());
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isServerToolsPath = exports.hideServerTools = exports.openGateArguments = exports.gatedCommand = exports.withServerBusybox = exports.serviceGateTmpfs = exports.serverToolsBinds = exports.serverBusybox = exports.ensureServerBusybox = exports.createServerTools = void 0;
4
+ const promises_1 = require("fs/promises");
5
+ const path_1 = require("path");
6
+ const promises_2 = require("stream/promises");
7
+ const tar_1 = require("tar");
8
+ const crypto_1 = require("crypto");
9
+ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
10
+ const transfer_tools_1 = require("../kubernetes/transfer-tools");
11
+ const pull_1 = require("./pull");
12
+ const remove_container_1 = require("./remove-container");
13
+ function createServerTools(hostBusybox) {
14
+ return { folder: `/.hammerkit-${(0, crypto_1.randomBytes)(16).toString('hex')}`, hostBusybox };
15
+ }
16
+ exports.createServerTools = createServerTools;
17
+ let busybox;
18
+ // The busybox on the docker host, copied out of the pinned image once per process.
19
+ function ensureServerBusybox(docker, status, environment) {
20
+ busybox ?? (busybox = copyBusybox(docker, status, environment).catch((e) => {
21
+ busybox = undefined;
22
+ throw e;
23
+ }));
24
+ return busybox;
25
+ }
26
+ exports.ensureServerBusybox = ensureServerBusybox;
27
+ async function copyBusybox(docker, status, environment) {
28
+ const name = (0, crypto_1.createHash)('sha256').update(transfer_tools_1.HELPER_TOOLS_IMAGE).digest('hex').slice(0, 16);
29
+ const folder = (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'tools');
30
+ const file = (0, path_1.join)(folder, `busybox-${name}`);
31
+ if (await (0, promises_1.stat)(file).catch(() => undefined)) {
32
+ return file;
33
+ }
34
+ await (0, pull_1.pull)(status, docker, transfer_tools_1.HELPER_TOOLS_IMAGE, environment);
35
+ await (0, promises_1.mkdir)(folder, { recursive: true, mode: 0o755 });
36
+ const temporary = await (0, promises_1.mkdtemp)((0, path_1.join)(folder, '.busybox-'));
37
+ const container = await docker.createContainer({ Image: transfer_tools_1.HELPER_TOOLS_IMAGE, Cmd: ['true'] });
38
+ try {
39
+ const archive = await container.getArchive({ path: '/bin/busybox' });
40
+ await (0, promises_2.pipeline)(archive, (0, tar_1.extract)({ cwd: temporary, filter: (path) => path === 'busybox' }));
41
+ await (0, promises_1.chmod)((0, path_1.join)(temporary, 'busybox'), 0o755);
42
+ await (0, promises_1.rename)((0, path_1.join)(temporary, 'busybox'), file);
43
+ }
44
+ finally {
45
+ await (0, remove_container_1.removeContainer)(container).catch(() => undefined);
46
+ await (0, promises_1.rm)(temporary, { recursive: true, force: true });
47
+ }
48
+ return file;
49
+ }
50
+ // the busybox in the container
51
+ function serverBusybox(tools) {
52
+ return `${tools.folder}/busybox`;
53
+ }
54
+ exports.serverBusybox = serverBusybox;
55
+ function serverToolsBinds(tools) {
56
+ return [`${tools.hostBusybox}:${serverBusybox(tools)}:ro`];
57
+ }
58
+ exports.serverToolsBinds = serverToolsBinds;
59
+ // a tmpfs of a service's container: the server writes `go` into it once the binds are checked
60
+ function serviceGateTmpfs(tools) {
61
+ return { [`${tools.folder}/run`]: 'rw,size=64k,mode=755' };
62
+ }
63
+ exports.serviceGateTmpfs = serviceGateTmpfs;
64
+ function gateFile(tools) {
65
+ return `${tools.folder}/run/go`;
66
+ }
67
+ // `command` run by the server's busybox in a container
68
+ function withServerBusybox(tools, command) {
69
+ return [serverBusybox(tools), ...command];
70
+ }
71
+ exports.withServerBusybox = withServerBusybox;
72
+ // Runs `command` (the service's own, as docker would) once the server opened the gate.
73
+ function gatedCommand(tools, command) {
74
+ const busybox = serverBusybox(tools);
75
+ const wait = `until ${busybox} test -e ${gateFile(tools)}; do ${busybox} sleep 0.1; done; exec "$@"`;
76
+ return [busybox, 'sh', '-c', wait, 'hammerkit-gate', ...command];
77
+ }
78
+ exports.gatedCommand = gatedCommand;
79
+ // what the server's busybox runs to open the gate
80
+ function openGateArguments(tools) {
81
+ return ['touch', gateFile(tools)];
82
+ }
83
+ exports.openGateArguments = openGateArguments;
84
+ // `text` (a log line, an error) without the name of the tools' folder
85
+ function hideServerTools(text, tools) {
86
+ return tools ? text.split(tools.folder).join('/.hammerkit-…') : text;
87
+ }
88
+ exports.hideServerTools = hideServerTools;
89
+ // A path of a container where an item's source, output, mount, volume or secret would
90
+ // hide or replace the server's tools: `/`, or at or in a folder `.hammerkit…` of `/`.
91
+ function isServerToolsPath(containerPath) {
92
+ const normalized = path_1.posix.normalize(containerPath).replace(/\/+$/, '') || '/';
93
+ return normalized === '/' || /^\/\.hammerkit($|[-/])/.test(normalized);
94
+ }
95
+ exports.isServerToolsPath = isServerToolsPath;
96
+ //# sourceMappingURL=server-tools.js.map
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.logStream = exports.awaitStream = void 0;
4
- const log_1 = require("../log");
4
+ const line_splitter_1 = require("../utils/line-splitter");
5
5
  async function awaitStream(status, stream) {
6
6
  return new Promise((resolve, reject) => {
7
7
  logStream(status, stream);
@@ -12,15 +12,23 @@ async function awaitStream(status, stream) {
12
12
  }
13
13
  exports.awaitStream = awaitStream;
14
14
  function logStream(status, stream) {
15
- demuxStream(stream, writeLog(status, 'stdout'), writeLog(status, 'stderr'));
15
+ const stdout = writeLog(status, 'stdout');
16
+ const stderr = writeLog(status, 'stderr');
17
+ demuxStream(stream, (buffer) => stdout.write(buffer), (buffer) => stderr.write(buffer));
18
+ // what is left of a last line without a line feed
19
+ const end = () => {
20
+ stdout.end();
21
+ stderr.end();
22
+ };
23
+ const events = stream;
24
+ events.on('end', end);
25
+ events.on('close', end);
16
26
  }
17
27
  exports.logStream = logStream;
28
+ // A line docker split between two frames is logged once it ends, whole: a secret value in it
29
+ // is masked per line.
18
30
  function writeLog(status, level) {
19
- return async (buffer) => {
20
- for (const log of (0, log_1.getLogs)(buffer)) {
21
- status.console(level, log.endsWith('\n') ? log.substring(0, log.length - 1) : log);
22
- }
23
- };
31
+ return (0, line_splitter_1.lineSplitter)((line) => status.console(level, line));
24
32
  }
25
33
  function demuxStream(stream, stdoutFn, stderrFn) {
26
34
  let nextDataType = null;
@@ -7,7 +7,7 @@ const INTERPOLATION = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
7
7
  // an empty string is set, as in a shell: CI providers leave many empty (a merge
8
8
  // request id on a branch pipeline).
9
9
  function resolveReference(name, environment, context, fromProcess) {
10
- const processValue = environment.processEnvs[name];
10
+ const processValue = (environment.hosted?.buildFileEnvs ?? environment.processEnvs)[name];
11
11
  if (processValue !== undefined && processValue !== null) {
12
12
  fromProcess?.add(name);
13
13
  return processValue;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRunSourceEnv = exports.RUN_SOURCE_ENVS = void 0;
4
+ // The variables a server sets for the process of a run, from what the run is from (see
5
+ // src/server/run-source-environment.ts). Nothing else sets them: the operator's `runs.env`
6
+ // can't name them, and a run that isn't from that source has none of them.
7
+ exports.RUN_SOURCE_ENVS = [
8
+ 'HAMMERKIT_RUN_REPO',
9
+ 'HAMMERKIT_RUN_REF',
10
+ 'HAMMERKIT_RUN_COMMIT',
11
+ 'HAMMERKIT_RUN_SANDBOX',
12
+ ];
13
+ // without case: Windows doesn't tell `hammerkit_run_ref` from `HAMMERKIT_RUN_REF`
14
+ function isRunSourceEnv(name) {
15
+ return exports.RUN_SOURCE_ENVS.includes(name.toUpperCase());
16
+ }
17
+ exports.isRunSourceEnv = isRunSourceEnv;
18
+ //# sourceMappingURL=run-source-envs.js.map
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openServiceGate = exports.readIdentity = exports.refuseUncheckableBinds = exports.refuseServerToolsPaths = exports.assertContainerBinds = void 0;
4
+ const path_1 = require("path");
5
+ const stream_1 = require("stream");
6
+ const work_task_1 = require("../planner/work-task");
7
+ const execute_docker_1 = require("./execute-docker");
8
+ const execution_steps_1 = require("./execution-steps");
9
+ const stat_beneath_1 = require("../file/stat-beneath");
10
+ const server_tools_1 = require("../docker/server-tools");
11
+ const get_container_binds_1 = require("./get-container-binds");
12
+ /**
13
+ * On a server, what a started container binds is what the run's files hold. The engine
14
+ * resolves a bind's path as the container starts and says nothing about what it found, so
15
+ * once it started, every folder and file the container sees at a bind is compared with the
16
+ * one of the run's files by device and inode. The host side is read from the run's root
17
+ * one name at a time without following a link (statBeneath); the container side by the
18
+ * server's own busybox (server-tools.ts), which is also all that has run in the container
19
+ * so far. A container that sees anything else is refused. Off a server nothing is checked:
20
+ * the files are the user's own.
21
+ */
22
+ async function assertContainerBinds(item, environment, container, binds, tools) {
23
+ const root = (0, execution_steps_1.hostedRoot)(environment);
24
+ if (!root) {
25
+ return;
26
+ }
27
+ if (!tools) {
28
+ throw new Error(`${item.name}: the server's tools are not in the container`);
29
+ }
30
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
31
+ const checks = binds
32
+ .filter((b) => (0, path_1.isAbsolute)(b.localPath))
33
+ .map(async (bind) => {
34
+ const expected = await (0, stat_beneath_1.statBeneath)(root, bind.localPath).catch((e) => {
35
+ throw new Error(`${item.name}: ${e.message}`);
36
+ });
37
+ const seen = await readIdentity(container, tools, (0, execute_docker_1.convertToPosixPath)(bind.containerPath));
38
+ if (seen.error !== undefined) {
39
+ throw new Error(`${item.name}: can not check what the container binds at ${bind.containerPath}: ${seen.error}`);
40
+ }
41
+ if (seen.identity !== `${expected.dev} ${expected.ino}`) {
42
+ throw new Error(`${item.name}: the container does not bind the files of the run at ${bind.containerPath}`);
43
+ }
44
+ });
45
+ const results = await Promise.allSettled(checks);
46
+ const failed = results.find((r) => r.status === 'rejected');
47
+ if (failed) {
48
+ throw failed.reason;
49
+ }
50
+ }
51
+ exports.assertContainerBinds = assertContainerBinds;
52
+ /**
53
+ * On a server, no source, output, mount, volume or secret file of an item may be where the
54
+ * server's tools are in a container (isServerToolsPath), where it would hide or replace them.
55
+ */
56
+ function refuseServerToolsPaths(item, environment) {
57
+ if (!(0, execution_steps_1.hostedRoot)(environment)) {
58
+ return;
59
+ }
60
+ const data = item.data;
61
+ const paths = [
62
+ ...((0, work_task_1.isContainerWorkTask)(data)
63
+ ? (0, get_container_binds_1.getContainerBinds)(item).map((b) => b.containerPath)
64
+ : [
65
+ ...data.src.map((s) => s.absolutePath),
66
+ ...data.mounts.map((m) => m.containerPath),
67
+ ...data.volumes.map((v) => v.containerPath),
68
+ ]),
69
+ ...data.secrets.flatMap((secret) => (secret.target.type === 'file' ? [secret.target.path] : [])),
70
+ ];
71
+ const over = paths.find((path) => (0, server_tools_1.isServerToolsPath)((0, execute_docker_1.convertToPosixPath)(path)));
72
+ if (over !== undefined) {
73
+ throw new Error(`${item.name}: ${over} is where the server keeps its tools in a container, nothing can be there`);
74
+ }
75
+ }
76
+ exports.refuseServerToolsPaths = refuseServerToolsPaths;
77
+ /**
78
+ * On a server's docker host, a task that adds capabilities runs in a sandboxed runtime
79
+ * (`backend.capabilities.runtime`, such as gVisor) that reports its own device numbers, so
80
+ * what such a container binds can not be compared with the run's files (assertContainerBinds).
81
+ * Until it can, such a task may bind no files of the run: it is refused before its container
82
+ * is created.
83
+ */
84
+ function refuseUncheckableBinds(item, environment) {
85
+ if (!(0, execution_steps_1.hostedRoot)(environment) || item.data.capAdd.length === 0) {
86
+ return;
87
+ }
88
+ const bound = (0, get_container_binds_1.getContainerBinds)(item).find((b) => (0, path_1.isAbsolute)(b.localPath));
89
+ if (bound) {
90
+ throw new Error(`${item.name}: adds capabilities and binds ${bound.containerPath}; on a server's docker host a task that adds capabilities can not bind files of the run`);
91
+ }
92
+ }
93
+ exports.refuseUncheckableBinds = refuseUncheckableBinds;
94
+ // The device and inode of `path` inside the container, as the server's busybox reads them.
95
+ async function readIdentity(container, tools, path) {
96
+ const result = await runServerCommand(container, tools, ['stat', '-c', '%d %i', '--', path]);
97
+ if (result.error !== undefined) {
98
+ return { error: result.error };
99
+ }
100
+ const match = result.stdout.match(/^(\d+) (\d+)\s*$/);
101
+ return match
102
+ ? { identity: `${BigInt(match[1])} ${BigInt(match[2])}` }
103
+ : { error: `unexpected answer ${result.stdout.trim()}` };
104
+ }
105
+ exports.readIdentity = readIdentity;
106
+ // Lets the command of a service's container run, once its binds are checked (see gatedCommand).
107
+ async function openServiceGate(container, tools) {
108
+ const result = await runServerCommand(container, tools, (0, server_tools_1.openGateArguments)(tools));
109
+ if (result.error !== undefined) {
110
+ throw new Error(`the service could not be started: ${result.error}`);
111
+ }
112
+ }
113
+ exports.openServiceGate = openServiceGate;
114
+ // Runs a tool of the server's busybox in the container, as root.
115
+ // What it says is kept free of the name of the tools' folder.
116
+ async function runServerCommand(container, tools, command, timeoutMs = 10000) {
117
+ try {
118
+ const exec = await container.exec({
119
+ Cmd: (0, server_tools_1.withServerBusybox)(tools, command),
120
+ AttachStdout: true,
121
+ AttachStderr: true,
122
+ User: '0',
123
+ });
124
+ const stream = await exec.start({ hijack: true, stdin: false });
125
+ const stdout = new stream_1.PassThrough();
126
+ const stderr = new stream_1.PassThrough();
127
+ const chunks = [];
128
+ const errors = [];
129
+ stdout.on('data', (chunk) => chunks.push(chunk));
130
+ stderr.on('data', (chunk) => errors.push(chunk));
131
+ container.modem.demuxStream(stream, stdout, stderr);
132
+ let timer;
133
+ const finished = await Promise.race([
134
+ new Promise((resolve) => {
135
+ stream.on('end', () => resolve(true));
136
+ stream.on('error', () => resolve(false));
137
+ }),
138
+ new Promise((resolve) => {
139
+ timer = setTimeout(() => resolve(false), timeoutMs);
140
+ }),
141
+ ]);
142
+ clearTimeout(timer);
143
+ if (!finished) {
144
+ stream.destroy();
145
+ return { error: `no answer within ${timeoutMs / 1000}s` };
146
+ }
147
+ const result = await exec.inspect();
148
+ if (result.ExitCode !== 0) {
149
+ const error = Buffer.concat(errors).toString('utf8').trim() || `exit code ${result.ExitCode}`;
150
+ return { error: (0, server_tools_1.hideServerTools)(error, tools) };
151
+ }
152
+ return { stdout: Buffer.concat(chunks).toString('utf8') };
153
+ }
154
+ catch (e) {
155
+ return { error: (0, server_tools_1.hideServerTools)(e.message, tools) };
156
+ }
157
+ }
158
+ //# sourceMappingURL=check-container-binds.js.map