@yarkivaev/scada 2.12.2 → 2.14.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/README.md +1 -1
- package/db/migrations/E0013__history_staged_corrections.sql +1 -1
- package/db/migrations/E0017__history_live_covering.sql +1 -1
- package/db/migrations/E0025__history_processor_properties.sql +76 -0
- package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
- package/index.js +43 -2
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/foldedMetricsSink.js +1 -1
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/application/runtime/collectorStartup.js +23 -0
- package/src/application/runtime/index.js +2 -0
- package/src/application/runtime/runCollector.js +46 -9
- package/src/application/runtime/runtimeServices.js +20 -2
- package/src/application/runtime/spoolHistory.js +12 -12
- package/src/application/runtime/spoolSurface.js +2 -2
- package/src/application/runtime/spooledOutput.js +27 -0
- package/src/application/siteServer.js +2 -2
- package/src/application/supervisorSink.js +5 -6
- package/src/application/sync/publishingOperations.js +52 -0
- package/src/application/sync/siteSync.js +1 -1
- package/src/application/sync/siteSyncRows.js +1 -1
- package/src/application/sync/siteSyncSites.js +1 -1
- package/src/application/telemetry/telemetryBackfill.js +127 -0
- package/src/application/timelineOperatorFromEnv.js +1 -1
- package/src/domain/ingest/telemetryTimestamp.js +7 -0
- package/src/domain/segment/dispatch.js +19 -17
- package/src/domain/segment/historyFold.js +2 -1
- package/src/domain/segment/intervalFold.js +1 -1
- package/src/domain/segment/segmentContinue.js +1 -1
- package/src/infrastructure/catalog/tagCatalog.js +7 -11
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
- package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
- package/src/infrastructure/http/plant/timelineOperator.js +2 -2
- package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
- package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
- package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
- package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
- package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
- package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
- package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
- package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
- package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
- package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
- package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
- package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
- package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
- package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
- package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
- package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
- package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
- package/src/infrastructure/persistence/pg/history.js +74 -56
- package/src/infrastructure/persistence/pg/historyContext.js +34 -17
- package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
- package/src/infrastructure/persistence/pg/historyFence.js +1 -1
- package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
- package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
- package/src/infrastructure/persistence/pg/historySeed.js +3 -3
- package/src/infrastructure/persistence/pg/historySession.js +15 -0
- package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
- package/src/infrastructure/persistence/postgresPool.js +6 -1
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/streams/modbusSource.js +1 -1
- package/src/infrastructure/streams/stompSend.js +1 -1
- package/src/infrastructure/sync/operationAmqp.js +26 -0
- package/src/infrastructure/sync/operationEvent.js +10 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
- package/src/infrastructure/catalog/tag-catalog.json +0 -27
|
@@ -1,25 +1,21 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
import { fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname, join } from 'node:path';
|
|
4
2
|
|
|
5
3
|
/**
|
|
6
|
-
* Loads hierarchical tag catalog entries from
|
|
4
|
+
* Loads hierarchical tag catalog entries from a configured JSON file.
|
|
7
5
|
*
|
|
8
|
-
*
|
|
9
|
-
* package copy without rebuilding the image.
|
|
6
|
+
* Uses an empty catalog when TAG_CATALOG_PATH is unset.
|
|
10
7
|
*
|
|
11
8
|
* @example
|
|
12
|
-
* const catalog = tagCatalog();
|
|
13
|
-
* catalog.labels()
|
|
9
|
+
* const catalog = tagCatalog({ TAG_CATALOG_PATH: '/etc/scada/tag-catalog.json' });
|
|
10
|
+
* catalog.labels();
|
|
14
11
|
*
|
|
15
12
|
* @param {object} [env] - environment map, defaults to process.env
|
|
16
|
-
* @returns {object} catalog with entries(), labels(),
|
|
13
|
+
* @returns {object} catalog with entries(), labels(), children(parent)
|
|
17
14
|
*/
|
|
18
15
|
export default function tagCatalog(env) {
|
|
19
16
|
const source = env || process.env;
|
|
20
|
-
const path = source.TAG_CATALOG_PATH
|
|
21
|
-
|
|
22
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
17
|
+
const path = source.TAG_CATALOG_PATH;
|
|
18
|
+
const raw = path ? JSON.parse(readFileSync(path, 'utf8')) : [];
|
|
23
19
|
if (!Array.isArray(raw)) {
|
|
24
20
|
throw new Error('tag catalog must be a JSON array');
|
|
25
21
|
}
|
|
@@ -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 =
|
|
116
|
-
{ input: JSON.stringify(plan.values), encoding: 'utf8' });
|
|
113
|
+
const manifests = renderRelease(plan, execute);
|
|
117
114
|
if (action === 'render') { return manifests; }
|
|
118
|
-
const kube =
|
|
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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { taskSpecHash } from '../../application/runtime/assignment.js';
|
|
2
|
+
|
|
3
|
+
function nodeIdentity(node, namespace, execute) {
|
|
4
|
+
const response = execute('kubectl', ['--context', node, '--namespace', namespace, '--request-timeout=10s', 'get', 'nodes', '-o', 'json'],
|
|
5
|
+
{ encoding: 'utf8', timeout: 15000 });
|
|
6
|
+
const nodes = JSON.parse(response).items;
|
|
7
|
+
if (nodes?.length !== 1 || !nodes[0].metadata?.uid) { throw new Error('Single physical node identity required'); }
|
|
8
|
+
return nodes[0];
|
|
9
|
+
}
|
|
10
|
+
function distinct(local, remote) {
|
|
11
|
+
const ips = local.status?.addresses?.filter((row) => { return row.type === 'InternalIP'; }).map((row) => { return row.address; }) ?? [];
|
|
12
|
+
if (local.metadata.uid === remote.metadata.uid || remote.status?.addresses?.some((row) => { return row.type === 'InternalIP' && ips.includes(row.address); })) {
|
|
13
|
+
throw new Error('Surviving reader must run on another physical node');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl }) {
|
|
17
|
+
const program = `const r=await fetch(${JSON.stringify(statusUrl)},{signal:AbortSignal.timeout(2000)});if(!r.ok)throw new Error('Reader unavailable');process.stdout.write(await r.text());`;
|
|
18
|
+
const response = execute('kubectl', ['--context', proof.nodeId, '--namespace', namespace, '--request-timeout=10s',
|
|
19
|
+
'exec', proof.workload, '-c', container, '--', 'node', '--input-type=module', '-e', program], { encoding: 'utf8', timeout: 15000 });
|
|
20
|
+
const status = JSON.parse(response);
|
|
21
|
+
const row = status.tasks?.find((item) => { return item.taskId === task.taskId; });
|
|
22
|
+
const at = now();
|
|
23
|
+
if (status.initialized !== true || status.stopping || status.fatal || row?.state !== 'running'
|
|
24
|
+
|| ['failed', 'degraded'].includes(row.health) || row.specHash !== taskSpecHash(task.spec)
|
|
25
|
+
|| !Number.isFinite(row.lastRead) || row.lastRead > at + clockSkewMs || at - row.lastRead > freshnessMs) {
|
|
26
|
+
throw new Error(`Fresh surviving reader required: ${task.taskId}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Probe a matching controlled collector or temporary static bridge immediately before retirement. */
|
|
30
|
+
export default function verifyCollectorCoverage({ cluster, namespace, tasks, evidence, execute, now = Date.now,
|
|
31
|
+
freshnessMs = 15000, clockSkewMs = 5000, workloads, container = 'collector', statusUrl = 'http://127.0.0.1:9091/status' }) {
|
|
32
|
+
if (!tasks.length) { return; }
|
|
33
|
+
const local = nodeIdentity(cluster, namespace, execute);
|
|
34
|
+
for (const task of tasks) {
|
|
35
|
+
const proof = evidence?.coverage?.find((item) => { return item.taskId === task.taskId; });
|
|
36
|
+
if (!proof || proof.nodeId === cluster || !task.eligibleNodes.includes(proof.nodeId)
|
|
37
|
+
|| !workloads?.includes(proof.workload)) {
|
|
38
|
+
throw new Error(`Live surviving reader coverage required: ${task.taskId}`);
|
|
39
|
+
}
|
|
40
|
+
distinct(local, nodeIdentity(proof.nodeId, namespace, execute));
|
|
41
|
+
liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { readKube } from './deploymentKube.js';
|
|
3
|
+
|
|
4
|
+
/** Bind supplied packet probe evidence to the live broker pod and network policy. */
|
|
5
|
+
export default function verifyPeerBrokerBoundary({ context, policy, allowedPeers, selector, proof, maxAgeMs = 900000 }, kube, now = Date.now()) {
|
|
6
|
+
if (!policy) { return; }
|
|
7
|
+
const verifiedAt = Date.parse(proof?.verifiedAt);
|
|
8
|
+
if (!proof || proof.cluster !== context || !proof.networkPolicyEnforced
|
|
9
|
+
|| !isDeepStrictEqual(proof.allowedPeers, [...allowedPeers].sort()) || !proof.deniedSources?.length
|
|
10
|
+
|| proof.deniedSources.some((source) => { return allowedPeers.includes(source); })
|
|
11
|
+
|| !(verifiedAt <= now && verifiedAt > now - maxAgeMs)) {
|
|
12
|
+
throw new Error('Fresh verified peer broker perimeter coverage evidence required');
|
|
13
|
+
}
|
|
14
|
+
const live = JSON.parse(readKube(kube, `networkpolicy/${policy.metadata.name}`));
|
|
15
|
+
if (live.metadata.uid !== proof.policyUID || live.metadata.resourceVersion !== proof.policyResourceVersion
|
|
16
|
+
|| !isDeepStrictEqual(live.spec, policy.spec)) {
|
|
17
|
+
throw new Error('Peer broker perimeter policy changed after packet probes');
|
|
18
|
+
}
|
|
19
|
+
const { items: pods } = JSON.parse(kube(['get', 'pods', '-l', selector, '-o', 'json'], undefined, true));
|
|
20
|
+
if (pods.length !== 1 || pods[0].metadata.uid !== proof.brokerPodUID
|
|
21
|
+
|| !pods[0].status.containerStatuses?.every((container) => { return container.ready; })) {
|
|
22
|
+
throw new Error('Peer broker identity changed after perimeter packet probes');
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -22,7 +22,7 @@ function body(raw) {
|
|
|
22
22
|
* decisionJson({
|
|
23
23
|
* username: 'Elena Volkov', operatorId: 2,
|
|
24
24
|
* decidedAt: new Date('2024-06-01T12:05:00.000Z'),
|
|
25
|
-
* payload: '{"tags":["
|
|
25
|
+
* payload: '{"tags":["needs_review"]}'
|
|
26
26
|
* });
|
|
27
27
|
*/
|
|
28
28
|
export default function decisionJson(row) {
|
|
@@ -73,7 +73,7 @@ async function respondToRequest(gate, timeline, requestId, req, res) {
|
|
|
73
73
|
* @returns {array} route objects
|
|
74
74
|
*
|
|
75
75
|
* @example
|
|
76
|
-
* timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: '
|
|
76
|
+
* timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: 'example-workstation' });
|
|
77
77
|
*/
|
|
78
78
|
export default function timelineRoute(basePath, plant, operatorOptions, decorate, currentPhase) {
|
|
79
79
|
const gate = timelineOperator(operatorOptions);
|