@tsplc/agent 0.4.4 → 0.5.1
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.
- package/README.md +5 -1
- package/dist/cli.js +1103 -152
- package/dist/cli.js.map +24 -14
- package/dist/client.js +19 -4
- package/dist/client.js.map +4 -4
- package/dist/index.js +372 -128
- package/dist/index.js.map +14 -12
- package/package.json +5 -5
- package/src/agent.ts +63 -7
- package/src/cli.ts +93 -12
- package/src/client.ts +6 -1
- package/src/codesys.ts +61 -1
- package/src/deploy.ts +37 -1
- package/src/index.ts +1 -0
- package/src/instance.ts +102 -0
- package/src/login.ts +7 -0
- package/src/maintenance.ts +313 -0
- package/src/operations.ts +17 -1
- package/src/processes.ts +24 -0
- package/src/protocol.ts +19 -1
- package/src/server-process.ts +195 -40
- package/src/service.ts +206 -0
- package/src/state.ts +10 -1
- package/src/upgrade.ts +149 -0
package/dist/index.js
CHANGED
|
@@ -2,19 +2,17 @@
|
|
|
2
2
|
import { timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { join as join7 } from "node:path";
|
|
4
4
|
import { loginCommandSchema } from "@tsplc/build";
|
|
5
|
-
import { z as
|
|
5
|
+
import { z as z5 } from "zod";
|
|
6
6
|
|
|
7
|
-
// packages/agent/src/
|
|
8
|
-
import {
|
|
9
|
-
import { join as join3 } from "node:path";
|
|
7
|
+
// packages/agent/src/codesys.ts
|
|
8
|
+
import { join } from "node:path";
|
|
10
9
|
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
} from "@tsplc/
|
|
17
|
-
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
10
|
+
builderImageStatus,
|
|
11
|
+
captureDocker,
|
|
12
|
+
gatewayImage,
|
|
13
|
+
setupReason
|
|
14
|
+
} from "@tsplc/build";
|
|
15
|
+
import { resolveConfig } from "@tsplc/config/build";
|
|
18
16
|
|
|
19
17
|
// packages/agent/src/errors.ts
|
|
20
18
|
class AgentError extends Error {
|
|
@@ -28,6 +26,94 @@ class AgentError extends Error {
|
|
|
28
26
|
}
|
|
29
27
|
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
30
28
|
|
|
29
|
+
// packages/agent/src/codesys.ts
|
|
30
|
+
var network = "tsplc-agent";
|
|
31
|
+
var codesysNetwork = "tsplc-agent-codesys";
|
|
32
|
+
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
33
|
+
var loginContainer = "tsplc-agent-login";
|
|
34
|
+
var deployContainer = "tsplc-agent-deploy";
|
|
35
|
+
var agentDockerResources = {
|
|
36
|
+
containers: [gateway.host, deployContainer, loginContainer],
|
|
37
|
+
networks: [network, codesysNetwork]
|
|
38
|
+
};
|
|
39
|
+
var credentialNames = {
|
|
40
|
+
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
41
|
+
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
42
|
+
};
|
|
43
|
+
var dockerTimeout = 60000;
|
|
44
|
+
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
45
|
+
var ensureNetwork = async (name, ...options) => {
|
|
46
|
+
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
47
|
+
await docker("network", "create", ...options, name);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
var setupNeeded = async () => {
|
|
51
|
+
const status = await builderImageStatus();
|
|
52
|
+
const reason = setupReason(status) ?? (await docker("image", "ls", "--quiet", gatewayImage) ? null : `the CODESYS gateway image ${gatewayImage} is missing`);
|
|
53
|
+
return { status, reason };
|
|
54
|
+
};
|
|
55
|
+
var requireBuilder = async () => {
|
|
56
|
+
const { status, reason } = await setupNeeded().catch((cause) => {
|
|
57
|
+
throw new AgentError(`Docker doesn't answer on the plant PC; start Docker Desktop there: ${errorMessage(cause)}`, 503);
|
|
58
|
+
});
|
|
59
|
+
if (reason) {
|
|
60
|
+
throw new AgentError(`The plant PC needs tsplc-agent setup: ${reason}. Run tsplc-agent setup there; the line's server keeps running meanwhile`, 409);
|
|
61
|
+
}
|
|
62
|
+
return status;
|
|
63
|
+
};
|
|
64
|
+
var describeBuilder = async () => {
|
|
65
|
+
const { status, reason } = await setupNeeded();
|
|
66
|
+
if (reason) {
|
|
67
|
+
return `Deployments and logins need tsplc-agent setup first: ${reason}`;
|
|
68
|
+
}
|
|
69
|
+
if (status.kind === "unverified") {
|
|
70
|
+
return `Warning: ${status.reason}. Deployments use it; run tsplc-agent setup once to rebuild and label it`;
|
|
71
|
+
}
|
|
72
|
+
return "The CODESYS images match this tsPLC";
|
|
73
|
+
};
|
|
74
|
+
var removeContainer = (name) => docker("rm", "--force", name);
|
|
75
|
+
var ensureGateway = async () => {
|
|
76
|
+
await ensureNetwork(network);
|
|
77
|
+
await ensureNetwork(codesysNetwork, "--internal");
|
|
78
|
+
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
79
|
+
await docker("rm", "--force", gateway.host);
|
|
80
|
+
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
81
|
+
}
|
|
82
|
+
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
83
|
+
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
84
|
+
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
var credentialEnvironment = (credentials) => ({
|
|
88
|
+
[credentialNames.usernameEnv]: credentials.username,
|
|
89
|
+
[credentialNames.passwordEnv]: credentials.password
|
|
90
|
+
});
|
|
91
|
+
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
92
|
+
...resolveConfig({
|
|
93
|
+
...release.manifest.config,
|
|
94
|
+
...settings.bulkImport && { bulkImport: true },
|
|
95
|
+
online: {
|
|
96
|
+
network: codesysNetwork,
|
|
97
|
+
gateway,
|
|
98
|
+
device: target,
|
|
99
|
+
credentials: credentialNames
|
|
100
|
+
}
|
|
101
|
+
}, join(release.directory, "manifest.json")),
|
|
102
|
+
outDir: controllerDirectory
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// packages/agent/src/debugging.ts
|
|
106
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
107
|
+
import { join as join4 } from "node:path";
|
|
108
|
+
import {
|
|
109
|
+
createDebugger,
|
|
110
|
+
createDebugHandler,
|
|
111
|
+
createLoginAdapter,
|
|
112
|
+
loadManifest,
|
|
113
|
+
timelineEntries
|
|
114
|
+
} from "@tsplc/debug";
|
|
115
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
116
|
+
|
|
31
117
|
// packages/agent/src/logs.ts
|
|
32
118
|
import { existsSync } from "node:fs";
|
|
33
119
|
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
@@ -71,7 +157,7 @@ import { tsplcConfigSchema } from "@tsplc/config";
|
|
|
71
157
|
import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
|
|
72
158
|
import { z } from "zod";
|
|
73
159
|
// packages/agent/package.json
|
|
74
|
-
var version = "0.
|
|
160
|
+
var version = "0.5.1";
|
|
75
161
|
|
|
76
162
|
// packages/agent/src/protocol.ts
|
|
77
163
|
var tsplcVersion = version;
|
|
@@ -177,7 +263,7 @@ var clientHeaders = {
|
|
|
177
263
|
scripts: "x-tsplc-scripts"
|
|
178
264
|
};
|
|
179
265
|
var agentVersionHeader = "x-tsplc-agent-version";
|
|
180
|
-
var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match:
|
|
266
|
+
var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
|
|
181
267
|
var clientIdentity = (request) => {
|
|
182
268
|
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
183
269
|
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
@@ -219,7 +305,7 @@ import {
|
|
|
219
305
|
stat as stat2,
|
|
220
306
|
writeFile
|
|
221
307
|
} from "node:fs/promises";
|
|
222
|
-
import { dirname, join, posix, sep } from "node:path";
|
|
308
|
+
import { dirname, join as join2, posix, sep } from "node:path";
|
|
223
309
|
import { z as z2 } from "zod";
|
|
224
310
|
|
|
225
311
|
// packages/agent/src/transfer.ts
|
|
@@ -315,18 +401,18 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
315
401
|
hash.update(file.path).update(createHash2("sha256").update(file.content).digest("hex"));
|
|
316
402
|
}
|
|
317
403
|
const id = hash.digest("hex").slice(0, 16);
|
|
318
|
-
const directory =
|
|
404
|
+
const directory = join2(releases, id);
|
|
319
405
|
if (!existsSync2(directory)) {
|
|
320
406
|
await mkdir(releases, { recursive: true });
|
|
321
|
-
const staging = await mkdtemp(
|
|
407
|
+
const staging = await mkdtemp(join2(releases, ".upload-"));
|
|
322
408
|
try {
|
|
323
409
|
for (const file of files) {
|
|
324
|
-
await mkdir(dirname(
|
|
325
|
-
await writeFile(
|
|
410
|
+
await mkdir(dirname(join2(staging, file.path)), { recursive: true });
|
|
411
|
+
await writeFile(join2(staging, file.path), file.content, {
|
|
326
412
|
mode: file.path === manifest.server ? 493 : 420
|
|
327
413
|
});
|
|
328
414
|
}
|
|
329
|
-
await writeFile(
|
|
415
|
+
await writeFile(join2(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
330
416
|
await rename2(staging, directory);
|
|
331
417
|
} catch (cause) {
|
|
332
418
|
await rm(staging, { recursive: true, force: true });
|
|
@@ -336,14 +422,14 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
336
422
|
return { id, directory, manifest };
|
|
337
423
|
};
|
|
338
424
|
var loadRelease = async (releases, id) => {
|
|
339
|
-
const directory =
|
|
340
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(
|
|
425
|
+
const directory = join2(releases, id);
|
|
426
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(join2(directory, "manifest.json"), "utf8")));
|
|
341
427
|
return { id, directory, manifest };
|
|
342
428
|
};
|
|
343
429
|
var createReleaseStore = (releases) => {
|
|
344
430
|
const indexes = new Map;
|
|
345
431
|
const readIndex = async (id) => {
|
|
346
|
-
const directory =
|
|
432
|
+
const directory = join2(releases, id);
|
|
347
433
|
const files = new Map;
|
|
348
434
|
for await (const found of new Bun.Glob("**/*").scan({
|
|
349
435
|
cwd: directory,
|
|
@@ -351,7 +437,7 @@ var createReleaseStore = (releases) => {
|
|
|
351
437
|
})) {
|
|
352
438
|
const path = found.split(sep).join("/");
|
|
353
439
|
if (path !== "manifest.json") {
|
|
354
|
-
files.set(path, shortDigest(await readFile2(
|
|
440
|
+
files.set(path, shortDigest(await readFile2(join2(directory, found))));
|
|
355
441
|
}
|
|
356
442
|
}
|
|
357
443
|
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
@@ -373,7 +459,7 @@ var createReleaseStore = (releases) => {
|
|
|
373
459
|
}
|
|
374
460
|
const stored = await Promise.all((await readdir(releases, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map(async ({ name }) => ({
|
|
375
461
|
name,
|
|
376
|
-
created: (await stat2(
|
|
462
|
+
created: (await stat2(join2(releases, name))).mtimeMs
|
|
377
463
|
})));
|
|
378
464
|
return stored.sort((left, right) => right.created - left.created)[0]?.name;
|
|
379
465
|
};
|
|
@@ -381,7 +467,7 @@ var createReleaseStore = (releases) => {
|
|
|
381
467
|
compare: async (buckets, deployed) => {
|
|
382
468
|
const candidates = [
|
|
383
469
|
...new Set([deployed, await newest()].filter((id) => id != null))
|
|
384
|
-
].filter((id) => existsSync2(
|
|
470
|
+
].filter((id) => existsSync2(join2(releases, id, "manifest.json")));
|
|
385
471
|
const compared = await Promise.all(candidates.map(async (id) => {
|
|
386
472
|
const { files, buckets: stored } = await index(id);
|
|
387
473
|
const changed = buckets.flatMap((digest, bucket) => stored[bucket] === digest ? [] : [bucket]);
|
|
@@ -409,13 +495,13 @@ var createReleaseStore = (releases) => {
|
|
|
409
495
|
throw new AgentError("The release upload sends a file twice", 400);
|
|
410
496
|
}
|
|
411
497
|
if (base !== null) {
|
|
412
|
-
if (!existsSync2(
|
|
498
|
+
if (!existsSync2(join2(releases, base, "manifest.json"))) {
|
|
413
499
|
throw new AgentError(`The release ${base} this upload builds on is gone; deploy again`, 409);
|
|
414
500
|
}
|
|
415
501
|
const removed = new Set(remove);
|
|
416
502
|
const reused = [...(await index(base)).files.keys()].filter((path) => !removed.has(path) && !files.has(path));
|
|
417
503
|
for (const path of reused) {
|
|
418
|
-
files.set(path, new Uint8Array(await readFile2(
|
|
504
|
+
files.set(path, new Uint8Array(await readFile2(join2(releases, base, path))));
|
|
419
505
|
}
|
|
420
506
|
}
|
|
421
507
|
const assembled = bucketDigests([...files].map(([path, content]) => ({
|
|
@@ -437,7 +523,7 @@ var createReleaseStore = (releases) => {
|
|
|
437
523
|
|
|
438
524
|
// packages/agent/src/secrets.ts
|
|
439
525
|
import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
440
|
-
import { dirname as dirname2, join as
|
|
526
|
+
import { dirname as dirname2, join as join3, relative } from "node:path";
|
|
441
527
|
import { secretPlaceholder, secretValue } from "@tsplc/config";
|
|
442
528
|
import { escapeString } from "@tsplc/iec/st";
|
|
443
529
|
var agentService = "tsplc-agent";
|
|
@@ -496,14 +582,14 @@ var withSecrets = async (config, secrets, directory) => {
|
|
|
496
582
|
cwd: config.sourceDir,
|
|
497
583
|
dot: true
|
|
498
584
|
})) {
|
|
499
|
-
const file =
|
|
585
|
+
const file = join3(directory, path);
|
|
500
586
|
await mkdir2(dirname2(file), { recursive: true });
|
|
501
|
-
await writeFile2(file, fillSecrets(await readFile3(
|
|
587
|
+
await writeFile2(file, fillSecrets(await readFile3(join3(config.sourceDir, path), "utf8"), secrets));
|
|
502
588
|
}
|
|
503
589
|
return {
|
|
504
590
|
...config,
|
|
505
591
|
sourceDir: directory,
|
|
506
|
-
entry:
|
|
592
|
+
entry: join3(directory, relative(config.sourceDir, config.entry))
|
|
507
593
|
};
|
|
508
594
|
};
|
|
509
595
|
|
|
@@ -517,7 +603,7 @@ var createDebugging = (context) => {
|
|
|
517
603
|
return null;
|
|
518
604
|
}
|
|
519
605
|
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
520
|
-
const manifestFile =
|
|
606
|
+
const manifestFile = join4(directory, debugManifestFile);
|
|
521
607
|
if (!existsSync3(manifestFile)) {
|
|
522
608
|
return null;
|
|
523
609
|
}
|
|
@@ -594,58 +680,6 @@ import {
|
|
|
594
680
|
} from "@tsplc/build";
|
|
595
681
|
import { loadManifest as loadManifest2 } from "@tsplc/debug";
|
|
596
682
|
import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
|
|
597
|
-
|
|
598
|
-
// packages/agent/src/codesys.ts
|
|
599
|
-
import { join as join4 } from "node:path";
|
|
600
|
-
import { captureDocker, gatewayImage } from "@tsplc/build";
|
|
601
|
-
import { resolveConfig } from "@tsplc/config/build";
|
|
602
|
-
var network = "tsplc-agent";
|
|
603
|
-
var codesysNetwork = "tsplc-agent-codesys";
|
|
604
|
-
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
605
|
-
var loginContainer = "tsplc-agent-login";
|
|
606
|
-
var deployContainer = "tsplc-agent-deploy";
|
|
607
|
-
var credentialNames = {
|
|
608
|
-
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
609
|
-
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
610
|
-
};
|
|
611
|
-
var dockerTimeout = 60000;
|
|
612
|
-
var docker = async (...args) => (await captureDocker(args, dockerTimeout)).stdout.trim();
|
|
613
|
-
var ensureNetwork = async (name, ...options) => {
|
|
614
|
-
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
615
|
-
await docker("network", "create", ...options, name);
|
|
616
|
-
}
|
|
617
|
-
};
|
|
618
|
-
var ensureGateway = async () => {
|
|
619
|
-
await ensureNetwork(network);
|
|
620
|
-
await ensureNetwork(codesysNetwork, "--internal");
|
|
621
|
-
if (!await docker("container", "ls", "--quiet", "--filter", `name=^${gateway.host}$`)) {
|
|
622
|
-
await docker("rm", "--force", gateway.host);
|
|
623
|
-
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
624
|
-
}
|
|
625
|
-
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
626
|
-
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
627
|
-
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
628
|
-
}
|
|
629
|
-
};
|
|
630
|
-
var credentialEnvironment = (credentials) => ({
|
|
631
|
-
[credentialNames.usernameEnv]: credentials.username,
|
|
632
|
-
[credentialNames.passwordEnv]: credentials.password
|
|
633
|
-
});
|
|
634
|
-
var controllerConfig = (release, target, controllerDirectory, settings) => ({
|
|
635
|
-
...resolveConfig({
|
|
636
|
-
...release.manifest.config,
|
|
637
|
-
...settings.bulkImport && { bulkImport: true },
|
|
638
|
-
online: {
|
|
639
|
-
network: codesysNetwork,
|
|
640
|
-
gateway,
|
|
641
|
-
device: target,
|
|
642
|
-
credentials: credentialNames
|
|
643
|
-
}
|
|
644
|
-
}, join4(release.directory, "manifest.json")),
|
|
645
|
-
outDir: controllerDirectory
|
|
646
|
-
});
|
|
647
|
-
|
|
648
|
-
// packages/agent/src/deploy.ts
|
|
649
683
|
var createDeployments = (context) => {
|
|
650
684
|
const { state, server } = context;
|
|
651
685
|
const warming = (async () => {
|
|
@@ -654,6 +688,7 @@ var createDeployments = (context) => {
|
|
|
654
688
|
if (!deployed || !target) {
|
|
655
689
|
return;
|
|
656
690
|
}
|
|
691
|
+
await requireBuilder();
|
|
657
692
|
await ensureGateway();
|
|
658
693
|
const release = await loadRelease(state.paths.releases, deployed.id);
|
|
659
694
|
await startWarmController(controllerConfig(release, target, state.paths.controller, context.codesys), deployContainer);
|
|
@@ -661,10 +696,25 @@ var createDeployments = (context) => {
|
|
|
661
696
|
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
662
697
|
});
|
|
663
698
|
return {
|
|
699
|
+
retire: async () => {
|
|
700
|
+
await warming;
|
|
701
|
+
const deployed = await state.release();
|
|
702
|
+
const target = await state.target();
|
|
703
|
+
if (deployed && target) {
|
|
704
|
+
await settleWarmController(controllerConfig(await loadRelease(state.paths.releases, deployed.id), target, state.paths.controller, context.codesys), deployContainer);
|
|
705
|
+
}
|
|
706
|
+
await removeContainer(deployContainer);
|
|
707
|
+
},
|
|
664
708
|
deploy: async (readRequest, client, clientTsplc) => {
|
|
665
709
|
if (clientTsplc.version !== undefined && clientTsplc.version !== tsplcVersion) {
|
|
666
|
-
throw new AgentError(versionMismatch({
|
|
710
|
+
throw new AgentError(versionMismatch({
|
|
711
|
+
agent: tsplcVersion,
|
|
712
|
+
client: clientTsplc.version,
|
|
713
|
+
agentUpgrades: true
|
|
714
|
+
}), 409);
|
|
667
715
|
}
|
|
716
|
+
context.operations.requireIdle();
|
|
717
|
+
const builder = await requireBuilder();
|
|
668
718
|
const { settings, upload } = await readRequest();
|
|
669
719
|
const target = await state.requireTarget();
|
|
670
720
|
if (await findControllerLogin(loginContainer)) {
|
|
@@ -674,6 +724,12 @@ var createDeployments = (context) => {
|
|
|
674
724
|
const secrets = await readSecrets(upload.manifest.secrets);
|
|
675
725
|
const scripts = await workerScriptsDigest();
|
|
676
726
|
return context.operations.stream("a deployment", async (emit) => {
|
|
727
|
+
if (builder.kind === "unverified") {
|
|
728
|
+
emit({
|
|
729
|
+
kind: "progress",
|
|
730
|
+
message: `Warning: ${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`
|
|
731
|
+
});
|
|
732
|
+
}
|
|
677
733
|
if (clientTsplc.version === undefined) {
|
|
678
734
|
emit({
|
|
679
735
|
kind: "progress",
|
|
@@ -791,6 +847,43 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
791
847
|
return found;
|
|
792
848
|
};
|
|
793
849
|
|
|
850
|
+
// packages/agent/src/instance.ts
|
|
851
|
+
import { z as z3 } from "zod";
|
|
852
|
+
|
|
853
|
+
// packages/agent/src/processes.ts
|
|
854
|
+
var isGone = (error) => error instanceof Error && ("code" in error) && error.code === "ESRCH";
|
|
855
|
+
var processAlive = (pid) => {
|
|
856
|
+
try {
|
|
857
|
+
process.kill(pid, 0);
|
|
858
|
+
return true;
|
|
859
|
+
} catch (error) {
|
|
860
|
+
return !isGone(error);
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
var signalProcess = (pid, name) => {
|
|
864
|
+
try {
|
|
865
|
+
process.kill(pid, name);
|
|
866
|
+
} catch (error) {
|
|
867
|
+
if (!isGone(error)) {
|
|
868
|
+
throw error;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
// packages/agent/src/instance.ts
|
|
874
|
+
var instanceSchema = z3.strictObject({
|
|
875
|
+
pid: z3.int().positive(),
|
|
876
|
+
version: z3.string(),
|
|
877
|
+
url: z3.url(),
|
|
878
|
+
serve: z3.array(z3.string()),
|
|
879
|
+
supervised: z3.boolean(),
|
|
880
|
+
startedAt: z3.iso.datetime()
|
|
881
|
+
});
|
|
882
|
+
var exitSchema = z3.strictObject({
|
|
883
|
+
server: z3.enum(["leave", "stop"]),
|
|
884
|
+
restart: z3.boolean()
|
|
885
|
+
});
|
|
886
|
+
|
|
794
887
|
// packages/agent/src/login.ts
|
|
795
888
|
import { setTimeout as delay } from "node:timers/promises";
|
|
796
889
|
import {
|
|
@@ -881,6 +974,8 @@ var createLogin = (context) => {
|
|
|
881
974
|
return result.values;
|
|
882
975
|
},
|
|
883
976
|
open: async (sent) => {
|
|
977
|
+
operations.requireIdle();
|
|
978
|
+
await requireBuilder();
|
|
884
979
|
const credentials = await controllerCredentials(sent);
|
|
885
980
|
context.log(`Opening a login with the ${sent ? "provided" : "stored"} controller user`);
|
|
886
981
|
const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller, context.codesys);
|
|
@@ -933,6 +1028,7 @@ var createLogin = (context) => {
|
|
|
933
1028
|
}
|
|
934
1029
|
});
|
|
935
1030
|
},
|
|
1031
|
+
isOpen: async () => await findControllerLogin2(loginContainer) !== undefined,
|
|
936
1032
|
status: async () => {
|
|
937
1033
|
const login = await findControllerLogin2(loginContainer);
|
|
938
1034
|
if (!login) {
|
|
@@ -973,7 +1069,11 @@ var createLogin = (context) => {
|
|
|
973
1069
|
import { requiresDownload, transferRollback } from "@tsplc/build";
|
|
974
1070
|
var createOperations = (log) => {
|
|
975
1071
|
let busy;
|
|
1072
|
+
let held = false;
|
|
976
1073
|
const requireIdle = () => {
|
|
1074
|
+
if (held) {
|
|
1075
|
+
throw new AgentError("The plant agent is being upgraded; try again once it is back", 503);
|
|
1076
|
+
}
|
|
977
1077
|
if (busy) {
|
|
978
1078
|
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
979
1079
|
}
|
|
@@ -981,6 +1081,14 @@ var createOperations = (log) => {
|
|
|
981
1081
|
return {
|
|
982
1082
|
busy: () => busy,
|
|
983
1083
|
requireIdle,
|
|
1084
|
+
hold: () => {
|
|
1085
|
+
requireIdle();
|
|
1086
|
+
held = true;
|
|
1087
|
+
},
|
|
1088
|
+
release: () => {
|
|
1089
|
+
held = false;
|
|
1090
|
+
},
|
|
1091
|
+
held: () => held,
|
|
984
1092
|
exclusive: async (operation, run) => {
|
|
985
1093
|
requireIdle();
|
|
986
1094
|
busy = operation;
|
|
@@ -1034,35 +1142,117 @@ var createOperations = (log) => {
|
|
|
1034
1142
|
};
|
|
1035
1143
|
|
|
1036
1144
|
// packages/agent/src/server-process.ts
|
|
1145
|
+
import {
|
|
1146
|
+
closeSync,
|
|
1147
|
+
existsSync as existsSync5,
|
|
1148
|
+
openSync,
|
|
1149
|
+
renameSync,
|
|
1150
|
+
statSync,
|
|
1151
|
+
writeFileSync
|
|
1152
|
+
} from "node:fs";
|
|
1153
|
+
import { readFile as readFile4, rm as rm3 } from "node:fs/promises";
|
|
1154
|
+
import { uptime } from "node:os";
|
|
1037
1155
|
import { dirname as dirname3 } from "node:path";
|
|
1038
1156
|
import { setTimeout as delay2 } from "node:timers/promises";
|
|
1157
|
+
import { z as z4 } from "zod";
|
|
1039
1158
|
var healthyWithinMs = 60000;
|
|
1040
1159
|
var settleMs = 5000;
|
|
1041
1160
|
var restartDelayMs = 2000;
|
|
1161
|
+
var watchMs = 2000;
|
|
1162
|
+
var adoptWithinMs = 1e4;
|
|
1163
|
+
var stopWithinMs = 1e4;
|
|
1164
|
+
var rotateBytes2 = 10 * 2 ** 20;
|
|
1165
|
+
var recordSchema = z4.strictObject({
|
|
1166
|
+
pid: z4.int().positive(),
|
|
1167
|
+
executable: z4.string(),
|
|
1168
|
+
startedAt: z4.number()
|
|
1169
|
+
});
|
|
1170
|
+
var mayStillRun = (record, machine) => record.startedAt > machine.now - machine.uptimeSeconds * 1000 && machine.alive(record.pid);
|
|
1042
1171
|
var createServerSupervisor = (options) => {
|
|
1043
1172
|
let current;
|
|
1173
|
+
const writeRecord = (record) => writeFileSync(options.record, JSON.stringify(record));
|
|
1174
|
+
const readRecord = async () => {
|
|
1175
|
+
if (!existsSync5(options.record)) {
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
return recordSchema.safeParse(await readFile4(options.record, "utf8").then((text) => JSON.parse(text), () => {
|
|
1179
|
+
return;
|
|
1180
|
+
})).data;
|
|
1181
|
+
};
|
|
1182
|
+
const restartWhenExited = (running, code) => {
|
|
1183
|
+
running.exited.then(() => {
|
|
1184
|
+
if (current !== running) {
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
options.log(`Server exited (${code()}); restarting it in ${restartDelayMs / 1000} s`);
|
|
1188
|
+
delay2(restartDelayMs).then(() => {
|
|
1189
|
+
if (current === running) {
|
|
1190
|
+
current = spawn(running.executable);
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
});
|
|
1194
|
+
};
|
|
1044
1195
|
const spawn = (executable) => {
|
|
1045
1196
|
const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
current = { executable, process: spawn(executable) };
|
|
1057
|
-
}
|
|
1197
|
+
if (existsSync5(options.output) && statSync(options.output).size >= rotateBytes2) {
|
|
1198
|
+
renameSync(options.output, `${options.output}.1`);
|
|
1199
|
+
}
|
|
1200
|
+
const output = openSync(options.output, "a");
|
|
1201
|
+
const child = (() => {
|
|
1202
|
+
try {
|
|
1203
|
+
return Bun.spawn(command, {
|
|
1204
|
+
cwd: dirname3(executable),
|
|
1205
|
+
detached: true,
|
|
1206
|
+
stdio: ["ignore", output, output]
|
|
1058
1207
|
});
|
|
1208
|
+
} finally {
|
|
1209
|
+
closeSync(output);
|
|
1059
1210
|
}
|
|
1060
|
-
});
|
|
1061
|
-
|
|
1211
|
+
})();
|
|
1212
|
+
const running = {
|
|
1213
|
+
executable,
|
|
1214
|
+
pid: child.pid,
|
|
1215
|
+
alive: () => child.exitCode === null && child.signalCode === null,
|
|
1216
|
+
exited: child.exited
|
|
1217
|
+
};
|
|
1218
|
+
writeRecord({ pid: child.pid, executable, startedAt: Date.now() });
|
|
1219
|
+
restartWhenExited(running, () => child.exitCode ?? child.signalCode);
|
|
1220
|
+
return running;
|
|
1221
|
+
};
|
|
1222
|
+
const adopt = (record) => {
|
|
1223
|
+
const exited = Promise.withResolvers();
|
|
1224
|
+
const watch = setInterval(() => {
|
|
1225
|
+
if (!processAlive(record.pid)) {
|
|
1226
|
+
clearInterval(watch);
|
|
1227
|
+
exited.resolve();
|
|
1228
|
+
}
|
|
1229
|
+
}, watchMs);
|
|
1230
|
+
watch.unref();
|
|
1231
|
+
const running = {
|
|
1232
|
+
executable: record.executable,
|
|
1233
|
+
pid: record.pid,
|
|
1234
|
+
alive: () => processAlive(record.pid),
|
|
1235
|
+
exited: exited.promise
|
|
1236
|
+
};
|
|
1237
|
+
restartWhenExited(running, () => "unknown status");
|
|
1238
|
+
return running;
|
|
1239
|
+
};
|
|
1240
|
+
const answers = async (alive, within) => {
|
|
1241
|
+
if (!options.healthUrl) {
|
|
1242
|
+
return alive();
|
|
1243
|
+
}
|
|
1244
|
+
const deadline = Date.now() + within;
|
|
1245
|
+
while (Date.now() < deadline && alive()) {
|
|
1246
|
+
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
1247
|
+
return true;
|
|
1248
|
+
}
|
|
1249
|
+
await delay2(1000);
|
|
1250
|
+
}
|
|
1251
|
+
return false;
|
|
1062
1252
|
};
|
|
1063
1253
|
const start = (executable) => {
|
|
1064
|
-
current =
|
|
1065
|
-
return current
|
|
1254
|
+
current = spawn(executable);
|
|
1255
|
+
return current;
|
|
1066
1256
|
};
|
|
1067
1257
|
const stop = async () => {
|
|
1068
1258
|
const running = current;
|
|
@@ -1070,26 +1260,39 @@ var createServerSupervisor = (options) => {
|
|
|
1070
1260
|
if (!running) {
|
|
1071
1261
|
return;
|
|
1072
1262
|
}
|
|
1073
|
-
running.
|
|
1074
|
-
await running.
|
|
1263
|
+
signalProcess(running.pid, "SIGTERM");
|
|
1264
|
+
await Promise.race([running.exited, delay2(stopWithinMs)]);
|
|
1265
|
+
if (running.alive()) {
|
|
1266
|
+
signalProcess(running.pid, "SIGKILL");
|
|
1267
|
+
await running.exited;
|
|
1268
|
+
}
|
|
1269
|
+
await rm3(options.record, { force: true });
|
|
1075
1270
|
};
|
|
1076
|
-
const healthy = async (
|
|
1271
|
+
const healthy = async (running) => {
|
|
1077
1272
|
if (!options.healthUrl) {
|
|
1078
1273
|
await delay2(settleMs);
|
|
1079
|
-
return
|
|
1274
|
+
return running.alive();
|
|
1080
1275
|
}
|
|
1081
|
-
|
|
1082
|
-
while (Date.now() < deadline && child.exitCode === null) {
|
|
1083
|
-
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
1084
|
-
return true;
|
|
1085
|
-
}
|
|
1086
|
-
await delay2(1000);
|
|
1087
|
-
}
|
|
1088
|
-
return false;
|
|
1276
|
+
return answers(running.alive, healthyWithinMs);
|
|
1089
1277
|
};
|
|
1090
1278
|
return {
|
|
1091
|
-
|
|
1279
|
+
resume: async (executable) => {
|
|
1280
|
+
const record = await readRecord();
|
|
1281
|
+
if (record?.executable === executable && mayStillRun(record, {
|
|
1282
|
+
now: Date.now(),
|
|
1283
|
+
uptimeSeconds: uptime(),
|
|
1284
|
+
alive: processAlive
|
|
1285
|
+
}) && await answers(() => processAlive(record.pid), adoptWithinMs)) {
|
|
1286
|
+
options.log(`Took over the running server (process ${record.pid})`);
|
|
1287
|
+
current = adopt(record);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
start(executable);
|
|
1291
|
+
},
|
|
1092
1292
|
stop,
|
|
1293
|
+
leave: () => {
|
|
1294
|
+
current = undefined;
|
|
1295
|
+
},
|
|
1093
1296
|
replace: async (executable) => {
|
|
1094
1297
|
const previous = current?.executable;
|
|
1095
1298
|
await stop();
|
|
@@ -1110,16 +1313,16 @@ var createServerSupervisor = (options) => {
|
|
|
1110
1313
|
},
|
|
1111
1314
|
status: () => current && {
|
|
1112
1315
|
executable: current.executable,
|
|
1113
|
-
running: current.
|
|
1316
|
+
running: current.alive()
|
|
1114
1317
|
}
|
|
1115
1318
|
};
|
|
1116
1319
|
};
|
|
1117
1320
|
|
|
1118
1321
|
// packages/agent/src/state.ts
|
|
1119
|
-
import { existsSync as
|
|
1120
|
-
import { mkdir as mkdir3, readFile as
|
|
1322
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
1323
|
+
import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
|
|
1121
1324
|
import { join as join6 } from "node:path";
|
|
1122
|
-
var readJsonFile = async (path, schema) =>
|
|
1325
|
+
var readJsonFile = async (path, schema) => existsSync6(path) ? schema.parse(JSON.parse(await readFile5(path, "utf8"))) : null;
|
|
1123
1326
|
var writeJsonFile = (path, value) => writeFile3(path, JSON.stringify(value, null, 2));
|
|
1124
1327
|
var openState = async (directory) => {
|
|
1125
1328
|
const paths = {
|
|
@@ -1130,9 +1333,14 @@ var openState = async (directory) => {
|
|
|
1130
1333
|
target: join6(directory, "target.json"),
|
|
1131
1334
|
deployments: join6(directory, "deployments.jsonl"),
|
|
1132
1335
|
audit: join6(directory, "audit.jsonl"),
|
|
1133
|
-
debug: join6(directory, "debug")
|
|
1336
|
+
debug: join6(directory, "debug"),
|
|
1337
|
+
server: join6(directory, "server.json"),
|
|
1338
|
+
agent: join6(directory, "agent.json"),
|
|
1339
|
+
logs: join6(directory, "logs"),
|
|
1340
|
+
serverLog: join6(directory, "logs", "server.log"),
|
|
1341
|
+
agentLog: join6(directory, "logs", "agent.log")
|
|
1134
1342
|
};
|
|
1135
|
-
await mkdir3(
|
|
1343
|
+
await mkdir3(paths.logs, { recursive: true });
|
|
1136
1344
|
const target = () => readJsonFile(paths.target, targetSchema);
|
|
1137
1345
|
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
1138
1346
|
return {
|
|
@@ -1169,12 +1377,15 @@ var createAgent = async (options) => {
|
|
|
1169
1377
|
const state = await openState(options.state);
|
|
1170
1378
|
const server = createServerSupervisor({
|
|
1171
1379
|
healthUrl: options.serverHealthUrl,
|
|
1380
|
+
record: state.paths.server,
|
|
1381
|
+
output: state.paths.serverLog,
|
|
1172
1382
|
log
|
|
1173
1383
|
});
|
|
1174
1384
|
const deployed = await state.release();
|
|
1175
1385
|
if (deployed?.server) {
|
|
1176
|
-
server.
|
|
1386
|
+
await server.resume(join7(state.paths.releases, deployed.server));
|
|
1177
1387
|
}
|
|
1388
|
+
describeBuilder().then(log, (error) => log(`Can't check the CODESYS builder image yet: ${errorMessage(error)}`));
|
|
1178
1389
|
const operations = createOperations(log);
|
|
1179
1390
|
const codesys = { bulkImport: options.bulkImport ?? false };
|
|
1180
1391
|
const releases = createReleaseStore(state.paths.releases);
|
|
@@ -1249,6 +1460,32 @@ var createAgent = async (options) => {
|
|
|
1249
1460
|
return Response.json(await login.command(loginCommandSchema.parse(await request.json()), clientIdentity(request)));
|
|
1250
1461
|
case "DELETE /login":
|
|
1251
1462
|
return Response.json(await login.logout());
|
|
1463
|
+
case "POST /agent/hold": {
|
|
1464
|
+
operations.hold();
|
|
1465
|
+
try {
|
|
1466
|
+
if (await login.isOpen()) {
|
|
1467
|
+
throw new AgentError("A login is open; log out before upgrading the agent: tsplc logout", 409);
|
|
1468
|
+
}
|
|
1469
|
+
await deployments.retire();
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
operations.release();
|
|
1472
|
+
throw error;
|
|
1473
|
+
}
|
|
1474
|
+
return Response.json({ held: true });
|
|
1475
|
+
}
|
|
1476
|
+
case "DELETE /agent/hold":
|
|
1477
|
+
operations.release();
|
|
1478
|
+
return Response.json({ held: false });
|
|
1479
|
+
case "POST /agent/exit": {
|
|
1480
|
+
const exit = exitSchema.parse(await request.json());
|
|
1481
|
+
if (!operations.held()) {
|
|
1482
|
+
throw new AgentError("Hold the agent before it exits, so no operation is cut short", 409);
|
|
1483
|
+
}
|
|
1484
|
+
setTimeout(() => {
|
|
1485
|
+
(exit.server === "leave" ? leave() : stop()).then(() => options.exit(exit));
|
|
1486
|
+
}, 100);
|
|
1487
|
+
return Response.json({ exiting: true });
|
|
1488
|
+
}
|
|
1252
1489
|
default:
|
|
1253
1490
|
return Response.json({ error: `No route ${key}` }, { status: 404 });
|
|
1254
1491
|
}
|
|
@@ -1280,13 +1517,21 @@ var createAgent = async (options) => {
|
|
|
1280
1517
|
if (error instanceof AgentError) {
|
|
1281
1518
|
return Response.json({ error: error.message }, { status: error.status });
|
|
1282
1519
|
}
|
|
1283
|
-
if (error instanceof
|
|
1284
|
-
return Response.json({ error:
|
|
1520
|
+
if (error instanceof z5.ZodError) {
|
|
1521
|
+
return Response.json({ error: z5.prettifyError(error) }, { status: 400 });
|
|
1285
1522
|
}
|
|
1286
1523
|
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1287
1524
|
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
1288
1525
|
}
|
|
1289
1526
|
};
|
|
1527
|
+
const stop = async () => {
|
|
1528
|
+
await debugging.close();
|
|
1529
|
+
await server.stop();
|
|
1530
|
+
};
|
|
1531
|
+
const leave = async () => {
|
|
1532
|
+
await debugging.close();
|
|
1533
|
+
server.leave();
|
|
1534
|
+
};
|
|
1290
1535
|
return {
|
|
1291
1536
|
fetch: async (request) => {
|
|
1292
1537
|
const response = await respond(request);
|
|
@@ -1298,10 +1543,8 @@ var createAgent = async (options) => {
|
|
|
1298
1543
|
headers
|
|
1299
1544
|
});
|
|
1300
1545
|
},
|
|
1301
|
-
stop
|
|
1302
|
-
|
|
1303
|
-
await server.stop();
|
|
1304
|
-
}
|
|
1546
|
+
stop,
|
|
1547
|
+
leave
|
|
1305
1548
|
};
|
|
1306
1549
|
};
|
|
1307
1550
|
// packages/agent/src/terminal.ts
|
|
@@ -1357,6 +1600,7 @@ var askCredentials = async () => ({
|
|
|
1357
1600
|
password: await askSecret("Controller password: ")
|
|
1358
1601
|
});
|
|
1359
1602
|
export {
|
|
1603
|
+
agentDockerResources,
|
|
1360
1604
|
ask,
|
|
1361
1605
|
askCredentials,
|
|
1362
1606
|
askSecret,
|
|
@@ -1378,5 +1622,5 @@ export {
|
|
|
1378
1622
|
variableSchema
|
|
1379
1623
|
};
|
|
1380
1624
|
|
|
1381
|
-
//# debugId=
|
|
1625
|
+
//# debugId=F1A3E3150174DB6464756E2164756E21
|
|
1382
1626
|
//# sourceMappingURL=index.js.map
|