@yarkivaev/scada 2.13.0 → 2.15.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 (88) hide show
  1. package/charts/scada/templates/processes.yaml +6 -1
  2. package/charts/scada/values.schema.json +1 -0
  3. package/index.js +29 -0
  4. package/package.json +3 -2
  5. package/src/application/control/agent.js +8 -14
  6. package/src/application/control/controlClient.js +1 -1
  7. package/src/application/control/createOnlyJSON.js +50 -0
  8. package/src/application/control/executionSnapshot.js +4 -5
  9. package/src/application/control/index.js +2 -0
  10. package/src/application/control/jsonAssignments.js +30 -0
  11. package/src/application/mcp/loadMetricSeries.js +69 -0
  12. package/src/application/mcp/locateMachineMetric.js +25 -0
  13. package/src/application/mcp/metricQueryPorts.js +78 -0
  14. package/src/application/mcp/parseBearerTokens.js +43 -0
  15. package/src/application/runtime/assignment.js +4 -1
  16. package/src/application/runtime/deliveryOperations.js +6 -3
  17. package/src/application/runtime/deliveryPublications.js +13 -11
  18. package/src/application/runtime/deliveryQueue.js +5 -4
  19. package/src/application/runtime/index.js +0 -1
  20. package/src/application/runtime/queuedDelivery.js +6 -5
  21. package/src/application/runtime/runCollector.js +8 -6
  22. package/src/application/runtime/runtime.js +1 -0
  23. package/src/application/runtime/runtimeServices.js +6 -26
  24. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  25. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  26. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  27. package/src/infrastructure/deploy/executeRelease.js +8 -11
  28. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  29. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  30. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  31. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  32. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  33. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  34. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  35. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  36. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  37. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  38. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  39. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  40. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  41. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  42. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  43. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  44. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  45. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  46. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  47. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  48. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  49. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  50. package/src/infrastructure/mdmesh/index.js +7 -0
  51. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  52. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  53. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  54. package/src/infrastructure/opcua/health.js +91 -0
  55. package/src/infrastructure/opcua/index.js +1 -0
  56. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  57. package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
  58. package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
  59. package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
  60. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  61. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  62. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  63. package/src/infrastructure/replication/snapshotSync.js +61 -0
  64. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  65. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  66. package/src/infrastructure/tls/mutualJSON.js +79 -0
  67. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  68. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  69. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  70. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  71. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  72. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  73. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  74. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  75. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
  76. package/src/application/control/snapshotFile.js +0 -24
  77. package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
  78. package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
  79. package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
  80. package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
  81. package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
  82. package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
  83. package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
  84. package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
  85. package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
  86. package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
  87. package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
  88. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
@@ -22,10 +22,11 @@ async function apply(runtime, document) {
22
22
  await runtime.apply(input);
23
23
  }
24
24
  }
25
- function healthView(runtime, state) {
25
+ function healthView(runtime, state, queue) {
26
26
  return { status() {
27
27
  const status = runtime.status();
28
- return { ...status, stopping: status.stopping || state.stopped, fatal: status.fatal || state.failed,
28
+ const { pending, bytes, maxBytes, recordLimit, droppedRecords, droppedBytes } = queue?.status?.() ?? {};
29
+ return { ...status, delivery: { pending, bytes, maxBytes, recordLimit, droppedRecords, droppedBytes }, stopping: status.stopping || state.stopped, fatal: status.fatal || state.failed,
29
30
  initialized: state.initialized && (!state.agent || state.agent.status().appliedGeneration !== null) };
30
31
  } };
31
32
  }
@@ -35,7 +36,7 @@ async function initialize(collector, owned, state, { env, registry, store }) {
35
36
  await owned.open?.();
36
37
  if (state.stopped) { throw new Error('Collector stopped during recovery'); }
37
38
  if (store) {
38
- state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, file: env.COLLECTOR_ASSIGNMENT_FILE, store, runtime,
39
+ state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, store, runtime,
39
40
  validate(document) { return validateManifest(document, registry); },
40
41
  onError(error) { process.stderr.write(`collector control: ${error.name}\n`); } });
41
42
  await state.agent.start({ waitForInitialTick: false });
@@ -76,7 +77,7 @@ export default async function runCollector({ registry, env = process.env, argv =
76
77
  const host = env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1';
77
78
  const store = env.COLLECTOR_CONTROL_ENDPOINTS
78
79
  ? controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX) : null;
79
- const owned = runtimeServices(env, { ...services, cursor: services.cursor ?? store?.cursor });
80
+ const owned = runtimeServices(env, services);
80
81
  let runtime;
81
82
  try { runtime = createRuntime({ registry, ...owned }); }
82
83
  catch (error) {
@@ -103,9 +104,10 @@ export default async function runCollector({ registry, env = process.env, argv =
103
104
  if (signals) { state.detach = collectorSignals(collector); }
104
105
  try {
105
106
  if (env.COLLECTOR_HEALTH_PORT) {
106
- Object.assign(state, { health: runtimeHealth(healthView(runtime, state), {
107
+ Object.assign(state, { health: runtimeHealth(healthView(runtime, state, owned.deliveryQueue), {
107
108
  port: Number(env.COLLECTOR_HEALTH_PORT), host,
108
- handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN, services.spoolMachine), staleMs: Number(env.COLLECTOR_LIVE_STALE_MS ?? 30000) }) });
109
+ handle: env.STATE_HTTP_TOKEN ? spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN, services.spoolMachine) : null,
110
+ staleMs: Number(env.COLLECTOR_LIVE_STALE_MS ?? 30000) }) });
109
111
  await state.health;
110
112
  }
111
113
  const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
@@ -55,6 +55,7 @@ async function remove(ctx, input, slot) {
55
55
  slot.generation = input.generation;
56
56
  slot.removed = true;
57
57
  await halt(slot, ctx);
58
+ await ctx.services.stateStore?.forget?.(slot.taskId);
58
59
  Object.assign(slot, { state: 'stopped' });
59
60
  return view(slot);
60
61
  }
@@ -1,37 +1,17 @@
1
- import pg from 'pg';
2
- import { mkdirSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import taskStatePg from '../../infrastructure/persistence/runtime/taskStatePg.js';
5
- import taskStateSqlite from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
6
- import deadline from './deadline.js';
1
+ import taskStateMemory from '../../infrastructure/persistence/runtime/taskStateMemory.js';
7
2
  import queuedDelivery from './queuedDelivery.js';
8
3
 
9
- function localStore(env, supplied) {
10
- if (!supplied.localTaskState || supplied.stateStore || env.COLLECTOR_STATE_URL || !env.COLLECTOR_SPOOL_DIR) {
11
- return undefined;
12
- }
13
- mkdirSync(env.COLLECTOR_SPOOL_DIR, { recursive: true });
14
- return taskStateSqlite(join(env.COLLECTOR_SPOOL_DIR, 'task-state.sqlite'));
15
- }
16
-
17
- /** Storage is optional for live-only tasks and mandatory for durable adapters. */
4
+ /** Collector-owned observations and task state are volatile. */
18
5
  export default function runtimeServices(env, supplied) {
19
- const pool = !supplied.stateStore && env.COLLECTOR_STATE_URL ? new pg.Pool({
20
- connectionString: env.COLLECTOR_STATE_URL, max: 4, connectionTimeoutMillis: 5000,
21
- query_timeout: 10000, statement_timeout: 10000, idleTimeoutMillis: 30000
22
- }) : null;
23
6
  const secrets = supplied.secrets ?? { get(name) { return env[name]; } };
24
- const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue);
25
- const local = localStore(env, supplied);
7
+ const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue, supplied.deliveryStore);
8
+ const local = supplied.stateStore ? undefined : taskStateMemory();
26
9
  return { ...supplied, secrets, deliveryQueue: delivery.queue,
27
10
  open() { return delivery.open(); },
28
- stateStore: supplied.stateStore ?? (pool ? taskStatePg(pool) : local),
11
+ stateStore: supplied.stateStore ?? local,
29
12
  async close() {
30
13
  try { await delivery.stop(); }
31
- finally {
32
- local?.close();
33
- if (pool) { await deadline(() => { return pool.end(); }, 10000); }
34
- }
14
+ finally { local?.close(); }
35
15
  }
36
16
  };
37
17
  }
@@ -0,0 +1,15 @@
1
+ /** Skip kubectl apply when server-side diff reports the live objects already match. */
2
+ export default function applyWhenChanged(execute) {
3
+ return (program, args, options) => {
4
+ if (program !== 'kubectl' || !args.includes('apply') || args.includes('--dry-run=server')) {
5
+ return execute(program, args, options);
6
+ }
7
+ try {
8
+ execute(program, args.map((arg) => { return arg === 'apply' ? 'diff' : arg; }), options);
9
+ return '';
10
+ } catch (error) {
11
+ if (error.status !== 1) { throw error; }
12
+ return execute(program, args, options);
13
+ }
14
+ };
15
+ }
@@ -0,0 +1,35 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ /** Bind every command to an explicit Kubernetes context and namespace. */
4
+ export function deploymentKube({ context, namespace }, execute = execFileSync, options = {}) {
5
+ if (![context, namespace].every((value) => { return typeof value === 'string' && value.trim(); })) {
6
+ throw new TypeError('Kubernetes context and namespace are required');
7
+ }
8
+ return (args, input, capture = false) => {
9
+ return execute('kubectl', ['--context', context, '--namespace', namespace, ...args],
10
+ { input, encoding: 'utf8', stdio: ['pipe', capture ? 'pipe' : 'inherit', 'inherit'], ...options });
11
+ };
12
+ }
13
+
14
+ export function readKube(kube, resource, output = 'json') {
15
+ return String(kube(['get', resource, '-o', output], undefined, true)).trim();
16
+ }
17
+
18
+ /** Verify an operation is aimed at the only node in a single-node installation. */
19
+ export function verifyKubeNode(kube, address, name) {
20
+ const { items } = JSON.parse(readKube(kube, 'nodes'));
21
+ const node = items?.[0];
22
+ if (items?.length !== 1 || (name !== undefined && node.metadata?.name !== name)
23
+ || !node.status?.addresses?.some((row) => { return row.type === 'InternalIP' && row.address === address; })) {
24
+ throw new Error('Kubernetes node identity differs from the selected deployment target');
25
+ }
26
+ return node;
27
+ }
28
+
29
+ export function preserveKubeRestart(kube, workload, annotations, namespace) {
30
+ const prefix = namespace ? ['--namespace', namespace] : [];
31
+ const raw = String(kube([...prefix, 'get', workload, '--ignore-not-found', '-o', 'json'], undefined, true) ?? '').trim();
32
+ const key = 'kubectl.kubernetes.io/restartedAt';
33
+ const restart = raw.startsWith('{') && JSON.parse(raw).spec?.template?.metadata?.annotations?.[key];
34
+ return restart ? { ...annotations, [key]: restart } : annotations;
35
+ }
@@ -0,0 +1,24 @@
1
+ import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
2
+
3
+ function verifyDestination(kube, target, allowedPods) {
4
+ verifyKubeNode(kube, target.nodeAddress);
5
+ const { items } = JSON.parse(readKube(kube, 'pods'));
6
+ if (items.some((pod) => { return !['Succeeded', 'Failed'].includes(pod.status?.phase) && !allowedPods.includes(pod.metadata.name); })) {
7
+ throw new Error('Stop all application writers before history seed');
8
+ }
9
+ }
10
+
11
+ /** Complete all bounded exports before writing to a verified, quiescent destination. */
12
+ export default function executeKubeSeed({ source, destination, transfers, allowedPods }, execute) {
13
+ if (source.context === destination.context) { throw new Error('Separate exact source and destination required'); }
14
+ const options = { timeout: 120000, stdio: ['pipe', 'pipe', 'pipe'] };
15
+ const origin = deploymentKube(source, execute, { ...options, encoding: null, maxBuffer: 64 * 1024 * 1024 });
16
+ const receiver = deploymentKube(destination, execute, { ...options, maxBuffer: 1024 * 1024 });
17
+ verifyDestination(receiver, destination, allowedPods);
18
+ const exports = transfers.map(({ read }) => { return origin(['exec', ...read]); });
19
+ verifyDestination(receiver, destination, allowedPods);
20
+ return transfers.map(({ name, write }, index) => {
21
+ receiver(['exec', '-i', ...write], exports[index]);
22
+ return name;
23
+ });
24
+ }
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { deploymentKube } from './deploymentKube.js';
2
3
 
3
4
  /** Retire only explicit Deployments with a single exact app label selector. */
4
5
  function validateRetirements(plan) {
@@ -34,14 +35,6 @@ function validate(plan, action) {
34
35
  });
35
36
  }
36
37
 
37
- /** Every Kubernetes command, including the post-rollout hook, shares this target. */
38
- function kubeAt(plan, execute) {
39
- return (args, input, capture = false) => {
40
- return execute('kubectl', ['--context', plan.context, '--namespace', plan.namespace, ...args],
41
- { input, encoding: 'utf8', stdio: ['pipe', capture ? 'pipe' : 'inherit', 'inherit'] });
42
- };
43
- }
44
-
45
38
  function applyWith(kube, manifests, flags, checkOnly) {
46
39
  const args = ['apply', ...flags, '-f', '-'];
47
40
  kube([...args, '--dry-run=server'], manifests);
@@ -99,6 +92,11 @@ function applyRelease(plan, action, kube, manifests) {
99
92
  return '';
100
93
  }
101
94
 
95
+ export function renderRelease(plan, execute = execFileSync) {
96
+ return execute('helm', ['template', plan.release, plan.chart, '--namespace', plan.namespace, '-f', '-'],
97
+ { input: JSON.stringify(plan.values), encoding: 'utf8' });
98
+ }
99
+
102
100
  /**
103
101
  * Renders a Helm release and executes the selected kubectl action synchronously.
104
102
  * Supply chart, release, namespace and values. Cluster actions additionally require
@@ -112,10 +110,9 @@ function applyRelease(plan, action, kube, manifests) {
112
110
  */
113
111
  export default function executeRelease(plan, action = 'render', execute = execFileSync) {
114
112
  validate(plan, action);
115
- const manifests = execute('helm', ['template', plan.release, plan.chart, '--namespace', plan.namespace, '-f', '-'],
116
- { input: JSON.stringify(plan.values), encoding: 'utf8' });
113
+ const manifests = renderRelease(plan, execute);
117
114
  if (action === 'render') { return manifests; }
118
- const kube = kubeAt(plan, execute);
115
+ const kube = deploymentKube(plan, execute);
119
116
  for (const resource of plan.prerequisites || []) { kube(['get', resource, '-o', 'name']); }
120
117
  if (action === 'diff') {
121
118
  return kube(['diff', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], manifests);
@@ -0,0 +1,85 @@
1
+ import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
2
+ import postgresRestoreObjects from './postgresRestoreObjects.js';
3
+
4
+ function jobState(job) {
5
+ if (!job) { throw new Error('Restore verification job disappeared'); }
6
+ if (job.status?.succeeded > 0) { return 'complete'; }
7
+ if (job.status?.conditions?.some((condition) => { return condition.type === 'Failed' && condition.status === 'True'; })
8
+ || (job.status?.failed > 0 && !job.status?.active)) {
9
+ throw new Error('Restore attempt failed; use a new attempt number and fresh scratch storage');
10
+ }
11
+ return 'running';
12
+ }
13
+
14
+ function waitVerification(plan, kube, initial) {
15
+ const deadline = Date.now() + 1800000;
16
+ let job = initial;
17
+ while (Date.now() < deadline) {
18
+ if (jobState(job) === 'complete') { return; }
19
+ try {
20
+ kube(['wait', '--for=condition=complete', `job/${plan.verificationName}`, '--timeout=10s']);
21
+ } catch {
22
+ // Check for a terminal Failed state after each short wait.
23
+ }
24
+ job = JSON.parse(readKube(kube, `job/${plan.verificationName}`));
25
+ }
26
+ throw new Error('Restore attempt did not finish in 30 minutes');
27
+ }
28
+
29
+ function optionalResource(kube, resource) {
30
+ return JSON.parse(kube(['get', resource, '--ignore-not-found', '-o', 'json']) || 'null');
31
+ }
32
+
33
+ function createVerification(plan, pod, kube) {
34
+ if (optionalResource(kube, `persistentvolumeclaim/${plan.verificationName}`)) {
35
+ throw new Error('Restore scratch already exists; use a new attempt number');
36
+ }
37
+ const image = pod.status?.containerStatuses?.[0]?.imageID?.replace(/^docker-pullable:\/\//u, '');
38
+ if (!image?.includes('@sha256:')) { throw new Error('Exact PostgreSQL image digest required'); }
39
+ const items = postgresRestoreObjects(plan, pod.spec.nodeName, image);
40
+ kube(['apply', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], JSON.stringify({ apiVersion: 'v1', kind: 'List', items }));
41
+ return JSON.parse(readKube(kube, `job/${plan.verificationName}`));
42
+ }
43
+
44
+ function verification(plan, pod, kube) {
45
+ const existing = optionalResource(kube, `job/${plan.verificationName}`);
46
+ if (existing && !Object.entries(plan.labels).every(([key, value]) => { return existing.metadata.labels?.[key] === value; })) {
47
+ throw new Error('Restore job ownership differs');
48
+ }
49
+ waitVerification(plan, kube, existing ?? createVerification(plan, pod, kube));
50
+ const log = kube(['logs', `job/${plan.verificationName}`]);
51
+ if (!log.includes('RESTORE_VERIFIED')) { throw new Error('Restore did not report success'); }
52
+ const counts = JSON.parse(log.split('\n').find((line) => { return line.startsWith('{'); }));
53
+ return { target: plan.context, backupId: plan.backupId, verified: true, counts };
54
+ }
55
+
56
+ function targetPod(plan, kube) {
57
+ const pod = JSON.parse(readKube(kube, `pod/${plan.pod}`));
58
+ if (!pod.spec?.nodeName) { throw new Error('Database pod node identity is missing'); }
59
+ verifyKubeNode(kube, plan.nodeAddress, pod.spec.nodeName);
60
+ if (!pod.spec.volumes?.some((volume) => { return volume.persistentVolumeClaim?.claimName === plan.claim; })) {
61
+ throw new Error('Database claim identity differs from the selected deployment target');
62
+ }
63
+ return pod;
64
+ }
65
+
66
+ function status(plan, pod) {
67
+ const ready = pod.status.containerStatuses.every((row) => { return row.ready; });
68
+ const claims = pod.spec.volumes.flatMap((row) => { return row.persistentVolumeClaim ? [row.persistentVolumeClaim.claimName] : []; });
69
+ return { target: plan.context, backupId: plan.backupId, ready, claims };
70
+ }
71
+
72
+ /** Backup or verify a backup using the selected cluster, workload and claim. */
73
+ export default function operatePostgresMaintenance(plan, action, execute) {
74
+ if (!['plan', 'backup', 'verify-restore', 'status'].includes(action)) { throw new TypeError('Unknown edge data action'); }
75
+ if (action === 'plan') { return plan; }
76
+ if (!plan.enabled) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
77
+ const kube = deploymentKube(plan, execute, { timeout: 1900000, stdio: ['pipe', 'pipe', 'pipe'] });
78
+ const pod = targetPod(plan, kube);
79
+ if (action === 'backup') {
80
+ kube(['exec', plan.pod, '--', ...plan.backupCommand]);
81
+ return { target: plan.context, backupId: plan.backupId, complete: true };
82
+ }
83
+ if (action === 'verify-restore') { return verification(plan, pod, kube); }
84
+ return status(plan, pod);
85
+ }
@@ -0,0 +1,54 @@
1
+ function quote(value) {
2
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
3
+ }
4
+
5
+ function backupCommand({ directory, database, backupRoot, osUser, runAs }) {
6
+ const script = `set -eu
7
+ umask 077
8
+ backup=${quote(directory)}
9
+ mkdir -p "$backup"
10
+ cd "$backup"
11
+ lock="$backup/.lock"
12
+ if ! mkdir "$lock" 2>/dev/null; then echo 'Backup already in progress' >&2; exit 75; fi
13
+ trap 'rmdir "$lock"' EXIT
14
+ if [ -f complete ]; then sha256sum -c complete; exit 0; fi
15
+ export PGPASSWORD="$POSTGRES_PASSWORD"
16
+ pg_dumpall -U "$POSTGRES_USER" --globals-only > roles.sql.partial
17
+ pg_dump -U "$POSTGRES_USER" -d ${quote(database)} --format=custom --file=${database}.dump.partial
18
+ mv roles.sql.partial roles.sql
19
+ mv ${database}.dump.partial ${database}.dump
20
+ sha256sum roles.sql ${database}.dump > complete.partial
21
+ mv complete.partial complete
22
+ sha256sum -c complete
23
+ `;
24
+ return ['sh', '-ceu', `set -eu; umask 077; mkdir -p ${quote(directory)}; chown ${osUser}:${osUser} ${quote(backupRoot)} ${quote(directory)}; exec ${runAs} ${osUser} sh -ceu ${quote(script)}`];
25
+ }
26
+
27
+ function dbBackupPlan(plan, backupId) {
28
+ const backupRoot = `${plan.dataMount}/${plan.backupSubdirectory}`;
29
+ const directory = `${backupRoot}/${backupId}`;
30
+ return { directory, backupCommand: backupCommand({ ...plan, directory, backupRoot }) };
31
+ }
32
+
33
+ function validatePlan(plan, backupId, attempt) {
34
+ if (!Number.isSafeInteger(attempt) || attempt < 1 || attempt > 999) {
35
+ throw new TypeError('Restore attempt must be 1 through 999');
36
+ }
37
+ if (!/^\d{8}-[a-z0-9][a-z0-9-]{0,29}$/u.test(backupId ?? '')) { throw new TypeError('Safe dated backup id required'); }
38
+ for (const value of [plan.database, plan.restoreRole, plan.osUser]) {
39
+ if (!/^[a-z_][a-z0-9_]*$/u.test(value ?? '')) { throw new TypeError('A simple database and operating system user are required'); }
40
+ }
41
+ if (!/^[a-z][a-z0-9-]*$/u.test(plan.runAs ?? '')) { throw new TypeError('A postgres user-switch command is required'); }
42
+ if (!/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+$/u.test(plan.dataMount ?? '')
43
+ || !/^[a-z0-9-]+$/u.test(plan.backupSubdirectory ?? '')) {
44
+ throw new TypeError('PostgreSQL maintenance requires a data mount and backup subdirectory');
45
+ }
46
+ }
47
+
48
+ /** Add a safe, immutable dated operation ID to a caller-selected database target. */
49
+ export default function postgresMaintenancePlan(plan, backupId, attempt = 1) {
50
+ validatePlan(plan, backupId, attempt);
51
+ const verificationName = `${plan.verificationNamePrefix}-${backupId}${attempt === 1 ? '' : `-r${attempt}`}`;
52
+ const labels = { ...plan.restoreLabels, [plan.backupLabel]: backupId };
53
+ return { ...plan, ...dbBackupPlan(plan, backupId), backupId, verificationName, labels };
54
+ }
@@ -0,0 +1,73 @@
1
+ function quote(value) {
2
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
3
+ }
4
+
5
+ /** Runs PostgreSQL with a local socket inside the isolated restore container. */
6
+ function restoreScript({ database, restoreRole, verificationSql }) {
7
+ const verify = verificationSql ? `psql -v ON_ERROR_STOP=1 -At -c ${quote(verificationSql)}` : "printf '{}\\n'";
8
+ return `set -eu
9
+ export PGDATA=/restore/pgdata PGHOST=/tmp PGPORT=55432 PGUSER=${restoreRole} PGDATABASE=${database}
10
+ cd /backup
11
+ sha256sum -c complete >/restore/checksum.log
12
+ initdb -D "$PGDATA" -U ${restoreRole} --auth=trust >/restore/initdb.log
13
+ pg_ctl -D "$PGDATA" -l /restore/postgres.log -o "-p 55432 -k /tmp -c listen_addresses='' -c shared_buffers=16MB -c maintenance_work_mem=32MB -c max_connections=10" -w start
14
+ trap 'pg_ctl -D "$PGDATA" -m fast -w stop >/restore/stop.log' EXIT
15
+ sed '/^CREATE ROLE ${restoreRole};$/d; /^CREATE ROLE "${restoreRole}";$/d' /backup/roles.sql | psql -v ON_ERROR_STOP=1 -d postgres >/restore/roles.log
16
+ createdb ${database}
17
+ pg_restore --exit-on-error --dbname=${database} /backup/${database}.dump 2>/restore/restore-errors.log
18
+ ${verify}
19
+ printf 'RESTORE_VERIFIED\\n'
20
+ `;
21
+ }
22
+
23
+ function verificationContainer(plan, image) {
24
+ return {
25
+ name: 'restore',
26
+ image,
27
+ command: ['/bin/sh', '-ceu', restoreScript(plan)],
28
+ resources: { requests: { cpu: '100m', memory: '256Mi' }, limits: { cpu: '500m', memory: '512Mi' } },
29
+ securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } },
30
+ volumeMounts: [
31
+ { name: 'backup', mountPath: '/backup', subPath: `${plan.backupSubdirectory}/${plan.backupId}`, readOnly: true },
32
+ { name: 'scratch', mountPath: '/restore' }
33
+ ]
34
+ };
35
+ }
36
+
37
+ /** An isolated restore job reads the source backup and writes only to fresh scratch. */
38
+ export default function postgresRestoreObjects(plan, nodeName, image) {
39
+ const { verificationName: name, namespace, labels } = plan;
40
+ const metadata = { name, namespace, labels };
41
+ return [
42
+ {
43
+ apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata,
44
+ spec: { accessModes: ['ReadWriteOnce'], storageClassName: plan.storageClass, resources: { requests: { storage: plan.scratchSize } } }
45
+ },
46
+ {
47
+ apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata,
48
+ spec: { podSelector: { matchLabels: labels }, policyTypes: ['Ingress', 'Egress'], ingress: [], egress: [] }
49
+ },
50
+ {
51
+ apiVersion: 'batch/v1', kind: 'Job', metadata,
52
+ spec: {
53
+ backoffLimit: 0,
54
+ activeDeadlineSeconds: 1800,
55
+ template: {
56
+ metadata: { labels },
57
+ spec: {
58
+ nodeSelector: { 'kubernetes.io/hostname': nodeName },
59
+ restartPolicy: 'Never',
60
+ automountServiceAccountToken: false,
61
+ imagePullSecrets: plan.imagePullSecrets,
62
+ securityContext: { runAsUser: plan.userId, runAsGroup: plan.groupId, fsGroup: plan.groupId, runAsNonRoot: true },
63
+ containers: [verificationContainer(plan, image)],
64
+ volumes: [
65
+ { name: 'backup', persistentVolumeClaim: { claimName: plan.claim, readOnly: true } },
66
+ { name: 'scratch', persistentVolumeClaim: { claimName: name } }
67
+ ]
68
+ }
69
+ }
70
+ }
71
+ }
72
+ ];
73
+ }
@@ -0,0 +1,76 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
3
+ import { renderRelease } from './executeRelease.js';
4
+
5
+ function requireSecretKeys(kube, secrets) {
6
+ for (const { name, keys } of secrets) {
7
+ if (keys) {
8
+ const present = readKube(kube, `secret/${name}`, 'go-template={{range $k,$v := .data}}{{$k}} {{end}}').split(/\s+/u);
9
+ const missing = keys.filter((key) => { return !present.includes(key); });
10
+ if (missing.length) { throw new Error(`Missing Secret ${name} keys: ${missing.join(', ')}`); }
11
+ } else {
12
+ readKube(kube, `secret/${name}`, 'name');
13
+ }
14
+ }
15
+ }
16
+
17
+ function verifyStorageLayout(kube, { name, volume, mountPath, claim, env, environmentValue }) {
18
+ const { spec } = JSON.parse(readKube(kube, `statefulset/${name}`)).spec.template;
19
+ const container = spec.containers[0];
20
+ if (container.env.find((row) => { return row.name === env; })?.value !== environmentValue
21
+ || container.volumeMounts.find((row) => { return row.name === volume; })?.mountPath !== mountPath
22
+ || spec.volumes.find((row) => { return row.name === volume; })?.persistentVolumeClaim?.claimName !== claim) {
23
+ throw new Error(`Storage data layout differs: ${name}; refusing storage adoption`);
24
+ }
25
+ }
26
+
27
+ function preserveStorageTemplates(kube, storage) {
28
+ for (const { name, values } of storage) {
29
+ const { template } = JSON.parse(readKube(kube, `statefulset/${name}`)).spec;
30
+ if (template.spec.containers[0].image !== values.image) {
31
+ throw new Error(`Storage image differs: ${name}; adoption must preserve it`);
32
+ }
33
+ Object.assign(values, { podTemplate: template });
34
+ }
35
+ }
36
+
37
+ function verifyStorageTemplates(kube, execute, { stage, workloads }, action) {
38
+ const manifests = renderRelease(stage, execute);
39
+ const flags = action === 'adopt' ? ['--field-manager=kubectl-client-side-apply'] : ['--server-side', `--field-manager=${stage.fieldManager}`];
40
+ const response = JSON.parse(kube(['apply', ...flags, '--dry-run=server', '-f', '-', '-o', 'json'], manifests, true));
41
+ const objects = response.items ?? [response];
42
+ for (const name of workloads) {
43
+ const desired = objects.find((row) => { return row.kind === 'StatefulSet' && row.metadata.name === name; });
44
+ const live = JSON.parse(readKube(kube, `statefulset/${name}`));
45
+ if (!desired || !isDeepStrictEqual(desired.spec.template, live.spec.template)) {
46
+ throw new Error(`Storage pod template differs: ${name}; adoption must not restart it`);
47
+ }
48
+ }
49
+ }
50
+
51
+ function verifyVolumeIdentity(kube, { name, claimUid, volumeName, volumeUid }) {
52
+ const live = JSON.parse(readKube(kube, `persistentvolumeclaim/${name}`));
53
+ if (!live.metadata.uid || live.status.phase !== 'Bound' || !live.spec.volumeName
54
+ || (claimUid && claimUid !== live.metadata.uid) || (volumeName && volumeName !== live.spec.volumeName)) {
55
+ throw new Error(`PVC identity mismatch: ${name}`);
56
+ }
57
+ const actualUid = readKube(kube, `persistentvolume/${live.spec.volumeName}`, 'jsonpath={.metadata.uid}');
58
+ if (!actualUid || (volumeUid && volumeUid !== actualUid)) { throw new Error(`PV identity mismatch: ${name}`); }
59
+ }
60
+
61
+ /** Inspect a live single-node deployment before constructing its staged cutover. */
62
+ export default function preflightKubeStorage(plan, action, execute) {
63
+ const kube = deploymentKube(plan, execute);
64
+ requireSecretKeys(kube, plan.secrets ?? []);
65
+ plan.beforeStorage?.(kube);
66
+ verifyKubeNode(kube, plan.nodeAddress);
67
+ for (const layout of plan.layouts ?? []) { verifyStorageLayout(kube, layout); }
68
+ preserveStorageTemplates(kube, plan.preserveTemplates ?? []);
69
+ plan.preserveAnnotations?.(kube);
70
+ if (plan.verifyTemplates) { verifyStorageTemplates(kube, execute, plan.verifyTemplates, action); }
71
+ for (const claim of plan.claims ?? []) { verifyVolumeIdentity(kube, claim); }
72
+ for (const resource of plan.resources ?? []) {
73
+ const prefix = resource.namespace ? ['--namespace', resource.namespace] : [];
74
+ kube([...prefix, 'get', resource.name, '-o', 'name'], undefined, !resource.namespace);
75
+ }
76
+ }
@@ -0,0 +1,95 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { verifyKubeNode } from './deploymentKube.js';
4
+
5
+ function encoded({ data, stringData }) {
6
+ return { ...data, ...Object.fromEntries(Object.entries(stringData ?? {}).map(([key, value]) => {
7
+ return [key, Buffer.from(value).toString('base64')];
8
+ })) };
9
+ }
10
+
11
+ function objectName({ kind, metadata }) {
12
+ return `${kind}/${metadata.name}`;
13
+ }
14
+
15
+ function objectKey({ name, namespace }) {
16
+ return `${namespace}/${name}`;
17
+ }
18
+
19
+ function clientFor(plan, execute) {
20
+ if (typeof plan.context !== 'string' || !plan.context.trim()) { throw new TypeError('Exact Kubernetes context required'); }
21
+ function kube(namespace, args, input) {
22
+ return String(execute('kubectl', ['--context', plan.context, ...(namespace ? ['--namespace', namespace] : []), ...args],
23
+ { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 30000 }));
24
+ }
25
+ const node = verifyKubeNode((args) => { return kube('', args); }, plan.nodeAddress);
26
+ const podCidrs = node.spec?.podCIDRs ?? [node.spec?.podCIDR].filter(Boolean);
27
+ if (plan.requirePodCidrs && !podCidrs.length) { throw new Error('Verified node pod CIDR required'); }
28
+ function optional(namespace, kind, name) {
29
+ return JSON.parse(kube(namespace, ['get', `${kind}/${name}`, '--ignore-not-found', '-o', 'json']) || 'null');
30
+ }
31
+ const namespaces = new Map(plan.namespaces.map((name) => { return [name, Boolean(optional('', 'namespace', name))]; }));
32
+ return {
33
+ podCidrs,
34
+ get(namespace, kind, name) {
35
+ return namespace && !namespaces.get(namespace) ? null : optional(namespace, kind, name);
36
+ },
37
+ create(object) {
38
+ kube(object.metadata.namespace ?? '', ['create', '-f', '-'], JSON.stringify(object));
39
+ }
40
+ };
41
+ }
42
+
43
+ function credential(request, supplied, found, action) {
44
+ const { name, namespace, keys, type: expectedType } = request;
45
+ if (found && supplied && !isDeepStrictEqual(found.data, encoded(supplied))) { throw new Error(`Existing Secret differs: ${name}`); }
46
+ if (supplied && keys.some((key) => { return !encoded(supplied)[key]; })) { throw new Error(`Missing supplied Secret keys: ${name}`); }
47
+ if (found && keys.some((key) => { return !found.data?.[key]; })) { throw new Error(`Missing existing Secret keys: ${name}`); }
48
+ if (action === 'apply' && !found && !supplied) {
49
+ throw new Error(`Missing prerequisites: provide ${name} through a protected Secret file`);
50
+ }
51
+ const source = supplied ?? found ?? {};
52
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: source.type ?? expectedType ?? 'Opaque', data: encoded(source) };
53
+ }
54
+
55
+ function credentialInputs(requests, secrets, client, action) {
56
+ const targets = new Set(requests.map(objectKey));
57
+ if (secrets.some((item) => { return item.kind !== 'Secret' || !item.metadata || !targets.has(objectKey(item.metadata)); })) {
58
+ throw new Error('Unexpected prerequisite Secret target');
59
+ }
60
+ const resolved = new Map();
61
+ return requests.map((request) => {
62
+ const key = objectKey(request);
63
+ const found = client.get(request.namespace, 'secret', request.name);
64
+ const mirrored = !found && request.copyFrom && resolved.get(objectKey(request.copyFrom));
65
+ const supplied = secrets.find(({ metadata }) => { return objectKey(metadata) === key; })
66
+ ?? (mirrored && request.keys.every((name) => { return mirrored.data[name]; }) ? { data: mirrored.data } : null);
67
+ const object = credential(request, supplied, found, action);
68
+ resolved.set(key, object);
69
+ return object;
70
+ });
71
+ }
72
+
73
+ function verifyExisting(object, client, preserved) {
74
+ const found = client.get(object.metadata.namespace ?? '', object.kind.toLowerCase(), object.metadata.name);
75
+ if (found && object.kind === 'Secret' && !isDeepStrictEqual(found.data, object.data)) {
76
+ throw new Error(`Existing Secret differs: ${object.metadata.name}`);
77
+ }
78
+ if (found) { preserved.push(objectName(object)); }
79
+ return !found;
80
+ }
81
+
82
+ /** Create missing prerequisites without replacing any live resource or credential. */
83
+ export default function prepareKubePrerequisites(plan, action = 'check', { execute = execFileSync, secrets = [] } = {}) {
84
+ if (!['render', 'check', 'apply'].includes(action)) { throw new TypeError('prepare action must be render, check or apply'); }
85
+ if (action === 'render') { return plan.objects([]); }
86
+ const target = plan.context;
87
+ if (action === 'apply' && !plan.enabled) { throw new Error(`${target} deployment disabled: target is offline`); }
88
+ const client = clientFor(plan, execute);
89
+ const objects = [...plan.objects(client.podCidrs), ...credentialInputs(plan.credentials ?? [], secrets, client, action)];
90
+ const preserved = [];
91
+ const pending = objects.filter((object) => { return verifyExisting(object, client, preserved); });
92
+ if (action === 'apply') { pending.forEach(client.create); }
93
+ const names = pending.map(objectName);
94
+ return { target, created: action === 'apply' ? names : [], missing: action === 'check' ? names : [], preserved };
95
+ }