hammerkit 2.1.0-next.19 → 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.
@@ -102,7 +102,7 @@ signal, fn) {
102
102
  // outputs of its deps are not mounted, so an output inside a folder of its src
103
103
  // (pkg/coverage/lcov.info) has a place in the pod even when the claim holds no src,
104
104
  // after a restore into a new claim
105
- 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)
106
106
  : own.reduce((array, v) => {
107
107
  if (!array.some((i) => i.name === v.mount.name)) {
108
108
  array.push({
@@ -1,18 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.restartPods = exports.syncChangedFiles = exports.SYNC_CHANGES = exports.getChangeTarget = exports.CHANGES_STAGING_DIR = void 0;
3
+ exports.restartPods = exports.syncChangedFiles = exports.podFolderOf = exports.SYNC_CHANGES = exports.APPLY_PATHS = exports.getChangeTarget = exports.CHANGES_STAGING_DIR = void 0;
4
4
  const fs_1 = require("fs");
5
+ const promises_1 = require("fs/promises");
6
+ const os_1 = require("os");
5
7
  const stream_1 = require("stream");
8
+ const promises_2 = require("stream/promises");
6
9
  const path_1 = require("path");
10
+ const tar_1 = require("tar");
7
11
  const volumes_1 = require("./volumes");
8
12
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
13
+ const ensure_kubernetes_deployment_exists_1 = require("./ensure-kubernetes-deployment-exists");
9
14
  const transfer_tools_1 = require("./transfer-tools");
10
- const tar_1 = require("../utils/tar");
15
+ const tar_2 = require("../utils/tar");
16
+ const tar_files_1 = require("../utils/tar-files");
11
17
  const resources_1 = require("./resources");
12
18
  // The folder of the claim the changed files of a sandbox are uploaded to, before they are
13
19
  // applied to the folder of the service (SYNC_CHANGES). It is not a folder of a state, so the
14
- // removal of other states leaves it be.
20
+ // removal of other states leaves it be. The pods only see it as a folder of the transfer pod.
15
21
  exports.CHANGES_STAGING_DIR = '.hammerkit-sync';
22
+ // how much of an archive goes into the standard input of an exec at once
23
+ const PIECE_BYTES = 256 * 1024;
16
24
  /**
17
25
  * Where the changed files of a service of a service run go, and whether its Deployment starts
18
26
  * again with them. A service that watches its files (`live`) gets them into the folder its
@@ -27,6 +35,54 @@ function getChangeTarget(live, restart, stateDir) {
27
35
  return restart ? { dir: stateDir, rollout: true } : undefined;
28
36
  }
29
37
  exports.getChangeTarget = getChangeTarget;
38
+ /**
39
+ * Applies the records on its standard input to the folder `$1` of a pod, NUL-separated: `d <path>`
40
+ * removes a path that is gone; `w <path>` clears the way for a file the archive writes next (a
41
+ * link or a folder at its place). The folder `$1` must exist: a pod whose mount is missing it is
42
+ * not one the files can go into. The checks of SYNC_CHANGES hold: each folder on the way from `$1`
43
+ * down must be a folder, not a link or a file, and a path that is empty, ends in `/`, has a `.` or
44
+ * `..` segment or a leading `/` is skipped and reported as `skipped <path>: <why>`. Only `w` paths
45
+ * get folders made. A path that is skipped is not written by the archive either (see
46
+ * applyThroughServicePod).
47
+ */
48
+ exports.APPLY_PATHS = `dst="$1"
49
+ [ -d "$dst" ] || exit 1
50
+ if [ -L "$dst" ]; then echo "skipped $dst: it is a link" >&2; exit 1; fi
51
+ # checks the folders of the relative path $1 under $dst: none may be a link or a file, and with
52
+ # $2 set the missing ones are made. False when one is a link or a file on the way.
53
+ walk() {
54
+ cur="$dst"
55
+ rest="$1"
56
+ while [ "$rest" != "\${rest#*/}" ]; do
57
+ comp="\${rest%%/*}"
58
+ rest="\${rest#*/}"
59
+ cur="$cur/$comp"
60
+ if [ -L "$cur" ]; then return 1; fi
61
+ if [ -e "$cur" ]; then
62
+ if [ ! -d "$cur" ]; then return 1; fi
63
+ elif [ -n "$2" ]; then
64
+ mkdir "$cur" || return 1
65
+ else
66
+ return 0
67
+ fi
68
+ done
69
+ return 0
70
+ }
71
+ tr '\\0' '\\n' | while IFS= read -r rec || [ -n "$rec" ]; do
72
+ case "$rec" in
73
+ "d "*) p="\${rec#d }"; made= ;;
74
+ "w "*) p="\${rec#w }"; made=yes ;;
75
+ *) continue ;;
76
+ esac
77
+ if [ -z "$p" ]; then echo "skipped (empty path): not a path of the sandbox"; continue; fi
78
+ case "$p" in
79
+ /*|*/|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $p: not a path of the sandbox"; continue ;;
80
+ esac
81
+ if ! walk "$p" $made; then echo "skipped $p: a link or a file is in its way"; continue; fi
82
+ t="$dst/$p"
83
+ if [ -z "$made" ] || [ -L "$t" ] || [ -d "$t" ]; then rm -rf "$t" || exit 1; fi
84
+ done || exit 1
85
+ exit 0`;
30
86
  /**
31
87
  * Applies the staged batch at `$1` to the folder `$2`. Its `deleted` file lists the paths that
32
88
  * are gone, NUL-separated, and its `files` folder the files that changed. The paths after `$2`
@@ -34,8 +90,10 @@ exports.getChangeTarget = getChangeTarget;
34
90
  * - Deletions come first. Then each file is written in place, only where its content or mode
35
91
  * differs, so a file a pod mounts keeps its inode.
36
92
  * - Nothing is written or removed through a link, or where a file is in the way of a folder:
37
- * each folder on the way is checked from `$2` down, one component at a time. Such a path, and
38
- * one with a `.` or `..` segment or a leading `/`, is skipped and reported as `skipped <path>: <why>`.
93
+ * each folder on the way is checked from `$2` down, one component at a time, and the folder a
94
+ * file goes into must still resolve under `$2` right before the write (`under`). Such a path,
95
+ * and one that is empty, ends in `/`, or has a `.` or `..` segment or a leading `/`, is skipped
96
+ * and reported as `skipped <path>: <why>`.
39
97
  * The staged folder goes at the end.
40
98
  */
41
99
  exports.SYNC_CHANGES = `src="$1"
@@ -43,6 +101,7 @@ dst="$2"
43
101
  shift 2
44
102
  mkdir -p "$src" "$dst" || exit 1
45
103
  if [ -L "$dst" ]; then echo "skipped $dst: it is a link" >&2; exit 1; fi
104
+ realdst=$(cd "$dst" && pwd -P) || exit 1
46
105
  # checks the folders of the relative path $1 under $dst: none may be a link or a file, and with
47
106
  # $2 set the missing ones are made. False when one is a link or a file on the way.
48
107
  walk() {
@@ -63,11 +122,18 @@ walk() {
63
122
  done
64
123
  return 0
65
124
  }
125
+ # right before a write or a removal of the path $1 under $dst: a link at the path is removed (the
126
+ # link itself, not what it points to), and the folder the path is in must resolve under $dst
127
+ under() {
128
+ if [ -L "$1" ]; then rm -f "$1" || return 1; fi
129
+ pdir=$(cd "$(dirname "$1")" 2>/dev/null && pwd -P) || return 1
130
+ case "$pdir/" in "$realdst/"*) return 0 ;; *) return 1 ;; esac
131
+ }
66
132
  if [ -f "$src/deleted" ]; then
67
133
  tr '\\0' '\\n' < "$src/deleted" | while IFS= read -r p || [ -n "$p" ]; do
68
134
  if [ -z "$p" ]; then continue; fi
69
135
  case "$p" in
70
- /*|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $p: not a path of the sandbox"; continue ;;
136
+ /*|*/|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $p: not a path of the sandbox"; continue ;;
71
137
  esac
72
138
  keep=
73
139
  for m in "$@"; do
@@ -75,6 +141,7 @@ if [ -f "$src/deleted" ]; then
75
141
  done
76
142
  if [ -n "$keep" ]; then continue; fi
77
143
  if ! walk "$p"; then echo "skipped $p: a link or a file is in its way"; continue; fi
144
+ if ! under "$dst/$p"; then echo "skipped $p: a link is in its way"; continue; fi
78
145
  rm -rf "$dst/$p" || exit 1
79
146
  done || exit 1
80
147
  fi
@@ -82,13 +149,14 @@ if [ -d "$src/files" ]; then
82
149
  find "$src/files" -type f | while IFS= read -r s; do
83
150
  f="\${s#"$src/files/"}"
84
151
  case "$f" in
85
- /*|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $f: not a path of the sandbox"; continue ;;
152
+ /*|*/|.|./*|*/.|*/./*|..|../*|*/..|*/../*) echo "skipped $f: not a path of the sandbox"; continue ;;
86
153
  esac
87
154
  if ! walk "$f" yes; then echo "skipped $f: a link or a file is in its way"; continue; fi
88
155
  t="$dst/$f"
89
- if [ -L "$t" ] || [ -d "$t" ]; then rm -rf "$t" || exit 1; fi
156
+ if ! under "$t"; then echo "skipped $f: a link is in its way"; continue; fi
157
+ if [ -d "$t" ]; then rm -rf "$t" || exit 1; fi
90
158
  if [ -e "$t" ]; then
91
- if ! cmp -s "$s" "$t"; then cat "$s" > "$t" || exit 1; fi
159
+ if ! cmp -s "$s" "$t"; then cat "$s" > "$t" && touch -r "$s" "$t" || exit 1; fi
92
160
  else
93
161
  cp -p "$s" "$t" || exit 1
94
162
  fi
@@ -102,66 +170,281 @@ exit 0`;
102
170
  function mountedUnder(persistence, dir) {
103
171
  return persistence.mounts.flatMap(({ mount }) => mount.subPath?.startsWith(`${dir}/`) ? [mount.subPath.slice(dir.length + 1)] : []);
104
172
  }
173
+ /**
174
+ * The writable mount of the service that holds `path` (a path of the sandbox): the longest folder
175
+ * of the writable twins (see addSyncMounts) that the path is in. Undefined when the path is in
176
+ * none, or when a mount of the service is inside that folder: the archive replaces the files of
177
+ * the folder, and a mount of one of them would lose its file (the inode rule of SYNC_CHANGES).
178
+ */
179
+ function podFolderOf(persistence, dir, path) {
180
+ const mounts = persistence.mounts.flatMap(({ mount, sync }) => mount.subPath?.startsWith(`${dir}/`)
181
+ ? [{ rel: mount.subPath.slice(dir.length + 1), mountPath: mount.mountPath, sync: !!sync && !mount.readOnly }]
182
+ : []);
183
+ const [best] = mounts
184
+ .filter((candidate) => candidate.sync && path.startsWith(`${candidate.rel}/`))
185
+ .sort((a, b) => b.rel.length - a.rel.length);
186
+ if (!best) {
187
+ return undefined;
188
+ }
189
+ const inside = mounts.some((other) => other.rel.startsWith(`${best.rel}/`));
190
+ return inside ? undefined : { mountPath: best.mountPath, rel: best.rel };
191
+ }
192
+ exports.podFolderOf = podFolderOf;
193
+ // The archive's entries, read whole, in the order they are in
194
+ async function readArchive(archive) {
195
+ const files = [];
196
+ await new Promise((resolve, reject) => {
197
+ const parser = new tar_1.Parser({
198
+ onReadEntry: (entry) => {
199
+ const file = { path: entry.path, mode: entry.mode ?? 0o644, content: Buffer.alloc(0) };
200
+ files.push(file);
201
+ const chunks = [];
202
+ entry.on('data', (chunk) => chunks.push(chunk));
203
+ entry.on('end', () => (file.content = Buffer.concat(chunks)));
204
+ },
205
+ });
206
+ parser.on('end', () => resolve());
207
+ parser.on('error', reject);
208
+ parser.end(archive);
209
+ });
210
+ return files;
211
+ }
212
+ // `data` as a stream of pieces of PIECE_BYTES: an exec's standard input takes them as they come
213
+ function piecesOf(data) {
214
+ return stream_1.Readable.from((function* () {
215
+ for (let offset = 0; offset < data.length; offset += PIECE_BYTES) {
216
+ yield data.subarray(offset, offset + PIECE_BYTES);
217
+ }
218
+ })());
219
+ }
105
220
  // Uploads the entries of the batch folder `batch` into `target` of the upload pod `pod`
106
221
  async function uploadStaged(instance, env, pod, batch, target) {
107
222
  const entries = (0, fs_1.readdirSync)(batch);
108
- const data = stream_1.Readable.from((0, tar_1.packArchive)({ cwd: batch }, entries));
223
+ const data = stream_1.Readable.from((0, tar_2.packArchive)({ cwd: batch }, entries));
109
224
  const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(['tar', 'xf', '-', '-C', target]), process.stdout, process.stderr, data, false);
110
225
  await new Promise((resolve, reject) => {
111
226
  res.on('error', reject);
112
227
  res.on('close', () => resolve());
113
228
  });
114
229
  }
115
- // Runs `command` in the upload pod `pod`: what failed (null when it went well), and what it printed
116
- async function execCapturing(instance, env, pod, command) {
230
+ // Runs `command` in the container `container` of the pod `pod`, with `stdin` as its standard
231
+ // input (null for none): what failed (null when it went well), and what it printed
232
+ async function execIn(instance, env, pod, container, command, stdin) {
117
233
  let failure = null;
234
+ let exitCode;
118
235
  let output = '';
119
236
  const out = new stream_1.PassThrough();
120
237
  out.on('data', (chunk) => (output += chunk.toString('utf8')));
121
- const res = await instance.exec.exec(env.namespace, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), out, process.stderr, null, false, (status) => {
238
+ const res = await instance.exec.exec(env.namespace, pod, container, command, out, process.stderr, stdin, false, (status) => {
122
239
  if (status.status !== 'Success') {
123
240
  failure = status.message ?? status.reason ?? 'unknown';
241
+ // the exit code of the command, as the API gives it in its causes
242
+ const code = status.details?.causes?.find((cause) => cause.reason === 'ExitCode')?.message;
243
+ exitCode = code === undefined ? undefined : Number(code);
124
244
  }
125
245
  });
126
246
  await new Promise((resolve, reject) => {
127
247
  res.on('error', reject);
128
248
  res.on('close', () => resolve());
129
249
  });
130
- return { failure, output };
250
+ return { failure, output, exitCode };
251
+ }
252
+ // The key of the tools answer for a container: the image it runs
253
+ function toolsKey(env, container) {
254
+ return `${env.namespace}/${container.image}`;
255
+ }
256
+ // one line of what a group took: how many paths, and the first few of them
257
+ function describePaths(paths) {
258
+ const shown = paths.slice(0, 5).join(', ');
259
+ return `${paths.length} path${paths.length === 1 ? '' : 's'}: ${shown}${paths.length > 5 ? ', ...' : ''}`;
260
+ }
261
+ // Runs `command` in the upload pod `pod`: what failed (null when it went well), and what it printed
262
+ function execCapturing(instance, env, pod, command) {
263
+ return execIn(instance, env, pod, 'volume', (0, transfer_tools_1.inTransferPod)(command), null);
264
+ }
265
+ // Whether the image of a container has sh, tar, tr and rm, by image. A probe that says one of them
266
+ // is missing (`command -v` exits 127 or 1, or the shell is not in the image) answers no; any other
267
+ // failure (a pod that is gone, an out of memory exit) is thrown, and asked again next time.
268
+ const toolsOf = new Map();
269
+ // The running pod of the service whose container mounts `mountPath`, with that container
270
+ async function podMounting(instance, env, service, mountPath) {
271
+ const pods = await instance.coreApi.listNamespacedPod({
272
+ namespace: env.namespace,
273
+ labelSelector: (0, resources_1.getItemSelector)(service, env),
274
+ });
275
+ const name = (0, ensure_kubernetes_deployment_exists_1.getServiceContainerName)(service);
276
+ for (const pod of pods.items) {
277
+ if (pod.status?.phase !== 'Running' || pod.metadata?.deletionTimestamp) {
278
+ continue;
279
+ }
280
+ const container = pod.spec?.containers.find((candidate) => candidate.name === name);
281
+ if (container?.volumeMounts?.some((mount) => mount.mountPath === mountPath)) {
282
+ return { pod, container };
283
+ }
284
+ }
285
+ return undefined;
286
+ }
287
+ // Whether the container's image has the tools a batch is applied with
288
+ async function hasTools(instance, env, service, pod, container) {
289
+ const key = toolsKey(env, container);
290
+ const known = toolsOf.get(key);
291
+ if (known !== undefined) {
292
+ return known;
293
+ }
294
+ const { failure, exitCode } = await execIn(instance, env, pod.metadata?.name ?? '', (0, ensure_kubernetes_deployment_exists_1.getServiceContainerName)(service), ['sh', '-c', 'command -v tar && command -v tr && command -v rm'], null);
295
+ if (failure === null) {
296
+ toolsOf.set(key, true);
297
+ return true;
298
+ }
299
+ const missing = exitCode === 127 || exitCode === 1 || /executable file not found/.test(failure);
300
+ if (!missing) {
301
+ throw new Error(`unable to find out whether ${service.name} has its tools: ${failure}`);
302
+ }
303
+ toolsOf.set(key, false);
304
+ return false;
131
305
  }
132
306
  /**
133
- * Syncs the changed files of a sandbox into the folder `dir` of the claim of `service`: only
134
- * what changed is uploaded and applied, nothing else of the service is touched. The batch
135
- * folder of the changes (`dirname` of `changes.dir`) gets its `deleted` list here, NUL-separated.
136
- * Returns the paths the pod skipped (see SYNC_CHANGES).
307
+ * The batch of one writable mount, into the pod that mounts it: the records of the gone and the
308
+ * written paths are applied by APPLY_PATHS, then the archive is extracted into the mount. When the
309
+ * script skipped a path (a link or a file is on its way), nothing is extracted and `applied` is
310
+ * false: the caller sends the batch another way. A failure of the extract is thrown.
137
311
  */
138
- async function syncChangedFiles(instance, env, service, persistence, dir, changes) {
312
+ async function applyThroughServicePod(instance, env, service, pod, folder, written, deleted,
313
+ // the key of the tools answer of the container's image (see toolsKey)
314
+ imageKey) {
315
+ const name = pod.metadata?.name ?? '';
316
+ const container = (0, ensure_kubernetes_deployment_exists_1.getServiceContainerName)(service);
317
+ // the paths are relative to the folder the pod mounts
318
+ const relative = (path) => path.slice(folder.rel.length + 1);
319
+ const records = [
320
+ ...deleted.map((path) => `d ${relative(path)}`),
321
+ ...written.map((file) => `w ${relative(file.path)}`),
322
+ ];
323
+ const checked = await execIn(instance, env, name, container, ['sh', '-c', exports.APPLY_PATHS, 'sh', folder.mountPath], piecesOf(Buffer.from(records.join('\0'))));
324
+ if (checked.failure) {
325
+ throw new Error(`unable to sync the changed files of ${service.name} into ${folder.mountPath}: ${checked.failure}`);
326
+ }
327
+ const skipped = checked.output.split('\n').filter((line) => line.startsWith('skipped '));
328
+ if (skipped.length > 0 || written.length === 0) {
329
+ return { skipped, applied: skipped.length === 0 };
330
+ }
331
+ // the archive names the paths from the sandbox: the folder's own depth is stripped off them
332
+ const depth = folder.rel.split('/').length;
333
+ const extracted = await execIn(instance, env, name, container, ['tar', 'xf', '-', '-C', folder.mountPath, `--strip-components=${depth}`], piecesOf((0, tar_files_1.tarFiles)(written)));
334
+ if (extracted.failure) {
335
+ // the image can not take the archive in its pod: the group goes through the transfer pod, and
336
+ // the image is not asked for the fast path again
337
+ toolsOf.set(imageKey, false);
338
+ service.status.write('info', `the archive could not be extracted into ${folder.mountPath}: ${extracted.failure}`);
339
+ return { skipped, applied: false };
340
+ }
341
+ return { skipped, applied: true };
342
+ }
343
+ // Stages the changes into `batch`: the files the archive holds, and the gone paths
344
+ async function stageArchive(batch, changes) {
345
+ await (0, promises_1.mkdir)((0, path_1.join)(batch, 'files'));
346
+ await (0, promises_2.pipeline)(stream_1.Readable.from([changes.archive]), (0, tar_1.extract)({ cwd: (0, path_1.join)(batch, 'files') }));
347
+ (0, fs_1.writeFileSync)((0, path_1.join)(batch, 'deleted'), changes.deleted.join('\0'));
348
+ }
349
+ // Syncs the batch through a transfer pod that mounts the claim: SYNC_CHANGES puts the files into
350
+ // the folder, and keeps the inode of each file a pod mounts. Returns the paths the pod skipped.
351
+ async function syncThroughTransferPod(instance, env, service, persistence, dir, changes) {
139
352
  const root = `/dev/hammerkit/${service.id()}`;
140
353
  const staging = `${root}/${exports.CHANGES_STAGING_DIR}`;
141
354
  const mounted = mountedUnder(persistence, dir);
142
- const batch = (0, path_1.dirname)(changes.dir);
143
- (0, fs_1.writeFileSync)((0, path_1.join)(batch, 'deleted'), changes.deleted.join('\0'));
355
+ // the folder is made first and removed in every case: a failure while it is staged leaves none
356
+ const batch = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-sync-'));
144
357
  const skipped = [];
145
- await (0, ensure_persistent_data_1.getPodForPersistence)(instance, env, service, persistence, 'write', undefined, async (pod) => {
146
- const cleared = await execCapturing(instance, env, pod, ['sh', '-c', 'rm -rf "$1" && mkdir -p "$1"', 'sh', staging]);
147
- if (cleared.failure) {
148
- throw new Error(`unable to stage the changes of ${service.name} in ${pod}: ${cleared.failure}`);
358
+ try {
359
+ await stageArchive(batch, changes);
360
+ await (0, ensure_persistent_data_1.getPodForPersistence)(instance, env, service, persistence, 'write', undefined, async (pod) => {
361
+ const cleared = await execCapturing(instance, env, pod, [
362
+ 'sh',
363
+ '-c',
364
+ 'rm -rf "$1" && mkdir -p "$1"',
365
+ 'sh',
366
+ staging,
367
+ ]);
368
+ if (cleared.failure) {
369
+ throw new Error(`unable to stage the changes of ${service.name} in ${pod}: ${cleared.failure}`);
370
+ }
371
+ await uploadStaged(instance, env, pod, batch, staging);
372
+ const { failure, output } = await execCapturing(instance, env, pod, [
373
+ 'sh',
374
+ '-c',
375
+ exports.SYNC_CHANGES,
376
+ 'sh',
377
+ staging,
378
+ `${root}/${dir}`,
379
+ ...mounted,
380
+ ]);
381
+ skipped.push(...output.split('\n').filter((line) => line.startsWith('skipped ')));
382
+ if (failure) {
383
+ throw new Error(`unable to sync the changed files of ${service.name} into ${dir}: ${failure}`);
384
+ }
385
+ });
386
+ }
387
+ finally {
388
+ await (0, promises_1.rm)(batch, { recursive: true, force: true });
389
+ }
390
+ return skipped;
391
+ }
392
+ /**
393
+ * Syncs the changed files of a sandbox into the folder `dir` of the claim of `service`: only what
394
+ * changed is applied, nothing else of the service is touched. The batch is grouped by the writable
395
+ * mount each path is in. A group goes into the pod that mounts it, when that pod has the tools and
396
+ * nothing of the group was skipped; any other group, and the paths in none, go through the
397
+ * transfer pod (see syncThroughTransferPod). Each group's outcome is written to the status of the
398
+ * service. Returns the paths the pods skipped (see SYNC_CHANGES and APPLY_PATHS).
399
+ */
400
+ async function syncChangedFiles(instance, env, service, persistence, dir, changes) {
401
+ const written = await readArchive(changes.archive);
402
+ const groups = new Map();
403
+ const groupOf = (path) => {
404
+ const folder = podFolderOf(persistence, dir, path);
405
+ const key = folder?.mountPath ?? '';
406
+ const group = groups.get(key) ?? { folder, written: [], deleted: [] };
407
+ groups.set(key, group);
408
+ return group;
409
+ };
410
+ for (const file of written) {
411
+ groupOf(file.path).written.push(file);
412
+ }
413
+ for (const path of changes.deleted) {
414
+ groupOf(path).deleted.push(path);
415
+ }
416
+ const skipped = [];
417
+ const transfer = { written: [], deleted: [] };
418
+ for (const group of groups.values()) {
419
+ const paths = [...group.written.map((file) => file.path), ...group.deleted];
420
+ if (!group.folder) {
421
+ transfer.written.push(...group.written);
422
+ transfer.deleted.push(...group.deleted);
423
+ continue;
149
424
  }
150
- await uploadStaged(instance, env, pod, batch, staging);
151
- const { failure, output } = await execCapturing(instance, env, pod, [
152
- 'sh',
153
- '-c',
154
- exports.SYNC_CHANGES,
155
- 'sh',
156
- staging,
157
- `${root}/${dir}`,
158
- ...mounted,
159
- ]);
160
- skipped.push(...output.split('\n').filter((line) => line.startsWith('skipped ')));
161
- if (failure) {
162
- throw new Error(`unable to sync the changed files of ${service.name} into ${dir}: ${failure}`);
425
+ const target = await podMounting(instance, env, service, group.folder.mountPath);
426
+ if (target && (await hasTools(instance, env, service, target.pod, target.container))) {
427
+ const result = await applyThroughServicePod(instance, env, service, target.pod, group.folder, group.written, group.deleted, toolsKey(env, target.container));
428
+ skipped.push(...result.skipped);
429
+ if (result.applied) {
430
+ service.status.write('info', `synced ${describePaths(paths)} through ${group.folder.mountPath}`);
431
+ continue;
432
+ }
163
433
  }
164
- });
434
+ // no pod of the service mounts it with the tools, the script skipped a path of it, or the
435
+ // archive did not extract
436
+ service.status.write('info', `synced ${describePaths(paths)} through the transfer pod`);
437
+ transfer.written.push(...group.written);
438
+ transfer.deleted.push(...group.deleted);
439
+ }
440
+ if (transfer.written.length + transfer.deleted.length > 0) {
441
+ skipped.push(...(await syncThroughTransferPod(instance, env, service, persistence, dir, {
442
+ archive: (0, tar_files_1.tarFiles)(transfer.written),
443
+ written: transfer.written.map((file) => file.path),
444
+ deleted: transfer.deleted,
445
+ restart: false,
446
+ })));
447
+ }
165
448
  return skipped;
166
449
  }
167
450
  exports.syncChangedFiles = syncChangedFiles;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getItemFilesDir = exports.isLiveService = exports.LIVE_FILES_DIR = exports.getStateFilesDir = exports.STATE_FILES_PREFIX = exports.getSandboxAffinity = exports.SANDBOX_LABEL = exports.getClaimMountLabel = exports.getClaimPodSpec = exports.getWorkspacePodSpec = exports.appendVolume = exports.getMountedSources = exports.getKubernetesPersistence = exports.getVolumeName = void 0;
3
+ exports.getItemFilesDir = exports.isLiveService = exports.WRITABLE_MOUNT_DIR = exports.LIVE_FILES_DIR = exports.getStateFilesDir = exports.STATE_FILES_PREFIX = exports.getSandboxAffinity = exports.SANDBOX_LABEL = exports.getClaimMountLabel = exports.getClaimPodSpec = exports.getWorkspacePodSpec = exports.appendVolume = exports.getMountedSources = exports.getKubernetesPersistence = exports.getVolumeName = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const crypto_1 = require("crypto");
@@ -100,9 +100,28 @@ stateKey) {
100
100
  volume.inherited ? dirOf(volume.inherited) : undefined);
101
101
  }
102
102
  }
103
+ if (isLiveService(work, kubernetes)) {
104
+ addSyncMounts(persistence);
105
+ }
103
106
  return persistence;
104
107
  }
105
108
  exports.getKubernetesPersistence = getKubernetesPersistence;
109
+ /**
110
+ * A live service's mounts of its watched folder are read only, as the app sees them. Each gets a
111
+ * twin: the same claim and subPath, writable, at WRITABLE_MOUNT_DIR and its app path. The changes of
112
+ * the sandbox are written through the twins (see syncChangedFiles), and the app sees them through
113
+ * its own mounts of the same folders. The app's mounts are not changed.
114
+ */
115
+ function addSyncMounts(persistence) {
116
+ const twins = persistence.mounts
117
+ .filter(({ mount, workspace, sync }) => !workspace && !sync && mount.readOnly && mount.subPath?.startsWith(`${exports.LIVE_FILES_DIR}/`))
118
+ .map((entry) => ({
119
+ ...entry,
120
+ mount: { ...entry.mount, mountPath: `${exports.WRITABLE_MOUNT_DIR}${entry.mount.mountPath}`, readOnly: false },
121
+ sync: true,
122
+ }));
123
+ persistence.mounts.push(...twins);
124
+ }
106
125
  // Whether the path `localPath` is a file: what it is on disk, as docker binds it, and else
107
126
  // `guess`, which goes by its name (a `Dockerfile` or `LICENSE` has no extension, and a
108
127
  // `conf.d` folder has one)
@@ -293,6 +312,9 @@ exports.getStateFilesDir = getStateFilesDir;
293
312
  // are uploaded into the folder of that state, and synced into this one from there: the pod
294
313
  // stays, and the service sees the files of the new commit (syncLiveFiles).
295
314
  exports.LIVE_FILES_DIR = `${exports.STATE_FILES_PREFIX}live`;
315
+ // Where the writable twins of a live service's mounts are in its pod: a folder of its own, which
316
+ // no app path is in (the transfer tools are in /.hammerkit, a different folder)
317
+ exports.WRITABLE_MOUNT_DIR = '/.hammerkit-sync';
296
318
  function isLiveService(work, kubernetes) {
297
319
  return (!!kubernetes.server?.serviceRun &&
298
320
  !kubernetes.server.workspace &&
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HostExecutor = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
3
+ exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.cacheNamespace = exports.defaultWorker = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const crypto_1 = require("crypto");
6
6
  const checks_1 = require("./checks");
@@ -126,6 +126,32 @@ exports.removeServiceRunVolumes = removeServiceRunVolumes;
126
126
  * nothing else. The cache is shared by the runs of the same source, a task is keyed by
127
127
  * its definition and sources and not by where they are.
128
128
  */
129
+ /**
130
+ * What a line the worker of a run wrote on its standard output does: the message it carries goes
131
+ * to the matching handler (a `sync-failed` one is told with the run's id). A line that is not a
132
+ * message is not the run's, and is left alone.
133
+ */
134
+ function relayWorkerLine(line, runId, relay) {
135
+ try {
136
+ const message = JSON.parse(line);
137
+ if (message.kind === 'event') {
138
+ relay.emit(message.event);
139
+ }
140
+ else if (message.kind === 'up') {
141
+ relay.up?.(message.targets);
142
+ }
143
+ else if (message.kind === 'sync-failed') {
144
+ relay.syncFailed?.(runId);
145
+ }
146
+ else if (message.kind === 'result') {
147
+ relay.result(message);
148
+ }
149
+ }
150
+ catch {
151
+ // not ours: whatever else the process prints is not an event of the run
152
+ }
153
+ }
154
+ exports.relayWorkerLine = relayWorkerLine;
129
155
  class HostExecutor {
130
156
  constructor(options) {
131
157
  this.options = options;
@@ -136,16 +162,15 @@ class HostExecutor {
136
162
  }
137
163
  /**
138
164
  * Hands the changed files of a sandbox to the process of a service run that is up here, which
139
- * syncs them into its services (see run-worker). False when no process of the run runs here.
165
+ * syncs them into its services (see run-worker). The archive goes in the line itself, so
166
+ * nothing is staged on this server. False when no process of the run runs here.
140
167
  */
141
168
  syncChildFiles(runId, changes) {
142
169
  const child = this.children.get(runId);
143
- const staging = this.options.sandboxes?.staging;
144
- if (!child?.stdin || !staging) {
170
+ if (!child?.stdin) {
145
171
  return false;
146
172
  }
147
- // the worker removes the batch folder only inside the staging folder of the run it is in
148
- child.stdin.write(`sync ${JSON.stringify({ staging: (0, path_1.join)(staging, runId), changes })}\n`);
173
+ child.stdin.write(`sync ${JSON.stringify({ ...changes, archive: changes.archive.toString('base64') })}\n`);
149
174
  return true;
150
175
  }
151
176
  // the docker daemon the runs' services are on, as their processes reach it
@@ -524,26 +549,17 @@ class HostExecutor {
524
549
  else {
525
550
  signal.addEventListener('abort', stop, { once: true });
526
551
  }
527
- (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => {
528
- try {
529
- const message = JSON.parse(line);
530
- if (message.kind === 'event') {
531
- context.emit(message.event);
532
- }
533
- else if (message.kind === 'up') {
534
- context.up?.(message.targets);
535
- }
536
- else if (message.kind === 'result') {
537
- result = message;
538
- // nothing left to tell the process
539
- this.children.delete(runId);
540
- child.stdin.end();
541
- }
542
- }
543
- catch {
544
- // not ours: whatever else the process prints is not an event of the run
545
- }
546
- });
552
+ (0, readline_1.createInterface)({ input: child.stdout }).on('line', (line) => relayWorkerLine(line, runId, {
553
+ emit: (event) => context.emit(event),
554
+ up: (targets) => context.up?.(targets),
555
+ syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
556
+ result: (message) => {
557
+ result = message;
558
+ // nothing left to tell the process
559
+ this.children.delete(runId);
560
+ child.stdin.end();
561
+ },
562
+ }));
547
563
  child.stderr.on('data', (chunk) => {
548
564
  stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
549
565
  });