hammerkit 2.0.0-next.2 → 2.0.0-next.20

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 (111) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  7. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  8. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +19 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +27 -9
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +80 -11
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-source-environment.js +39 -0
  91. package/dist/server/run-worker.js +71 -9
  92. package/dist/server/runs.js +133 -7
  93. package/dist/server/sandbox-files.js +339 -55
  94. package/dist/server/sandbox-patch.js +43 -17
  95. package/dist/server/sandboxes.js +57 -23
  96. package/dist/server/server-config.js +28 -5
  97. package/dist/server/server.js +94 -16
  98. package/dist/server/service-runs.js +50 -5
  99. package/dist/server/sources.js +68 -11
  100. package/dist/server/timings.js +23 -3
  101. package/dist/utils/buffer-context.js +30 -20
  102. package/dist/utils/limit.js +30 -0
  103. package/dist/utils/line-splitter.js +52 -0
  104. package/dist/utils/read-lines.js +65 -0
  105. package/dist/utils/tar.js +51 -1
  106. package/dist/utils/units.js +36 -1
  107. package/dist/utils/web-links.js +34 -0
  108. package/package.json +1 -1
  109. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  110. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  111. package/dist/dashboard/favicon.svg +0 -1
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.followPodLogs = void 0;
3
+ exports.followPodLogs = exports.MAX_LOG_LINE_CHARS = void 0;
4
4
  const stream_1 = require("stream");
5
- const readline_1 = require("readline");
6
5
  const log_1 = require("../log");
6
+ const read_lines_1 = require("../utils/read-lines");
7
7
  // what is read of an instance of a container that already ended
8
8
  const MAX_ENDED_LOG_BYTES = 1024 * 1024;
9
+ // how often in a row the log of one instance is read again after its reading broke off at once
10
+ const MAX_READS = 20;
11
+ // the most of one line of a followed log that is held, its timestamp included
12
+ exports.MAX_LOG_LINE_CHARS = 64 * 1024;
13
+ // `timestamps: true` puts the time a line was written before it (RFC3339 with up to nine
14
+ // digits of a second), which says where a log that broke off got to
15
+ const TIMESTAMPED = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z(?: (.*))?$/;
9
16
  /**
10
17
  * Follows the log of a container in the pods of a selector, as `docker attach` does for a
11
18
  * service on Docker: the instance that runs as it writes, and an instance that ended before
@@ -14,7 +21,12 @@ const MAX_ENDED_LOG_BYTES = 1024 * 1024;
14
21
  */
15
22
  function followPodLogs(instance, namespace, labelSelector, container, onLine, options = {}) {
16
23
  const seen = new Set();
17
- const following = [];
24
+ const positions = new Map();
25
+ // the logs followed now, resolved when they end
26
+ const streams = new Map();
27
+ const following = new Map();
28
+ // the instances that ended, by the last look
29
+ const ended = new Set();
18
30
  const reading = new Set();
19
31
  let stopped = false;
20
32
  let failed = false;
@@ -34,28 +46,91 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
34
46
  const tracked = promise.catch(fail).finally(() => reading.delete(tracked));
35
47
  reading.add(tracked);
36
48
  };
37
- const readEnded = async (pod, previous) => {
49
+ const positionOf = (id) => {
50
+ let position = positions.get(id);
51
+ if (!position) {
52
+ position = { at: null, since: null, count: 0, reads: 0 };
53
+ positions.set(id, position);
54
+ }
55
+ return position;
56
+ };
57
+ // a reader of the log of one instance from where it got to: the lines read before, again
58
+ // at the start of a log read since their second, are passed over
59
+ const reader = (position) => {
60
+ const from = position.at;
61
+ const skip = position.count;
62
+ let atFrom = 0;
63
+ return (raw) => {
64
+ const match = TIMESTAMPED.exec(raw);
65
+ if (!match) {
66
+ onLine(raw);
67
+ return;
68
+ }
69
+ const at = `${match[1]}.${(match[2] ?? '').padEnd(9, '0')}`;
70
+ if (from !== null && at <= from) {
71
+ if (at < from || ++atFrom <= skip) {
72
+ return;
73
+ }
74
+ }
75
+ if (at === position.at) {
76
+ position.count++;
77
+ }
78
+ else {
79
+ position.at = at;
80
+ position.since = `${match[1]}Z`;
81
+ position.count = 1;
82
+ }
83
+ onLine(match[3] ?? '');
84
+ };
85
+ };
86
+ const readEnded = async (pod, id, previous) => {
87
+ const position = positionOf(id);
88
+ position.reads++;
38
89
  const log = await instance.coreApi.readNamespacedPodLog({
39
90
  name: pod,
40
91
  namespace,
41
92
  container,
42
93
  previous,
94
+ timestamps: true,
43
95
  limitBytes: MAX_ENDED_LOG_BYTES,
96
+ // this call takes no sinceTime: a minute more than since then, for clocks that differ
97
+ ...(position.since
98
+ ? { sinceSeconds: Math.max(1, Math.ceil((Date.now() - Date.parse(position.since)) / 1000) + 60) }
99
+ : {}),
44
100
  });
101
+ const read = reader(position);
45
102
  for (const line of String(log ?? '').split(/\r?\n/)) {
46
103
  if (line.length > 0) {
47
- onLine(line);
104
+ read(line);
48
105
  }
49
106
  }
50
107
  };
51
- const follow = async (pod) => {
108
+ const follow = async (pod, id) => {
109
+ const position = positionOf(id);
110
+ position.reads++;
52
111
  const output = new stream_1.PassThrough();
53
- let ended = false;
54
- // the instance ended or the request broke: a restarted one is looked for at once
112
+ const started = Date.now();
113
+ let over = false;
114
+ let done = () => undefined;
115
+ const stream = new Promise((resolve) => (done = resolve));
116
+ streams.set(id, stream);
117
+ // the instance ended or the request broke: it is looked at again at once, a restarted
118
+ // one followed, and what this one wrote after the break read from where it got to
55
119
  const end = () => {
56
- if (!ended) {
57
- ended = true;
120
+ if (!over) {
121
+ over = true;
58
122
  streaming--;
123
+ // a follow that lasted is cut now and then (a quiet stretch, a proxy): only reads
124
+ // that break off at once count against the limit
125
+ if (Date.now() - started >= 10000) {
126
+ position.reads = 0;
127
+ }
128
+ streams.delete(id);
129
+ following.delete(id);
130
+ done();
131
+ if (!stopped && position.reads < MAX_READS) {
132
+ seen.delete(id);
133
+ }
59
134
  wake();
60
135
  }
61
136
  };
@@ -64,11 +139,15 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
64
139
  end();
65
140
  }));
66
141
  output.on('end', end);
67
- (0, readline_1.createInterface)({ input: output }).on('line', (line) => onLine(line));
142
+ (0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(position));
68
143
  streaming++;
69
144
  let controller;
70
145
  try {
71
- controller = await instance.log.log(namespace, pod, container, output, { follow: true });
146
+ controller = await instance.log.log(namespace, pod, container, output, {
147
+ follow: true,
148
+ timestamps: true,
149
+ ...(position.since ? { sinceTime: position.since } : {}),
150
+ });
72
151
  }
73
152
  catch (e) {
74
153
  end();
@@ -78,7 +157,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
78
157
  controller.abort();
79
158
  }
80
159
  else {
81
- following.push(controller);
160
+ following.set(id, controller);
82
161
  }
83
162
  };
84
163
  const look = (pod) => {
@@ -91,22 +170,28 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
91
170
  // an instance that ended before this one, not seen while it ran: its lines go first
92
171
  let before = Promise.resolve();
93
172
  const last = status.lastState?.terminated?.containerID;
173
+ const current = status.containerID;
174
+ if (last) {
175
+ ended.add(last);
176
+ }
177
+ if (current && status.state?.terminated) {
178
+ ended.add(current);
179
+ }
94
180
  if (last && !seen.has(last)) {
95
181
  seen.add(last);
96
- before = readEnded(name, true).catch(fail);
182
+ before = readEnded(name, last, true).catch(fail);
97
183
  track(before);
98
184
  }
99
- const current = status.containerID;
100
185
  if (!current || seen.has(current)) {
101
186
  return;
102
187
  }
103
188
  if (status.state?.running) {
104
189
  seen.add(current);
105
- track(before.then(() => follow(name)));
190
+ track(before.then(() => follow(name, current)));
106
191
  }
107
192
  else if (status.state?.terminated) {
108
193
  seen.add(current);
109
- track(before.then(() => readEnded(name, false)));
194
+ track(before.then(() => readEnded(name, current, false)));
110
195
  }
111
196
  };
112
197
  const poll = async () => {
@@ -157,26 +242,40 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
157
242
  async settle() {
158
243
  await polling;
159
244
  await poll();
160
- // what follows a running instance never ends by itself
161
- const ended = [...reading];
162
- let wait;
163
- await Promise.race([
164
- Promise.all(ended),
165
- new Promise((resolve) => {
166
- wait = setTimeout(resolve, 5000);
167
- wait.unref?.();
168
- }),
169
- ]);
170
- clearTimeout(wait);
245
+ // what follows an instance that ended ends by itself once it has read all there is
246
+ const endedStreams = () => [...streams].filter(([id]) => ended.has(id));
247
+ await within(Promise.all([...reading, ...endedStreams().map(([, stream]) => stream)]), 5000);
248
+ // one still going after that is cut, and read from where it got to
249
+ const cut = endedStreams();
250
+ if (cut.length > 0) {
251
+ for (const [id] of cut) {
252
+ following.get(id)?.abort();
253
+ }
254
+ await within(Promise.all(cut.map(([, stream]) => stream)), 1000);
255
+ await poll();
256
+ await within(Promise.all([...reading]), 5000);
257
+ }
171
258
  },
172
259
  stop() {
173
260
  stopped = true;
174
261
  clearTimeout(timer);
175
- for (const controller of following.splice(0)) {
262
+ for (const controller of following.values()) {
176
263
  controller.abort();
177
264
  }
265
+ following.clear();
178
266
  },
179
267
  };
180
268
  }
181
269
  exports.followPodLogs = followPodLogs;
270
+ async function within(promise, ms) {
271
+ let wait;
272
+ await Promise.race([
273
+ promise,
274
+ new Promise((resolve) => {
275
+ wait = setTimeout(resolve, ms);
276
+ wait.unref?.();
277
+ }),
278
+ ]);
279
+ clearTimeout(wait);
280
+ }
182
281
  //# sourceMappingURL=follow-pod-logs.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evictKeptClaims = exports.sweepKeptClaims = exports.expireKeptClaims = exports.recordClaimState = exports.forgetClaimState = exports.useClaimState = exports.isKeptClaim = exports.getClaimName = exports.EXPIRES_ANNOTATION = exports.STATE_ANNOTATION = exports.KEPT_BY_LABEL = exports.VOLUME_SCOPE_LABEL = void 0;
3
+ exports.evictKeptClaims = exports.sweepKeptClaims = exports.expireKeptClaims = exports.recordClaimState = exports.forgetClaimState = exports.rememberedClaimState = exports.useClaimState = exports.isKeptClaim = exports.getClaimName = exports.EXPIRES_ANNOTATION = exports.STATE_ANNOTATION = exports.KEPT_BY_LABEL = exports.VOLUME_SCOPE_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const apply_1 = require("./apply");
6
6
  const sleep_1 = require("../utils/sleep");
@@ -98,6 +98,21 @@ async function annotate(instance, namespace, name, annotations) {
98
98
  throw e;
99
99
  }
100
100
  }
101
+ // The state key of the outputs whose folder is whole in the claim of a task of a service run
102
+ // (see getStateFilesDir), null when it names none (also while the claim is being removed),
103
+ // undefined when there is no claim. The run's namespace is its own, and only the run writes
104
+ // to the claim: it forgets the state before it writes, records it after.
105
+ async function rememberedClaimState(instance, kubernetes, name) {
106
+ const claim = await readClaim(instance, kubernetes.namespace, name);
107
+ if (!claim) {
108
+ return undefined;
109
+ }
110
+ if (claim.metadata?.deletionTimestamp) {
111
+ return null;
112
+ }
113
+ return claim.metadata?.annotations?.[exports.STATE_ANNOTATION] ?? null;
114
+ }
115
+ exports.rememberedClaimState = rememberedClaimState;
101
116
  // Before a task writes to its kept claim: the outputs in it stop being those of a state.
102
117
  // Whether the claim was there, with what an earlier run left in it.
103
118
  function forgetClaimState(instance, kubernetes, name) {
@@ -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.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");
@@ -21,7 +21,7 @@ const resources_1 = require("./resources");
21
21
  const PROXY_LABEL = 'hammerkit.dev/proxy-for';
22
22
  const NETWORK_OF_LABEL = 'hammerkit.dev/network-of';
23
23
  // on the proxy of a task on a sandbox: the sandbox, whose pod of files it stays with
24
- const PROXY_OF_SANDBOX_LABEL = 'hammerkit.dev/proxy-of-sandbox';
24
+ exports.PROXY_OF_SANDBOX_LABEL = 'hammerkit.dev/proxy-of-sandbox';
25
25
  const PROXY_READY_TIMEOUT_MS = 60000;
26
26
  // the token of the endpoints of secret providers, in a Secret named like the proxy
27
27
  const SECRET_TOKEN_KEY = 'token';
@@ -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
  }
@@ -77,7 +85,7 @@ exports.getSandboxProxy = getSandboxProxy;
77
85
  function getProxyLabels(env, item, proxy) {
78
86
  return {
79
87
  [NETWORK_OF_LABEL]: item.id(),
80
- ...(proxy.sandbox ? { [PROXY_OF_SANDBOX_LABEL]: proxy.sandbox.label } : (0, job_placement_1.getRunLabels)(env)),
88
+ ...(proxy.sandbox ? { [exports.PROXY_OF_SANDBOX_LABEL]: proxy.sandbox.label } : (0, job_placement_1.getRunLabels)(env)),
81
89
  };
82
90
  }
83
91
  function getNetworkPolicyName(item, scope) {
@@ -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;
@@ -543,7 +565,7 @@ async function removeSandboxProxies(instance, namespace, of, keep = () => false)
543
565
  const deployments = await instance.appsApi.listNamespacedDeployment({
544
566
  namespace,
545
567
  labelSelector: [
546
- `${PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
568
+ `${exports.PROXY_OF_SANDBOX_LABEL}=${of.sandbox}`,
547
569
  ...(of.item ? [`${NETWORK_OF_LABEL}=${of.item.id()}`] : []),
548
570
  ].join(','),
549
571
  });
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QuotaWait = exports.exceedsQuota = exports.getQuotaRefusal = exports.QUOTA_TIMEOUT = void 0;
4
+ const units_1 = require("../utils/units");
5
+ // How long a pod the quota of its namespace refuses waits for room before what needs it fails:
6
+ // a transfer pod in any case, a task's or service's only when no pod that will end holds the
7
+ // room (see QuotaWait)
8
+ exports.QUOTA_TIMEOUT = 10 * 60 * 1000;
9
+ // What a refusal of the quota of the namespace says, from where it starts: `exceeded quota:
10
+ // hammerkit, requested: limits.memory=4Gi, used: limits.memory=24Gi, limited: limits.memory=26Gi`
11
+ function getQuotaRefusal(message) {
12
+ const index = message ? message.search(/exceeded quota/i) : -1;
13
+ return message && index >= 0 ? message.slice(index) : null;
14
+ }
15
+ exports.getQuotaRefusal = getQuotaRefusal;
16
+ // A pod that asks for more of a resource than the quota allows at all never fits.
17
+ function exceedsQuota(refusal) {
18
+ const requested = readAmounts(/requested: (\S+?)(?:,\s|$)/.exec(refusal)?.[1]);
19
+ const limited = readAmounts(/limited: (\S+?)(?:,\s|$)/.exec(refusal)?.[1]);
20
+ return [...requested].some(([resource, amount]) => {
21
+ const limit = limited.get(resource);
22
+ return limit !== undefined && amount > limit;
23
+ });
24
+ }
25
+ exports.exceedsQuota = exceedsQuota;
26
+ // `limits.memory=4Gi,requests.cpu=1` → limits.memory 4Gi, requests.cpu 1
27
+ function readAmounts(list = '') {
28
+ const amounts = new Map();
29
+ for (const entry of list.split(',')) {
30
+ const [resource, value] = entry.split('=');
31
+ const amount = (0, units_1.parseQuantity)(value);
32
+ if (resource && amount !== undefined) {
33
+ amounts.set(resource, amount);
34
+ }
35
+ }
36
+ return amounts;
37
+ }
38
+ // A pod that will end and free its room: one of a Job (a task) or a pod of its own (the copy of
39
+ // a task's files). The pods of a Deployment (a service) stay as long as what needs them.
40
+ function willEnd(pod) {
41
+ if (pod.metadata?.deletionTimestamp || (pod.status?.phase !== 'Pending' && pod.status?.phase !== 'Running')) {
42
+ return false;
43
+ }
44
+ return !(pod.metadata?.ownerReferences ?? []).some((owner) => owner.kind === 'ReplicaSet');
45
+ }
46
+ /**
47
+ * The wait of a pod the quota of its namespace refuses. It is told what the quota refused,
48
+ * fails at once when the pod asks for more than the quota allows at all, and after `timeout`
49
+ * goes on waiting only while a pod that will end (a task's, another run's) holds room in the
50
+ * namespace: when only services hold it, they wait for what waits for them, and it fails.
51
+ */
52
+ class QuotaWait {
53
+ constructor(instance, env, options) {
54
+ this.instance = instance;
55
+ this.env = env;
56
+ this.options = options;
57
+ this.since = null;
58
+ this.told = '';
59
+ }
60
+ // Called on each poll with what the quota refused now, or null when nothing is refused.
61
+ async check(refusal) {
62
+ const now = this.options.now ?? Date.now;
63
+ if (!refusal) {
64
+ this.since = null;
65
+ return;
66
+ }
67
+ if (refusal !== this.told) {
68
+ this.told = refusal;
69
+ this.options.onWaiting?.(`waits for room under the quota of the namespace: ${refusal}`);
70
+ }
71
+ if (exceedsQuota(refusal)) {
72
+ throw new Error(`${this.options.subject} asks for more than the quota of the namespace allows: ${refusal}`);
73
+ }
74
+ this.since = this.since ?? now();
75
+ if (now() - this.since < this.options.timeout) {
76
+ return;
77
+ }
78
+ if (await this.othersWillEnd()) {
79
+ // checked again after another `timeout`
80
+ this.since = now();
81
+ return;
82
+ }
83
+ throw new Error(`${this.options.subject} did not fit the quota of the namespace within ${Math.round(this.options.timeout / 60000)} minutes, and only services hold its room: ${refusal}`);
84
+ }
85
+ async othersWillEnd() {
86
+ try {
87
+ const pods = await this.instance.coreApi.listNamespacedPod({ namespace: this.env.namespace });
88
+ return pods.items.some(willEnd);
89
+ }
90
+ catch {
91
+ // what it can not see may still end
92
+ return true;
93
+ }
94
+ }
95
+ }
96
+ exports.QuotaWait = QuotaWait;
97
+ //# sourceMappingURL=quota-wait.js.map