@yarkivaev/scada 2.15.0 → 2.17.0

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 (47) hide show
  1. package/db/bootstrap/apply-hba.sh +11 -0
  2. package/db/bootstrap/entrypoint.sh +6 -0
  3. package/db/bootstrap/ownership.sql +18 -0
  4. package/db/bootstrap/zz-auth.sh +3 -0
  5. package/index.js +1 -0
  6. package/package.json +3 -2
  7. package/src/application/control/controller.js +2 -9
  8. package/src/application/control/periodicReconciliation.js +19 -0
  9. package/src/application/control/publishControlCatalog.js +25 -0
  10. package/src/application/control/reconcileStoredChoice.js +10 -0
  11. package/src/application/deploy/controlPlacement.js +71 -0
  12. package/src/application/deploy/controlPlan.js +124 -0
  13. package/src/application/deploy/deploymentCommands.js +29 -0
  14. package/src/application/deploy/deploymentPlan.js +84 -0
  15. package/src/application/deploy/readDeploymentDocument.js +25 -0
  16. package/src/application/deploy/readDocumentFile.js +28 -0
  17. package/src/application/deploy/releases.js +14 -10
  18. package/src/infrastructure/deploy/applyHelmResources.js +17 -0
  19. package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
  20. package/src/infrastructure/deploy/brokerReplicaTopology.js +75 -0
  21. package/src/infrastructure/deploy/buildDeploymentStages.js +23 -0
  22. package/src/infrastructure/deploy/compileDeploymentHooks.js +48 -0
  23. package/src/infrastructure/deploy/deploymentChecks.js +68 -0
  24. package/src/infrastructure/deploy/deploymentPatch.js +36 -0
  25. package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
  26. package/src/infrastructure/deploy/executeRelease.js +6 -2
  27. package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
  28. package/src/infrastructure/deploy/index.js +36 -0
  29. package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
  30. package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
  31. package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
  32. package/src/infrastructure/deploy/stagedStoragePreflight.js +72 -0
  33. package/src/infrastructure/deploy/validateStagedDeploymentEvidence.js +16 -0
  34. package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
  35. package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
  36. package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
  37. package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
  38. package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
  39. package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
  40. package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
  41. package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
  42. package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
  43. package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
  44. package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
  45. package/src/infrastructure/management/serveReconciliation.js +17 -0
  46. package/src/infrastructure/mdmesh/hmiPlan.js +123 -0
  47. package/src/infrastructure/mdmesh/index.js +1 -0
@@ -0,0 +1,11 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ hba="$PGDATA/pg_hba.conf"
4
+ awk '
5
+ /^# DSL target pod CIDRs/ { next }
6
+ $1 == "host" && $2 == "all" && $3 == "all" { next }
7
+ { print }
8
+ ' "$hba" > "$hba.dsl"
9
+ cat /pg-auth/pg_hba.conf.fragment >> "$hba.dsl"
10
+ cat "$hba.dsl" > "$hba"
11
+ rm -f "$hba.dsl"
@@ -0,0 +1,6 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ if [ -f "$PGDATA/PG_VERSION" ]; then
4
+ /pg-auth/apply-hba.sh
5
+ fi
6
+ exec /usr/local/bin/docker-entrypoint.sh postgres
@@ -0,0 +1,18 @@
1
+ CREATE TABLE IF NOT EXISTS schema_migrations (
2
+ version TEXT PRIMARY KEY,
3
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
4
+ );
5
+
6
+ DO $$
7
+ BEGIN
8
+ IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '@RUNTIME_ROLE@') THEN
9
+ CREATE ROLE @RUNTIME_ROLE@ NOLOGIN;
10
+ END IF;
11
+ END
12
+ $$;
13
+
14
+ ALTER TABLE IF EXISTS public.segments OWNER TO @RUNTIME_ROLE@;
15
+ ALTER TABLE IF EXISTS public.alerts OWNER TO @RUNTIME_ROLE@;
16
+ ALTER SEQUENCE IF EXISTS public.alerts_id_seq OWNER TO @RUNTIME_ROLE@;
17
+ ALTER TABLE IF EXISTS public.user_decisions OWNER TO @OWNER_ROLE@;
18
+ ALTER TABLE IF EXISTS public.schema_migrations OWNER TO @RUNTIME_ROLE@;
@@ -0,0 +1,3 @@
1
+ #!/bin/sh
2
+ set -eu
3
+ /pg-auth/apply-hba.sh
package/index.js CHANGED
@@ -158,3 +158,4 @@ export { default as prepareKubePrerequisites } from './src/infrastructure/deploy
158
158
  export { default as executeKubeSeed } from './src/infrastructure/deploy/executeKubeSeed.js';
159
159
  export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
160
160
  export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
161
+ export * from './src/infrastructure/deploy/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.15.0",
3
+ "version": "2.17.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,7 +21,8 @@
21
21
  "./runtime": "./src/application/runtime/index.js",
22
22
  "./streams": "./src/infrastructure/streams/index.js",
23
23
  "./control": "./src/application/control/index.js",
24
- "./mdmesh": "./src/infrastructure/mdmesh/index.js"
24
+ "./mdmesh": "./src/infrastructure/mdmesh/index.js",
25
+ "./deployment": "./src/infrastructure/deploy/index.js"
25
26
  },
26
27
  "bin": {
27
28
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -1,4 +1,5 @@
1
1
  import schedule from './schedule.js';
2
+ import periodicReconciliation from './periodicReconciliation.js';
2
3
  export async function reconcile(store, nodeId, options = {}) {
3
4
  const token = await store.acquire(nodeId);
4
5
  if (!token) { return false; }
@@ -10,13 +11,5 @@ export async function reconcile(store, nodeId, options = {}) {
10
11
  export default function controlLoop(store, nodeId, { intervalMs = 5000, onError = () => {
11
12
  // Optional diagnostic sink.
12
13
  }, ...options } = {}) {
13
- let stopped = false;
14
- let pending = null;
15
- function tick() {
16
- pending ??= reconcile(store, nodeId, options).catch(onError).finally(() => { pending = null; });
17
- return pending;
18
- }
19
- const timer = setInterval(() => { if (!stopped) { void tick(); } }, intervalMs);
20
- void tick();
21
- return { tick, async stop() { stopped = true; clearInterval(timer); await pending; } };
14
+ return periodicReconciliation(() => { return reconcile(store, nodeId, options); }, { intervalMs, onError });
22
15
  }
@@ -0,0 +1,19 @@
1
+ /** Run one reconciliation at a time, starting immediately. */
2
+ export default function periodicReconciliation(run, { intervalMs, onError }) {
3
+ const state = { stopped: false, pending: null };
4
+ function tick() {
5
+ if (state.stopped) { return state.pending; }
6
+ state.pending ??= Promise.resolve().then(run).catch(onError).finally(() => { state.pending = null; });
7
+ return state.pending;
8
+ }
9
+ const timer = setInterval(() => { void tick(); }, intervalMs);
10
+ void tick();
11
+ return {
12
+ tick,
13
+ async stop() {
14
+ state.stopped = true;
15
+ clearInterval(timer);
16
+ await state.pending;
17
+ }
18
+ };
19
+ }
@@ -0,0 +1,25 @@
1
+ /** Publish desired catalog independently of bootstrap; disconnected agents remain explicitly pending. */
2
+ export default async function publishControlCatalog(plan, store, publish, { now = Date.now, freshnessMs = 15000, clockSkewMs = 5000 } = {}) {
3
+ const result = await publish(store, plan.catalog);
4
+ const view = await store.read();
5
+ const nodes = plan.catalog.nodes.map(({ id }) => {
6
+ const assignment = view.assignments[id];
7
+ const report = view.reports.find((item) => { return item.nodeId === id; });
8
+ const epoch = plan.catalog.controlEpoch ?? 'initial';
9
+ const matching = assignment?.catalogVersion === plan.catalog.version
10
+ && (assignment?.controlEpoch ?? 'initial') === epoch
11
+ && (report?.controlEpoch ?? 'initial') === epoch;
12
+ const received = matching && (report?.receivedGeneration ?? report?.appliedGeneration) === assignment.generation;
13
+ const applied = received && report?.appliedGeneration === assignment.generation;
14
+ const errors = received ? (report.tasks ?? []).filter((task) => { return task.state === 'failed'; })
15
+ .map(({ taskId, state }) => { return { taskId, state }; }) : [];
16
+ let status = applied ? 'applied' : 'pending';
17
+ if (errors.length) { status = 'error'; }
18
+ const at = now();
19
+ const fresh = Number.isFinite(report?.receivedAt) && report.receivedAt <= at + clockSkewMs && at - report.receivedAt <= freshnessMs;
20
+ if (received && !fresh) { status = 'stale'; }
21
+ return { nodeId: id, status, errors,
22
+ desiredGeneration: assignment?.generation ?? null, appliedGeneration: report?.appliedGeneration ?? null };
23
+ });
24
+ return { ...result, nodes };
25
+ }
@@ -0,0 +1,10 @@
1
+ /** Publish a choice only if its observed revision still matches, then use the stored value. */
2
+ export default async function reconcileStoredChoice({ key, read, choose, compareAndSet }) {
3
+ const view = await read();
4
+ const previous = view.assignments[key] ?? {};
5
+ const next = choose(previous, view);
6
+ if (JSON.stringify(next) === JSON.stringify(previous)) { return { record: previous, view }; }
7
+ const committed = await compareAndSet(view.revisions[`assignments/${key}`], next);
8
+ if (!committed) { return { record: previous, view }; }
9
+ return { record: (await read()).assignments[key] ?? next, view };
10
+ }
@@ -0,0 +1,71 @@
1
+ function places(tokens, home, nodes, groups) {
2
+ const selected = tokens.flatMap((token) => {
3
+ if (token === 'home') { return home ? [home] : []; }
4
+ if (Object.hasOwn(groups, token)) {
5
+ const { prefix, excludeHome } = groups[token];
6
+ if (typeof prefix !== 'string' || !prefix) { throw new TypeError(`Invalid placement group ${token}`); }
7
+ return nodes.filter((node) => {
8
+ return node.startsWith(prefix) && !(excludeHome && node === home);
9
+ }).sort();
10
+ }
11
+ if (!nodes.includes(token)) { throw new TypeError(`Unknown placement place ${token}`); }
12
+ return [token];
13
+ });
14
+ return [...new Set(selected)];
15
+ }
16
+
17
+ function policy(copies, preference) {
18
+ return { copies, cost: 1, eligibleNodes: preference, preference };
19
+ }
20
+
21
+ function validated(policyInput, node, config, { task, pinned, validateAdapter }) {
22
+ const nodeIds = config.nodes.map(({ id }) => { return id; });
23
+ const eligibleNodes = policyInput.eligibleNodes ?? nodeIds;
24
+ const copies = policyInput.copies ?? config.defaultCopies;
25
+ const cost = policyInput.cost ?? 1;
26
+ if (!Number.isSafeInteger(copies) || copies < 1 || copies > eligibleNodes.length
27
+ || new Set(eligibleNodes).size !== eligibleNodes.length
28
+ || eligibleNodes.some((id) => { return !nodeIds.includes(id); }) || !Number.isFinite(cost) || cost <= 0) {
29
+ throw new TypeError('Invalid input replication policy');
30
+ }
31
+ validateAdapter?.(task, copies);
32
+ if (pinned && ((policyInput.copies !== undefined && policyInput.copies !== 1)
33
+ || (policyInput.eligibleNodes && (eligibleNodes.length !== 1 || eligibleNodes[0] !== node.id)))) {
34
+ throw new TypeError('Serial reader must remain pinned to its physical owner');
35
+ }
36
+ return { copies: pinned ? 1 : copies, cost, eligibleNodes: pinned ? [node.id] : eligibleNodes,
37
+ ...(policyInput.preference && !pinned && { preference: policyInput.preference }), ...(pinned && { pinnedNode: node.id }) };
38
+ }
39
+
40
+ /** Build read and calculation placement from named node groups and declared priorities. */
41
+ export default function controlPlacement({ groups = {}, validateAdapter } = {}) {
42
+ return {
43
+ readPlacement(config, streams, home, nodeIds) {
44
+ const rules = config.placement?.areas ?? [];
45
+ const matches = [...new Set(streams.map((stream) => {
46
+ return rules.find(({ match }) => { return stream?.includes(`/${match}/`); });
47
+ }).filter(Boolean))];
48
+ if (matches.length > 1) { throw new TypeError('Conflicting placement area for grouped reader'); }
49
+ const [rule] = matches;
50
+ if (!rule?.read) { return null; }
51
+ const preference = places(rule.read, home, nodeIds, groups);
52
+ const copies = Math.min(config.placement.readCopies ?? config.defaultCopies, preference.length);
53
+ if (copies < 1) { throw new TypeError(`Invalid placement preference for ${home}`); }
54
+ return policy(copies, preference);
55
+ },
56
+ calculatePlacement(config, areaMatch, home, nodeIds) {
57
+ const rule = config.placement?.areas?.find(({ match }) => { return match === areaMatch; });
58
+ if (!rule?.calculate) { return null; }
59
+ if (rule.calculate.includes('cache') && !rule.read) {
60
+ throw new TypeError(`Calculation cache for ${areaMatch} needs a read list`);
61
+ }
62
+ const tokens = rule.calculate.flatMap((token) => { return token === 'cache' ? rule.read : [token]; });
63
+ const preference = places(tokens, home, nodeIds, groups);
64
+ if (!preference.length) { throw new TypeError(`Invalid calculation preference for ${home}`); }
65
+ return policy(1, preference);
66
+ },
67
+ taskPlacement(policyInput, node, config, { task, pinned } = {}) {
68
+ return validated(policyInput, node, config, { task, pinned, validateAdapter });
69
+ }
70
+ };
71
+ }
@@ -0,0 +1,124 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function endpoint(address, port) {
4
+ const host = address.includes(':') && !address.startsWith('[') ? `[${address}]` : address;
5
+ return `https://${host}:${port}`;
6
+ }
7
+
8
+ /** Derive etcd peer and client addresses from declared voting roles. */
9
+ export function etcdMembership(nodes, { clientPort, peerPort }) {
10
+ const voters = nodes.filter(({ voter }) => { return voter; });
11
+ return {
12
+ endpoints: voters.map(({ address }) => { return endpoint(address, clientPort); }).join(','),
13
+ initialCluster: voters.map(({ id, address }) => { return `${id}=${endpoint(address, peerPort)}`; }).join(',')
14
+ };
15
+ }
16
+
17
+ /** Build a stable catalog revision using exactly the scheduling inputs. */
18
+ export function versionedControlCatalog({ version, controlEpoch, nodes, tasks }) {
19
+ if (new Set(tasks.map(({ taskId }) => { return taskId; })).size !== tasks.length) {
20
+ throw new TypeError('Duplicate control task identity');
21
+ }
22
+ const content = { controlEpoch, nodes: nodes.map(({ id, capacity }) => { return { id, capacity }; }), tasks };
23
+ const digest = createHash('sha256').update(JSON.stringify(content)).digest('hex');
24
+ return { version: `${version}:${digest}`, ...content };
25
+ }
26
+
27
+ /** Validate the requests and limits object accepted by a Kubernetes chart. */
28
+ export function deploymentResources(value) {
29
+ if (value === undefined) { return; }
30
+ if (!value || typeof value !== 'object' || Array.isArray(value)
31
+ || ['requests', 'limits'].some((key) => {
32
+ return value[key] !== undefined && (!value[key] || typeof value[key] !== 'object' || Array.isArray(value[key]));
33
+ })) {
34
+ throw new TypeError('Invalid control resources');
35
+ }
36
+ }
37
+
38
+ function recoveryTimeout(value = 900000) {
39
+ if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) { throw new TypeError('Invalid collector recovery timeout'); }
40
+ return value;
41
+ }
42
+
43
+ function agentCapacity(config, node, limits, extra = {}) {
44
+ if (node.agent !== undefined && (!node.agent || typeof node.agent !== 'object' || Array.isArray(node.agent))) {
45
+ throw new TypeError('Invalid collector capacity');
46
+ }
47
+ const result = {
48
+ ...extra, ...Object.fromEntries(limits.map((key) => { return [key, config[key]]; })),
49
+ recoveryTimeoutMs: config.recoveryTimeoutMs, resources: config.agentResources, ...node.agent
50
+ };
51
+ for (const key of limits) {
52
+ if (!Number.isSafeInteger(result[key]) || result[key] < 1) { throw new TypeError(`Invalid collector ${key}`); }
53
+ }
54
+ deploymentResources(result.resources);
55
+ if (result.heapMb !== undefined && (!Number.isSafeInteger(result.heapMb) || result.heapMb < 1)) {
56
+ throw new TypeError('Invalid collector heapMb');
57
+ }
58
+ return result;
59
+ }
60
+
61
+ function collectorStartupProbe(timeout) {
62
+ const periodSeconds = 5;
63
+ return {
64
+ httpGet: { path: '/startup', port: 9092 },
65
+ periodSeconds,
66
+ timeoutSeconds: 2,
67
+ failureThreshold: Math.ceil(timeout / (periodSeconds * 1000)) + 1
68
+ };
69
+ }
70
+
71
+ /** Render the standard SCADA collector agent runtime with caller-provided credential references. */
72
+ export function collectorControlDeployment(config, node, { endpoints, brokerEndpoints, hostDevices, deliverySecret, renderDeployment = false }) {
73
+ const capacity = agentCapacity(config, node, ['spoolMaxBytes', 'spoolMaxRecords'], { storage: config.agentStorage });
74
+ const recoveryMs = recoveryTimeout(capacity.recoveryTimeoutMs);
75
+ return {
76
+ nodeId: node.id, renderDeployment, image: config.agentImage,
77
+ tlsSecret: node.clientTlsSecret ?? `${node.id}-control-client`,
78
+ authSecret: node.authSecret ?? `${node.id}-control-auth`,
79
+ authUsernameKey: config.authUsernameKey, authPasswordKey: config.authPasswordKey,
80
+ deliverySecret, storage: capacity.storage, resources: capacity.resources,
81
+ hostDevices, startupProbe: collectorStartupProbe(recoveryMs),
82
+ env: {
83
+ ...(capacity.heapMb !== undefined && { NODE_OPTIONS: `--max-old-space-size=${capacity.heapMb}` }),
84
+ COLLECTOR_RECOVERY_TIMEOUT_MS: String(recoveryMs), COLLECTOR_NODE_ID: node.id,
85
+ COLLECTOR_BROKER_ENDPOINTS: JSON.stringify(brokerEndpoints), COLLECTOR_CONTROL_ENDPOINTS: endpoints,
86
+ COLLECTOR_CONTROL_PREFIX: config.prefix, COLLECTOR_ASSIGNMENT_FILE: '/data/assignment.json',
87
+ COLLECTOR_CONTROL_CA: '/tls/ca.crt', COLLECTOR_CONTROL_CERT: '/tls/tls.crt', COLLECTOR_CONTROL_KEY: '/tls/tls.key',
88
+ COLLECTOR_HEALTH_HOST: '0.0.0.0', COLLECTOR_HEALTH_PORT: '9091', COLLECTOR_STARTUP_PORT: '9092',
89
+ COLLECTOR_LIVE_STALE_MS: '2147483647', COLLECTOR_SPOOL_DIR: '/data/spool',
90
+ COLLECTOR_SPOOL_MAX_BYTES: String(capacity.spoolMaxBytes), COLLECTOR_SPOOL_MAX_RECORDS: String(capacity.spoolMaxRecords)
91
+ }
92
+ };
93
+ }
94
+
95
+ /** Mount writable temporary storage in a collector with a read-only root filesystem. */
96
+ export function withCollectorScratch(collector) {
97
+ return { ...collector, readOnlyRootFilesystem: true,
98
+ env: { ...collector.env, TMPDIR: '/tmp', XDG_CONFIG_HOME: '/tmp/config' },
99
+ volumeMounts: [...(collector.volumeMounts ?? []), { name: 'collector-tmp', mountPath: '/tmp' }],
100
+ volumes: [...(collector.volumes ?? []), { name: 'collector-tmp', emptyDir: { medium: 'Memory', sizeLimit: '64Mi' } }] };
101
+ }
102
+
103
+ /** Render a control agent using bounded in-memory queues and temporary storage. */
104
+ export function collectorMemoryDeployment(config, node, options) {
105
+ const { endpoints, brokerEndpoints, hostDevices, deliverySecret, extraEnv = {}, renderDeployment = false } = options;
106
+ const capacity = agentCapacity(config, node, ['queueMaxBytes', 'queueMaxRecords']);
107
+ const recoveryMs = recoveryTimeout(capacity.recoveryTimeoutMs);
108
+ return withCollectorScratch({
109
+ nodeId: node.id, renderDeployment, image: config.agentImage,
110
+ tlsSecret: node.clientTlsSecret ?? `${node.id}-control-client`, authSecret: node.authSecret ?? `${node.id}-control-auth`,
111
+ authUsernameKey: config.authUsernameKey, authPasswordKey: config.authPasswordKey, deliverySecret, resources: capacity.resources,
112
+ hostDevices, startupProbe: collectorStartupProbe(recoveryMs),
113
+ env: {
114
+ ...extraEnv, ...(capacity.heapMb !== undefined && { NODE_OPTIONS: `--max-old-space-size=${capacity.heapMb}` }),
115
+ COLLECTOR_RECOVERY_TIMEOUT_MS: String(recoveryMs), COLLECTOR_NODE_ID: node.id,
116
+ COLLECTOR_BROKER_ENDPOINTS: JSON.stringify(brokerEndpoints), COLLECTOR_CONTROL_ENDPOINTS: endpoints,
117
+ COLLECTOR_CONTROL_PREFIX: config.prefix,
118
+ COLLECTOR_CONTROL_CA: '/tls/ca.crt', COLLECTOR_CONTROL_CERT: '/tls/tls.crt', COLLECTOR_CONTROL_KEY: '/tls/tls.key',
119
+ COLLECTOR_HEALTH_HOST: '0.0.0.0', COLLECTOR_HEALTH_PORT: '9091', COLLECTOR_STARTUP_PORT: '9092',
120
+ COLLECTOR_LIVE_STALE_MS: '2147483647',
121
+ COLLECTOR_QUEUE_MAX_BYTES: String(capacity.queueMaxBytes), COLLECTOR_QUEUE_MAX_RECORDS: String(capacity.queueMaxRecords)
122
+ }
123
+ });
124
+ }
@@ -0,0 +1,29 @@
1
+ function entries(configuration, plugins) {
2
+ if (!configuration || typeof configuration !== 'object' || Array.isArray(configuration)) {
3
+ throw new TypeError('Deployment commands must be a mapping');
4
+ }
5
+ return new Map(Object.entries(configuration).map(([name, declaration]) => {
6
+ const plugin = Object.hasOwn(plugins, declaration?.plugin) ? plugins[declaration.plugin] : undefined;
7
+ if (!plugin) { throw new TypeError(`Unknown deployment plugin for ${name}`); }
8
+ const methods = new Map(['plan', 'deploy'].filter((method) => {
9
+ return declaration[method] === true;
10
+ }).map((method) => {
11
+ if (typeof plugin[method] !== 'function') {
12
+ throw new TypeError(`Deployment plugin ${declaration.plugin} does not implement ${method}`);
13
+ }
14
+ return [method, plugin[method].bind(plugin)];
15
+ }));
16
+ if (!methods.size) { throw new TypeError(`Deployment command ${name} has no actions`); }
17
+ return [name, methods];
18
+ }));
19
+ }
20
+
21
+ /** Selects deployment ports from modules registered by the application. */
22
+ export default function deploymentCommands(configuration, plugins) {
23
+ const commands = entries(configuration, plugins);
24
+ return function run(name, method, options) {
25
+ const command = commands.get(name)?.get(method);
26
+ if (!command) { throw new TypeError(`Unsupported deployment command ${name} ${method}`); }
27
+ return command(options);
28
+ };
29
+ }
@@ -0,0 +1,84 @@
1
+ import { isIP } from 'node:net';
2
+ import expand from './expand.js';
3
+ import { releaseFor } from './releases.js';
4
+ import { serverFor } from './releaseNodes.js';
5
+
6
+ /** Resolve deployment inputs once for a plant module that builds chart values. */
7
+ export function deploymentContext(document, cluster) {
8
+ const expanded = expand(document);
9
+ const server = serverFor(expanded, cluster);
10
+ const profile = expanded.profiles[server.profile.id];
11
+ return { expanded, server, profile, ...releaseFor(expanded, server) };
12
+ }
13
+
14
+ /** Merge device mounts and assignments into one collector process for a node. */
15
+ export function collectorDeployment(processes, options) {
16
+ const { assignments, command, image, resources, environment, hostSecurity, healthPort = 9091 } = options;
17
+ if (!image) { throw new TypeError('Universal collector image required in DSL'); }
18
+ if (!processes.length) { return []; }
19
+ const hostDevices = [...new Set(processes.flatMap((process) => { return process.hostDevices ?? []; }))].sort();
20
+ return [{
21
+ name: 'collector',
22
+ adapter: 'collector',
23
+ health: { port: healthPort },
24
+ command,
25
+ image,
26
+ resources,
27
+ hostDevices,
28
+ ...(hostDevices.length && hostSecurity && { podSecurityContext: hostSecurity }),
29
+ env: {
30
+ ...environment,
31
+ COLLECTOR_HEALTH_PORT: String(healthPort),
32
+ COLLECTOR_HEALTH_HOST: '0.0.0.0',
33
+ COLLECTOR_LIVE_STALE_MS: '2147483647',
34
+ COLLECTOR_MANIFEST: JSON.stringify({ assignments })
35
+ }
36
+ }];
37
+ }
38
+
39
+ /** Convert predecessor names into exact workload and label bindings. */
40
+ export function retiredDeployments({ prefix, groups, desired = [], extra = [] }) {
41
+ const retired = new Set();
42
+ const replacements = groups.flatMap((names) => {
43
+ if (!Array.isArray(names)) { throw new TypeError('invalid replacement list'); }
44
+ return names.map((name) => {
45
+ if (typeof name !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name)
46
+ || retired.has(name) || desired.some((item) => { return item.name === name; })) {
47
+ throw new TypeError('invalid replacement deployment');
48
+ }
49
+ retired.add(name);
50
+ return { workload: `deployment/${prefix}-${name}`, selector: `app=${name}` };
51
+ });
52
+ });
53
+ return [...replacements, ...extra.map(({ name, label }) => {
54
+ return { workload: `deployment/${prefix}-${name}`, selector: `app=${label}` };
55
+ })];
56
+ }
57
+
58
+ /** Bind a release target and default chart values across a sequence of stages. */
59
+ export function stageFor(common, values) {
60
+ return (id, fragment, workloads) => {
61
+ return { ...common, id, values: { ...values, ...fragment }, workloads };
62
+ };
63
+ }
64
+
65
+ /** Generate a node-port service and its peer-scoped ingress policy. */
66
+ export function peerNodePort({ name, namespace, selector, peerAddresses, portName, port, nodePort, additionalPorts = [], namespacePeers = [] }) {
67
+ if (!selector || !Object.keys(selector).length) { throw new TypeError('NodePort workload selector is required'); }
68
+ const metadata = { name, namespace };
69
+ const service = { apiVersion: 'v1', kind: 'Service', metadata, spec: {
70
+ type: 'NodePort', externalTrafficPolicy: 'Local', selector, ports: [{ name: portName, port, targetPort: port, nodePort }]
71
+ } };
72
+ const peers = [...namespacePeers.map((namespaceSelector) => { return { namespaceSelector }; }),
73
+ ...peerAddresses.map((address) => {
74
+ if (isIP(address) !== 4) { throw new TypeError('Peer ingress requires an IPv4 address'); }
75
+ return { ipBlock: { cidr: `${address}/32` } };
76
+ })];
77
+ const ingress = [
78
+ ...(peers.length ? [{ from: peers, ports: [{ protocol: 'TCP', port }] }] : []),
79
+ ...(additionalPorts.length ? [{ ports: additionalPorts.map((number) => { return { protocol: 'TCP', port: number }; }) }] : [])
80
+ ];
81
+ return [service, { apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata, spec: {
82
+ podSelector: { matchLabels: selector }, policyTypes: ['Ingress'], ingress
83
+ } }];
84
+ }
@@ -0,0 +1,25 @@
1
+ import readDocumentFile, { selectDeploymentPhase } from './readDocumentFile.js';
2
+
3
+ function fileSelection(file) {
4
+ if (file instanceof URL) {
5
+ return { path: file, phase: file.hash ? decodeURIComponent(file.hash.slice(1)) : undefined };
6
+ }
7
+ const fragment = file.lastIndexOf('#');
8
+ return fragment < 0 ? { path: file } : { path: file.slice(0, fragment), phase: file.slice(fragment + 1) };
9
+ }
10
+
11
+ /** A deployment document can declare its phase policy and be opened as path#phase. */
12
+ export default function readDeploymentDocument(file, parse) {
13
+ const { path, phase } = fileSelection(file);
14
+ const { deploymentPhase: policy, ...document } = readDocumentFile(path, parse);
15
+ if (policy === undefined) {
16
+ if (phase !== undefined) { throw new TypeError('Deployment phase policy is missing'); }
17
+ return document;
18
+ }
19
+ if (typeof policy?.section !== 'string' || typeof policy.selection !== 'string'
20
+ || !Array.isArray(policy.fields) || !policy.fields.length
21
+ || policy.fields.some((field) => { return typeof field !== 'string'; })) {
22
+ throw new TypeError('Invalid deployment phase policy');
23
+ }
24
+ return selectDeploymentPhase(phase === undefined ? document : { ...document, [policy.selection]: phase }, policy);
25
+ }
@@ -0,0 +1,28 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import readDocument from './readDocument.js';
5
+
6
+ /** Load one deployment document and resolve its includes beside the root document. */
7
+ export default function readDocumentFile(file, parse = readDocument) {
8
+ const path = file instanceof URL ? fileURLToPath(file) : file;
9
+ const directory = dirname(path);
10
+ return parse(readFileSync(path, 'utf8'), (name) => {
11
+ return readFileSync(join(directory, name), 'utf8');
12
+ });
13
+ }
14
+
15
+ /** Apply only declared boolean options when a deployment document selects a phase. */
16
+ export function selectDeploymentPhase(document, { selection, section, fields, label = section }) {
17
+ if (document[selection] === undefined) { return document; }
18
+ const configuration = document[section];
19
+ const phases = configuration?.phases;
20
+ const name = document[selection];
21
+ const selected = phases && Object.hasOwn(phases, name) ? phases[name] : undefined;
22
+ if (!selected || typeof selected !== 'object' || Array.isArray(selected)
23
+ || fields.some((field) => { return !Object.hasOwn(selected, field); })
24
+ || Object.entries(selected).some(([key, value]) => { return !fields.includes(key) || typeof value !== 'boolean'; })) {
25
+ throw new TypeError(`Invalid ${label} phase`);
26
+ }
27
+ return { ...document, [section]: { ...configuration, ...selected } };
28
+ }
@@ -94,6 +94,19 @@ function scadaRelease(document, server, profile, edges) {
94
94
  return withFlows(withProcess(values, profile, server), owned, routes, buses);
95
95
  }
96
96
 
97
+ /** Build the release values for a concrete server in an already expanded document. */
98
+ export function releaseFor(expanded, host) {
99
+ const links = edgesOf(expanded);
100
+ const profile = profileFor(expanded, host);
101
+ assertHeld(expanded, links);
102
+ return frozen({
103
+ ...(expanded.hmi !== undefined && { hmi: expanded.hmi }),
104
+ ...(profile.target && { target: profile.target }),
105
+ apps: passedApps(profile),
106
+ scada: scadaRelease(expanded, host, profile, links)
107
+ });
108
+ }
109
+
97
110
  /**
98
111
  * Cuts one cluster out of a system document.
99
112
  *
@@ -105,14 +118,5 @@ function scadaRelease(document, server, profile, edges) {
105
118
  */
106
119
  export default function releases(document, cluster) {
107
120
  const expanded = expand(document);
108
- const host = serverFor(expanded, cluster);
109
- const links = edgesOf(expanded);
110
- const profile = profileFor(expanded, host);
111
- assertHeld(expanded, links);
112
- return frozen({
113
- ...(expanded.hmi !== undefined && { hmi: expanded.hmi }),
114
- ...(profile.target && { target: profile.target }),
115
- apps: passedApps(profile),
116
- scada: scadaRelease(expanded, host, profile, links)
117
- });
121
+ return releaseFor(expanded, serverFor(expanded, cluster));
118
122
  }
@@ -0,0 +1,17 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { deploymentKube } from './deploymentKube.js';
3
+ import executeRelease from './executeRelease.js';
4
+
5
+ /** Apply only the named kinds in a rendered chart under an independent field manager. */
6
+ export default function applyHelmResources(plan, { kinds, decode, encode }, execute = execFileSync) {
7
+ if (!Array.isArray(kinds) || !kinds.length || kinds.some((kind) => { return typeof kind !== 'string' || !kind; })) {
8
+ throw new TypeError('An explicit nonempty list of resource kinds is required');
9
+ }
10
+ if (typeof plan.fieldManager !== 'string' || !plan.fieldManager.trim()) { throw new TypeError('Resource apply requires a field manager'); }
11
+ const kube = deploymentKube(plan, execute, { stdio: ['pipe', 'pipe', 'inherit'] });
12
+ const selected = new Set(kinds);
13
+ const rendered = decode(String(executeRelease(plan, 'render', execute)));
14
+ const resources = rendered.filter((resource) => { return resource && selected.has(resource.kind); });
15
+ if (!resources.length) { throw new Error('No resources matched the selected kinds'); }
16
+ return kube(['apply', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], resources.map((resource) => { return encode(resource); }).join('---\n'));
17
+ }
@@ -0,0 +1,28 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { deploymentKube } from './deploymentKube.js';
3
+ import executeRelease from './executeRelease.js';
4
+
5
+ function assertBootstrapTarget({ context, namespace, stage, storage }, action) {
6
+ if (!['check', 'apply'].includes(action)) { throw new TypeError('Storage bootstrap action must be check or apply'); }
7
+ if (!Array.isArray(storage) || !storage.length) { throw new TypeError('Storage bootstrap requires explicit workload references'); }
8
+ if (stage?.context !== context || stage?.namespace !== namespace) { throw new Error('Storage stage must match the bootstrap target'); }
9
+ }
10
+
11
+ /** Provision absent storage alone, preserving an existing complete storage set. */
12
+ export default function bootstrapKubeStorage(profile, action, execute = execFileSync) {
13
+ const { context, stage, storage, blockers = ['deployments', 'pods'] } = profile;
14
+ assertBootstrapTarget(profile, action);
15
+ const kube = deploymentKube(profile, execute, { stdio: ['pipe', 'pipe', 'pipe'] });
16
+ function get(resource) {
17
+ const output = kube(['get', resource, '--ignore-not-found', '-o', 'json'], undefined, true);
18
+ return JSON.parse(String(output ?? '').trim() || 'null');
19
+ }
20
+ const live = storage.map(get);
21
+ if (live.every(Boolean)) { return { target: context, created: false, preserved: true }; }
22
+ if (live.some(Boolean)) { throw new Error('Partial storage exists; refusing implicit replacement'); }
23
+ if (blockers.some((kind) => { return get(kind)?.items?.length; })) {
24
+ throw new Error('Existing workloads prevent fresh storage bootstrap');
25
+ }
26
+ executeRelease(stage, action, execute);
27
+ return { target: context, created: action === 'apply', preserved: false };
28
+ }