hammerkit 2.0.0-next.15 → 2.0.0-next.17

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.
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.readLastResolvedRecord = exports.writeLastResolvedRecord = exports.getLastResolvedFile = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const path_1 = require("path");
6
+ const within_root_1 = require("../file/within-root");
6
7
  const work_task_cache_description_1 = require("../optimizer/work-task-cache-description");
7
8
  // Stored in the project's `.hammerkit` dir (local-first, alongside the local
8
9
  // runtime state file) keyed by task name. The name is sanitized for the
@@ -14,8 +15,18 @@ function getLastResolvedFile(task) {
14
15
  return (0, path_1.join)(task.data.cwd, '.hammerkit', 'last-resolved', `${sanitized}-${suffix}.json`);
15
16
  }
16
17
  exports.getLastResolvedFile = getLastResolvedFile;
18
+ // The record is written into the project, which a server does not own: a checkout or a
19
+ // sandbox whose `.hammerkit` may be a link a contributor committed or a task made, and the
20
+ // record would overwrite whatever it points at. A server writes none (`explain` runs where
21
+ // the project is), and on a machine a record that would go through a link is left out.
17
22
  async function writeLastResolvedRecord(environment, task, record) {
23
+ if (environment.hosted) {
24
+ return;
25
+ }
18
26
  const file = getLastResolvedFile(task);
27
+ if (await (0, within_root_1.findRootEscape)(task.data.cwd, file)) {
28
+ return;
29
+ }
19
30
  await environment.file.createDirectory((0, path_1.join)(task.data.cwd, '.hammerkit', 'last-resolved'));
20
31
  const payload = {
21
32
  taskId: task.id(),
@@ -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());
@@ -112,7 +112,16 @@ async function dockerService(docker, item, options, environment) {
112
112
  const relay = await network.connect(container);
113
113
  const stream = await container.attach({ stream: true, stdout: true, stderr: true });
114
114
  (0, stream_1.logStream)(item.status, stream);
115
+ // the engine resolves the paths it binds when the container starts: check them right before, and after
116
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
115
117
  await container.start();
118
+ const started = container;
119
+ await (0, execution_steps_1.refuseHostLinks)(item, environment).catch(async (e) => {
120
+ // not kept, not even for a daemon
121
+ container = null;
122
+ await (0, remove_container_1.removeContainer)(started);
123
+ throw e;
124
+ });
116
125
  const published = options.publishPorts ? await readPublishedPorts(relay ?? container, item.data.ports) : [];
117
126
  if (!item.data.healthcheck || !options.waitForReady) {
118
127
  options.state.set({
@@ -99,6 +99,8 @@ async function dockerTask(docker, item, environment, options) {
99
99
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
100
100
  const itemNetwork = network;
101
101
  const succeeded = await (0, using_container_1.usingContainer)(docker, item, containerOptions, async (container) => {
102
+ // the engine resolved the paths it binds as the container started: once more, before anything runs in it
103
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
102
104
  await itemNetwork.connect(container);
103
105
  await (0, execution_steps_1.setUserPermissions)(item, container, environment);
104
106
  for (const generate of outputsToReset.filter((g) => !g.isFile)) {
@@ -20,8 +20,9 @@ exports.hostedRoot = hostedRoot;
20
20
  * reads or writes for it, has to stay inside the run's files with no link on the way:
21
21
  * tasks of this or an earlier run on a sandbox, or the commit of a ref, could have left
22
22
  * one pointing anywhere on the server. The runtime checks before an item runs; this is
23
- * checked again right before a container is made and before outputs are copied, after
24
- * other tasks of the run had their turn.
23
+ * checked again right before a container is made, after it started (the engine resolves
24
+ * the paths it binds as it starts) and before outputs are copied, after other tasks of the
25
+ * run had their turn.
25
26
  */
26
27
  async function refuseHostLinks(item, environment) {
27
28
  const root = hostedRoot(environment);
@@ -8,7 +8,9 @@ const path_1 = require("path");
8
8
  * checkout, a sandbox), or null when it stays inside. A path may not lead out of the
9
9
  * root, and none of its parts that exist may be a symbolic link, since docker, tar
10
10
  * and the file system would follow it wherever it points. A part that doesn't exist
11
- * yet is fine, it can't be a link until something makes it.
11
+ * yet is fine, it can't be a link until something makes it. A part that can't be looked
12
+ * at (a folder the server may not read) is not: what reads it later, a rootful docker,
13
+ * may well follow a link behind it.
12
14
  */
13
15
  async function findRootEscape(root, path) {
14
16
  const inside = (0, path_1.relative)((0, path_1.resolve)(root), (0, path_1.resolve)(root, path));
@@ -21,9 +23,16 @@ async function findRootEscape(root, path) {
21
23
  let current = (0, path_1.resolve)(root);
22
24
  for (const part of inside.split(path_1.sep)) {
23
25
  current = (0, path_1.join)(current, part);
24
- const stats = await (0, promises_1.lstat)(current).catch(() => undefined);
25
- if (!stats) {
26
- return null;
26
+ let stats;
27
+ try {
28
+ stats = await (0, promises_1.lstat)(current);
29
+ }
30
+ catch (e) {
31
+ const code = e.code;
32
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
33
+ return null;
34
+ }
35
+ return `can not be checked for symbolic links at ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')} (${code ?? e})`;
27
36
  }
28
37
  if (stats.isSymbolicLink()) {
29
38
  return `goes through the symbolic link ${(0, path_1.relative)(root, current).split(path_1.sep).join('/')}`;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = void 0;
3
+ exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.getRun = exports.followRun = exports.getMoveTarget = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
4
4
  const path_1 = require("path");
5
5
  const token_source_1 = require("../remote/token-source");
6
6
  // a write carries up to 32 MiB
@@ -9,6 +9,9 @@ const TIMEOUT_MS = 60000;
9
9
  const POLL_WAIT = '1s';
10
10
  // a cancelled run waits this long for the server to take the cancel, before it gives up
11
11
  const CANCEL_WAIT_MS = 10000;
12
+ // what is read of a page of an endpoint: an app can answer with any amount, and only
13
+ // the start of it is shown
14
+ exports.MAX_ENDPOINT_BYTES = 256 * 1024;
12
15
  class SandboxClientError extends Error {
13
16
  constructor(message, status) {
14
17
  super(message);
@@ -213,9 +216,10 @@ class SandboxClient {
213
216
  }
214
217
  /**
215
218
  * A page of an endpoint of a service run, as the caller sees it: only at an address the
216
- * server gave the run, so the token goes to the server and nowhere else.
219
+ * server gave the run, so the token goes to the server and nowhere else. At most
220
+ * `maxBytes` of the body are read, `truncated` tells when there was more.
217
221
  */
218
- async fetchEndpoint(id, path, service, signal) {
222
+ async fetchEndpoint(id, path, service, signal, maxBytes = exports.MAX_ENDPOINT_BYTES) {
219
223
  const run = await this.getRun(id);
220
224
  const endpoint = run.up?.endpoints.find((candidate) => service === undefined || candidate.service === service);
221
225
  if (!endpoint) {
@@ -232,11 +236,13 @@ class SandboxClient {
232
236
  redirect: 'manual',
233
237
  signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]),
234
238
  });
239
+ const { text, truncated } = await readTextUpTo(response, maxBytes);
235
240
  return {
236
241
  url: url.toString(),
237
242
  status: response.status,
238
243
  type: response.headers.get('content-type') ?? '',
239
- body: await response.text(),
244
+ body: text,
245
+ truncated,
240
246
  };
241
247
  }
242
248
  /**
@@ -305,6 +311,35 @@ function oneAtATime() {
305
311
  };
306
312
  }
307
313
  exports.oneAtATime = oneAtATime;
314
+ // The body of an answer as text, read up to `maxBytes` and then cancelled, so a page
315
+ // of any size takes no more memory than that. A character cut at the limit is left out.
316
+ async function readTextUpTo(response, maxBytes) {
317
+ if (!response.body) {
318
+ return { text: '', truncated: false };
319
+ }
320
+ const reader = response.body.getReader();
321
+ const decoder = new TextDecoder();
322
+ let text = '';
323
+ let read = 0;
324
+ try {
325
+ for (;;) {
326
+ const { done, value } = await reader.read();
327
+ if (done) {
328
+ return { text: text + decoder.decode(), truncated: false };
329
+ }
330
+ const room = maxBytes - read;
331
+ if (value.byteLength > room) {
332
+ return { text: text + decoder.decode(value.subarray(0, room), { stream: true }), truncated: true };
333
+ }
334
+ read += value.byteLength;
335
+ text += decoder.decode(value, { stream: true });
336
+ }
337
+ }
338
+ finally {
339
+ await reader.cancel().catch(() => undefined);
340
+ }
341
+ }
342
+ exports.readTextUpTo = readTextUpTo;
308
343
  // a run that is over, its state does not change any more
309
344
  exports.FINAL_RUN_STATES = ['succeeded', 'failed', 'cancelled', 'rejected'];
310
345
  async function submitRun(connection, request) {
@@ -120,8 +120,8 @@ exports.SERVICE_TOOLS = [
120
120
  required: ['run', 'path'],
121
121
  async call(client, args, signal) {
122
122
  const page = await client.fetchEndpoint(args.run, args.path, args.service || undefined, signal);
123
- const body = page.body.length > MAX_PAGE_CHARS
124
- ? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.body.length} characters, the first ${MAX_PAGE_CHARS} shown)`
123
+ const body = page.truncated || page.body.length > MAX_PAGE_CHARS
124
+ ? `${page.body.slice(0, MAX_PAGE_CHARS)}\n… (${page.truncated ? 'more than ' : ''}${page.body.length} characters, the first ${Math.min(MAX_PAGE_CHARS, page.body.length)} shown)`
125
125
  : page.body;
126
126
  return [`GET ${page.url}: ${page.status}${page.type ? ` (${page.type})` : ''}`, '', body].join('\n');
127
127
  },
@@ -17,6 +17,8 @@ const ensure_kubernetes_persistent_volume_claim_exists_1 = require("./ensure-kub
17
17
  const stream_1 = require("stream");
18
18
  const job_placement_1 = require("./job-placement");
19
19
  const assert_item_paths_1 = require("../planner/utils/assert-item-paths");
20
+ const transfer_tools_1 = require("./transfer-tools");
21
+ const network_policy_1 = require("./network-policy");
20
22
  // A previous run that crashed between creating an upload/download pod and its
21
23
  // `finally` cleanup leaves a pod behind under the same deterministic name. apply()
22
24
  // would then patch that stale pod in place — and if it is stuck in a terminal
@@ -102,6 +104,12 @@ signal, fn) {
102
104
  }
103
105
  return array;
104
106
  }, []);
107
+ // its tools are in a folder of their own, which no output may be in or over: it would
108
+ // replace them with what the task wrote
109
+ const overTools = mounts.find((mount) => (0, transfer_tools_1.isTransferToolsPath)(mount.mountPath));
110
+ if (overTools) {
111
+ throw new Error(`${service.name}: an output can not be at ${overTools.mountPath}, ${transfer_tools_1.TRANSFER_TOOLS_PATH} is the folder of hammerkit's tools`);
112
+ }
105
113
  // only the claims it mounts: one of a dep it doesn't read would only bind where it goes
106
114
  const volumes = persistence.volumes.filter((volume) => mounts.some((mount) => mount.name === volume.name));
107
115
  // Guarantee the claims exist right before scheduling the pod that mounts
@@ -123,7 +131,12 @@ signal, fn) {
123
131
  metadata: {
124
132
  namespace: env.namespace,
125
133
  name,
126
- labels: { ...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)), ...claims.labels },
134
+ labels: {
135
+ ...(serving ? (0, job_placement_1.getRunLabels)(env) : (0, resources_1.getItemLabels)(service, env)),
136
+ ...claims.labels,
137
+ // on a server it reaches nothing and nothing reaches it (see getNamespacePolicies)
138
+ ...(env.server ? (0, network_policy_1.getTransferNetworkLabels)() : {}),
139
+ },
127
140
  annotations: {
128
141
  'hammerkit.dev/version': (0, version_1.getVersion)(),
129
142
  },
@@ -138,18 +151,20 @@ signal, fn) {
138
151
  ...(0, job_placement_1.getPodPlacement)(env.server, 'pool' in service.data ? service.data.pool : undefined),
139
152
  }
140
153
  : {}),
154
+ initContainers: [(0, transfer_tools_1.getTransferToolsInitContainer)()],
141
155
  containers: [
142
156
  {
143
157
  name: 'volume',
144
- image: 'alpine',
145
- command: ['sh'],
158
+ image: transfer_tools_1.HELPER_TOOLS_IMAGE,
159
+ command: (0, transfer_tools_1.inTransferPod)(['sh']),
146
160
  tty: true,
147
- volumeMounts: mounts,
161
+ env: transfer_tools_1.TRANSFER_TOOLS_ENV,
162
+ volumeMounts: [...mounts, transfer_tools_1.TRANSFER_TOOLS_MOUNT],
148
163
  resources: exports.TRANSFER_POD_RESOURCES,
149
164
  ...(0, job_placement_1.getContainerSecurity)(env),
150
165
  },
151
166
  ],
152
- volumes,
167
+ volumes: [...volumes, ...transfer_tools_1.TRANSFER_TOOLS_VOLUMES],
153
168
  },
154
169
  };
155
170
  service.status.write('debug', `create pod ${name}`);
@@ -194,7 +209,7 @@ exports.clearClaim = clearClaim;
194
209
  // Runs `command` in the upload pod `pod`: what failed, or null when it went well
195
210
  async function execInPod(instance, env, pod, command) {
196
211
  let failure = null;
197
- const res = await instance.exec.exec(env.namespace, pod, 'volume', command, process.stdout, process.stderr, null, false, (status) => {
212
+ const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), process.stdout, process.stderr, null, false, (status) => {
198
213
  if (status.status !== 'Success') {
199
214
  failure = status.message ?? status.reason ?? 'unknown';
200
215
  }
@@ -457,7 +472,7 @@ options = {}) {
457
472
  const data = packSource(source);
458
473
  service.status.write('info', `upload ${source.localPath}`);
459
474
  const targetPath = `/dev/hammerkit/${service.id()}`;
460
- const res = await instance.exec.exec(env.namespace, name, 'volume', ['tar', 'xf', '-', '-C', targetPath], process.stdout, process.stderr, data, false, (status) => {
475
+ const res = await instance.exec.exec(env.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(['tar', 'xf', '-', '-C', targetPath]), process.stdout, process.stderr, data, false, (status) => {
461
476
  service.status.write('debug', `upload ${source.localPath} to ${name}: ${status}`);
462
477
  });
463
478
  await new Promise((resolve, reject) => {