hammerkit 2.1.0-next.2 → 2.1.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 (87) hide show
  1. package/build.schema.json +39 -18
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/environment/replace-env-variables.js +8 -5
  8. package/dist/environment/run-source-envs.js +2 -1
  9. package/dist/executer/archive-task-entry.js +1 -1
  10. package/dist/executer/deadline.js +63 -10
  11. package/dist/executer/event-cache.js +5 -1
  12. package/dist/executer/execute-work-task.js +15 -3
  13. package/dist/executer/runner-commands.js +36 -0
  14. package/dist/file/get-file-context.js +4 -7
  15. package/dist/harness/connect.js +12 -8
  16. package/dist/harness/reconnect.js +141 -0
  17. package/dist/harness/sandbox-client.js +159 -30
  18. package/dist/harness/service-tools.js +11 -2
  19. package/dist/kubernetes/cluster-state.js +48 -14
  20. package/dist/kubernetes/ensure-persistent-data.js +15 -4
  21. package/dist/kubernetes/follow-pod-logs.js +8 -5
  22. package/dist/kubernetes/kept-claims.js +26 -5
  23. package/dist/kubernetes/resources.js +5 -1
  24. package/dist/kubernetes/sandbox-runner.js +526 -156
  25. package/dist/kubernetes/store-kubernetes-data.js +18 -3
  26. package/dist/kubernetes/sync-changes.js +463 -0
  27. package/dist/kubernetes/volumes.js +23 -1
  28. package/dist/optimizer/get-work-cache-stats.js +7 -0
  29. package/dist/optimizer/work-task-cache-description.js +3 -2
  30. package/dist/planner/image-build.js +5 -0
  31. package/dist/planner/utils/dependency-outputs.js +7 -6
  32. package/dist/planner/validate.js +41 -0
  33. package/dist/planner/work-item-status.js +12 -2
  34. package/dist/planner/work-runtime-aggregate.js +1 -0
  35. package/dist/planner/work-runtime-docker.js +33 -6
  36. package/dist/planner/work-runtime-kubernetes.js +313 -70
  37. package/dist/planner/work-runtime-local.js +8 -4
  38. package/dist/planner/work-secret.js +33 -11
  39. package/dist/planner/work-service-id.js +30 -6
  40. package/dist/program.js +19 -1
  41. package/dist/remote/annotations.js +37 -5
  42. package/dist/remote/bundle.js +6 -8
  43. package/dist/remote/collect-bundle.js +3 -2
  44. package/dist/remote/device-login.js +4 -1
  45. package/dist/remote/remote-commands.js +16 -7
  46. package/dist/remote/remote-work-commands.js +266 -75
  47. package/dist/remote/server-client.js +38 -40
  48. package/dist/schema/build-file-base-task-schema.js +16 -1
  49. package/dist/schema/build-file-image-build-schema.js +5 -8
  50. package/dist/schema/reference-parser.js +108 -43
  51. package/dist/schema/work-scope-parser.js +8 -0
  52. package/dist/secrets/prefetch-secrets.js +20 -1
  53. package/dist/server/artifacts-api.js +56 -0
  54. package/dist/server/definitions-api.js +62 -8
  55. package/dist/server/executor.js +117 -30
  56. package/dist/server/http.js +4 -1
  57. package/dist/server/keep-artifacts.js +230 -0
  58. package/dist/server/kubernetes-backend.js +186 -59
  59. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  60. package/dist/server/overview.js +73 -9
  61. package/dist/server/paging.js +167 -0
  62. package/dist/server/plan.js +16 -1
  63. package/dist/server/run-access.js +24 -0
  64. package/dist/server/run-artifacts.js +171 -0
  65. package/dist/server/run-logs.js +25 -1
  66. package/dist/server/run-request.js +11 -0
  67. package/dist/server/run-source-environment.js +1 -1
  68. package/dist/server/run-worker.js +267 -33
  69. package/dist/server/runs.js +527 -99
  70. package/dist/server/sandbox-files-api.js +27 -12
  71. package/dist/server/sandbox-files.js +12 -10
  72. package/dist/server/sandbox-follow.js +54 -0
  73. package/dist/server/sandbox-pod.js +1 -1
  74. package/dist/server/sandbox-storage.js +38 -1
  75. package/dist/server/sandbox-sync.js +392 -0
  76. package/dist/server/sandboxes-api.js +116 -19
  77. package/dist/server/sandboxes.js +38 -3
  78. package/dist/server/server-config.js +14 -0
  79. package/dist/server/server.js +169 -38
  80. package/dist/server/task-order.js +56 -0
  81. package/dist/utils/project-path.js +20 -0
  82. package/dist/utils/tar-files.js +52 -0
  83. package/dist/utils/tar.js +37 -1
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  86. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  87. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -1,10 +1,18 @@
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.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
3
+ exports.request = exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.downloadRunArtifact = exports.getRunArtifacts = exports.getRun = exports.followRun = exports.getMoveTarget = exports.lookupChecks = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.getServerConnection = 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
+ const reconnect_1 = require("./reconnect");
7
+ const fs_1 = require("fs");
8
+ const stream_1 = require("stream");
9
+ const promises_1 = require("stream/promises");
6
10
  // a write carries up to 32 MiB
7
11
  const TIMEOUT_MS = 60000;
12
+ // an output of a run carries up to runs.artifacts.maxBytes, 256 MiB by default: 30 minutes is
13
+ // what that takes at about 150 KiB/s, the slowest link the default still downloads over. A
14
+ // server with a larger maxBytes needs a longer timeout, as the download is not split up.
15
+ const DOWNLOAD_TIMEOUT_MS = 30 * 60000;
8
16
  // a run is asked for this long at a time, the log is read in between
9
17
  const POLL_WAIT = '1s';
10
18
  // a cancelled run waits this long for the server to take the cancel, before it gives up
@@ -19,6 +27,17 @@ class SandboxClientError extends Error {
19
27
  }
20
28
  }
21
29
  exports.SandboxClientError = SandboxClientError;
30
+ // A connection to a registered server, which says when it reconnects, on stderr unless told
31
+ // where else, and stops when the command is stopped.
32
+ function getServerConnection(environment, name, server, say = (line) => environment.stderr.write(`${line}\n`)) {
33
+ return {
34
+ url: server.url,
35
+ ...(0, token_source_1.getTokenSource)(environment, name, server),
36
+ say,
37
+ signal: environment.abortCtrl.signal,
38
+ };
39
+ }
40
+ exports.getServerConnection = getServerConnection;
22
41
  // What the agent is told of a check, on each harness.
23
42
  exports.CHECK_DESCRIPTION = 'Run a task as a check before you push, such as test or e2e: it runs on a copy of the files a push ' +
24
43
  'would commit (what .gitignore leaves out is not there, so dependencies are installed by the tasks ' +
@@ -92,9 +111,14 @@ class SandboxClient {
92
111
  static async list(connection) {
93
112
  return (await json(await call(connection, 'GET', '/v1/sandboxes'))).sandboxes;
94
113
  }
95
- // checks out the ref again, what changed in the sandbox is gone
114
+ // checks out the ref again, and the server refuses that over changes of the sandbox. Not sent
115
+ // again after a lost answer: the server may have moved the sandbox already, and a second
116
+ // fetch would move it again, past what the agent did since.
96
117
  static async fetch(connection, id, ref) {
97
- return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, { body: { ref } }));
118
+ return json(await call(connection, 'POST', `/v1/sandboxes/${encodeURIComponent(id)}/fetch`, {
119
+ body: { ref },
120
+ repeat: 'unsent',
121
+ }));
98
122
  }
99
123
  async stat(path) {
100
124
  if (checkSandboxPath(path) === '') {
@@ -111,8 +135,9 @@ class SandboxClient {
111
135
  }
112
136
  return Buffer.from(await response.arrayBuffer());
113
137
  }
138
+ // not sent again after a lost answer: a write sent again would write over what the agent did since
114
139
  async writeRaw(path, content) {
115
- return json(await call(this.connection, 'PUT', this.file(path), { raw: content }));
140
+ return json(await call(this.connection, 'PUT', this.file(path), { raw: content, repeat: 'unsent' }));
116
141
  }
117
142
  // numbered lines, like `cat -n`
118
143
  async read(path, offset, limit) {
@@ -122,11 +147,15 @@ class SandboxClient {
122
147
  return json(await call(this.connection, 'GET', `${this.base()}/tree`, { query: { ...query } }));
123
148
  }
124
149
  async search(query) {
125
- return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query }));
150
+ return json(await call(this.connection, 'POST', `${this.base()}/search`, { body: query, repeat: 'always' }));
126
151
  }
127
- // all or nothing
152
+ // all or nothing; a replace or a patch sent again would not find what it changed, so only a
153
+ // dry run is sent again on a broken connection
128
154
  async edit(ops, dryRun = false) {
129
- const answer = await call(this.connection, 'POST', `${this.base()}/edits`, { body: { dryRun, ops } });
155
+ const answer = await call(this.connection, 'POST', `${this.base()}/edits`, {
156
+ body: { dryRun, ops },
157
+ repeat: dryRun ? 'always' : 'unsent',
158
+ });
130
159
  return (await json(answer)).files;
131
160
  }
132
161
  async changes() {
@@ -204,15 +233,16 @@ class SandboxClient {
204
233
  ...(request.ttl ? { ttl: request.ttl } : {}),
205
234
  ...(request.sleepTtl ? { sleepTtl: request.sleepTtl } : {}),
206
235
  ...(request.name ? { name: request.name } : {}),
236
+ ...(request.restart?.length ? { restart: request.restart } : {}),
207
237
  source: request.branch
208
238
  ? { type: 'ref', repo: this.sandbox.repo, ref: request.branch }
209
239
  : { type: 'sandbox', id: this.id },
210
240
  });
211
241
  return followRun(this.connection, submitted, { signal: options.signal, untilUp: true });
212
242
  }
213
- // Stops a run: a service run takes its services and endpoints down.
243
+ // Stops a run: a service run takes its services and endpoints down. The same however often it comes.
214
244
  async stop(id) {
215
- return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`));
245
+ return json(await call(this.connection, 'POST', `/v1/runs/${encodeURIComponent(id)}/cancel`, { repeat: 'always' }));
216
246
  }
217
247
  /**
218
248
  * A page of an endpoint of a service run, as the caller sees it: only at an address the
@@ -346,6 +376,12 @@ async function submitRun(connection, request) {
346
376
  return json(await call(connection, 'POST', '/v1/runs', { body: request }));
347
377
  }
348
378
  exports.submitRun = submitRun;
379
+ // The newest passed run of each check key, as `POST /v1/checks/lookup` answers it: a read,
380
+ // asked again while the server is away.
381
+ async function lookupChecks(connection, repo, keys) {
382
+ return json(await call(connection, 'POST', '/v1/checks/lookup', { body: { repo, keys }, repeat: 'always' }));
383
+ }
384
+ exports.lookupChecks = lookupChecks;
349
385
  /**
350
386
  * Follows a run to its end: its log as it grows, and its state. A signal cancels the run
351
387
  * on the server and fails the follow. A service run that moved to another commit is followed
@@ -372,29 +408,70 @@ function isThere(run, submitted) {
372
408
  }
373
409
  async function followRun(connection, submitted, options = {}) {
374
410
  const path = `/v1/runs/${encodeURIComponent(submitted.id)}`;
411
+ // the stop of the follow, or of the command when it names none
412
+ const signal = options.signal ?? connection.signal;
375
413
  let cancelling;
376
414
  const cancel = () => {
377
415
  if (!submitted.moved) {
378
- cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`).catch(() => undefined));
416
+ // the same however often it comes, and waited for only as long as the follow waits for it
417
+ cancelling ?? (cancelling = call(connection, 'POST', `${path}/cancel`, {
418
+ repeat: 'always',
419
+ reconnectMs: CANCEL_WAIT_MS,
420
+ signal: null,
421
+ }).catch(() => undefined));
379
422
  }
380
423
  };
381
424
  if (!options.detach) {
382
- options.signal?.addEventListener('abort', cancel, { once: true });
425
+ signal?.addEventListener('abort', cancel, { once: true });
383
426
  }
384
427
  const lines = [];
385
428
  let from = submitted.moved?.logFrom ?? 1;
386
429
  let truncated = false;
430
+ // where the log went on after a server that was killed lost its end (LogPage.lost), as the
431
+ // follow last heard it, and the last line it read itself: it reads again from `lost` only
432
+ // when it read lines there, which are gone, not when it started past it (a moved run)
433
+ let lost;
434
+ let read = 0;
387
435
  const add = (line) => {
388
436
  lines.push(line);
389
437
  options.onLine?.(line);
390
438
  };
439
+ // a server that is away is waited for until the signal stops the follow, which goes on then
440
+ // as a stopped one
441
+ const stoppable = (read) => read.catch((e) => {
442
+ if (signal?.aborted) {
443
+ return undefined;
444
+ }
445
+ throw e;
446
+ });
391
447
  const readLog = async () => {
392
448
  for (;;) {
393
- const page = await json(await call(connection, 'GET', `${path}/logs`, { query: { task: options.task, from, limit: 1000 } }));
449
+ const page = await stoppable(call(connection, 'GET', `${path}/logs`, {
450
+ query: { task: options.task, from, limit: 1000 },
451
+ signal,
452
+ }).then(json));
453
+ if (!page) {
454
+ return;
455
+ }
394
456
  truncated = page.truncated;
457
+ if (page.lost !== undefined && page.lost !== lost) {
458
+ lost = page.lost;
459
+ if (read >= page.lost) {
460
+ // the lines from there on are not the ones read before: they are gone with the server
461
+ add({
462
+ line: 0,
463
+ task: 'hammerkit',
464
+ stream: 'stderr',
465
+ text: `… the server restarted and lost the last lines it had sent, the log goes on from line ${page.lost}`,
466
+ });
467
+ from = page.lost;
468
+ continue;
469
+ }
470
+ }
395
471
  for (const line of page.lines) {
396
472
  add(line);
397
473
  from = line.line + 1;
474
+ read = line.line;
398
475
  }
399
476
  if (!page.next) {
400
477
  return;
@@ -405,10 +482,10 @@ async function followRun(connection, submitted, options = {}) {
405
482
  let run = submitted;
406
483
  let waitingSaid = false;
407
484
  for (;;) {
408
- if (options.signal?.aborted && options.detach) {
485
+ if (signal?.aborted && options.detach) {
409
486
  break;
410
487
  }
411
- if (options.signal?.aborted) {
488
+ if (signal?.aborted) {
412
489
  // the process may exit after this, so the cancel has to reach the server first
413
490
  cancel();
414
491
  let timer;
@@ -424,7 +501,8 @@ async function followRun(connection, submitted, options = {}) {
424
501
  if (exports.FINAL_RUN_STATES.includes(run.state) || (options.untilUp && isThere(run, submitted))) {
425
502
  break;
426
503
  }
427
- run = await json(await call(connection, 'GET', path, { query: { wait: POLL_WAIT } }));
504
+ run =
505
+ (await stoppable(call(connection, 'GET', path, { query: { wait: POLL_WAIT }, signal }).then(json))) ?? run;
428
506
  }
429
507
  if (truncated) {
430
508
  truncatedEnd(run, options.task).forEach(add);
@@ -432,7 +510,7 @@ async function followRun(connection, submitted, options = {}) {
432
510
  return { run, lines, truncated };
433
511
  }
434
512
  finally {
435
- options.signal?.removeEventListener('abort', cancel);
513
+ signal?.removeEventListener('abort', cancel);
436
514
  }
437
515
  }
438
516
  exports.followRun = followRun;
@@ -459,6 +537,26 @@ async function getRun(connection, id) {
459
537
  return response.status === 404 ? null : json(response);
460
538
  }
461
539
  exports.getRun = getRun;
540
+ // null when the caller may not see the run (or the server keeps none of it)
541
+ async function getRunArtifacts(connection, id) {
542
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts`, { missing: true });
543
+ return response.status === 404 ? null : json(response);
544
+ }
545
+ exports.getRunArtifacts = getRunArtifacts;
546
+ /**
547
+ * Writes the archive of one output of a run to `file`: a gzipped tar of its paths in the
548
+ * project. It may be large, so it is written as it comes and may take longer than a call.
549
+ */
550
+ async function downloadRunArtifact(connection, id, output, file) {
551
+ const response = await call(connection, 'GET', `/v1/runs/${encodeURIComponent(id)}/artifacts/${output}`, {
552
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
553
+ });
554
+ if (!response.body) {
555
+ throw new SandboxClientError(`${connection.url} answered without the archive`);
556
+ }
557
+ await (0, promises_1.pipeline)(stream_1.Readable.fromWeb(response.body), (0, fs_1.createWriteStream)(file));
558
+ }
559
+ exports.downloadRunArtifact = downloadRunArtifact;
462
560
  /**
463
561
  * Reads the log of a run as it is now, every line or the last `tail` of them, of one task or
464
562
  * of all: also of a run that ended, as long as the server keeps it.
@@ -565,42 +663,73 @@ exports.quotePosix = quotePosix;
565
663
  function json(response) {
566
664
  return response.json();
567
665
  }
568
- async function call(connection, method, path, options = {}) {
666
+ /**
667
+ * The answer to a call, whatever its status. A call the server is away for is sent again as
668
+ * `repeat` allows, within the window of the connection; a token the server does not accept is
669
+ * renewed once and the call sent again.
670
+ */
671
+ async function request(connection, method, path, options = {}) {
569
672
  const url = new URL(`${connection.url.replace(/\/$/, '')}${path}`);
570
673
  for (const [key, value] of Object.entries(options.query ?? {})) {
571
674
  if (value !== undefined) {
572
675
  url.searchParams.set(key, String(value));
573
676
  }
574
677
  }
575
- const send = async () => {
576
- const token = await connection.token();
577
- if (!(0, token_source_1.isToken)(token)) {
678
+ const shown = (0, reconnect_1.showUrl)(connection.url);
679
+ // the stop of the command, unless the call names its own or none
680
+ const stop = options.signal === undefined ? connection.signal : options.signal ?? undefined;
681
+ const timing = connection.reconnect ?? reconnect_1.RECONNECT_TIMING;
682
+ const reconnecting = new reconnect_1.Reconnecting({
683
+ url: connection.url,
684
+ timing: options.reconnectMs !== undefined ? { ...timing, windowMs: options.reconnectMs } : timing,
685
+ say: connection.say,
686
+ signal: stop,
687
+ fail: options.fail ?? ((message) => new SandboxClientError(message)),
688
+ });
689
+ const attempt = async () => {
690
+ const token = 'token' in connection ? await connection.token() : undefined;
691
+ if (token !== undefined && !(0, token_source_1.isToken)(token)) {
578
692
  // a header refuses such a value and would quote it whole in its error
579
693
  throw new SandboxClientError('the token is not a single line of visible characters');
580
694
  }
695
+ // a try after one that failed takes no longer than what is left of the window
696
+ const timeout = AbortSignal.timeout(reconnecting.timeoutMs(options.timeoutMs ?? TIMEOUT_MS));
581
697
  return fetch(url, {
582
698
  method,
583
699
  headers: {
584
- authorization: `Bearer ${token}`,
700
+ ...(token !== undefined ? { authorization: `Bearer ${token}` } : {}),
585
701
  ...(options.body !== undefined ? { 'content-type': 'application/json' } : {}),
586
702
  ...(options.raw !== undefined ? { 'content-type': 'application/octet-stream' } : {}),
587
703
  },
588
704
  body: options.body !== undefined ? JSON.stringify(options.body) : options.raw,
589
- signal: AbortSignal.timeout(TIMEOUT_MS),
705
+ signal: stop ? AbortSignal.any([timeout, stop]) : timeout,
590
706
  // an answer from anywhere else is not the server's, and a PUT would send its file on
591
707
  redirect: 'error',
592
- }).catch((e) => {
593
- throw new SandboxClientError(`unable to reach ${connection.url}: ${redact(fetchFailure(e), token)}`);
594
- });
708
+ }).then((response) => ({ response }), (e) => ({
709
+ error: e,
710
+ message: stop?.aborted
711
+ ? `stopped while asking ${shown}`
712
+ : `unable to reach ${shown}: ${token === undefined ? fetchFailure(e) : redact(fetchFailure(e), token)}`,
713
+ }));
595
714
  };
596
- let response = await send();
597
- if (response.status === 401 && connection.renew) {
715
+ const repeat = options.repeat ?? (method === 'GET' || method === 'PUT' ? 'always' : 'unsent');
716
+ let response = await reconnecting.send(attempt, repeat);
717
+ // a new token is asked for within the window the call has left, not after it ran out
718
+ if (response.status === 401 && 'token' in connection && connection.renew && !reconnecting.exhausted) {
598
719
  await connection.renew();
599
- response = await send();
720
+ response = await reconnecting.send(attempt, repeat);
600
721
  }
722
+ return response;
723
+ }
724
+ exports.request = request;
725
+ // The body of a call that answers 2xx (or a 404 it was asked to take as an answer); any other
726
+ // status is an error, which says what the server answered.
727
+ async function call(connection, method, path, options = {}) {
728
+ const response = await request(connection, method, path, options);
601
729
  if (response.ok || (options.missing && response.status === 404)) {
602
730
  return response;
603
731
  }
732
+ const shown = (0, reconnect_1.showUrl)(connection.url);
604
733
  let said = '';
605
734
  try {
606
735
  const body = await json(response);
@@ -610,8 +739,8 @@ async function call(connection, method, path, options = {}) {
610
739
  // no JSON
611
740
  }
612
741
  if (response.status === 401) {
613
- throw new SandboxClientError(`${connection.url} did not accept the token`, 401);
742
+ throw new SandboxClientError(`${shown} did not accept the token`, 401);
614
743
  }
615
- throw new SandboxClientError(said || `${connection.url} answered ${response.status}`, response.status);
744
+ throw new SandboxClientError(said || `${shown} answered ${response.status}`, response.status);
616
745
  }
617
746
  //# sourceMappingURL=sandbox-client.js.map
@@ -71,8 +71,11 @@ exports.SERVICE_TOOLS = [
71
71
  description: 'Start services of the published build file on the hammerkit server, with the files of the sandbox (or of ' +
72
72
  'a branch), and keep them up for a person to look at: each endpoint (service:port) gets an address of its ' +
73
73
  'own behind the sign-in of the server. Answers once they are up, with the addresses and until when they ' +
74
- 'stay. A second start with the same name replaces the first, so its addresses stay the same. A server on ' +
75
- 'Kubernetes starts services from a branch only: push the sandbox and pass branch.',
74
+ 'stay. A second start with the same name replaces the first, so its addresses stay the same. Services from ' +
75
+ 'the sandbox on a Kubernetes server follow its edits a few seconds after each one: the changed files go into ' +
76
+ 'the services that watch their files (continuous), and the others keep the files they started with, unless ' +
77
+ 'restart names them, which starts them again with the new files. On a host the services run on the sandbox ' +
78
+ 'files themselves, so there is nothing to follow and restart is refused.',
76
79
  parameters: {
77
80
  services: { type: 'string[]', description: 'The services to start, as the build file names them' },
78
81
  endpoints: { type: 'string[]', description: 'The ports to publish, as service:port, such as web:8080' },
@@ -93,6 +96,11 @@ exports.SERVICE_TOOLS = [
93
96
  type: 'string',
94
97
  description: 'Start from this pushed branch of the repository instead of the files of the sandbox',
95
98
  },
99
+ restart: {
100
+ type: 'string[]',
101
+ description: 'The services that start again with the files of the sandbox after an edit of it; the others keep ' +
102
+ 'the files they started with. Only with the sandbox, not with branch',
103
+ },
96
104
  },
97
105
  required: ['services'],
98
106
  async call(client, args, signal) {
@@ -103,6 +111,7 @@ exports.SERVICE_TOOLS = [
103
111
  sleepTtl: args.sleepTtl || undefined,
104
112
  name: args.name || undefined,
105
113
  branch: args.branch || undefined,
114
+ restart: args.restart?.length ? args.restart : undefined,
106
115
  }, { signal });
107
116
  return describeServiceRun(followed.run);
108
117
  },
@@ -45,7 +45,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
45
45
  }
46
46
  }
47
47
  for (const status of mainStatuses(pod, container)) {
48
- const failure = getContainerFailure(status, restartsEnded(pod, status), restarts);
48
+ const failure = getContainerFailure(pod, status, restartsEnded(pod, status), restarts);
49
49
  if (failure) {
50
50
  return failure;
51
51
  }
@@ -53,7 +53,7 @@ function getPodFailure(pod, container, restarts = exports.CRASHES_TO_FAIL) {
53
53
  return null;
54
54
  }
55
55
  exports.getPodFailure = getPodFailure;
56
- function getContainerFailure(status, restartsEnded, restarts) {
56
+ function getContainerFailure(pod, status, restartsEnded, restarts) {
57
57
  const waiting = status.state?.waiting;
58
58
  const reason = waiting?.reason;
59
59
  const said = waiting?.message ? `: ${cut(waiting.message)}` : '';
@@ -78,18 +78,33 @@ function getContainerFailure(status, restartsEnded, restarts) {
78
78
  return { text: `its container could not be started (${reason})${said}`, final: false };
79
79
  case 'CrashLoopBackOff':
80
80
  return status.restartCount >= restarts
81
- ? { text: `it keeps crashing: ${describeLastExit(status)}`, final: true }
81
+ ? { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true }
82
82
  : null;
83
83
  }
84
84
  // a kubelet may leave an instance that ended as it is until its back-off is over, and say
85
85
  // CrashLoopBackOff only when it looks at the pod again, a minute later: the same crash
86
86
  if (restartsEnded && status.state?.terminated && status.restartCount >= restarts) {
87
- return { text: `it keeps crashing: ${describeLastExit(status)}`, final: true };
87
+ return { text: `it keeps crashing: ${describeLastExit(status, pod)}`, final: true };
88
88
  }
89
89
  return null;
90
90
  }
91
- // How the last instance of a container ended, as the cluster says it.
92
- function describeLastExit(status) {
91
+ // The signals a container is most often ended by, by their Linux numbers: containers here
92
+ // are Linux ones, and other systems number some signals differently.
93
+ const SIGNALS = {
94
+ 1: 'SIGHUP',
95
+ 2: 'SIGINT',
96
+ 6: 'SIGABRT',
97
+ 9: 'SIGKILL',
98
+ 11: 'SIGSEGV',
99
+ 15: 'SIGTERM',
100
+ };
101
+ /**
102
+ * How the last instance of a container ended, as the cluster says it: its exit code and
103
+ * reason, and the signal of an exit code above 128. The kubelet kills a container whose
104
+ * liveness probe (its healthcheck) keeps failing, so a container of `pod` with one that was
105
+ * killed says that it may be why; one without a healthcheck never does.
106
+ */
107
+ function describeLastExit(status, pod) {
93
108
  // the instance that ended now, else the one before the one that waits or runs
94
109
  const last = status.state?.terminated ?? status.lastState?.terminated;
95
110
  const restarts = `, restarted ${status.restartCount} time${status.restartCount === 1 ? '' : 's'}`;
@@ -99,8 +114,14 @@ function describeLastExit(status) {
99
114
  if (last.reason === 'OOMKilled') {
100
115
  return `it was killed for using more memory than its limit (OOMKilled)${restarts}`;
101
116
  }
102
- // the kubelet kills a container whose liveness probe (its healthcheck) keeps failing
103
- const killed = last.exitCode === 137 || last.exitCode === 143 ? ', killed as when its healthcheck kept failing' : '';
117
+ // A shell, and the runtime for process 1, exit with 128 plus the signal that ended a
118
+ // process: 129 to 159 are the signals 1 to 31, which Linux has; a higher code is the
119
+ // process's own.
120
+ const signal = last.exitCode >= 129 && last.exitCode <= 159 ? last.exitCode - 128 : undefined;
121
+ const probed = !!pod.spec?.containers?.find((container) => container.name === status.name)?.livenessProbe;
122
+ const killed = signal === undefined
123
+ ? ''
124
+ : `, killed by ${SIGNALS[signal] ?? `signal ${signal}`}${probed && (signal === 9 || signal === 15) ? ' as when its healthcheck keeps failing' : ''}`;
104
125
  return `it exited with code ${last.exitCode}${last.reason ? ` (${last.reason})` : ''}${killed}${restarts}`;
105
126
  }
106
127
  exports.describeLastExit = describeLastExit;
@@ -125,14 +146,14 @@ function getPodWaiting(pod, container) {
125
146
  case 'RunContainerError':
126
147
  return `can not start its container yet (${waiting.reason})${said}`;
127
148
  case 'CrashLoopBackOff':
128
- return `crashed and starts again: ${describeLastExit(status)}`;
149
+ return `crashed and starts again: ${describeLastExit(status, pod)}`;
129
150
  }
130
151
  const ended = status.state?.terminated;
131
152
  if (ended && restartsEnded(pod, status)) {
132
- return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status)}`;
153
+ return `${ended.exitCode === 0 ? 'ended' : 'crashed'} and starts again: ${describeLastExit(status, pod)}`;
133
154
  }
134
155
  if (status.restartCount > 0 && status.state?.running && !status.ready) {
135
- return `restarted: ${describeLastExit(status)}`;
156
+ return `restarted: ${describeLastExit(status, pod)}`;
136
157
  }
137
158
  }
138
159
  return undefined;
@@ -167,16 +188,29 @@ function describePod(pod) {
167
188
  const said = failure ?? waiting;
168
189
  const parts = [phase, ...(said ? [said] : [])];
169
190
  for (const status of crashed) {
170
- if (!said?.includes(describeLastExit(status))) {
171
- parts.push(`${status.name}: ${describeLastExit(status)}`);
191
+ const exit = describeLastExit(status, pod);
192
+ if (!said?.includes(exit)) {
193
+ parts.push(`container ${status.name}: ${exit}`);
172
194
  }
173
195
  }
174
196
  if (!said && unready.length > 0) {
175
197
  parts.push(`not ready: ${unready.join(', ')}`);
176
198
  }
177
- return `pod ${name}: ${parts.join(', ')}`;
199
+ return `pod ${name}${describeHelper(pod)}: ${parts.join(', ')}`;
178
200
  }
179
201
  exports.describePod = describePod;
202
+ // what a pod hammerkit runs beside a task or service does, so it is not taken for the item
203
+ function describeHelper(pod) {
204
+ const item = pod.metadata?.annotations?.[resources_1.ITEM_ANNOTATION];
205
+ switch (item ? pod.metadata?.annotations?.[resources_1.HELPER_ANNOTATION] : undefined) {
206
+ case 'upload':
207
+ return ` (a helper that copies the files of ${item} into its volume, not ${item} itself)`;
208
+ case 'download':
209
+ return ` (a helper that copies the outputs of ${item} out of its volume, not ${item} itself)`;
210
+ default:
211
+ return '';
212
+ }
213
+ }
180
214
  /**
181
215
  * The message of a warning event, as far as it is the cluster's: a failed probe says the
182
216
  * output of the command, which is the service's, and is left out.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.TRANSFER_POD_RESOURCES = void 0;
3
+ exports.ensurePersistentData = exports.packSource = exports.clearStateFiles = exports.ENSURE_OUTPUT_FILES = exports.restoreLiveFiles = exports.syncLiveFiles = exports.SYNC_FILES = exports.getStateDirsInUse = exports.REMOVE_OTHER_STATES = exports.execInPod = exports.clearClaim = exports.getPodForPersistence = exports.applyWithinQuota = exports.QUOTA_TIMEOUT = exports.getTransferPodScript = exports.TRANSFER_POD_RESOURCES = void 0;
4
4
  const quota_wait_1 = require("./quota-wait");
5
5
  Object.defineProperty(exports, "QUOTA_TIMEOUT", { enumerable: true, get: function () { return quota_wait_1.QUOTA_TIMEOUT; } });
6
6
  const volumes_1 = require("./volumes");
@@ -54,6 +54,15 @@ exports.TRANSFER_POD_RESOURCES = {
54
54
  requests: { cpu: '50m', memory: '64Mi' },
55
55
  limits: { memory: '512Mi' },
56
56
  };
57
+ // What the transfer pod runs while files are copied through exec: it waits, and ends at once
58
+ // and with 0 when the pod is deleted. A shell as process 1 ignores SIGTERM unless it traps it,
59
+ // and was killed at the end of the grace period of its deletion, 30 seconds later and with
60
+ // 137, which the log of a run that failed meanwhile showed as a failed pod.
61
+ // `busybox` is the one of the pod.
62
+ function getTransferPodScript(busybox) {
63
+ return `trap 'kill $! 2>/dev/null; exit 0' TERM; ${busybox} sleep 2147483647 & wait`;
64
+ }
65
+ exports.getTransferPodScript = getTransferPodScript;
57
66
  // A Job waits for room under a full quota, a pod is refused: so a transfer pod is
58
67
  // created again until the pods of the tasks it runs beside are done and make room
59
68
  async function applyWithinQuota(instance, podSpec, service, timeout = quota_wait_1.QUOTA_TIMEOUT, pollInterval = 2000,
@@ -93,7 +102,7 @@ signal, fn) {
93
102
  // outputs of its deps are not mounted, so an output inside a folder of its src
94
103
  // (pkg/coverage/lcov.info) has a place in the pod even when the claim holds no src,
95
104
  // after a restore into a new claim
96
- own.filter((m) => service.data.type !== 'container-task' || !m.mount.readOnly).map((m) => m.mount)
105
+ own.filter((m) => !m.sync && (service.data.type !== 'container-task' || !m.mount.readOnly)).map((m) => m.mount)
97
106
  : own.reduce((array, v) => {
98
107
  if (!array.some((i) => i.name === v.mount.name)) {
99
108
  array.push({
@@ -139,6 +148,8 @@ signal, fn) {
139
148
  },
140
149
  annotations: {
141
150
  'hammerkit.dev/version': (0, version_1.getVersion)(),
151
+ [resources_1.HELPER_ANNOTATION]: type === 'write' ? 'upload' : 'download',
152
+ [resources_1.ITEM_ANNOTATION]: service.name,
142
153
  },
143
154
  },
144
155
  spec: {
@@ -156,8 +167,8 @@ signal, fn) {
156
167
  {
157
168
  name: 'volume',
158
169
  image: transfer_tools_1.HELPER_TOOLS_IMAGE,
159
- command: (0, transfer_tools_1.inTransferPod)(['sh']),
160
- tty: true,
170
+ // no tty: it kept an interactive shell waiting, which ignores SIGTERM
171
+ command: (0, transfer_tools_1.inTransferPod)(['sh', '-c', getTransferPodScript(transfer_tools_1.TRANSFER_BUSYBOX)]),
161
172
  env: transfer_tools_1.TRANSFER_TOOLS_ENV,
162
173
  volumeMounts: [...mounts, transfer_tools_1.TRANSFER_TOOLS_MOUNT],
163
174
  resources: exports.TRANSFER_POD_RESOURCES,
@@ -49,14 +49,17 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
49
49
  const positionOf = (id) => {
50
50
  let position = positions.get(id);
51
51
  if (!position) {
52
- position = { at: null, since: null, count: 0, reads: 0 };
52
+ const from = Array.isArray(options.from) ? options.from.find((cursor) => cursor?.container === id) : undefined;
53
+ position = from
54
+ ? { at: from.at, since: `${from.at.slice(0, 19)}Z`, count: from.count, reads: 0 }
55
+ : { at: null, since: null, count: 0, reads: 0 };
53
56
  positions.set(id, position);
54
57
  }
55
58
  return position;
56
59
  };
57
60
  // a reader of the log of one instance from where it got to: the lines read before, again
58
61
  // at the start of a log read since their second, are passed over
59
- const reader = (position) => {
62
+ const reader = (id, position) => {
60
63
  const from = position.at;
61
64
  const skip = position.count;
62
65
  let atFrom = 0;
@@ -80,7 +83,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
80
83
  position.since = `${match[1]}Z`;
81
84
  position.count = 1;
82
85
  }
83
- onLine(match[3] ?? '');
86
+ onLine(match[3] ?? '', { container: id, at, count: position.count });
84
87
  };
85
88
  };
86
89
  const readEnded = async (pod, id, previous) => {
@@ -98,7 +101,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
98
101
  ? { sinceSeconds: Math.max(1, Math.ceil((Date.now() - Date.parse(position.since)) / 1000) + 60) }
99
102
  : {}),
100
103
  });
101
- const read = reader(position);
104
+ const read = reader(id, position);
102
105
  for (const line of String(log ?? '').split(/\r?\n/)) {
103
106
  if (line.length > 0) {
104
107
  read(line);
@@ -139,7 +142,7 @@ function followPodLogs(instance, namespace, labelSelector, container, onLine, op
139
142
  end();
140
143
  }));
141
144
  output.on('end', end);
142
- (0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(position));
145
+ (0, read_lines_1.readLines)(output, exports.MAX_LOG_LINE_CHARS, reader(id, position));
143
146
  streaming++;
144
147
  let controller;
145
148
  try {