@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,75 @@
1
+ import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
2
+
3
+ function endpoint(value, blockedHost) {
4
+ const url = new URL(value);
5
+ if (url.host === blockedHost) { throw new TypeError(`Replica shovel must stay off the blocked broker ${url.host}`); }
6
+ if (!url.username) {
7
+ url.username = 'guest';
8
+ url.password = 'guest';
9
+ }
10
+ return url.toString().replace(/\/$/u, '');
11
+ }
12
+
13
+ function shovel(stream, source, target, options, restore) {
14
+ const queue = `${stream.queue}.to-${target.node}`;
15
+ const exchange = restore ? stream.restore.exchange : undefined;
16
+ const outbox = stream.forwardOutbox ? queue : stream.queue;
17
+ const landing = restore ? stream.restore.queue : outbox;
18
+ return {
19
+ vhost: options.vhost,
20
+ component: 'shovel',
21
+ name: `${stream.name}-to-${target.node}`,
22
+ value: {
23
+ 'src-protocol': 'amqp091', 'src-uri': source.uri, 'src-queue': queue,
24
+ 'dest-protocol': 'amqp091', 'dest-uri': target.uri,
25
+ ...(exchange === undefined ? { 'dest-queue': landing } : { 'dest-exchange': exchange }),
26
+ 'reconnect-delay': options.reconnectDelay, 'dest-publish-properties': { delivery_mode: 2 }
27
+ }
28
+ };
29
+ }
30
+
31
+ /** Plan primary-to-standby copies and standby-to-primary restoration for declared streams. */
32
+ export function replicaShovels({ leader, standby, brokers, blocked, streams, vhost = '/', reconnectDelay = 30 }) {
33
+ if (leader === standby) { throw new TypeError('Replica endpoints cannot use the same node'); }
34
+ const blockedHost = blocked ? new URL(blocked).host : undefined;
35
+ const primary = { node: leader, uri: endpoint(brokers[leader], blockedHost) };
36
+ const secondary = { node: standby, uri: endpoint(brokers[standby], blockedHost) };
37
+ return streams.flatMap((stream) => {
38
+ return [
39
+ shovel(stream, primary, secondary, { vhost, reconnectDelay }, false),
40
+ shovel(stream, secondary, primary, { vhost, reconnectDelay }, true)
41
+ ];
42
+ });
43
+ }
44
+
45
+ function appendDistinct(target, rows) {
46
+ rows.forEach((row) => {
47
+ if (!target.some((item) => { return item.name === row.name && item.vhost === row.vhost; })) {
48
+ target.push(row);
49
+ }
50
+ });
51
+ }
52
+
53
+ function append(result, input) {
54
+ const { exchanges, queues, bindings } = rabbitmqDefinitions(input);
55
+ appendDistinct(result.exchanges, exchanges);
56
+ appendDistinct(result.queues, queues);
57
+ result.bindings.push(...bindings);
58
+ }
59
+
60
+ function routes(source, destination, keys = []) {
61
+ return keys.map((key) => { return { source, destination, key }; });
62
+ }
63
+
64
+ /** Add replica resources to an existing broker definition without replacing its declarations. */
65
+ export function appendReplicaTopology(result, { landings = [], copies = [], vhost = '/' }) {
66
+ landings.forEach(({ exchange, queue, keys, bindings = [] }) => {
67
+ append(result, { vhost, exchanges: [exchange], queues: [queue], bindings: [...routes(exchange, queue, keys), ...bindings] });
68
+ });
69
+ copies.forEach(({ shovel: copy, source, keys }) => {
70
+ const queue = copy.value['src-queue'];
71
+ result.parameters.push(copy);
72
+ append(result, { vhost, queues: [queue], bindings: routes(source, queue, keys) });
73
+ });
74
+ return result;
75
+ }
@@ -0,0 +1,23 @@
1
+ function checkDeclarations(declarations, ports) {
2
+ if (!Array.isArray(declarations) || !declarations.length) { throw new TypeError('Deployment stages must be a nonempty list'); }
3
+ const known = new Set();
4
+ for (const { id } of declarations) {
5
+ if (typeof id !== 'string' || !id) { throw new TypeError('Deployment stage id is required'); }
6
+ if (known.has(id)) { throw new TypeError(`Duplicate deployment stage ${id}`); }
7
+ if (!Object.hasOwn(ports, id) || typeof ports[id] !== 'function') {
8
+ throw new TypeError(`Unknown deployment stage binding ${id}`);
9
+ }
10
+ known.add(id);
11
+ }
12
+ }
13
+
14
+ /** Assemble ordered releases from declarative identity and caller-provided stage values. */
15
+ export default function buildDeploymentStages(declarations, { common = {}, defaults = {}, ports }) {
16
+ checkDeclarations(declarations, ports);
17
+ return declarations.flatMap(({ id, inheritValues = true, ...declaration }) => {
18
+ const binding = ports[id]();
19
+ if (binding === null) { return []; }
20
+ const { values, ...options } = binding;
21
+ return [{ ...common, id, ...declaration, ...options, values: { ...(inheritValues ? defaults : {}), ...values } }];
22
+ });
23
+ }
@@ -0,0 +1,48 @@
1
+ import { requireWorkloadEnvironment, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
2
+ import verifyCollectorCoverage from './verifyCollectorCoverage.js';
3
+
4
+ const timings = new Set(['beforeApply', 'afterReady']);
5
+
6
+ export function deploymentStage(plan, id) {
7
+ const stage = plan.stages.find((candidate) => { return candidate.id === id; });
8
+ if (!stage) { throw new TypeError(`Unknown deployment stage ${id}`); }
9
+ return stage;
10
+ }
11
+
12
+ function builtInChecks({ plan, evidence, execute }) {
13
+ return {
14
+ collectorCoverage(_stage, _kube, { stage: id, workloads, namespace = plan.namespace, freshnessMs, clockSkewMs, container, statusUrl }) {
15
+ const { controlCatalog, cutoverTasks } = deploymentStage(plan, id);
16
+ if (controlCatalog) {
17
+ verifyCollectorCoverage({ cluster: plan.context, namespace, evidence, execute,
18
+ tasks: cutoverTasks, workloads, freshnessMs, clockSkewMs, container, statusUrl });
19
+ }
20
+ },
21
+ environment(_stage, kube, declaration) { requireWorkloadEnvironment(kube, declaration); },
22
+ job(_stage, kube, { prerequisite, name, timeout }) {
23
+ waitForJob(kube, prerequisite ? plan.prerequisites?.[prerequisite] : name, timeout);
24
+ },
25
+ postgresReadiness(_stage, kube, declaration) { verifyPostgresReadiness(kube, declaration); }
26
+ };
27
+ }
28
+
29
+ function compileTiming(timing, steps, checks) {
30
+ if (!timings.has(timing) || !Array.isArray(steps)) { throw new TypeError(`Invalid deployment hook ${timing}`); }
31
+ const handlers = steps.map((step) => {
32
+ if (!Object.hasOwn(checks, step?.check) || typeof checks[step.check] !== 'function') {
33
+ throw new TypeError(`Unknown deployment check ${step?.check}`);
34
+ }
35
+ return (stage, kube) => { checks[step.check](stage, kube, step); };
36
+ });
37
+ return (stage, kube) => { handlers.forEach((handler) => { handler(stage, kube); }); };
38
+ }
39
+
40
+ /** Compile ordered stage checks using built-in operations and explicitly registered application ports. */
41
+ export default function compileDeploymentHooks(declarations, { plan, evidence, execute, ports = {} }) {
42
+ const checks = { ...ports, ...builtInChecks({ plan, evidence, execute }) };
43
+ return Object.fromEntries(Object.entries(declarations ?? {}).map(([stage, hooks]) => {
44
+ return [stage, Object.fromEntries(Object.entries(hooks).map(([timing, steps]) => {
45
+ return [timing, compileTiming(timing, steps, checks)];
46
+ }))];
47
+ }));
48
+ }
@@ -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)
@@ -0,0 +1,31 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import applyWhenChanged from './applyWhenChanged.js';
3
+ import { requireReleaseAction } from './executeRelease.js';
4
+ import executeStages from './executeStages.js';
5
+
6
+ function selected(plan, omit) {
7
+ if (omit.length === 0) { return plan; }
8
+ return { ...plan, stages: plan.stages.filter(({ id }) => { return !omit.includes(id); }) };
9
+ }
10
+
11
+ function stagePlans(plan, hooks) {
12
+ return plan.stages.map((stage) => {
13
+ return { ...stage, ...(Object.hasOwn(hooks, stage.id) ? hooks[stage.id] : {}) };
14
+ });
15
+ }
16
+
17
+ /** Execute declared stages with guarded preparation and stage-specific application ports. */
18
+ export default function executeStagedDeployment(profile, execute = execFileSync) {
19
+ const { action = 'render', plan, prepare, omitStages = [], validateMutation, preflight, stageHooks, afterApply,
20
+ actions = {}, disabledActions = [] } = profile;
21
+ if (disabledActions.includes(action)) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
22
+ const scoped = selected(plan, omitStages);
23
+ if (Object.hasOwn(actions, action)) { return actions[action](scoped, execute); }
24
+ requireReleaseAction(action);
25
+ const mutate = ['apply', 'adopt'].includes(action);
26
+ if (mutate) { validateMutation?.(scoped); }
27
+ const prepared = prepare ? selected(prepare(action, scoped), omitStages) : scoped;
28
+ if (action !== 'render') { preflight?.(prepared, action, mutate); }
29
+ const output = executeStages(stagePlans(prepared, stageHooks?.(prepared) ?? {}), action, applyWhenChanged(execute)).join('\n');
30
+ return mutate && afterApply ? `${output}\n${afterApply(prepared, execute)}` : output;
31
+ }
@@ -0,0 +1,36 @@
1
+ export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
2
+ export { collectorControlDeployment, collectorMemoryDeployment, withCollectorScratch, deploymentResources, etcdMembership, versionedControlCatalog } from '../../application/deploy/controlPlan.js';
3
+ export { default as executeStagedDeployment } from './executeStagedDeployment.js';
4
+ export { default as executeChartDeployment } from './executeChartDeployment.js';
5
+ export { requireWorkloadEnvironment, validateDeploymentEvidence, verifyPostgresReadiness, waitForJob } from './deploymentChecks.js';
6
+ export { default as publishControlCatalog } from '../../application/control/publishControlCatalog.js';
7
+ export { default as deploymentPatch } from './deploymentPatch.js';
8
+ export { default as reconcileDeployments } from './reconcileDeployments.js';
9
+ export { default as serveReconciliation } from '../management/serveReconciliation.js';
10
+ export { default as reconcileStoredChoice } from '../../application/control/reconcileStoredChoice.js';
11
+ export { default as operateKiosk } from '../management/kiosk/operateKiosk.js';
12
+ export { default as bootstrapKubeStorage } from './bootstrapKubeStorage.js';
13
+ export { default as verifyRuntimeCapabilities } from './verifyRuntimeCapabilities.js';
14
+ export { postgresBootstrapObjects, postgresRuntimeRoleJob } from './postgresBootstrap.js';
15
+ export { default as deploymentCommands } from '../../application/deploy/deploymentCommands.js';
16
+ export { default as readDocumentFile, selectDeploymentPhase } from '../../application/deploy/readDocumentFile.js';
17
+ export { default as applyHelmResources } from './applyHelmResources.js';
18
+ export { default as requestFromWorkload } from './requestFromWorkload.js';
19
+ export { default as renderKioskResources } from '../management/kiosk/renderKioskResources.js';
20
+ export { default as freezeDeploymentDocument } from '../../application/deploy/frozen.js';
21
+ export { default as readDocument } from '../../application/deploy/readDocument.js';
22
+ export { default as expand } from '../../application/deploy/expand.js';
23
+ export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './deploymentKube.js';
24
+ export { default as executeRelease } from './executeRelease.js';
25
+ export { default as verifyCollectorCoverage } from './verifyCollectorCoverage.js';
26
+ export { default as verifyPeerBrokerPerimeter } from './verifyPeerBrokerPerimeter.js';
27
+ export { default as preflightKubeStorage } from './preflightKubeStorage.js';
28
+ export { default as applyWhenChanged } from './applyWhenChanged.js';
29
+ export { default as prepareKubePrerequisites } from './prepareKubePrerequisites.js';
30
+ export { default as readDeploymentDocument } from '../../application/deploy/readDeploymentDocument.js';
31
+ export { appendReplicaTopology, replicaShovels } from './brokerReplicaTopology.js';
32
+ export { default as compileDeploymentHooks } from './compileDeploymentHooks.js';
33
+ export { default as stagedStoragePreflight } from './stagedStoragePreflight.js';
34
+ export { default as validateStagedDeploymentEvidence } from './validateStagedDeploymentEvidence.js';
35
+ export { default as controlPlacement } from '../../application/deploy/controlPlacement.js';
36
+ export { default as buildDeploymentStages } from './buildDeploymentStages.js';
@@ -0,0 +1,79 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { isIP } from 'node:net';
4
+
5
+ const databaseAssets = new URL('../../../db/', import.meta.url);
6
+
7
+ function asset(name) {
8
+ return readFileSync(new URL(name, databaseAssets), 'utf8');
9
+ }
10
+
11
+ function authData(podCidrs) {
12
+ const allowed = podCidrs.map((cidr) => {
13
+ const [address, bits, extra] = cidr.split('/');
14
+ const version = isIP(address);
15
+ const prefix = Number(bits);
16
+ if (extra !== undefined || !version || !Number.isInteger(prefix) || prefix < 1 || prefix > (version === 4 ? 32 : 128)) {
17
+ throw new Error('Invalid target pod CIDR');
18
+ }
19
+ return `host all all ${cidr} scram-sha-256`;
20
+ });
21
+ return {
22
+ 'pg_hba.conf.fragment': ['# DSL target pod CIDRs', ...allowed, 'host all all 0.0.0.0/0 reject', 'host all all ::/0 reject', ''].join('\n'),
23
+ 'entrypoint.sh': asset('bootstrap/entrypoint.sh'),
24
+ 'apply-hba.sh': asset('bootstrap/apply-hba.sh')
25
+ };
26
+ }
27
+
28
+ function schemaData(ownerRole, runtimeRole) {
29
+ const roles = [ownerRole, runtimeRole];
30
+ if (ownerRole === runtimeRole || roles.some((role) => { return typeof role !== 'string' || !/^[a-z_][a-z0-9_]{0,62}$/u.test(role); })) {
31
+ throw new TypeError('Invalid PostgreSQL bootstrap roles');
32
+ }
33
+ const ownership = asset('bootstrap/ownership.sql')
34
+ .replaceAll('@RUNTIME_ROLE@', runtimeRole).replaceAll('@OWNER_ROLE@', ownerRole);
35
+ const grants = asset('migrations/C0002__central_revoke_delete.sql').replaceAll('supervisor_sink', runtimeRole);
36
+ const sql = [
37
+ asset('migrations/V0001__baseline.sql'), asset('migrations/V0002__sink_extension_tables.sql'),
38
+ ownership, grants
39
+ ].map((part) => { return part.trimEnd(); }).join('\n\n');
40
+ return { 'schema.sql': `${sql}\n`, 'zz-auth.sh': asset('bootstrap/zz-auth.sh') };
41
+ }
42
+
43
+ /** Render PostgreSQL bootstrap ConfigMaps using an installation's names and CIDRs. */
44
+ export function postgresBootstrapObjects({ namespace, authConfigMap, schemaConfigMap, ownerRole, runtimeRole }, podCidrs = []) {
45
+ return [
46
+ { apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: authConfigMap, namespace }, data: authData(podCidrs) },
47
+ { apiVersion: 'v1', kind: 'ConfigMap', metadata: { name: schemaConfigMap, namespace }, data: schemaData(ownerRole, runtimeRole) }
48
+ ];
49
+ }
50
+
51
+ function roleContainer({ image, command, credentials, resources }) {
52
+ return {
53
+ name: 'runtime-role', image, command,
54
+ env: ['POSTGRES_URL', 'POSTGRES_ADMIN_URL'].map((key) => {
55
+ return { name: key, valueFrom: { secretKeyRef: { name: credentials, key } } };
56
+ }),
57
+ resources: resources ?? { requests: { cpu: '10m', memory: '64Mi' }, limits: { cpu: '250m', memory: '256Mi' } },
58
+ securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: ['ALL'] } }
59
+ };
60
+ }
61
+
62
+ /** Bind the runtime-role setup job to a selected application image and Secret. */
63
+ export function postgresRuntimeRoleJob(settings) {
64
+ const { namespace, namePrefix, image, pullSecret } = settings;
65
+ const revision = createHash('sha256').update(image).digest('hex').slice(0, 12);
66
+ return {
67
+ apiVersion: 'batch/v1', kind: 'Job', metadata: { name: `${namePrefix}-${revision}`, namespace },
68
+ spec: {
69
+ backoffLimit: 4, activeDeadlineSeconds: 300,
70
+ template: {
71
+ spec: {
72
+ restartPolicy: 'OnFailure', automountServiceAccountToken: false,
73
+ imagePullSecrets: [{ name: pullSecret }], securityContext: { runAsNonRoot: true, runAsUser: 1000 },
74
+ containers: [roleContainer(settings)]
75
+ }
76
+ }
77
+ }
78
+ };
79
+ }
@@ -0,0 +1,47 @@
1
+ import kubeServiceAccount from '../management/kubeServiceAccount.js';
2
+
3
+ const patchJson = 'application/json-patch+json';
4
+ const dnsName = /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u;
5
+
6
+ function validName(name) {
7
+ if (typeof name !== 'string' || !dnsName.test(name)) { throw new TypeError('Invalid Kubernetes deployment target'); }
8
+ return name;
9
+ }
10
+
11
+ function guards(body) {
12
+ const version = body.metadata?.resourceVersion;
13
+ if (typeof version !== 'string' || !version) { throw new Error('Missing Kubernetes resource version'); }
14
+ return [{ op: 'test', path: '/metadata/resourceVersion', value: version }];
15
+ }
16
+
17
+ function concurrentEdit({ status, body }) {
18
+ return status === 409 || (status === 422 && /test failed/u.test(body));
19
+ }
20
+
21
+ /** Recompute a bounded JSON patch from the live Deployment before each mutation. */
22
+ export default function reconcileDeployments({
23
+ namespace, exchange = kubeServiceAccount('https://kubernetes.default.svc'), maxChanges = 5, onPatch
24
+ }) {
25
+ const prefix = `/apis/apps/v1/namespaces/${validName(namespace)}/deployments`;
26
+ function resource(name) { return `${prefix}/${validName(name)}`; }
27
+ async function get(name) {
28
+ const result = await exchange('GET', resource(name));
29
+ if (result.status === 404) { return null; }
30
+ if (result.status !== 200) { throw new Error(`Kubernetes read failed for ${name} with HTTP ${result.status}`); }
31
+ return JSON.parse(result.body);
32
+ }
33
+ async function apply(step, operation) {
34
+ for (let i = 0; i < maxChanges; i += 1) {
35
+ // Read after each attempted patch to incorporate concurrent changes.
36
+ // eslint-disable-next-line no-await-in-loop
37
+ const body = await get(step.name);
38
+ const patch = body && operation(body, step);
39
+ if (!patch) { return; }
40
+ // eslint-disable-next-line no-await-in-loop
41
+ const result = await exchange('PATCH', resource(step.name), [...guards(body), patch], patchJson);
42
+ if (result.status >= 200 && result.status < 300) { onPatch?.(step, patch); }
43
+ else if (!concurrentEdit(result)) { throw new Error(`Kubernetes patch failed for ${step.name} with HTTP ${result.status}`); }
44
+ }
45
+ }
46
+ return { get, apply };
47
+ }
@@ -0,0 +1,30 @@
1
+ const requestProgram = `
2
+ import { readFileSync } from 'node:fs';
3
+ const { url, method, tokenEnv, configuration, body, requireApplied } = JSON.parse(readFileSync(0, 'utf8'));
4
+ if (configuration) {
5
+ const file = process.env[configuration.pathEnv] || configuration.defaultPath;
6
+ const deployed = JSON.parse(readFileSync(file, 'utf8'));
7
+ if (JSON.stringify(deployed) !== JSON.stringify(configuration.expected)) {
8
+ throw new Error(configuration.mismatch);
9
+ }
10
+ }
11
+ const headers = { 'content-type': 'application/json', authorization: 'Bearer ' + process.env[tokenEnv] };
12
+ const response = await fetch(url, { method, headers, redirect: 'error', ...(body !== undefined && { body: JSON.stringify(body) }) });
13
+ const result = await response.text();
14
+ if (!response.ok || (requireApplied && JSON.parse(result).applied !== true)) {
15
+ process.stderr.write(result + '\\n');
16
+ process.exitCode = 1;
17
+ } else {
18
+ process.stdout.write(result + '\\n');
19
+ }
20
+ `;
21
+
22
+ /** Send a protected loopback request inside a running workload with optional config fencing. */
23
+ export default function requestFromWorkload(kube, { workload, url, method, tokenEnv, configuration, body, requireApplied }) {
24
+ const parsed = new URL(url);
25
+ if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1' || parsed.username || parsed.password) {
26
+ throw new TypeError('Workload request requires an HTTP loopback endpoint');
27
+ }
28
+ const input = JSON.stringify({ url, method, tokenEnv, configuration, body, requireApplied });
29
+ return kube(['exec', '-i', workload, '--', 'node', '--input-type=module', '-e', requestProgram], input);
30
+ }
@@ -0,0 +1,72 @@
1
+ import { deploymentStage } from './compileDeploymentHooks.js';
2
+ import { preserveKubeRestart } from './deploymentKube.js';
3
+ import preflightKubeStorage from './preflightKubeStorage.js';
4
+ import verifyPeerBrokerPerimeter from './verifyPeerBrokerPerimeter.js';
5
+
6
+ function preserveRestart(plan, declarations, kube) {
7
+ for (const declaration of declarations) {
8
+ const stage = plan.stages.find(({ id }) => { return id === declaration.stage; });
9
+ if (stage && declaration.workload) {
10
+ stage.values.podAnnotations = preserveKubeRestart(kube, declaration.workload, stage.values.podAnnotations);
11
+ }
12
+ for (const object of stage?.values.extraObjects ?? []) {
13
+ if (declaration.objectKind && object.kind === declaration.objectKind) {
14
+ const { metadata } = object.spec.template;
15
+ metadata.annotations = preserveKubeRestart(kube, `${object.kind.toLowerCase()}/${object.metadata.name}`, metadata.annotations, stage.namespace);
16
+ }
17
+ }
18
+ }
19
+ }
20
+
21
+ function secrets({ postgresSecret, brokerSecrets, runtimeSecret, requiredSecretKeys, databaseRuntime }, database) {
22
+ return [
23
+ ...(brokerSecrets ?? []).map((name) => { return { name }; }),
24
+ { name: runtimeSecret, keys: requiredSecretKeys },
25
+ { name: postgresSecret, keys: database.secretKeys },
26
+ ...(databaseRuntime ? [{ name: databaseRuntime.runtimeSecret, keys: [databaseRuntime.runtimeKey] }] : [])
27
+ ];
28
+ }
29
+
30
+ function storageTemplates(plan, database, postgres, broker, rabbitmq) {
31
+ if (!plan.preserveStoragePodTemplates) { return []; }
32
+ return [{ name: database.name, values: postgres }, ...(plan.brokerSecurity ? [] : [{ name: broker.name, values: rabbitmq }])];
33
+ }
34
+
35
+ function checkPerimeter(plan, evidence, selector, kube) {
36
+ const policy = plan.prerequisites.peerBrokerPerimeter;
37
+ if (!policy) { return; }
38
+ const allowedPeers = policy.spec.ingress[0].from.filter((peer) => { return peer.ipBlock; }).map((peer) => {
39
+ return peer.ipBlock.cidr.replace(/\/(?:32|128)$/u, '');
40
+ });
41
+ verifyPeerBrokerPerimeter({ context: plan.context, policy, allowedPeers, selector, proof: evidence.peerBrokerPerimeter }, kube);
42
+ }
43
+
44
+ function storageResources(plan, policy) {
45
+ const declared = (policy.requiredResources ?? []).filter(({ stage }) => {
46
+ return !stage || plan.stages.some(({ id }) => { return stage === id; });
47
+ }).map(({ name, namespace }) => { return { name, namespace }; });
48
+ return [...plan.prerequisites.preservedConfigMaps.map((name) => { return { name: `configmap/${name}` }; }), ...declared];
49
+ }
50
+
51
+ /** Bind rollout storage checks to the projected resources and supplied identity evidence. */
52
+ export default function stagedStoragePreflight(plan, policy, { evidence, execute, action }) {
53
+ const stage = deploymentStage(plan, policy.stage);
54
+ const { postgres, rabbitmq } = stage.values;
55
+ const { database, broker } = policy;
56
+ return preflightKubeStorage({
57
+ context: plan.context,
58
+ namespace: plan.namespace,
59
+ nodeAddress: plan.nodeAddress,
60
+ secrets: secrets(plan.prerequisites, database),
61
+ beforeStorage: evidence && ((kube) => { checkPerimeter(plan, evidence, broker.selector, kube); }),
62
+ layouts: [{ name: database.name, volume: database.volume, mountPath: database.mountPath, claim: postgres.existingClaim,
63
+ env: database.environment, environmentValue: postgres.data }],
64
+ preserveTemplates: storageTemplates(plan, database, postgres, broker, rabbitmq),
65
+ preserveAnnotations(kube) { preserveRestart(plan, policy.preserveRestart ?? [], kube); },
66
+ verifyTemplates: evidence && { stage, workloads: rabbitmq.definitionsSecret ? [database.name] : [database.name, broker.name] },
67
+ claims: plan.prerequisites.existingClaims.map((name) => {
68
+ return { name, claimUid: evidence?.claims[name], volumeName: evidence?.volumes[name].name, volumeUid: evidence?.volumes[name].uid };
69
+ }),
70
+ resources: storageResources(plan, policy)
71
+ }, action, execute);
72
+ }
@@ -0,0 +1,16 @@
1
+ import { deploymentStage } from './compileDeploymentHooks.js';
2
+ import { validateDeploymentEvidence } from './deploymentChecks.js';
3
+
4
+ /** Validate rollout proof against the readers assigned by the prepared plan. */
5
+ export default function validateStagedDeploymentEvidence(plan, policy, evidence, now) {
6
+ const collector = deploymentStage(plan, policy.collectorStage);
7
+ const { controlCatalog } = collector;
8
+ const tasks = controlCatalog ? controlCatalog.tasks.filter(({ pinnedNode }) => {
9
+ return pinnedNode === plan.context;
10
+ }) : JSON.parse(collector.values.processes[0].env.COLLECTOR_MANIFEST).assignments;
11
+ const readers = Object.fromEntries(Object.entries(policy.optionalReaders ?? {}).map(([key, adapter]) => {
12
+ return [key, tasks.some((task) => { return task.spec.adapter === adapter; })];
13
+ }));
14
+ return validateDeploymentEvidence({ context: plan.context, required: policy.required,
15
+ claims: plan.prerequisites.existingClaims, catalogVersion: controlCatalog?.version, readers }, evidence, now);
16
+ }
@@ -0,0 +1,34 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ function capabilities({ image, role, entrypoint, args = [] }, subject, execute) {
4
+ let result;
5
+ try {
6
+ const options = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 };
7
+ const output = execute('docker', ['run', '--rm', '--read-only', '--network=none', '--tmpfs', '/tmp', '--entrypoint', entrypoint, image, ...args], options);
8
+ result = JSON.parse(String(output));
9
+ } catch {
10
+ throw new Error(`Unable to verify ${subject} ${role} candidate`);
11
+ }
12
+ return result;
13
+ }
14
+
15
+ /** Probe isolated runtime images and require common capabilities declared by the profile. */
16
+ export default function verifyRuntimeCapabilities({ candidates, required, match, subject = 'runtime',
17
+ mismatch = 'Runtime candidates must support the same protocol' }, execute = execFileSync) {
18
+ const results = new Map();
19
+ for (const candidate of candidates) {
20
+ const result = capabilities(candidate, subject, execute);
21
+ if (result?.role !== candidate.role || !Array.isArray(result.historyProtocols)
22
+ || required.some((protocol) => { return !result.historyProtocols.includes(protocol); })) {
23
+ throw new Error(`Incompatible ${subject} ${candidate.role} candidate`);
24
+ }
25
+ results.set(candidate.role, result.historyProtocols);
26
+ }
27
+ if (match) {
28
+ const preferred = match.roles.map((role) => {
29
+ if (!results.has(role)) { throw new Error(`Missing runtime candidate role ${role}`); }
30
+ return match.preference.find((protocol) => { return results.get(role).includes(protocol); });
31
+ });
32
+ if (new Set(preferred).size !== 1) { throw new Error(mismatch); }
33
+ }
34
+ }