@yarkivaev/scada 2.14.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.
- package/charts/scada/templates/processes.yaml +6 -1
- package/charts/scada/values.schema.json +1 -0
- package/db/bootstrap/apply-hba.sh +11 -0
- package/db/bootstrap/entrypoint.sh +6 -0
- package/db/bootstrap/ownership.sql +18 -0
- package/db/bootstrap/zz-auth.sh +3 -0
- package/index.js +1 -0
- package/package.json +3 -2
- package/src/application/control/agent.js +8 -14
- package/src/application/control/controller.js +2 -9
- package/src/application/control/executionSnapshot.js +4 -5
- package/src/application/control/periodicReconciliation.js +19 -0
- package/src/application/control/publishControlCatalog.js +25 -0
- package/src/application/control/reconcileStoredChoice.js +10 -0
- package/src/application/deploy/controlPlan.js +93 -0
- package/src/application/deploy/deploymentCommands.js +29 -0
- package/src/application/deploy/deploymentPlan.js +84 -0
- package/src/application/deploy/readDocumentFile.js +28 -0
- package/src/application/deploy/releases.js +14 -10
- package/src/application/runtime/deliveryOperations.js +6 -3
- package/src/application/runtime/deliveryPublications.js +13 -11
- package/src/application/runtime/deliveryQueue.js +5 -4
- package/src/application/runtime/index.js +0 -1
- package/src/application/runtime/queuedDelivery.js +6 -5
- package/src/application/runtime/runCollector.js +8 -6
- package/src/application/runtime/runtime.js +1 -0
- package/src/application/runtime/runtimeServices.js +6 -26
- package/src/infrastructure/deploy/applyHelmResources.js +17 -0
- package/src/infrastructure/deploy/bootstrapKubeStorage.js +28 -0
- package/src/infrastructure/deploy/deploymentChecks.js +68 -0
- package/src/infrastructure/deploy/deploymentPatch.js +36 -0
- package/src/infrastructure/deploy/executeChartDeployment.js +19 -0
- package/src/infrastructure/deploy/executeRelease.js +6 -2
- package/src/infrastructure/deploy/executeStagedDeployment.js +31 -0
- package/src/infrastructure/deploy/index.js +29 -0
- package/src/infrastructure/deploy/postgresBootstrap.js +79 -0
- package/src/infrastructure/deploy/reconcileDeployments.js +47 -0
- package/src/infrastructure/deploy/requestFromWorkload.js +30 -0
- package/src/infrastructure/deploy/verifyRuntimeCapabilities.js +34 -0
- package/src/infrastructure/management/kiosk/kiosk-browser.py +91 -0
- package/src/infrastructure/management/kiosk/kiosk-volume.sh +105 -0
- package/src/infrastructure/management/kiosk/listen.mjs.txt +14 -0
- package/src/infrastructure/management/kiosk/operateKiosk.js +74 -0
- package/src/infrastructure/management/kiosk/renderKioskResources.js +41 -0
- package/src/infrastructure/management/kiosk/shellArgument.js +4 -0
- package/src/infrastructure/management/kiosk/wait-x11.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-liveness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog-readiness.sh +1 -0
- package/src/infrastructure/management/kiosk/watchdog.sh +137 -0
- package/src/infrastructure/management/serveReconciliation.js +17 -0
- package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
- package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
- package/src/application/control/snapshotFile.js +0 -24
- package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
- package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
- package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
- package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
- package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
- package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
- package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
- package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
- package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
|
@@ -2,15 +2,16 @@ import deliveryQueue from './deliveryQueue.js';
|
|
|
2
2
|
import { sinks } from './streamPorts.js';
|
|
3
3
|
|
|
4
4
|
/** Configured once per node; queue draining outlives any individual assignment. */
|
|
5
|
-
export default function queuedDelivery(env, secrets, supplied) {
|
|
5
|
+
export default function queuedDelivery(env, secrets, supplied, store) {
|
|
6
6
|
let timer;
|
|
7
7
|
let stopped = false;
|
|
8
8
|
let burst = 0;
|
|
9
|
-
const queue = supplied ??
|
|
10
|
-
maxBytes: Number(env.
|
|
11
|
-
|
|
9
|
+
const queue = supplied ?? deliveryQueue({
|
|
10
|
+
maxBytes: Number(env.COLLECTOR_QUEUE_MAX_BYTES ?? 16 * 1024 * 1024),
|
|
11
|
+
maxRecords: Number(env.COLLECTOR_QUEUE_MAX_RECORDS ?? 4096),
|
|
12
|
+
factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
|
|
12
13
|
onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
|
|
13
|
-
}
|
|
14
|
+
}, store);
|
|
14
15
|
function nextDelay(result) {
|
|
15
16
|
const status = queue.status?.();
|
|
16
17
|
if (result?.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
|
|
@@ -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
|
-
|
|
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,
|
|
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,
|
|
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)
|
|
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);
|
|
@@ -1,37 +1,17 @@
|
|
|
1
|
-
import
|
|
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
|
-
|
|
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 =
|
|
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 ??
|
|
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,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
|
-
|
|
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,29 @@
|
|
|
1
|
+
export { collectorDeployment, deploymentContext, peerNodePort, retiredDeployments, stageFor } from '../../application/deploy/deploymentPlan.js';
|
|
2
|
+
export { collectorControlDeployment, 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';
|
|
@@ -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,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
|
+
}
|