@yarkivaev/scada 2.15.0 → 2.16.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 (38) 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/controlPlan.js +93 -0
  12. package/src/application/deploy/deploymentCommands.js +29 -0
  13. package/src/application/deploy/deploymentPlan.js +84 -0
  14. package/src/application/deploy/readDocumentFile.js +28 -0
  15. package/src/application/deploy/releases.js +14 -10
  16. package/src/infrastructure/deploy/applyHelmResources.js +17 -0
  17. package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
  18. package/src/infrastructure/deploy/deploymentChecks.js +68 -0
  19. package/src/infrastructure/deploy/deploymentPatch.js +36 -0
  20. package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
  21. package/src/infrastructure/deploy/executeRelease.js +6 -2
  22. package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
  23. package/src/infrastructure/deploy/index.js +29 -0
  24. package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
  25. package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
  26. package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
  27. package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
  28. package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
  29. package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
  30. package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
  31. package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
  32. package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
  33. package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
  34. package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
  35. package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
  36. package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
  37. package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
  38. package/src/infrastructure/management/serveReconciliation.js +17 -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.16.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,93 @@
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) {
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
+ storage: config.agentStorage, spoolMaxBytes: config.spoolMaxBytes, spoolMaxRecords: config.spoolMaxRecords,
49
+ recoveryTimeoutMs: config.recoveryTimeoutMs, resources: config.agentResources, ...node.agent
50
+ };
51
+ for (const key of ['spoolMaxBytes', 'spoolMaxRecords']) {
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);
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
+ }
@@ -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,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
+ }
@@ -0,0 +1,68 @@
1
+ import { readKube } from './deploymentKube.js';
2
+
3
+ function podValue(pod, container, key) {
4
+ const definition = pod.spec?.containers?.find((entry) => { return entry.name === container; });
5
+ return definition?.env?.find((entry) => { return entry.name === key; })?.value;
6
+ }
7
+
8
+ /** Require matching environment on the desired workload and all currently selected pods. */
9
+ export function requireWorkloadEnvironment(kube, { workload, selector, container, key, value,
10
+ workloadError = 'Workload environment differs', podError = 'Pod environment differs' }) {
11
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) { throw new TypeError('Invalid environment variable name'); }
12
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(container ?? '')) { throw new TypeError('Invalid workload container name'); }
13
+ const query = `jsonpath={range .spec.template.spec.containers[?(@.name=="${container}")]}{.env[?(@.name=="${key}")].value}{end}`;
14
+ if (readKube(kube, workload, query) !== value) { throw new Error(workloadError); }
15
+ const { items } = JSON.parse(kube(['get', 'pods', '-l', selector, '-o', 'json'], undefined, true));
16
+ if (!Array.isArray(items) || !items.length || items.some((pod) => { return podValue(pod, container, key) !== value; })) {
17
+ throw new Error(podError);
18
+ }
19
+ }
20
+
21
+ function jobTarget(job) {
22
+ if (typeof job === 'string' && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(job)) {
23
+ return [`job/${job}`];
24
+ }
25
+ if (typeof job?.selector === 'string' && /^[A-Za-z0-9_./-]+=[A-Za-z0-9_.-]+$/u.test(job.selector)) {
26
+ return ['job', '-l', job.selector];
27
+ }
28
+ throw new TypeError('Kubernetes readiness requires an explicit Job name or exact label');
29
+ }
30
+
31
+ export function waitForJob(kube, job, timeout = '300s') {
32
+ kube(['wait', '--for=condition=complete', ...jobTarget(job), `--timeout=${timeout}`]);
33
+ }
34
+
35
+ /** Verify PostgreSQL from the deployed application, or directly while it is absent. */
36
+ export function verifyPostgresReadiness(kube, { workload, fallback, connectionEnv = 'POSTGRES_URL' }) {
37
+ const live = kube(['get', workload, '--ignore-not-found', '-o', 'name'], undefined, true);
38
+ if (!String(live).trim()) {
39
+ kube(['exec', fallback.target, '--', 'pg_isready', '-U', fallback.user, '-d', fallback.database]);
40
+ return;
41
+ }
42
+ const env = JSON.stringify(connectionEnv);
43
+ const probe = `import pg from 'pg'; const client = new pg.Client({ connectionString: process.env[${env}], connectionTimeoutMillis: 5000, query_timeout: 5000 }); try { await client.connect(); await client.query('SELECT 1'); console.log('PostgreSQL service verified'); } finally { await client.end(); }`;
44
+ kube(['exec', workload, '--', 'node', '--input-type=module', '-e', probe]);
45
+ }
46
+
47
+ /** Require recent, target-bound proof before a rollout that replaces live data paths. */
48
+ export function validateDeploymentEvidence({ context, required, claims, catalogVersion, readers = {} }, evidence, now = Date.now()) {
49
+ if (!evidence || evidence.cluster !== context || !required.every((key) => { return evidence[key]; })
50
+ || !(Date.parse(evidence.expiresAt) > now)) {
51
+ throw new Error('Verified per-host deployment evidence required');
52
+ }
53
+ if (catalogVersion !== undefined && evidence.controlCatalogVersion !== catalogVersion) {
54
+ throw new Error('Published control catalog version evidence required before collector cutover');
55
+ }
56
+ for (const [key, value] of Object.entries(readers)) {
57
+ if (evidence.optionalReaders?.[key] !== value) {
58
+ throw new Error(`Deployment evidence optional reader mismatch: ${key}`);
59
+ }
60
+ }
61
+ for (const claim of claims) {
62
+ const claimUid = evidence.claims?.[claim];
63
+ const volume = evidence.volumes?.[claim];
64
+ if (typeof claimUid !== 'string' || !claimUid || !volume?.name || !volume.uid) {
65
+ throw new Error('PVC identity evidence required');
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,36 @@
1
+ function aliasChange(env, path, rename) {
2
+ if (!rename) { return null; }
3
+ const { aliases, name } = rename;
4
+ const index = env.findIndex((row) => { return aliases.includes(row.name); });
5
+ if (index < 0) { return null; }
6
+ if (env[index].name !== name) { return { op: 'replace', path: `${path}/${index}/name`, value: name }; }
7
+ const duplicate = env.findIndex((row, other) => { return index !== other && aliases.includes(row.name); });
8
+ return duplicate < 0 ? null : { op: 'remove', path: `${path}/${duplicate}` };
9
+ }
10
+
11
+ function envChange(container, path, name, value) {
12
+ const env = container.env ?? [];
13
+ const item = { name, value };
14
+ if (!container.env) { return { op: 'add', path, value: [item] }; }
15
+ const index = env.findIndex((row) => { return row.name === name; });
16
+ if (index < 0) { return { op: 'add', path: `${path}/-`, value: item }; }
17
+ if (env[index].value === value && !env[index].valueFrom) { return null; }
18
+ if (env[index].valueFrom) { return { op: 'replace', path: `${path}/${index}`, value: item }; }
19
+ return { op: 'replace', path: `${path}/${index}/value`, value };
20
+ }
21
+
22
+ /** Select one change so each deployment update can be recomputed from fresh state. */
23
+ export default function deploymentPatch(body, { containerIndex = 0, rename, environment = {}, replicas }) {
24
+ const container = body.spec.template.spec.containers[containerIndex];
25
+ const path = `/spec/template/spec/containers/${containerIndex}/env`;
26
+ const alias = aliasChange(container.env ?? [], path, rename);
27
+ if (alias) { return alias; }
28
+ for (const [name, value] of Object.entries(environment)) {
29
+ if (value !== undefined) {
30
+ const op = envChange(container, path, name, value);
31
+ if (op) { return op; }
32
+ }
33
+ }
34
+ return Number.isInteger(replicas) && body.spec.replicas !== replicas
35
+ ? { op: Object.hasOwn(body.spec, 'replicas') ? 'replace' : 'add', path: '/spec/replicas', value: replicas } : null;
36
+ }
@@ -0,0 +1,19 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import applyWhenChanged from './applyWhenChanged.js';
4
+ import { deploymentKube, verifyKubeNode } from './deploymentKube.js';
5
+ import executeRelease, { requireReleaseAction } from './executeRelease.js';
6
+
7
+ /** Execute a chart release after binding live checks and dependencies to its target. */
8
+ export default function executeChartDeployment(profile, execute = execFileSync) {
9
+ const { action = 'render', plan, chartRoot, preflight, release } = profile;
10
+ requireReleaseAction(action);
11
+ const chart = path.resolve(chartRoot, plan.chart);
12
+ if (action !== 'render') {
13
+ const kube = deploymentKube(plan, execute, { stdio: ['pipe', 'pipe', 'pipe'] });
14
+ verifyKubeNode(kube, plan.nodeAddress);
15
+ preflight?.(plan, kube);
16
+ }
17
+ execute('helm', ['dependency', 'build', '--skip-refresh', chart], { stdio: 'pipe' });
18
+ return executeRelease({ ...plan, ...release?.(plan), chart }, action, applyWhenChanged(execute));
19
+ }
@@ -16,11 +16,15 @@ function validateRetirements(plan) {
16
16
  }
17
17
  }
18
18
 
19
- /** Validates the target before helm or kubectl can fall back to a default. */
20
- function validate(plan, action) {
19
+ export function requireReleaseAction(action) {
21
20
  if (!['render', 'check', 'diff', 'apply', 'adopt', 'check-adoption'].includes(action)) {
22
21
  throw new Error('action must be render, check, diff or apply (adopt/check-adoption for migration)');
23
22
  }
23
+ }
24
+
25
+ /** Validates the target before helm or kubectl can fall back to a default. */
26
+ function validate(plan, action) {
27
+ requireReleaseAction(action);
24
28
  const fields = action === 'render' ? ['chart', 'release', 'namespace'] : ['chart', 'release', 'namespace', 'context', 'fieldManager'];
25
29
  validateRetirements(plan);
26
30
  if (plan.podsAbsentBeforeApply !== undefined && (!Array.isArray(plan.podsAbsentBeforeApply)