hammerkit 2.0.0-next.16 → 2.0.0-next.18

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.
@@ -114,15 +114,21 @@ class RegistryClient {
114
114
  // on some Node versions.
115
115
  async request(method, urlOrPath, init = {}) {
116
116
  const url = urlOrPath.startsWith('http') ? urlOrPath : this.url(urlOrPath);
117
+ // the credentials are the registry's: an upload location or a next page elsewhere (another
118
+ // host, another port, or http in place of https) gets none, as fetch does on a redirect
119
+ const own = new URL(url).origin === new URL(this.url('')).origin;
117
120
  const send = () => fetch(url, {
118
121
  method,
119
- headers: { ...(init.headers ?? {}), ...(this.authorization ? { authorization: this.authorization } : {}) },
122
+ headers: {
123
+ ...(init.headers ?? {}),
124
+ ...(own && this.authorization ? { authorization: this.authorization } : {}),
125
+ },
120
126
  // BodyInit of Node's fetch, also when the dashboard checks these types with the DOM's
121
127
  body: init.body?.(),
122
128
  redirect: init.redirect ?? 'follow',
123
129
  });
124
130
  let response = await send();
125
- if (response.status === 401 && (await this.authenticate(response.headers.get('www-authenticate')))) {
131
+ if (own && response.status === 401 && (await this.authenticate(response.headers.get('www-authenticate')))) {
126
132
  await response.body?.cancel();
127
133
  response = await send();
128
134
  }
@@ -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;
@@ -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;
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeCommand = exports.processEnv = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const os_1 = require("os");
6
- const log_1 = require("../log");
6
+ const line_splitter_1 = require("../utils/line-splitter");
7
7
  const abort_1 = require("./abort");
8
8
  const abort_event_1 = require("../utils/abort-event");
9
9
  const environment_config_1 = require("../utils/environment-config");
@@ -43,25 +43,19 @@ async function executeCommand(status, abortSignal, cwd, command, envs, environme
43
43
  // they would keep running and holding the output open
44
44
  detached: !windows,
45
45
  });
46
- // decode across chunk boundaries, so a multi-byte character split between
47
- // two chunks stays intact
48
- ps.stdout?.setEncoding('utf8');
49
- ps.stderr?.setEncoding('utf8');
50
- ps.stdout?.on('data', async (data) => {
51
- for (const log of (0, log_1.getLogs)(data)) {
52
- status.console('stdout', log);
53
- }
54
- });
55
- ps.stderr?.on('data', async (data) => {
56
- for (const log of (0, log_1.getLogs)(data)) {
57
- status.console('stderr', log);
58
- }
59
- });
46
+ // a line that two chunks split is logged once it ends, whole: a multi-byte character
47
+ // stays intact, and so does a secret value, which is masked per line
48
+ const stdout = (0, line_splitter_1.lineSplitter)((line) => status.console('stdout', line));
49
+ const stderr = (0, line_splitter_1.lineSplitter)((line) => status.console('stderr', line));
50
+ ps.stdout?.on('data', (data) => stdout.write(data));
51
+ ps.stderr?.on('data', (data) => stderr.write(data));
60
52
  ps.on('error', (err) => {
61
53
  reject(err);
62
54
  });
63
55
  ps.on('close', (code) => {
64
56
  abortListener.close();
57
+ stdout.end();
58
+ stderr.end();
65
59
  if (abortSignal.aborted) {
66
60
  reject(new abort_1.AbortError());
67
61
  return;
@@ -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) => {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
3
+ exports.getOpenNetworkGate = exports.OPEN_NETWORK_GATE_SETTING = exports.METADATA_ADDRESS = exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
4
+ const net_1 = require("net");
4
5
  const egress_proxy_1 = require("../network/egress-proxy");
5
6
  // Some network plugins (kind's kindnet among them) enforce a NetworkPolicy a
6
7
  // moment after a pod started, so a limited pod's first connections could
@@ -8,6 +9,9 @@ const egress_proxy_1 = require("../network/egress-proxy");
8
9
  // the pod no longer reaches the cluster DNS, which the policy of every limited
9
10
  // item denies, so the item's own containers start only once the policy holds.
10
11
  // A policy that never takes hold fails the pod instead of running it open.
12
+ // A pod with an open network on a server is limited too, by the policy of its
13
+ // namespace, which denies it the cloud's metadata address among others: its gate
14
+ // waits until that address is out of reach instead (see getOpenNetworkGate).
11
15
  // A script for `node -e` in the proxy's image, like the proxy.
12
16
  exports.NETWORK_GATE_TIMEOUT_MS = 60000;
13
17
  // the name of the gate's init container
@@ -20,23 +24,30 @@ const resolvConf = process.env.HAMMERKIT_GATE_RESOLV_CONF || '/etc/resolv.conf'
20
24
  const port = parseInt(process.env.HAMMERKIT_GATE_PORT || '53', 10)
21
25
  const deadline = Date.now() + parseInt(process.env.HAMMERKIT_GATE_TIMEOUT_MS || '${exports.NETWORK_GATE_TIMEOUT_MS}', 10)
22
26
  function fail(message) {
27
+ if (process.env.HAMMERKIT_GATE_HINT) {
28
+ message += ' (' + process.env.HAMMERKIT_GATE_HINT + ')'
29
+ }
23
30
  process.stderr.write('hammerkit: ' + message + '\\n')
24
31
  try {
25
32
  fs.writeFileSync('/dev/termination-log', 'hammerkit: ' + message)
26
33
  } catch (e) {}
27
34
  process.exit(1)
28
35
  }
29
- let conf = ''
30
- try {
31
- conf = fs.readFileSync(resolvConf, 'utf8')
32
- } catch (e) {}
33
- const match = /^nameserver\\s+(\\S+)/m.exec(conf)
34
- if (!match) {
35
- fail('the pod has no cluster DNS, so its network policy can not be checked')
36
+ const probeMs = parseInt(process.env.HAMMERKIT_GATE_PROBE_MS || '2000', 10)
37
+ let nameserver = process.env.HAMMERKIT_GATE_HOST
38
+ if (!nameserver) {
39
+ let conf = ''
40
+ try {
41
+ conf = fs.readFileSync(resolvConf, 'utf8')
42
+ } catch (e) {}
43
+ const match = /^nameserver\\s+(\\S+)/m.exec(conf)
44
+ if (!match) {
45
+ fail('the pod has no cluster DNS, so its network policy can not be checked')
46
+ }
47
+ nameserver = match[1]
36
48
  }
37
- const nameserver = match[1]
38
49
  function attempt() {
39
- const socket = net.connect({ host: nameserver, port, timeout: 2000 })
50
+ const socket = net.connect({ host: nameserver, port, timeout: probeMs })
40
51
  socket.once('connect', () => {
41
52
  socket.destroy()
42
53
  if (Date.now() > deadline) {
@@ -58,14 +69,66 @@ exports.HELPER_SECURITY_CONTEXT = {
58
69
  readOnlyRootFilesystem: true,
59
70
  capabilities: { drop: ['ALL'] },
60
71
  };
61
- function getNetworkGateContainer() {
72
+ // how long the gate of an open pod waits for an answer of its target: a link-local
73
+ // address answers at once, when it is reached at all
74
+ const OPEN_GATE_PROBE_MS = 1000;
75
+ // `target`: the address of an open pod's gate (getOpenNetworkGate); without it, the
76
+ // cluster DNS a limited pod is denied
77
+ function getNetworkGateContainer(target) {
62
78
  return {
63
79
  name: exports.NETWORK_GATE_CONTAINER,
64
80
  image: egress_proxy_1.EGRESS_PROXY_IMAGE,
65
81
  command: ['node', '-e', exports.NETWORK_GATE_SCRIPT],
82
+ ...(target
83
+ ? {
84
+ env: [
85
+ { name: 'HAMMERKIT_GATE_HOST', value: target.host },
86
+ { name: 'HAMMERKIT_GATE_PORT', value: `${target.port}` },
87
+ { name: 'HAMMERKIT_GATE_PROBE_MS', value: `${OPEN_GATE_PROBE_MS}` },
88
+ {
89
+ name: 'HAMMERKIT_GATE_HINT',
90
+ value: `the server's ${exports.OPEN_NETWORK_GATE_SETTING} points this wait at another address ` +
91
+ 'the namespace denies, or turns it off with false',
92
+ },
93
+ ],
94
+ }
95
+ : {}),
66
96
  securityContext: exports.HELPER_SECURITY_CONTEXT,
67
97
  resources: { limits: { memory: '64Mi' } },
68
98
  };
69
99
  }
70
100
  exports.getNetworkGateContainer = getNetworkGateContainer;
101
+ // The metadata endpoint of the clouds, which hands out the node's identity
102
+ exports.METADATA_ADDRESS = '169.254.169.254';
103
+ // the setting of the server that turns the gate of open pods off or points it elsewhere
104
+ exports.OPEN_NETWORK_GATE_SETTING = 'backend.openNetworkGate';
105
+ /**
106
+ * The gate of the pods with an open network on a server: they wait until they no longer
107
+ * reach an address the policy of their namespace denies them, by default the metadata
108
+ * endpoint (`backend.deniedEgress` covers it). The operator points it elsewhere, or turns
109
+ * it off with `false` (`backend.openNetworkGate`). None when the operator did not state that
110
+ * the cluster enforces NetworkPolicy, or when the address isn't denied or is allowed: the
111
+ * gate would never open.
112
+ */
113
+ function getOpenNetworkGate(backend) {
114
+ if (backend.networkPolicy !== 'enforced' || backend.openNetworkGate === false) {
115
+ return undefined;
116
+ }
117
+ const target = backend.openNetworkGate ?? { host: exports.METADATA_ADDRESS, port: 80 };
118
+ const covers = (ranges) => {
119
+ const list = new net_1.BlockList();
120
+ for (const range of ranges) {
121
+ const [address, prefix] = range.split('/');
122
+ if ((0, net_1.isIPv4)(address)) {
123
+ list.addSubnet(address, prefix === undefined ? 32 : parseInt(prefix, 10), 'ipv4');
124
+ }
125
+ }
126
+ return list.check(target.host, 'ipv4');
127
+ };
128
+ if (!covers(backend.deniedEgress) || covers(backend.allowedEgress)) {
129
+ return undefined;
130
+ }
131
+ return target;
132
+ }
133
+ exports.getOpenNetworkGate = getOpenNetworkGate;
71
134
  //# sourceMappingURL=network-gate.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.PROXY_OF_SANDBOX_LABEL = exports.RUN_LABEL = void 0;
3
+ exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.getTransferNetworkLabels = exports.TRANSFER_LABEL = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.PROXY_OF_SANDBOX_LABEL = exports.RUN_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const stream_1 = require("stream");
6
6
  const readline_1 = require("readline");
@@ -35,6 +35,14 @@ const POD_END_POLL_MS = 500;
35
35
  exports.NETWORK_LABEL = 'hammerkit.dev/network';
36
36
  exports.NETWORK_LIMITED = 'limited';
37
37
  exports.NETWORK_PROXY = 'proxy';
38
+ // on the pods that copy files into and out of a claim on a server: they need no network, so
39
+ // the policies of the caller's namespace for open pods leave them out (`limited`), and one
40
+ // of its own lets nothing in or out (see getNamespacePolicies)
41
+ exports.TRANSFER_LABEL = 'hammerkit.dev/transfer';
42
+ function getTransferNetworkLabels() {
43
+ return { [exports.NETWORK_LABEL]: exports.NETWORK_LIMITED, [exports.TRANSFER_LABEL]: 'true' };
44
+ }
45
+ exports.getTransferNetworkLabels = getTransferNetworkLabels;
38
46
  function getNetworkLabels(env, item) {
39
47
  return env.server && (0, work_network_1.getEffectiveNetwork)(item.data).type !== 'open' ? { [exports.NETWORK_LABEL]: exports.NETWORK_LIMITED } : {};
40
48
  }
@@ -88,6 +96,13 @@ exports.getNetworkPolicyName = getNetworkPolicyName;
88
96
  function getItemPodLabels(item, scope) {
89
97
  return { [resources_1.ID_LABEL]: item.id(), ...(scope.run ? { [job_placement_1.RUN_LABEL]: scope.run } : {}) };
90
98
  }
99
+ // The pods of the item, but those that copy files into and out of its claims on a server,
100
+ // which carry its labels too: the policy of their namespace lets nothing in or out of them,
101
+ // and the item's policy doesn't widen it.
102
+ const NOT_TRANSFER = { key: exports.TRANSFER_LABEL, operator: 'DoesNotExist' };
103
+ function withoutTransferPods(labels) {
104
+ return { matchLabels: labels, matchExpressions: [NOT_TRANSFER] };
105
+ }
91
106
  function toSelector(labels) {
92
107
  return Object.entries(labels)
93
108
  .map(([key, value]) => `${key}=${value}`)
@@ -110,7 +125,7 @@ function getIngress(env, item) {
110
125
  // on a server, of this run: the runs of a caller share their namespace
111
126
  const run = (0, job_placement_1.getRunLabels)(env);
112
127
  const from = {
113
- matchExpressions: [{ key: resources_1.ID_LABEL, operator: 'In', values: ids }],
128
+ matchExpressions: [{ key: resources_1.ID_LABEL, operator: 'In', values: ids }, NOT_TRANSFER],
114
129
  ...(Object.keys(run).length > 0 ? { matchLabels: run } : {}),
115
130
  };
116
131
  // the client's name for `from`, a reserved word
@@ -133,12 +148,12 @@ function buildNetworkPolicy(env, item, network, scope, proxy = getRunProxy(item,
133
148
  ...(scope.owners ? { ownerReferences: scope.owners } : {}),
134
149
  },
135
150
  spec: {
136
- podSelector: { matchLabels: getItemPodLabels(item, scope) },
151
+ podSelector: withoutTransferPods(getItemPodLabels(item, scope)),
137
152
  policyTypes: ['Ingress', 'Egress'],
138
153
  ingress: getIngress(env, item),
139
154
  egress: [
140
155
  ...(needs.length > 0
141
- ? [{ to: needs.map((need) => ({ podSelector: { matchLabels: (0, resources_1.getItemLabels)(need.service, env) } })) }]
156
+ ? [{ to: needs.map((need) => ({ podSelector: withoutTransferPods((0, resources_1.getItemLabels)(need.service, env)) })) }]
142
157
  : []),
143
158
  ...(proxied
144
159
  ? [
@@ -172,7 +187,7 @@ function buildProxyPolicy(env, item, network, scope, proxy = getRunProxy(item, s
172
187
  policyTypes: ['Ingress'],
173
188
  ingress: [
174
189
  {
175
- _from: [{ podSelector: { matchLabels: getItemPodLabels(item, scope) } }],
190
+ _from: [{ podSelector: withoutTransferPods(getItemPodLabels(item, scope)) }],
176
191
  ports: (0, egress_proxy_1.getEgressProxyPorts)(network).map((port) => ({ protocol: 'TCP', port })),
177
192
  },
178
193
  ],
@@ -203,7 +218,9 @@ async function ensureKubernetesItemNetwork(instance, env, item, options) {
203
218
  // without the rights to manage NetworkPolicies, hammerkit never made one
204
219
  await removeKubernetesItemNetwork(instance, env, item, { run: null }, { ignoreForbidden: true });
205
220
  }
206
- return { env: [], secretEnv: [], hostAliases, initContainers: [], close() { } };
221
+ // on a server, the policy of its namespace limits it: it starts once that holds
222
+ const gate = env.server?.openGate && env.networkPolicyEnforced ? [(0, network_gate_1.getNetworkGateContainer)(env.server.openGate)] : [];
223
+ return { env: [], secretEnv: [], hostAliases, initContainers: gate, close() { } };
207
224
  }
208
225
  const secretHosts = options.secretHosts ?? [];
209
226
  if (secretHosts.length > 0 && options.sandbox) {
@@ -285,13 +302,18 @@ async function removeKubernetesItemNetwork(instance, env, item, scope, options =
285
302
  }
286
303
  }
287
304
  exports.removeKubernetesItemNetwork = removeKubernetesItemNetwork;
288
- // Waits until no pod with the labels runs or waits to run.
289
- async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_MS) {
305
+ // Waits until no pod with the labels (or of the label selector) runs or waits to run.
306
+ async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_MS, pollInterval = POD_END_POLL_MS,
307
+ // stops the wait: they count as not ended
308
+ signal) {
290
309
  const deadline = Date.now() + timeout;
291
310
  for (;;) {
311
+ if (signal?.aborted) {
312
+ return false;
313
+ }
292
314
  const pods = await instance.coreApi.listNamespacedPod({
293
315
  namespace: env.namespace,
294
- labelSelector: toSelector(labels),
316
+ labelSelector: typeof labels === 'string' ? labels : toSelector(labels),
295
317
  });
296
318
  if (pods.items.every((pod) => pod.status?.phase === 'Succeeded' || pod.status?.phase === 'Failed')) {
297
319
  return true;
@@ -299,7 +321,7 @@ async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_M
299
321
  if (Date.now() >= deadline) {
300
322
  return false;
301
323
  }
302
- await (0, sleep_1.sleep)(POD_END_POLL_MS);
324
+ await (0, sleep_1.sleep)(pollInterval);
303
325
  }
304
326
  }
305
327
  exports.awaitPodsEnded = awaitPodsEnded;
@@ -4,12 +4,18 @@ exports.getStaleItemSelector = exports.removeStaleItems = void 0;
4
4
  const job_placement_1 = require("./job-placement");
5
5
  const resources_1 = require("./resources");
6
6
  const apply_1 = require("./apply");
7
+ const network_policy_1 = require("./network-policy");
7
8
  /**
8
9
  * What a service run made for items it has no more, once it moved to another commit: the
9
10
  * Deployment, Service, Secret, policies and Jobs of a service or task whose id changed (a new
10
- * image, other volumes). Their claims stay, with the namespace of the run.
11
+ * image, other volumes). Their claims stay, with the namespace of the run. The policies go
12
+ * last, once the pods they limit ended: a pod that is still terminating would otherwise run
13
+ * a moment without its limits. When pods outlast the wait, the policies stay, and the next
14
+ * move or the end of the run removes them.
11
15
  */
12
- async function removeStaleItems(instance, env, ids) {
16
+ async function removeStaleItems(instance, env, ids,
17
+ // a run stopped while its old pods end: the policies stay, and go with the run
18
+ options = {}) {
13
19
  if (!env.server) {
14
20
  return;
15
21
  }
@@ -20,6 +26,13 @@ async function removeStaleItems(instance, env, ids) {
20
26
  await instance.batchApi.deleteCollectionNamespacedJob({ ...selector, propagationPolicy: 'Background' });
21
27
  await instance.coreApi.deleteCollectionNamespacedService(selector);
22
28
  await instance.coreApi.deleteCollectionNamespacedSecret(selector);
29
+ const ended = await (0, network_policy_1.awaitPodsEnded)(instance, env, labelSelector, options.podEndTimeout, options.podEndPollInterval, options.signal);
30
+ if (options.signal?.aborted) {
31
+ return;
32
+ }
33
+ if (!ended) {
34
+ throw new Error('pods of the previous commit are still running, so their network policies stay');
35
+ }
23
36
  const policies = await instance.objectApi.list('networking.k8s.io/v1', 'NetworkPolicy', namespace, undefined, undefined, undefined, undefined, labelSelector);
24
37
  for (const policy of policies.items) {
25
38
  const metadata = { name: policy.metadata?.name, namespace };
@@ -6,6 +6,7 @@ const log_1 = require("../log");
6
6
  const volumes_1 = require("./volumes");
7
7
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
8
8
  const claim_layout_1 = require("./claim-layout");
9
+ const transfer_tools_1 = require("./transfer-tools");
9
10
  // Unpacks the archive of an output that is a file to `$1`: by its content, since the name in
10
11
  // the archive is the file's and the one in the claim may carry a hash (see getClaimSubPath)
11
12
  exports.RESTORE_FILE = 'mkdir -p "$(dirname "$1")" && rm -rf "$1" && tar xzf - -O > "$1"';
@@ -49,13 +50,13 @@ options = {}) {
49
50
  // a claim made for this run (a server removes the claims of a run when it
50
51
  // ends) does not have the directory of the output yet
51
52
  let failure = null;
52
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', [
53
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)([
53
54
  'sh',
54
55
  '-c',
55
56
  files.has(generatedArchive.path) ? exports.RESTORE_FILE : 'mkdir -p "$1" && tar xzf - -C "$1"',
56
57
  'sh',
57
58
  targetPath,
58
- ], process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
59
+ ]), process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
59
60
  work.status.write('debug', `upload ${generatedArchive.filename} to ${name}: ${status.status}`);
60
61
  if (status.status !== 'Success') {
61
62
  failure = status.message ?? status.reason ?? 'unknown';