@yarkivaev/scada 2.16.0 → 2.18.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/index.js +1 -2
- package/package.json +3 -2
- package/src/application/deploy/collectorSourcePlan.js +97 -0
- package/src/application/deploy/compileCollectorTasks.js +31 -0
- package/src/application/deploy/compileControlCatalog.js +66 -0
- package/src/application/deploy/controlPlacement.js +71 -0
- package/src/application/deploy/controlPlan.js +51 -4
- package/src/application/deploy/controlPlaneConfiguration.js +62 -0
- package/src/application/deploy/controlReaderSpecs.js +37 -0
- package/src/application/deploy/liveReleaseOverlay.js +17 -0
- package/src/application/deploy/projectControlPlane.js +48 -0
- package/src/application/deploy/projectTopology.js +41 -0
- package/src/application/deploy/readDeploymentDocument.js +25 -0
- package/src/infrastructure/deploy/brokerReplicaTopology.js +97 -0
- package/src/infrastructure/deploy/brokerSecurity.js +89 -0
- package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
- package/src/infrastructure/deploy/brokerTopology.js +125 -0
- package/src/infrastructure/deploy/buildDeploymentStages.js +23 -0
- package/src/infrastructure/deploy/centralTelemetry.js +51 -0
- package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
- package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
- package/src/infrastructure/deploy/compileDeploymentHooks.js +48 -0
- package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
- package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
- package/src/infrastructure/deploy/databaseSecurity.js +39 -0
- package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
- package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
- package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
- package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
- package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
- package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
- package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
- package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
- package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
- package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
- package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
- package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
- package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
- package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
- package/src/infrastructure/deploy/highAvailability/index.js +14 -0
- package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
- package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
- package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
- package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
- package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
- package/src/infrastructure/deploy/index.js +33 -1
- package/src/infrastructure/deploy/projectClassification.js +42 -0
- package/src/infrastructure/deploy/securityPolicy.js +16 -0
- package/src/infrastructure/deploy/stagedStoragePreflight.js +72 -0
- package/src/infrastructure/deploy/validateStagedDeploymentEvidence.js +16 -0
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
- package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
- package/src/infrastructure/mdmesh/hmiPlan.js +123 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
- package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
- package/src/infrastructure/opcua/projectSources.js +36 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { acceptEpoch } from './highAvailability/supervisorReplica.js';
|
|
2
|
+
import rabbitmqDefinitions, { brokerShovel } from '../messaging/rabbitmq/definitions.js';
|
|
3
|
+
|
|
4
|
+
function endpoint(value, blockedHost) {
|
|
5
|
+
const url = new URL(value);
|
|
6
|
+
if (url.host === blockedHost) { throw new TypeError(`Replica shovel must stay off the blocked broker ${url.host}`); }
|
|
7
|
+
if (!url.username) {
|
|
8
|
+
url.username = 'guest';
|
|
9
|
+
url.password = 'guest';
|
|
10
|
+
}
|
|
11
|
+
return url.toString().replace(/\/$/u, '');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function shovel(stream, source, target, options, restore) {
|
|
15
|
+
const queue = `${stream.queue}.to-${target.node}`;
|
|
16
|
+
const exchange = restore ? stream.restore.exchange : undefined;
|
|
17
|
+
const outbox = stream.forwardOutbox ? queue : stream.queue;
|
|
18
|
+
const landing = restore ? stream.restore.queue : outbox;
|
|
19
|
+
return brokerShovel({ vhost: options.vhost, reconnectDelay: options.reconnectDelay, name: `${stream.name}-to-${target.node}`,
|
|
20
|
+
sourceUri: source.uri, queue, destinationUri: target.uri, exchange,
|
|
21
|
+
destinationQueue: exchange === undefined ? landing : undefined });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Plan primary-to-standby copies and standby-to-primary restoration for declared streams. */
|
|
25
|
+
export function replicaShovels({ leader, standby, brokers, blocked, streams, vhost = '/', reconnectDelay = 30 }) {
|
|
26
|
+
if (leader === standby) { throw new TypeError('Replica endpoints cannot use the same node'); }
|
|
27
|
+
const blockedHost = blocked ? new URL(blocked).host : undefined;
|
|
28
|
+
const primary = { node: leader, uri: endpoint(brokers[leader], blockedHost) };
|
|
29
|
+
const secondary = { node: standby, uri: endpoint(brokers[standby], blockedHost) };
|
|
30
|
+
return streams.flatMap((stream) => {
|
|
31
|
+
return [
|
|
32
|
+
shovel(stream, primary, secondary, { vhost, reconnectDelay }, false),
|
|
33
|
+
shovel(stream, secondary, primary, { vhost, reconnectDelay }, true)
|
|
34
|
+
];
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Describe pair ownership, ingest queues and restoration targets for configured streams. */
|
|
39
|
+
export function brokerReplicaPlan({ leader, standby, epoch, brokers, blocked, exchange, streams, vhost, reconnectDelay }) {
|
|
40
|
+
if (!brokers[leader] || !brokers[standby]) { throw new TypeError('Missing replica broker'); }
|
|
41
|
+
if (!acceptEpoch(epoch, epoch)) { throw new TypeError(`Writer epoch must be positive, message ${epoch} current ${epoch}`); }
|
|
42
|
+
const shovels = replicaShovels({ leader, standby, brokers, blocked, streams, vhost, reconnectDelay });
|
|
43
|
+
const ingest = Object.fromEntries(streams.map(({ id, queue }) => { return [id, queue]; }));
|
|
44
|
+
const restore = Object.fromEntries(streams.map(({ id, restore: target }) => { return [id, target.exchange ?? target.queue]; }));
|
|
45
|
+
return { writer: leader, standby, epoch, exchange, shovels, ingest: { node: standby, ...ingest }, restore: { node: leader, ...restore } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function appendDistinct(target, rows) {
|
|
49
|
+
rows.forEach((row) => {
|
|
50
|
+
if (!target.some((item) => { return item.name === row.name && item.vhost === row.vhost; })) {
|
|
51
|
+
target.push(row);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function append(result, input) {
|
|
57
|
+
const { exchanges, queues, bindings } = rabbitmqDefinitions(input);
|
|
58
|
+
appendDistinct(result.exchanges, exchanges);
|
|
59
|
+
appendDistinct(result.queues, queues);
|
|
60
|
+
result.bindings.push(...bindings);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function routes(source, destination, keys = []) {
|
|
64
|
+
return keys.map((key) => { return { source, destination, key }; });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Add replica resources to an existing broker definition without replacing its declarations. */
|
|
68
|
+
export function appendReplicaTopology(result, { landings = [], copies = [], vhost = '/' }) {
|
|
69
|
+
landings.forEach(({ exchange, queue, keys, bindings = [] }) => {
|
|
70
|
+
append(result, { vhost, exchanges: [exchange], queues: [queue], bindings: [...routes(exchange, queue, keys), ...bindings] });
|
|
71
|
+
});
|
|
72
|
+
copies.forEach(({ shovel: copy, source, keys }) => {
|
|
73
|
+
const queue = copy.value['src-queue'];
|
|
74
|
+
result.parameters.push(copy);
|
|
75
|
+
append(result, { vhost, queues: [queue], bindings: routes(source, queue, keys) });
|
|
76
|
+
});
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
function replicaCopies(replica, { brokers, blocked, vhost, host }) {
|
|
82
|
+
const { shovels } = brokerReplicaPlan({ ...replica, brokers, blocked, vhost });
|
|
83
|
+
return replica.streams.flatMap(({ source, keys }, index) => {
|
|
84
|
+
return shovels.slice(index * 2, index * 2 + 2).filter(({ value }) => {
|
|
85
|
+
return new URL(value['src-uri']).host === host;
|
|
86
|
+
}).map((copy) => { return { shovel: copy, source, keys }; });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Attach local landings and the copies published by a broker in an ordered fleet. */
|
|
91
|
+
export function appendBrokerReplicas(result, { node, brokers, blocked, replicas, vhost = '/' }) {
|
|
92
|
+
const landings = replicas.filter(({ leader }) => { return leader === node; })
|
|
93
|
+
.flatMap((replica) => { return replica.landings; });
|
|
94
|
+
const host = brokers[node] && new URL(brokers[node]).host;
|
|
95
|
+
const copies = host ? replicas.flatMap((replica) => { return replicaCopies(replica, { brokers, blocked, vhost, host }); }) : [];
|
|
96
|
+
return appendReplicaTopology(result, { landings, copies, vhost });
|
|
97
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
function account(value) {
|
|
4
|
+
if (!value || typeof value.name !== 'string' || !value.name || value.name === 'guest'
|
|
5
|
+
|| typeof value.password !== 'string' || value.password.length < 16) {
|
|
6
|
+
throw new TypeError('Broker credentials require a named non-guest identity and password of at least 16 characters');
|
|
7
|
+
}
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
/** Preserve encoded vhost/path while replacing, never concatenating, credentials. */
|
|
11
|
+
export function brokerUri(uri, credentials) {
|
|
12
|
+
const target = new URL(uri);
|
|
13
|
+
const { name, password } = account(credentials);
|
|
14
|
+
if (!['amqp:', 'amqps:'].includes(target.protocol)) { throw new TypeError('Expected AMQP broker URI'); }
|
|
15
|
+
target.username = encodeURIComponent(name);
|
|
16
|
+
target.password = encodeURIComponent(password);
|
|
17
|
+
return target.toString();
|
|
18
|
+
}
|
|
19
|
+
function user(credentials, tags) {
|
|
20
|
+
const { name, password, password_hash: passwordHash } = account(credentials);
|
|
21
|
+
// Stable public per-identity salt keeps pure desired-state rendering idempotent.
|
|
22
|
+
// Production passwords must be random; callers may instead supply a precomputed RabbitMQ hash.
|
|
23
|
+
const salt = createHash('sha256').update(name).digest().subarray(0, 4);
|
|
24
|
+
const digest = createHash('sha256').update(salt).update(password).digest();
|
|
25
|
+
return { name, 'password_hash': passwordHash || Buffer.concat([salt, digest]).toString('base64'),
|
|
26
|
+
'hashing_algorithm': 'rabbit_password_hashing_sha256', tags };
|
|
27
|
+
}
|
|
28
|
+
function credential(uri, security) {
|
|
29
|
+
const parsed = new URL(uri);
|
|
30
|
+
const port = parsed.port || (parsed.protocol === 'amqps:' ? '5671' : '5672');
|
|
31
|
+
if (['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname)) { return security.federation; }
|
|
32
|
+
return security.peers?.[`${parsed.hostname}:${port}`];
|
|
33
|
+
}
|
|
34
|
+
function switchShovels(result, security) {
|
|
35
|
+
for (const parameter of result.parameters || []) {
|
|
36
|
+
const fields = [];
|
|
37
|
+
if (parameter.component === 'shovel') { fields.push('src-uri', 'dest-uri'); }
|
|
38
|
+
if (parameter.component === 'federation-upstream') { fields.push('uri'); }
|
|
39
|
+
for (const field of fields) {
|
|
40
|
+
const uri = new URL(parameter.value[field]);
|
|
41
|
+
const credentials = credential(parameter.value[field], security);
|
|
42
|
+
if (!credentials) { throw new TypeError(`Missing peer credentials for ${parameter.component} ${parameter.name || ''}`); }
|
|
43
|
+
parameter.value[field] = brokerUri(uri, credentials);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Credentials enter memory from the deployment's encrypted source; never serialize this into a ConfigMap. */
|
|
48
|
+
// eslint-disable-next-line max-statements -- One staged transformation preserves the complete durable topology.
|
|
49
|
+
export function secureBrokerDefinitions(desired, security, { resources, messaging }) {
|
|
50
|
+
if (!security) { return desired; }
|
|
51
|
+
if (!['prepare', 'switch', 'retire'].includes(security.phase)) { throw new TypeError('Explicit broker migration phase required'); }
|
|
52
|
+
const roles = ['runtime', 'federation', 'maintenance'];
|
|
53
|
+
roles.forEach(role => { return account(security[role]); });
|
|
54
|
+
if (new Set(roles.map(role => { return security[role].name; })).size !== roles.length) { throw new TypeError('Broker role identities must be distinct'); }
|
|
55
|
+
const result = structuredClone(desired);
|
|
56
|
+
const replaced = new Set(roles.map(role => { return security[role].name; }));
|
|
57
|
+
if (security.phase === 'retire') { replaced.add('guest'); }
|
|
58
|
+
result.users = (result.users || []).filter(row => { return !replaced.has(row.name); });
|
|
59
|
+
result.permissions = (result.permissions || []).filter(row => { return !replaced.has(row.user); });
|
|
60
|
+
for (const role of roles) {
|
|
61
|
+
result.users.push(user(security[role], role === 'maintenance' ? ['policymaker'] : []));
|
|
62
|
+
result.permissions.push({ user: security[role].name, vhost: '/', configure: resources, read: messaging, write: messaging });
|
|
63
|
+
}
|
|
64
|
+
if (security.phase !== 'prepare') { switchShovels(result, security); }
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
/** Reconciliation must move to this identity before retiring guest's management access. */
|
|
68
|
+
export function brokerManagement(base, security) {
|
|
69
|
+
const credentials = account(security.maintenance);
|
|
70
|
+
return { base, vhost: '/', username: credentials.name, password: credentials.password };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Requires chart Secret-mount support; no shovel password may enter a ConfigMap. */
|
|
74
|
+
export function secureBrokerValues(values, security, permissions) {
|
|
75
|
+
if (!security) { return values; }
|
|
76
|
+
if (!security.definitionsSecret || !security.runtimeSecret) { throw new TypeError('Broker definitions Secret and runtime Secret required'); }
|
|
77
|
+
return { ...values, definitions: secureBrokerDefinitions(values.definitions, security, permissions), definitionsSecret: security.definitionsSecret,
|
|
78
|
+
podAnnotations: { ...values.podAnnotations, 'scada/broker-security-phase': security.phase },
|
|
79
|
+
...(security.phase !== 'prepare' && { runtimeSecret: security.runtimeSecret }),
|
|
80
|
+
extraConfig: { ...values.extraConfig, ...(security.phase === 'retire' && {
|
|
81
|
+
'mqtt.allow_anonymous': 'false', 'loopback_users.guest': 'true'
|
|
82
|
+
}) } };
|
|
83
|
+
}
|
|
84
|
+
export function brokerClientEnvironment(security) {
|
|
85
|
+
if (!security?.runtimeSecret) { throw new TypeError('Broker runtime Secret required'); }
|
|
86
|
+
return Object.fromEntries(['AMQP_URL', 'MQTT_URL', 'MQTT_USERNAME', 'MQTT_PASSWORD', 'STOMP_LOGIN', 'STOMP_PASSCODE'].map(name => {
|
|
87
|
+
return [name, { valueFrom: { secretKeyRef: { name: security.runtimeSecret, key: name } } }];
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { databaseSecurity } from './databaseSecurity.js';
|
|
3
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
4
|
+
|
|
5
|
+
/** Deployment supplies an ephemeral 0600 file decrypted from its existing secret store. */
|
|
6
|
+
export default function brokerSecurityInput(path) {
|
|
7
|
+
if (!path) { return undefined; }
|
|
8
|
+
try {
|
|
9
|
+
const metadata = statSync(path);
|
|
10
|
+
// eslint-disable-next-line no-bitwise -- Inspect POSIX group/other permission bits.
|
|
11
|
+
if (!metadata.isFile() || (metadata.mode & 0o077)) { throw new Error(); }
|
|
12
|
+
const security = JSON.parse(readFileSync(path, 'utf8'));
|
|
13
|
+
if (!security || typeof security !== 'object' || Array.isArray(security)) { throw new Error(); }
|
|
14
|
+
brokerPolicy(security);
|
|
15
|
+
return security;
|
|
16
|
+
} catch {
|
|
17
|
+
// Never allow JSON parser diagnostics to echo a secret fragment.
|
|
18
|
+
throw new TypeError('Broker security input must be a valid protected 0600 JSON file');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const phases = { prepare: 1, switch: 2, retire: 3 };
|
|
23
|
+
function captured(execute, { cluster, namespace }, args) {
|
|
24
|
+
try {
|
|
25
|
+
return String(execute('kubectl', ['--context', cluster, '--namespace', namespace, ...args],
|
|
26
|
+
{ encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }) || '').trim();
|
|
27
|
+
} catch { throw new Error('Cannot verify persisted broker controller state'); }
|
|
28
|
+
}
|
|
29
|
+
function namedBrokerUsers(users, ignorePattern) {
|
|
30
|
+
return users.split('\n').map(row => { return row.trim().split(/\s+/u)[0]; }).filter(name => { return name && name !== 'guest' && !ignorePattern?.test(name); });
|
|
31
|
+
}
|
|
32
|
+
function livePhase(state) {
|
|
33
|
+
const annotations = { ...state.metadata?.annotations, ...state.spec?.template?.metadata?.annotations };
|
|
34
|
+
const recorded = Object.entries(annotations).filter(([name]) => { return name.includes('broker-security-phase'); });
|
|
35
|
+
const volumes = state.spec?.template?.spec?.volumes || [];
|
|
36
|
+
const mounts = (state.spec?.template?.spec?.containers || []).flatMap(row => { return row.volumeMounts || []; });
|
|
37
|
+
const definitions = new Set(mounts.filter(row => { return row.mountPath?.endsWith('/definitions.json'); }).map(row => { return row.name; }));
|
|
38
|
+
const mounted = volumes.some(row => { return row.secret && (definitions.has(row.name) || row.name.includes('definitions')); });
|
|
39
|
+
return Math.max(mounted ? 1 : 0, ...recorded.map(([, phase]) => { return phases[phase] || 0; }));
|
|
40
|
+
}
|
|
41
|
+
function verifyLiveDatabase(state, canonical) {
|
|
42
|
+
const verified = (state.spec?.template?.spec?.containers || []).filter((container) => {
|
|
43
|
+
return (container.env || []).some((field) => { return field.name === 'SUPERVISOR_MIGRATIONS' && field.value === 'verify'; });
|
|
44
|
+
});
|
|
45
|
+
for (const container of verified) {
|
|
46
|
+
const env = Object.fromEntries((container.env || []).map((field) => { return [field.name,field]; }));
|
|
47
|
+
const reference = env.POSTGRES_URL?.valueFrom?.secretKeyRef;
|
|
48
|
+
if (!canonical || !reference || reference.name !== canonical.runtimeSecret || reference.key !== canonical.runtimeKey) {
|
|
49
|
+
throw new Error('Persisted database verification policy missing or mismatched');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Private reads precede every deploy mutation; render remains strictly offline. */
|
|
55
|
+
// eslint-disable-next-line max-statements -- Resolve persisted credentials and reject downgrade before the first deployment write.
|
|
56
|
+
export function readDeployedBrokerSecurity(action, target, execute, explicit) {
|
|
57
|
+
if (action === 'render') { brokerPolicy(explicit); return explicit; }
|
|
58
|
+
const { controllerSecret, brokerWorkload, applicationWorkload, ignoreUserPrefix, repairMessage } = target;
|
|
59
|
+
try {
|
|
60
|
+
const raw = captured(execute, target, ['get', controllerSecret, '--ignore-not-found', '-o', 'json']);
|
|
61
|
+
const controller = raw ? JSON.parse(Buffer.from(JSON.parse(raw).data['security.json'], 'base64').toString('utf8')) : undefined;
|
|
62
|
+
const workload = captured(execute, target, ['get', brokerWorkload, '--ignore-not-found', '-o', 'json']);
|
|
63
|
+
const state = workload ? JSON.parse(workload) : {};
|
|
64
|
+
const persisted = livePhase(state);
|
|
65
|
+
const security = explicit || controller;
|
|
66
|
+
const broker = brokerPolicy(security);
|
|
67
|
+
const previousBroker = brokerPolicy(controller);
|
|
68
|
+
const previousDatabase = databaseSecurity(controller);
|
|
69
|
+
const application = captured(execute, target, ['get', applicationWorkload, '--ignore-not-found', '-o', 'json']);
|
|
70
|
+
verifyLiveDatabase(application ? JSON.parse(application) : {}, previousDatabase);
|
|
71
|
+
if (previousDatabase && JSON.stringify(previousDatabase) !== JSON.stringify(databaseSecurity(security))) { throw new Error(); }
|
|
72
|
+
if (!previousBroker && persisted) { throw new Error(); }
|
|
73
|
+
const minimum = Math.max(persisted, phases[previousBroker?.phase] || 0);
|
|
74
|
+
if (minimum && !broker) { throw new Error(); }
|
|
75
|
+
if (!previousBroker && workload) {
|
|
76
|
+
const users = captured(execute, target, ['exec', brokerWorkload, '--', 'rabbitmqctl', '-s', 'list_users']);
|
|
77
|
+
if (namedBrokerUsers(users, ignoreUserPrefix).length) { throw new Error(); }
|
|
78
|
+
}
|
|
79
|
+
if (broker && phases[broker.phase] < minimum) { throw new Error(); }
|
|
80
|
+
return security;
|
|
81
|
+
} catch {
|
|
82
|
+
// Captured stdout/stderr, parser errors and decoded JSON must never escape.
|
|
83
|
+
throw new Error(repairMessage ?? 'Broker controller Secret missing, invalid, or migration phase would downgrade');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import subscriptions from '../../application/deploy/subscriptions.js';
|
|
2
|
+
import rabbitmqDefinitions from '../messaging/rabbitmq/definitions.js';
|
|
3
|
+
|
|
4
|
+
export { brokerShovel } from '../messaging/rabbitmq/definitions.js';
|
|
5
|
+
|
|
6
|
+
/** Normalize an AMQP URL with an optional fallback or overriding identity. */
|
|
7
|
+
export function brokerUri(uri, { username, password, override = false } = {}) {
|
|
8
|
+
const parsed = new URL(uri);
|
|
9
|
+
if (username && (override || !parsed.username)) {
|
|
10
|
+
parsed.username = username;
|
|
11
|
+
parsed.password = password;
|
|
12
|
+
}
|
|
13
|
+
return parsed.toString().replace(/\/$/u, '');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Resolve a declared service or a broker NodePort on the host of another service. */
|
|
17
|
+
export function brokerEndpoint(document, node, { service, fallbackService, fallbackPort, identity } = {}) {
|
|
18
|
+
const services = document.servers?.find(({ id }) => { return id === node; })?.api || [];
|
|
19
|
+
const direct = services.find(({ id }) => { return id === service; })?.url;
|
|
20
|
+
if (direct) { return identity ? brokerUri(direct, identity) : direct; }
|
|
21
|
+
const fallback = services.find(({ id }) => { return id === fallbackService; })?.url;
|
|
22
|
+
if (!fallback || !fallbackPort) { throw new TypeError(`Missing broker endpoint for ${node}`); }
|
|
23
|
+
const uri = `amqp://${new URL(fallback).hostname}:${fallbackPort}`;
|
|
24
|
+
return identity ? brokerUri(uri, identity) : uri;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Merge federation resources and restrict bindings to keys published at this node. */
|
|
28
|
+
export function attachBrokerMesh(document, node, topology, { peers, endpoint, federation, restrict }) {
|
|
29
|
+
const present = new Set((document.servers || []).map(({ id }) => { return id; }));
|
|
30
|
+
if (!peers.includes(node) || !present.has(node)) { return topology; }
|
|
31
|
+
const endpoints = Object.fromEntries(peers.filter((id) => { return present.has(id); }).flatMap((id) => {
|
|
32
|
+
try { return [[id, endpoint(document, id)]]; } catch { return []; }
|
|
33
|
+
}));
|
|
34
|
+
const extra = federation(node, endpoints);
|
|
35
|
+
for (const kind of ['parameters', 'policies', 'bindings']) {
|
|
36
|
+
topology[kind] = [...topology[kind] || [], ...extra[kind] || []];
|
|
37
|
+
}
|
|
38
|
+
for (const kind of ['queues', 'exchanges']) {
|
|
39
|
+
const names = new Set((topology[kind] || []).map(({ name }) => { return name; }));
|
|
40
|
+
topology[kind] = [...topology[kind] || [], ...(extra[kind] || []).filter(({ name }) => { return !names.has(name); })];
|
|
41
|
+
}
|
|
42
|
+
if (restrict) {
|
|
43
|
+
topology.bindings = topology.bindings.map((row) => {
|
|
44
|
+
if (row.destination !== restrict.queue || !Object.hasOwn(restrict.keys, row.routing_key)) { return row; }
|
|
45
|
+
return { ...row, routing_key: restrict.keys[row.routing_key] };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return topology;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Publishers on an API and physical inputs local to the broker. */
|
|
52
|
+
export function brokerStreamRoutes(source, { service, passive, local }) {
|
|
53
|
+
const publishers = source.api.find(({ id }) => { return id === service; })?.publishes || [];
|
|
54
|
+
return [...publishers.map(passive), ...source.fan_in.filter(({ from }) => { return from.includes('://'); }).map(local)];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Use a family wildcard when every declared route in that family is subscribed. */
|
|
58
|
+
export function brokerStreamBindings(routes, subscribed) {
|
|
59
|
+
const families = new Map();
|
|
60
|
+
routes.forEach((row) => {
|
|
61
|
+
if (!row.family) { return; }
|
|
62
|
+
if (!families.has(row.family)) { families.set(row.family, []); }
|
|
63
|
+
families.get(row.family).push(row);
|
|
64
|
+
});
|
|
65
|
+
return [...new Set([...families].flatMap(([family, rows]) => {
|
|
66
|
+
const selected = rows.filter(({ name }) => { return subscribed.has(name); });
|
|
67
|
+
return selected.length === rows.length ? [`${family}.#`] : selected.flatMap(({ keys }) => { return keys; });
|
|
68
|
+
}))];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Effective physical inputs and subscriptions when one broker also hosts a peer's inputs. */
|
|
72
|
+
export function brokerStreams(document, source, { service, additionalSource }) {
|
|
73
|
+
const additional = additionalSource && document.servers.find(({ id }) => { return id === additionalSource; });
|
|
74
|
+
const host = additional ? { ...source, fan_in: [...source.fan_in,
|
|
75
|
+
...additional.fan_in.filter(({ from }) => { return from.includes('://'); })] } : source;
|
|
76
|
+
const links = [...subscriptions(document, source.id), ...(additional ? subscriptions(document, additional.id) : [])]
|
|
77
|
+
.filter(({ api }) => { return !api || api === service; });
|
|
78
|
+
return {
|
|
79
|
+
host,
|
|
80
|
+
subscriptionsTo(to) {
|
|
81
|
+
return new Set(links.filter((row) => { return row.to === to; }).map(({ name }) => { return name; }));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** One outbox per route group selected by the downstream subscription. */
|
|
87
|
+
export function brokerPeerOutboxes(peer, routes, subscribed, outbox) {
|
|
88
|
+
const rows = routes.filter(({ peer: group, name }) => { return group && subscribed.has(name); });
|
|
89
|
+
return [...new Set(rows.map(({ peer: group }) => { return group; }))].map((group) => {
|
|
90
|
+
const selected = rows.filter((row) => { return row.peer === group; });
|
|
91
|
+
return { ...outbox(group, peer), keys: [...new Set(selected.flatMap(({ keys }) => { return keys; }))] };
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Durable forwarders to a declared endpoint, skipping families with no subscribed keys. */
|
|
96
|
+
export function brokerOutboxes(families, { sourceUri, destinationUri, reconnectDelay, exchange, destination }) {
|
|
97
|
+
return families.filter(({ keys }) => { return keys.length; }).map(({ family, keys }) => {
|
|
98
|
+
const name = exchange(family);
|
|
99
|
+
return { exchange: name, queue: `${name}.outbox`, keys,
|
|
100
|
+
shovel: { name: `${family.replaceAll('_', '-')}-to-${destination}`, sourceUri, destinationUri,
|
|
101
|
+
destinationExchange: name, reconnectDelay } };
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Add durable queues, typed bindings, and missing topic exchanges to a definition. */
|
|
106
|
+
export function appendBrokerResources(result, { vhost = '/', exchanges = [], queues = [], bindings = [] }) {
|
|
107
|
+
const resources = rabbitmqDefinitions({ vhost, queues, exchanges });
|
|
108
|
+
const names = new Set(result.exchanges.filter((row) => { return row.vhost === vhost; }).map(({ name }) => { return name; }));
|
|
109
|
+
result.exchanges.push(...resources.exchanges.filter(({ name }) => { return !names.has(name); })
|
|
110
|
+
.map((row) => { return { ...row, arguments: {} }; }));
|
|
111
|
+
result.queues.push(...resources.queues);
|
|
112
|
+
result.bindings.push(...bindings.map(({ source, destination, key, type = 'queue' }) => {
|
|
113
|
+
return { source, vhost, destination, destination_type: type, routing_key: key, arguments: {} };
|
|
114
|
+
}));
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Declare topic exchanges and the queue bindings needed by a collector. */
|
|
119
|
+
export function brokerSinkOptions(broker, exchange) {
|
|
120
|
+
const bindings = broker.bindings.filter(({ source }) => { return source === exchange; });
|
|
121
|
+
const queues = new Set(bindings.map(({ destination }) => { return destination; }));
|
|
122
|
+
return { exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }],
|
|
123
|
+
queues: [...queues].map((name) => { return { name, options: { durable: true, autoDelete: false } }; }),
|
|
124
|
+
bindings: bindings.map(({ destination, source, routing_key: pattern }) => { return { queue: destination, exchange: source, pattern }; }) };
|
|
125
|
+
}
|
|
@@ -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,51 @@
|
|
|
1
|
+
import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
|
|
2
|
+
import centralTelemetryPolicy, { centralTelemetryVersion, normalizeCentralPolicy } from '../ingest/telemetry/centralPolicy.js';
|
|
3
|
+
|
|
4
|
+
const policyRuntime = { centralTelemetryPolicy, centralTelemetryVersion };
|
|
5
|
+
const metricsAdapters = new Set(['amqp-metrics', 'mqtt-metrics', 'amqp-pg-metrics', 'mqtt-pg-metrics', 'silent-streams']);
|
|
6
|
+
|
|
7
|
+
export function centralTelemetryValues(document) {
|
|
8
|
+
return normalizeCentralPolicy(document.centralTelemetry);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function centralTelemetryChartEnv(document, file, previous = []) {
|
|
12
|
+
const value = JSON.stringify(centralTelemetryValues(document));
|
|
13
|
+
return [...previous.filter(({ name }) => { return !['CENTRAL_TELEMETRY_POLICY', 'CENTRAL_TELEMETRY_DSL'].includes(name); }),
|
|
14
|
+
{ name: 'CENTRAL_TELEMETRY_POLICY', value }, { name: 'CENTRAL_TELEMETRY_DSL', value: file }];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function checkRuntime(policy, runtime) {
|
|
18
|
+
if (runtime.centralTelemetryVersion !== centralTelemetryVersion || typeof runtime.centralTelemetryPolicy !== 'function') {
|
|
19
|
+
throw new TypeError(`Matching central telemetry runtime version ${centralTelemetryVersion} is required`);
|
|
20
|
+
}
|
|
21
|
+
runtime.centralTelemetryPolicy(policy);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Resolve the declared archive policy before opening any telemetry consumers. */
|
|
25
|
+
export function centralTelemetryEnvironment(env, { file, runtime = policyRuntime } = {}) {
|
|
26
|
+
if (env.SINK_DB_PROFILE !== undefined && env.SINK_DB_PROFILE !== 'central') {
|
|
27
|
+
throw new TypeError('Central telemetry requires the central database profile');
|
|
28
|
+
}
|
|
29
|
+
const policy = centralTelemetryValues(readDeploymentDocument(env.CENTRAL_TELEMETRY_DSL ?? file));
|
|
30
|
+
const serialized = JSON.stringify(policy);
|
|
31
|
+
if (env.CENTRAL_TELEMETRY_POLICY && JSON.stringify(normalizeCentralPolicy(JSON.parse(env.CENTRAL_TELEMETRY_POLICY))) !== serialized) {
|
|
32
|
+
throw new TypeError('Environment telemetry policy disagrees with the DSL');
|
|
33
|
+
}
|
|
34
|
+
checkRuntime(policy, runtime);
|
|
35
|
+
return { ...env, SINK_DB_PROFILE: 'central', CENTRAL_TELEMETRY_POLICY: serialized };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Apply the archive's canonical admission policy to external ClickHouse telemetry writers. */
|
|
39
|
+
export function centralTelemetryTasks(tasks, document, runtime = policyRuntime) {
|
|
40
|
+
return tasks.map((task) => {
|
|
41
|
+
const { spec } = task;
|
|
42
|
+
if ((!spec.clickhouse && !spec.clickhouseUrl) || !metricsAdapters.has(spec.adapter)) { return task; }
|
|
43
|
+
const telemetryPolicy = centralTelemetryValues(document);
|
|
44
|
+
checkRuntime(telemetryPolicy, runtime);
|
|
45
|
+
if (spec.telemetryPolicy && JSON.stringify(normalizeCentralPolicy(spec.telemetryPolicy)) !== JSON.stringify(telemetryPolicy)) {
|
|
46
|
+
throw new TypeError('Collector telemetry policy disagrees with the DSL');
|
|
47
|
+
}
|
|
48
|
+
if (spec.table && spec.table !== 'scada.metrics') { throw new TypeError('Central telemetry executor requires the canonical metrics table'); }
|
|
49
|
+
return { ...task, spec: { ...spec, telemetryPolicy, telemetryAmqp: spec.telemetryAmqp ?? { $secret: 'AMQP_URL' }, table: 'scada.metrics' } };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { clickhouseHistoryComment as historyComment } from '../persistence/clickhouse/localHistory.js';
|
|
3
|
+
|
|
4
|
+
function schemaSql(settings) {
|
|
5
|
+
const { retentionDays, coordinatedRetention, ttlMergeSeconds } = settings;
|
|
6
|
+
const expiry = `TTL toDateTime(ts, 'UTC') + INTERVAL ${retentionDays} DAY DELETE`;
|
|
7
|
+
return `CREATE DATABASE IF NOT EXISTS scada;
|
|
8
|
+
CREATE TABLE IF NOT EXISTS scada.metrics (
|
|
9
|
+
topic LowCardinality(String),
|
|
10
|
+
ts DateTime64(6, 'UTC') CODEC(Delta, ZSTD(1)),
|
|
11
|
+
value Float64 CODEC(Gorilla, ZSTD(1))
|
|
12
|
+
) ENGINE=MergeTree
|
|
13
|
+
PARTITION BY toDate(ts)
|
|
14
|
+
ORDER BY (topic, ts)
|
|
15
|
+
${coordinatedRetention ? '' : expiry}
|
|
16
|
+
SETTINGS merge_with_ttl_timeout=${ttlMergeSeconds}, non_replicated_deduplication_window=10000;
|
|
17
|
+
${coordinatedRetention ? '' : `ALTER TABLE scada.metrics MODIFY ${expiry};`}
|
|
18
|
+
${coordinatedRetention ? `ALTER TABLE scada.metrics MODIFY COMMENT '${historyComment}';` : ''}
|
|
19
|
+
ALTER TABLE scada.metrics MODIFY SETTING merge_with_ttl_timeout=${ttlMergeSeconds}, non_replicated_deduplication_window=10000;
|
|
20
|
+
`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const migrateRetention = `set -eu
|
|
24
|
+
has_ttl=$(clickhouse-client --config-file=/schema/client.xml --query="SELECT position(create_table_query, 'TTL ') > 0 FROM system.tables WHERE database='scada' AND name='metrics' FORMAT TabSeparatedRaw")
|
|
25
|
+
case "$has_ttl" in
|
|
26
|
+
1) clickhouse-client --config-file=/schema/client.xml --query='ALTER TABLE scada.metrics REMOVE TTL' ;;
|
|
27
|
+
0) ;;
|
|
28
|
+
*) echo 'Cannot verify raw history TTL state' >&2; exit 1 ;;
|
|
29
|
+
esac
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
function serverConfig(settings) {
|
|
33
|
+
return `<clickhouse>
|
|
34
|
+
<max_server_memory_usage>${settings.memoryBytes}</max_server_memory_usage>
|
|
35
|
+
<mark_cache_size>268435456</mark_cache_size>
|
|
36
|
+
<uncompressed_cache_size>67108864</uncompressed_cache_size>
|
|
37
|
+
<logger><level>warning</level><console>1</console><size>10M</size><count>3</count></logger>
|
|
38
|
+
<query_log><ttl>event_date + INTERVAL 7 DAY DELETE</ttl></query_log>
|
|
39
|
+
<part_log><ttl>event_date + INTERVAL 7 DAY DELETE</ttl></part_log>
|
|
40
|
+
<metric_log remove="remove"/><asynchronous_metric_log remove="remove"/><query_thread_log remove="remove"/><trace_log remove="remove"/><text_log remove="remove"/><opentelemetry_span_log remove="remove"/><processors_profile_log remove="remove"/><query_views_log remove="remove"/><session_log remove="remove"/><zookeeper_log remove="remove"/><filesystem_cache_log remove="remove"/><asynchronous_insert_log remove="remove"/>
|
|
41
|
+
<storage_configuration><disks><default><keep_free_space_bytes>${settings.reserveBytes}</keep_free_space_bytes></default></disks></storage_configuration>
|
|
42
|
+
<prometheus><endpoint>/metrics</endpoint><port>9363</port><metrics>true</metrics><events>true</events><asynchronous_metrics>true</asynchronous_metrics></prometheus>
|
|
43
|
+
</clickhouse>`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const users = `<clickhouse><profiles><default><max_threads>2</max_threads><max_memory_usage>1073741824</max_memory_usage><max_bytes_before_external_group_by>268435456</max_bytes_before_external_group_by><max_bytes_before_external_sort>268435456</max_bytes_before_external_sort><date_time_input_format>best_effort</date_time_input_format></default></profiles></clickhouse>`;
|
|
47
|
+
|
|
48
|
+
/** Compiles local telemetry storage policy without embedding credentials in desired state. */
|
|
49
|
+
export default function clickhouseTelemetryPolicy(settings, label = 'ClickHouse telemetry') {
|
|
50
|
+
if (settings.backend !== 'clickhouse' || !settings.image || !settings.serverImage || !settings.secret) {
|
|
51
|
+
throw new Error(`${label} requires ClickHouse images and a credential secret`);
|
|
52
|
+
}
|
|
53
|
+
for (const field of ['retentionDays', 'ttlMergeSeconds', 'reserveBytes', 'memoryBytes', 'batchSize', 'prefetch', 'maxWaitMs']) {
|
|
54
|
+
if (!Number.isSafeInteger(settings[field]) || settings[field] <= 0) { throw new Error(`Invalid ${label.toLowerCase()} ${field}`); }
|
|
55
|
+
}
|
|
56
|
+
if (settings.batchSize > settings.prefetch || settings.retentionDays > 365 || settings.reserveBytes < 1073741824) {
|
|
57
|
+
throw new Error(`Invalid ${label.toLowerCase()} retention or buffer policy`);
|
|
58
|
+
}
|
|
59
|
+
const schema = schemaSql(settings);
|
|
60
|
+
const retentionMigration = settings.coordinatedRetention ? migrateRetention : '';
|
|
61
|
+
const config = serverConfig(settings);
|
|
62
|
+
const schemaJob = `edge-clickhouse-schema-${createHash('sha256').update(schema + retentionMigration).digest('hex').slice(0, 12)}`;
|
|
63
|
+
return { ...settings, schema, retentionMigration, config, users, schemaJob };
|
|
64
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { collectorDeployment, deploymentContext, retiredDeployments } from '../../application/deploy/deploymentPlan.js';
|
|
2
|
+
import { brokerClientEnvironment } from './brokerSecurity.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
import { brokerPolicy } from './securityPolicy.js';
|
|
5
|
+
|
|
6
|
+
function collectorApp(profile, server, policy) {
|
|
7
|
+
const app = profile.apps.scada;
|
|
8
|
+
const companion = profile[policy.companion];
|
|
9
|
+
const image = server.profile.variables?.[policy.imageVariable];
|
|
10
|
+
return { ...app, ...(companion && { [policy.companion]: companion }),
|
|
11
|
+
...(image && { collector: { ...app.collector, image } }) };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function compileCollectors(context, policy, ports) {
|
|
15
|
+
const { app, target, scada } = context;
|
|
16
|
+
const machines = scada.machines.filter(({ from }) => {
|
|
17
|
+
return !policy.excludedSources.some((prefix) => { return from.startsWith(prefix); });
|
|
18
|
+
});
|
|
19
|
+
const sources = ports.processes(machines, app);
|
|
20
|
+
const initial = sources[0];
|
|
21
|
+
const defaults = initial ? deploymentTemplate(policy.environment, target) : {};
|
|
22
|
+
const environment = Object.fromEntries(Object.entries(defaults).map(([key, value]) => {
|
|
23
|
+
return [key, Object.hasOwn(initial.env, key) ? initial.env[key] : value];
|
|
24
|
+
}));
|
|
25
|
+
const assignments = ports.assignments(context);
|
|
26
|
+
const { collector } = app;
|
|
27
|
+
const processes = collectorDeployment(sources, { image: collector?.image, resources: collector?.resources,
|
|
28
|
+
command: policy.command, hostSecurity: policy.hostSecurity, environment, assignments }).map((process) => {
|
|
29
|
+
return ports.control(process, context);
|
|
30
|
+
});
|
|
31
|
+
return { sources, processes };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function secureValues(rabbitmq, processes, broker, ports) {
|
|
35
|
+
if (!broker) { return rabbitmq; }
|
|
36
|
+
const secured = ports.brokerValues(rabbitmq, broker);
|
|
37
|
+
if (broker.phase !== 'prepare') {
|
|
38
|
+
const { AMQP_URL: amqp, MQTT_URL: mqtt } = brokerClientEnvironment(broker);
|
|
39
|
+
processes.forEach(({ env }) => { Object.assign(env, { AMQP_URL: amqp, MQTT_URL: mqtt }); });
|
|
40
|
+
}
|
|
41
|
+
return secured;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function chartPlan(context, policy, ports) {
|
|
45
|
+
const { app, cluster, scada, target, server, broker } = context;
|
|
46
|
+
const { namespace, ...settings } = target;
|
|
47
|
+
const { sources, processes } = compileCollectors(context, policy, ports);
|
|
48
|
+
const rabbitmq = secureValues({ ...scada.rabbitmq, extraConfig: { ...scada.rabbitmq.extraConfig, cluster_name: cluster },
|
|
49
|
+
definitions: ports.broker(context) }, processes, broker, ports);
|
|
50
|
+
const { values, extra } = ports.project({ ...context, values: { ...scada, ...settings, processes, rabbitmq } });
|
|
51
|
+
const adapters = sources.length ? ['collector', ...sources.map(({ adapter }) => { return adapter; })] : [];
|
|
52
|
+
const groups = adapters.map((adapter) => { return app[adapter]?.replaces || []; });
|
|
53
|
+
const nodeAddress = new URL(server.api.find(({ id }) => { return id === policy.address; }).url).hostname;
|
|
54
|
+
return { context: cluster, namespace, nodeAddress, release: cluster, chart: policy.chart, values,
|
|
55
|
+
retirements: retiredDeployments({ prefix: settings.prefix, groups, desired: processes, extra }) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Compile collector and transport requirements for a chart with caller-supplied source and application ports. */
|
|
59
|
+
export default function collectorChartPlan(cluster, document, security, policy, ports) {
|
|
60
|
+
if (!policy.targets.includes(cluster)) { throw new Error(policy.targetError); }
|
|
61
|
+
const broker = brokerPolicy(security);
|
|
62
|
+
const plant = document || ports.read();
|
|
63
|
+
const context = deploymentContext(plant, cluster);
|
|
64
|
+
const { target, profile, server } = context;
|
|
65
|
+
if (target.namespace !== policy.namespace || target.prefix !== policy.prefix) { throw new Error(policy.scopeError); }
|
|
66
|
+
const app = collectorApp(profile, server, policy);
|
|
67
|
+
return chartPlan({ ...context, app, broker, plant, cluster, security }, policy, ports);
|
|
68
|
+
}
|