@yarkivaev/scada 2.17.0 → 2.19.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 +14 -2
- package/package.json +5 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- 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/controlPlan.js +16 -0
- package/src/application/deploy/controlPlaneConfiguration.js +62 -0
- package/src/application/deploy/controlReaderSpecs.js +37 -0
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +79 -0
- package/src/application/deploy/liveReleaseOverlay.js +17 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/projectControlPlane.js +48 -0
- package/src/application/deploy/projectTopology.js +41 -0
- package/src/application/deploy/topologyGraph.js +81 -0
- package/src/application/edgeOperatorCatalog.js +9 -7
- package/src/application/mcp/analyticsMcpPort.js +20 -0
- package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
- package/src/application/mcp/analyticsTextContent.js +13 -0
- package/src/application/mcp/plantReadPorts.js +168 -0
- package/src/application/mcp/textContentCatalog.js +7 -0
- package/src/application/operationPrefixes.js +67 -0
- package/src/application/operatorCatalogView.js +8 -0
- package/src/application/projectPlantShops.js +17 -0
- package/src/application/runtime/collectorDslManifest.js +44 -0
- package/src/application/runtime/collectorLaunch.js +34 -0
- package/src/application/runtime/collectorOptions.js +21 -0
- package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
- package/src/application/runtime/embeddedCollectors.js +6 -0
- package/src/application/runtime/index.js +7 -1
- package/src/application/runtime/pagedDelivery.js +87 -0
- package/src/application/runtime/resolveSecrets.js +9 -0
- package/src/application/siteOperatorCatalog.js +8 -7
- package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
- package/src/application/siteRuntime/cutoverOperations.js +25 -0
- package/src/application/siteRuntime/databaseMigrations.js +27 -0
- package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
- package/src/application/siteRuntime/history.js +29 -0
- package/src/application/siteRuntime/index.js +16 -0
- package/src/application/siteRuntime/measurementTopic.js +9 -0
- package/src/application/siteRuntime/operationFederation.js +15 -0
- package/src/application/siteRuntime/operationSnapshot.js +18 -0
- package/src/application/siteRuntime/operatorField.js +49 -0
- package/src/application/siteRuntime/operatorUpdates.js +37 -0
- package/src/application/siteRuntime/telemetry.js +31 -0
- package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
- package/src/application/timelineMetrics.js +36 -0
- package/src/domain/timeline/cyclePhases.js +191 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
- package/src/infrastructure/deploy/brokerReplicaTopology.js +34 -12
- 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/centralTelemetry.js +51 -0
- package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
- package/src/infrastructure/deploy/collectorChartPlan.js +68 -0
- package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
- package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
- package/src/infrastructure/deploy/configuredClassification.js +74 -0
- package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
- package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
- package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
- package/src/infrastructure/deploy/configuredHistorySeed.js +54 -0
- package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -0
- package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -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/configuredBrokerReconciliation.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 +15 -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 +46 -2
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/projectClassification.js +42 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/securityPolicy.js +16 -0
- package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
- package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
- package/src/infrastructure/http/edge/attachClassify.js +30 -0
- package/src/infrastructure/http/edge/classifyProxy.js +72 -0
- package/src/infrastructure/http/edge/classifyRecord.js +32 -0
- package/src/infrastructure/http/edge/classifyRouting.js +14 -0
- package/src/infrastructure/http/edge/siteAccess.js +7 -0
- package/src/infrastructure/http/edge/writeGuard.js +84 -0
- package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
- package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
- package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
- package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
- package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
- package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +29 -8
- package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +5 -0
- package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
- package/src/infrastructure/opcua/projectSources.js +36 -0
- package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
- package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
- package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
- package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
- package/src/infrastructure/streams/boundedTextFrames.js +27 -0
- package/src/infrastructure/streams/framedSerialSource.js +25 -0
- package/src/infrastructure/streams/index.js +5 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/serialLine.js +26 -0
- package/src/infrastructure/streams/watchCurrentReading.js +31 -0
- package/src/infrastructure/streams/windowPublication.js +73 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { databaseEnvironment } from './databaseSecurity.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
|
|
5
|
+
function aliases(machine, policy) {
|
|
6
|
+
const pattern = new RegExp(policy.machinePattern, 'u');
|
|
7
|
+
const match = pattern.exec(machine);
|
|
8
|
+
if (!match) { return ''; }
|
|
9
|
+
const { number } = match.groups;
|
|
10
|
+
const rows = policy.topicRows.map((row) => { return deploymentTemplate(policy.machineAlias, { number, ...row }); }).join('\n');
|
|
11
|
+
return deploymentTemplate(policy.routeAlias, { machine, aliases: rows });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Resolve an app checkpoint to its declared local endpoint. */
|
|
15
|
+
export function configuredObservationUrl(policy) {
|
|
16
|
+
return function observation(node, home) {
|
|
17
|
+
if (node.startsWith(policy.homePrefix)) { return home; }
|
|
18
|
+
return policy.endpoints[node] ?? policy.fallback;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function supervisorConfig(policy, text, observationUrl) {
|
|
23
|
+
const clientPattern = new RegExp(policy.clientPattern, 'u');
|
|
24
|
+
return function render(cluster, authenticatedMqtt = false, machines = null, checkpointUrl = observationUrl(cluster, policy.checkpointUrl)) {
|
|
25
|
+
const selected = machines === null && cluster.startsWith(policy.homePrefix) ? policy.defaultMachines : (machines ?? []);
|
|
26
|
+
return deploymentTemplate(text(policy.config), {
|
|
27
|
+
client: cluster.replace(clientPattern, policy.clientPrefix), checkpointUrl,
|
|
28
|
+
authentication: authenticatedMqtt ? policy.authenticatedMqtt : '',
|
|
29
|
+
routing: selected.length ? selected.map((machine) => { return aliases(machine, policy); }).join('\n') : policy.emptyRouting,
|
|
30
|
+
tags: text(policy.tags), phases: text(policy.phases).trim(),
|
|
31
|
+
machines: selected.map((machine) => { return deploymentTemplate(policy.machine, { machine }); }).join(', ')
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Render concrete site environment, Kubernetes objects and supervisor file assets. */
|
|
37
|
+
export function configuredSiteAssets(settings, base, startupHistoryPolicy) {
|
|
38
|
+
function text(file) { return readFileSync(new URL(file, base), 'utf8'); }
|
|
39
|
+
const observationUrl = configuredObservationUrl(settings.observation);
|
|
40
|
+
return {
|
|
41
|
+
observationUrl,
|
|
42
|
+
supervisorConfig: supervisorConfig(settings.supervisor, text, observationUrl),
|
|
43
|
+
siteEnvironment(cluster, app, security) {
|
|
44
|
+
const repairHistoryOnStart = startupHistoryPolicy(app.ingest.stomp.repairHistoryOnStart);
|
|
45
|
+
const bindings = { app, number: cluster.at(-1), repairHistoryOnStart };
|
|
46
|
+
return databaseEnvironment(deploymentTemplate(settings.apiEnvironment, bindings), security, app.api.secret);
|
|
47
|
+
},
|
|
48
|
+
siteObjects(namespace, app) { return deploymentTemplate(settings.apiObjects, { namespace, app }, { text }); }
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import compileDeploymentHooks, { deploymentStage } from './compileDeploymentHooks.js';
|
|
3
|
+
import executeStagedDeployment from './executeStagedDeployment.js';
|
|
4
|
+
import stagedStoragePreflight from './stagedStoragePreflight.js';
|
|
5
|
+
import validateStagedDeploymentEvidence from './validateStagedDeploymentEvidence.js';
|
|
6
|
+
|
|
7
|
+
function registeredHooks(plan, policy, evidence, execute, ports) {
|
|
8
|
+
return compileDeploymentHooks(policy.hooks, { plan, evidence, execute, ports: {
|
|
9
|
+
reconcileBroker(ready, kube, { process, pruneShovels }) {
|
|
10
|
+
const { rabbitmq } = deploymentStage(plan, policy.storage.stage).values;
|
|
11
|
+
const input = { ...ready, brokerReconcileProcess: process, brokerPruneShovels: pruneShovels,
|
|
12
|
+
values: { ...ready.values, rabbitmq } };
|
|
13
|
+
ports.reconcile(input, kube, plan.brokerSecurity, execute);
|
|
14
|
+
}
|
|
15
|
+
} });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function operations(plan, policy, execute, operate) {
|
|
19
|
+
return Object.fromEntries(Object.entries(policy.operations ?? {}).map(([command, action]) => {
|
|
20
|
+
return [command, () => { return operate(plan.kiosk, action, execute); }];
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Execute isolation and evidence guards around a declared staged deployment. */
|
|
25
|
+
export default function configuredStagedDeployment(policy, ports) {
|
|
26
|
+
return function deploy(cluster, action = 'render', options = {}) {
|
|
27
|
+
const { execute = execFileSync, evidence, document, security: input, now = Date.now(), backendOnly = false } = options;
|
|
28
|
+
if (backendOnly && action.startsWith(policy.backendOnlyActionPrefix)) { throw new Error(policy.backendOnlyError); }
|
|
29
|
+
const plan = ports.plan(cluster, document, input);
|
|
30
|
+
return executeStagedDeployment({
|
|
31
|
+
plan, action,
|
|
32
|
+
disabledActions: plan.deploymentEnabled ? [] : policy.disabledActions,
|
|
33
|
+
omitStages: backendOnly ? policy.backendOnlyOmit : [],
|
|
34
|
+
actions: operations(plan, policy, execute, ports.operate),
|
|
35
|
+
prepare(mode) {
|
|
36
|
+
const security = ports.security(mode, cluster, execute, input);
|
|
37
|
+
const prepared = ports.plan(cluster, document, security);
|
|
38
|
+
return mode === 'render' ? ports.publicOutput(prepared) : prepared;
|
|
39
|
+
},
|
|
40
|
+
validateMutation(current) { validateStagedDeploymentEvidence(current, policy.evidence, evidence, now); },
|
|
41
|
+
preflight(current, mode, mutate) {
|
|
42
|
+
stagedStoragePreflight(current, policy.storage, { evidence: mutate ? evidence : null, execute, action: mode });
|
|
43
|
+
},
|
|
44
|
+
stageHooks(current) { return registeredHooks(current, policy, evidence, execute, ports); },
|
|
45
|
+
afterApply: backendOnly ? undefined : (current) => { return ports.operate(current.kiosk, policy.afterApply, execute); }
|
|
46
|
+
}, execute);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
function secretName(value) {
|
|
2
|
+
return typeof value === 'string' && value.length <= 253 && !/[^a-z0-9.-]/u.test(value)
|
|
3
|
+
&& value.split('.').every((label) => { return label.length <= 63 && /^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/u.test(label); });
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Only public Secret references belong in database deployment policy. */
|
|
7
|
+
export function databaseSecurity(security) {
|
|
8
|
+
const database = security?.database;
|
|
9
|
+
if (database === undefined) { return undefined; }
|
|
10
|
+
if (!database || typeof database !== 'object' || Array.isArray(database)
|
|
11
|
+
|| Object.keys(database).some((key) => { return !['migrationsMode','runtimeSecret','runtimeKey'].includes(key); })
|
|
12
|
+
|| database.migrationsMode !== 'verify'
|
|
13
|
+
|| !secretName(database.runtimeSecret)) { throw new TypeError('Database security requires verify mode and a named runtime Secret'); }
|
|
14
|
+
const runtimeKey = database.runtimeKey === undefined ? 'url' : database.runtimeKey;
|
|
15
|
+
if (typeof runtimeKey !== 'string' || !runtimeKey || runtimeKey.length > 253 || /[^-._a-zA-Z0-9]/u.test(runtimeKey)
|
|
16
|
+
|| ['postgres_admin_url','adminurl'].includes(runtimeKey.toLowerCase())) { throw new TypeError('Database runtime key must name a restricted connection URL'); }
|
|
17
|
+
return {migrationsMode:database.migrationsMode,runtimeSecret:database.runtimeSecret,runtimeKey};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function databaseEnvironment(environment, security, apiSecret) {
|
|
21
|
+
const database = databaseSecurity(security);
|
|
22
|
+
if (!database) { return environment; }
|
|
23
|
+
if (database.runtimeSecret === apiSecret && database.runtimeKey !== 'POSTGRES_URL') {
|
|
24
|
+
throw new TypeError('Database runtime reference in the application Secret must use POSTGRES_URL');
|
|
25
|
+
}
|
|
26
|
+
const result = {...environment,SUPERVISOR_MIGRATIONS:'verify',POSTGRES_URL:{valueFrom:{secretKeyRef:{
|
|
27
|
+
name:database.runtimeSecret,key:database.runtimeKey}}}};
|
|
28
|
+
delete result.POSTGRES_ADMIN_URL;
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function databaseValues(postgres, security) {
|
|
33
|
+
const database = databaseSecurity(security);
|
|
34
|
+
if (!database) { return postgres; }
|
|
35
|
+
if (database.runtimeSecret === postgres.secret || database.runtimeKey !== 'url') {
|
|
36
|
+
throw new TypeError('Database chart runtime Secret must be distinct from bootstrap and use the url key');
|
|
37
|
+
}
|
|
38
|
+
return {...postgres,runtimeSecret:database.runtimeSecret,migrationsMode:'verify'};
|
|
39
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import bootstrapKubeStorage from './bootstrapKubeStorage.js';
|
|
3
|
+
import { deploymentStage } from './compileDeploymentHooks.js';
|
|
4
|
+
import { waitForJob } from './deploymentChecks.js';
|
|
5
|
+
import prepareKubePrerequisites from './prepareKubePrerequisites.js';
|
|
6
|
+
|
|
7
|
+
function prerequisiteObjects(plan, policy, objects, podCidrs) {
|
|
8
|
+
const storage = deploymentStage(plan, policy.storageStage).values;
|
|
9
|
+
const namespaces = policy.namespaces.map((name) => { return { apiVersion: 'v1', kind: 'Namespace', metadata: { name } }; });
|
|
10
|
+
const claims = Object.entries(policy.claims).map(([name, role]) => {
|
|
11
|
+
const { storageClass, storage: size } = storage[role];
|
|
12
|
+
return { apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata: { name, namespace: plan.namespace },
|
|
13
|
+
spec: { accessModes: ['ReadWriteOnce'], storageClassName: storageClass, resources: { requests: { storage: size } } } };
|
|
14
|
+
});
|
|
15
|
+
return [...namespaces, ...objects(podCidrs), ...claims];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function preparePlan(plan, policy, objects, action, { execute, secrets }) {
|
|
19
|
+
return prepareKubePrerequisites({
|
|
20
|
+
context: plan.context, enabled: plan.deploymentEnabled, nodeAddress: plan.nodeAddress,
|
|
21
|
+
requirePodCidrs: policy.requirePodCidrs, namespaces: policy.namespaces, credentials: policy.credentials,
|
|
22
|
+
objects(podCidrs) { return prerequisiteObjects(plan, policy, objects, podCidrs); }
|
|
23
|
+
}, action, { execute, secrets });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function bootstrap(plan, policy, objects, action, execute) {
|
|
27
|
+
if (!plan.deploymentEnabled) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
|
|
28
|
+
const { missing } = preparePlan(plan, policy, objects, 'check', { execute });
|
|
29
|
+
if (missing.length) { throw new Error(`Prepare prerequisites first: ${missing.join(', ')}`); }
|
|
30
|
+
const stage = { ...deploymentStage(plan, policy.storageStage) };
|
|
31
|
+
if (policy.job) { stage.afterReady = (_ready, kube) => { waitForJob(kube, plan.prerequisites[policy.job]); }; }
|
|
32
|
+
return bootstrapKubeStorage({ context: plan.context, namespace: plan.namespace, storage: policy.workloads, stage }, action, execute);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Prepare prerequisites and stage durable storage without starting application readers. */
|
|
36
|
+
export default function deploymentRecovery({ policy, planFor, objects }) {
|
|
37
|
+
return {
|
|
38
|
+
prerequisites(target, document, podCidrs = []) {
|
|
39
|
+
return prerequisiteObjects(planFor(target, document), policy, objects, podCidrs);
|
|
40
|
+
},
|
|
41
|
+
prepare(target, action = 'check', { execute, secrets, document } = {}) {
|
|
42
|
+
return preparePlan(planFor(target, document), policy, objects, action, { execute, secrets });
|
|
43
|
+
},
|
|
44
|
+
bootstrap(target, action = 'check', { execute = execFileSync, document } = {}) {
|
|
45
|
+
if (!['check', 'apply'].includes(action)) { throw new TypeError('Storage bootstrap action must be check or apply'); }
|
|
46
|
+
return bootstrap(planFor(target, document), policy, objects, action, execute);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
function reference(bindings, path, optional = false) {
|
|
2
|
+
if (typeof path !== 'string' || !path.length) { throw new TypeError('Invalid template reference'); }
|
|
3
|
+
let value = bindings;
|
|
4
|
+
for (const key of path.split('.')) {
|
|
5
|
+
if (value === null || value === undefined || !Object.hasOwn(value, key)) {
|
|
6
|
+
if (optional) { return undefined; }
|
|
7
|
+
throw new TypeError(`Unknown template reference ${path}`);
|
|
8
|
+
}
|
|
9
|
+
value = value[key];
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function interpolate(source, bindings) {
|
|
15
|
+
return source.replace(/\{\{(?<path>[\w.-]+)\}\}/gu, (_match, path) => {
|
|
16
|
+
const value = reference(bindings, path);
|
|
17
|
+
if (!['string', 'number', 'boolean'].includes(typeof value)) { throw new TypeError(`Template reference ${path} must be scalar`); }
|
|
18
|
+
return String(value);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function directives(bindings, text, render) {
|
|
23
|
+
return {
|
|
24
|
+
$ref(path) { return reference(bindings, path); },
|
|
25
|
+
$string(value) { return String(render(value)); },
|
|
26
|
+
$json(value) { return JSON.stringify(render(value)); },
|
|
27
|
+
$text(value) {
|
|
28
|
+
if (!text) { throw new TypeError('Deployment template requires an asset reader'); }
|
|
29
|
+
return text(render(value));
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Resolve typed references and text placeholders using explicitly supplied bindings. */
|
|
35
|
+
export default function deploymentTemplate(template, bindings, { text } = {}) {
|
|
36
|
+
function render(value) {
|
|
37
|
+
if (typeof value === 'string') { return interpolate(value, bindings); }
|
|
38
|
+
if (Array.isArray(value)) { return value.map(render); }
|
|
39
|
+
if (value === null || typeof value !== 'object') { return value; }
|
|
40
|
+
const entries = Object.entries(value);
|
|
41
|
+
const [key, parameter] = entries[0] ?? [];
|
|
42
|
+
const operations = directives(bindings, text, render);
|
|
43
|
+
if (entries.length === 1 && Object.hasOwn(operations, key)) { return operations[key](parameter); }
|
|
44
|
+
return Object.fromEntries(entries.map(([name, item]) => { return [name, render(item)]; }));
|
|
45
|
+
}
|
|
46
|
+
return render(template);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Check whether a binding enables a declarative deployment item. */
|
|
50
|
+
export function deploymentCondition(path, bindings) {
|
|
51
|
+
return Boolean(reference(bindings, path, true));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function expandReferences(entry, bindings) {
|
|
55
|
+
if (typeof entry === 'string') { return [deploymentTemplate(entry, bindings)]; }
|
|
56
|
+
if (entry.when && !deploymentCondition(entry.when, bindings)) { return []; }
|
|
57
|
+
const rows = entry.each === undefined ? [bindings] : reference(bindings, entry.each).map((item) => { return { ...bindings, item }; });
|
|
58
|
+
const resources = rows.flatMap((row) => {
|
|
59
|
+
return entry.group ? entry.group.flatMap((child) => { return expandReferences(child, row); }) : deploymentTemplate(entry.resources, row);
|
|
60
|
+
});
|
|
61
|
+
return entry.unique ? [...new Set(resources)] : resources;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Expand required and conditionally enabled resource references in declared order. */
|
|
65
|
+
export function deploymentReferences(entries, bindings) {
|
|
66
|
+
return entries.flatMap((entry) => { return expandReferences(entry, bindings); });
|
|
67
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { waitForJob } from './deploymentChecks.js';
|
|
3
|
+
import { preserveKubeRestart } from './deploymentKube.js';
|
|
4
|
+
import deploymentTemplate, { deploymentCondition, deploymentReferences } from './deploymentTemplate.js';
|
|
5
|
+
import executeChartDeployment from './executeChartDeployment.js';
|
|
6
|
+
import { requireReleaseAction } from './executeRelease.js';
|
|
7
|
+
|
|
8
|
+
function writeValue(values, path, update) {
|
|
9
|
+
const parts = path.split('.');
|
|
10
|
+
const key = parts.pop();
|
|
11
|
+
const target = parts.reduce((current, part) => {
|
|
12
|
+
if (!current || !Object.hasOwn(current, part)) { throw new TypeError(`Unknown deployment value ${path}`); }
|
|
13
|
+
return current[part];
|
|
14
|
+
}, values);
|
|
15
|
+
if (['__proto__', 'constructor', 'prototype'].includes(key)) { throw new TypeError(`Invalid deployment value ${path}`); }
|
|
16
|
+
update(target, key);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function preserveRestarts(plan, declarations, kube) {
|
|
20
|
+
for (const { when, workload, annotations } of declarations ?? []) {
|
|
21
|
+
if (!when || deploymentCondition(when, plan)) {
|
|
22
|
+
writeValue(plan, annotations, (row, key) => { row[key] = preserveKubeRestart(kube, workload, row[key]); });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function overrideValues(values, settings) {
|
|
28
|
+
for (const [path, value] of Object.entries(settings.set ?? {})) {
|
|
29
|
+
writeValue(values, path, (row, key) => { row[key] = deploymentTemplate(value, { values }); });
|
|
30
|
+
}
|
|
31
|
+
for (const path of settings.remove ?? []) {
|
|
32
|
+
writeValue(values, path, (row, key) => { delete row[key]; });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function release(plan, policy, settings, { bindings, afterReady }) {
|
|
37
|
+
overrideValues(plan.values, settings);
|
|
38
|
+
const current = { ...bindings, ...plan };
|
|
39
|
+
return { fieldManager: policy.fieldManager, ...(settings.retirements && { retirements: settings.retirements }),
|
|
40
|
+
prerequisites: deploymentReferences(policy.prerequisites, current),
|
|
41
|
+
workloads: deploymentReferences(policy.workloads, current),
|
|
42
|
+
afterReady: policy.afterReady && deploymentCondition(policy.afterReady.when, current) ? (ready, kube) => {
|
|
43
|
+
const { job } = policy.afterReady;
|
|
44
|
+
if (job && (!job.when || deploymentCondition(job.when, ready))) {
|
|
45
|
+
waitForJob(kube, deploymentTemplate(job.target, ready), job.timeout);
|
|
46
|
+
}
|
|
47
|
+
afterReady?.(ready, kube);
|
|
48
|
+
} : undefined };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Apply configured chart actions with scoped runtime ports and declarative release gates. */
|
|
52
|
+
export default function executeConfiguredChartDeployment(policy, action, { create, chartRoot, preflight, afterReady, execute = execFileSync }) {
|
|
53
|
+
const overrides = policy.actionOverrides;
|
|
54
|
+
const settings = overrides && Object.hasOwn(overrides, action) ? overrides[action] : {};
|
|
55
|
+
const mode = settings.action ?? action;
|
|
56
|
+
try { requireReleaseAction(mode); } catch (error) { throw new Error(policy.actionError ?? error.message); }
|
|
57
|
+
const { plan, bindings } = create();
|
|
58
|
+
return executeChartDeployment({ plan, action: mode, chartRoot,
|
|
59
|
+
preflight(current, kube) {
|
|
60
|
+
preserveRestarts(current, policy.preserveRestarts, kube);
|
|
61
|
+
preflight?.(current, kube);
|
|
62
|
+
},
|
|
63
|
+
release(current) { return release(current, policy, settings, { bindings, afterReady }); }
|
|
64
|
+
}, execute);
|
|
65
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import applyHelmResources from './applyHelmResources.js';
|
|
4
|
+
import { waitForJob } from './deploymentChecks.js';
|
|
5
|
+
import { deploymentKube } from './deploymentKube.js';
|
|
6
|
+
import { deploymentCondition, deploymentReferences } from './deploymentTemplate.js';
|
|
7
|
+
import executeRelease from './executeRelease.js';
|
|
8
|
+
|
|
9
|
+
const releaseActions = ['render', 'check', 'diff', 'apply'];
|
|
10
|
+
|
|
11
|
+
function applyPlatform(plan, policy, ports, kube, execute) {
|
|
12
|
+
applyHelmResources({ ...plan, fieldManager: policy.fieldManager, values: { ...plan.values, ...policy.values } }, {
|
|
13
|
+
kinds: policy.kinds, decode: ports.decode, encode: ports.encode
|
|
14
|
+
}, execute);
|
|
15
|
+
return `${JSON.stringify(ports.bootstrap(plan, kube))}\n`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function applyRelease(plan, policy, action, ports, { kube, execute }) {
|
|
19
|
+
const release = { ...plan, prerequisites: deploymentReferences(policy.release.prerequisites, plan),
|
|
20
|
+
workloads: deploymentReferences(policy.release.workloads, plan),
|
|
21
|
+
beforeApply() { ports.beforeApply?.(plan, kube); },
|
|
22
|
+
afterReady() {
|
|
23
|
+
const { job } = policy.release;
|
|
24
|
+
if (job && (!job.when || deploymentCondition(job.when, plan))) {
|
|
25
|
+
waitForJob(kube, job.target, job.timeout);
|
|
26
|
+
}
|
|
27
|
+
} };
|
|
28
|
+
const output = executeRelease(release, action, execute);
|
|
29
|
+
return action === 'apply' && policy.afterApply ? ports.operate(policy.afterApply, plan, kube) : output;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Execute application releases, platform bootstrap, and explicitly registered operations. */
|
|
33
|
+
export default function executeManagedDeployment(planFor, policy, action, { chartRoot, execute = execFileSync, device, ...ports }) {
|
|
34
|
+
const operations = policy.operations ?? {};
|
|
35
|
+
const platform = policy.platform && action === policy.platform.action;
|
|
36
|
+
if (!releaseActions.includes(action) && !platform && !Object.hasOwn(operations, action)) {
|
|
37
|
+
throw new Error(policy.actionError ?? 'Unknown deployment action');
|
|
38
|
+
}
|
|
39
|
+
const selected = planFor();
|
|
40
|
+
const plan = { ...selected, chart: path.resolve(chartRoot, selected.chart) };
|
|
41
|
+
const target = deploymentKube(plan, execute, { stdio: ['pipe', 'pipe', 'inherit'] });
|
|
42
|
+
function kube(args, input) { return String(target(args, input)); }
|
|
43
|
+
if (platform) { return applyPlatform(plan, policy.platform, ports, kube, execute); }
|
|
44
|
+
if (Object.hasOwn(operations, action)) { return ports.operate(operations[action], plan, kube, device); }
|
|
45
|
+
return applyRelease(plan, policy, action, ports, { kube, execute });
|
|
46
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { federationOwnership } from './classifyFederation.js';
|
|
2
|
+
|
|
3
|
+
/** Limit topology pruning to definitions owned by the specified deployment. */
|
|
4
|
+
export function brokerOwnership(desired, rules, pruneShovels = []) {
|
|
5
|
+
const { sourcePrefix, outboxPattern, shovelSuffix } = rules.brokerPruning;
|
|
6
|
+
const outboxes = new RegExp(outboxPattern, 'u');
|
|
7
|
+
const queues = new Set(desired.queues.map(({ name }) => { return name; }));
|
|
8
|
+
return {
|
|
9
|
+
...federationOwnership(rules),
|
|
10
|
+
ownsBinding(row) {
|
|
11
|
+
return row.destination_type === 'queue' && row.source.startsWith(sourcePrefix)
|
|
12
|
+
&& (queues.has(row.destination) || outboxes.test(row.destination));
|
|
13
|
+
},
|
|
14
|
+
ownsShovel(row) {
|
|
15
|
+
return (row.name.endsWith(shovelSuffix) || pruneShovels.includes(row.name))
|
|
16
|
+
&& String(row.value['src-queue']).startsWith(sourcePrefix);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reconciles collector assignments from a mounted catalog.
|
|
3
|
+
*
|
|
4
|
+
* The controller identity can write assignments and the leader key, not the
|
|
5
|
+
* catalog key. The desired catalog is therefore a file, and collector tasks
|
|
6
|
+
* stay separate from classification.
|
|
7
|
+
*
|
|
8
|
+
* {{{
|
|
9
|
+
* withCatalog(store, { version: 'v', nodes: [], tasks: [] })
|
|
10
|
+
* }}}
|
|
11
|
+
*/
|
|
12
|
+
import fs, { existsSync, realpathSync } from 'node:fs';
|
|
13
|
+
import { pathToFileURL } from 'node:url';
|
|
14
|
+
import { clientFromEnv } from '../../../application/control/controlClient.js';
|
|
15
|
+
import controller from '../../../application/control/controller.js';
|
|
16
|
+
import controlStore from '../../../application/control/controlStore.js';
|
|
17
|
+
import { visible } from './classifyGate.js';
|
|
18
|
+
import { openClassify } from './classifyLoop.js';
|
|
19
|
+
import { classifierFederation, federationOwnership } from './classifyFederation.js';
|
|
20
|
+
import { reconcileRabbitmqFederation } from '../../messaging/rabbitmq/reconcile.js';
|
|
21
|
+
import { applyShovels } from './classifyShovels.js';
|
|
22
|
+
|
|
23
|
+
/** Collector tasks only. A classification adapter must not reach a collector. */
|
|
24
|
+
export function readable(catalog, managedAdapter = 'supervisor-classify') {
|
|
25
|
+
const tasks = catalog.tasks.filter((task) => { return task.spec?.adapter !== managedAdapter; });
|
|
26
|
+
return { ...catalog, tasks };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Read path that substitutes the mounted catalog for the stored one. */
|
|
30
|
+
export function withCatalog(store, catalog, managedAdapter) {
|
|
31
|
+
const selected = readable(catalog, managedAdapter);
|
|
32
|
+
return { ...store, async read() { const view = await store.read(); return visible({ ...view, catalog: selected }); } };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function brokerFederation(record, rules) {
|
|
36
|
+
const base = process.env.RABBITMQ_MANAGEMENT;
|
|
37
|
+
if (!base || !rules.mesh) { return; }
|
|
38
|
+
const endpoints = JSON.parse(process.env.CONTROL_BROKER_ENDPOINTS || '{}');
|
|
39
|
+
const options = { base, username: process.env.RABBITMQ_USERNAME || 'guest',
|
|
40
|
+
password: process.env.RABBITMQ_PASSWORD || 'guest', vhost: '/' };
|
|
41
|
+
await reconcileRabbitmqFederation(classifierFederation(process.env.CONTROL_NODE_ID, endpoints, rules), { ...options, ...federationOwnership(rules) });
|
|
42
|
+
await applyShovels(record, endpoints, { ...options, nodeId: process.env.CONTROL_NODE_ID,
|
|
43
|
+
central: process.env.CONTROL_CENTRAL_BUS || 'amqp://central.invalid' }, rules);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function start() {
|
|
47
|
+
if (!process.env.CONTROL_NODE_ID || !process.env.CONTROL_CATALOG_FILE) { throw new Error('Catalog reconciler requires a node id and catalog file'); }
|
|
48
|
+
const catalog = JSON.parse(fs.readFileSync(process.env.CONTROL_CATALOG_FILE, 'utf8'));
|
|
49
|
+
const rules = process.env.CONTROL_CLASSIFY_RULES && JSON.parse(fs.readFileSync(process.env.CONTROL_CLASSIFY_RULES, 'utf8'));
|
|
50
|
+
const call = clientFromEnv(process.env);
|
|
51
|
+
const raw = controlStore(call, process.env.CONTROL_PREFIX);
|
|
52
|
+
const host = controller(withCatalog(raw, catalog, rules?.managedAdapter), process.env.CONTROL_NODE_ID, { clockSkewMs: Number(process.env.CONTROL_CLOCK_SKEW_MS ?? 5000), replacementDelayMs: Number(process.env.CONTROL_REPLACEMENT_DELAY_MS ?? 30000), onError(error) { process.stderr.write(`catalog reconciler: ${error.name}\n`); } });
|
|
53
|
+
const gate = rules ? openClassify({ env: process.env, call, rules, read: () => { return raw.read(); },
|
|
54
|
+
prefix: process.env.CONTROL_PREFIX, namespace: process.env.CONTROL_CLASSIFY_APPLY === 'true' ? rules.namespace : undefined,
|
|
55
|
+
federate(record) { return brokerFederation(record, rules); } }) : { stop() { return undefined; } };
|
|
56
|
+
for (const signal of ['SIGTERM', 'SIGINT']) { process.once(signal, () => { void host.stop(); gate.stop(); }); }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (process.argv[1] && existsSync(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
60
|
+
try { start(); } catch (error) { process.stderr.write(`catalog reconciler: ${error.name}\n`); process.exitCode = 1; }
|
|
61
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
function upstream(peer, uri, mesh) {
|
|
2
|
+
return { vhost: '/', component: 'federation-upstream', name: `${mesh.upstreamPrefix}${peer}`,
|
|
3
|
+
value: { uri, 'ack-mode': 'on-confirm', 'max-hops': 1 } };
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
function policy(mesh) {
|
|
7
|
+
const pattern = mesh.meshExchange.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
8
|
+
return { vhost: '/', name: mesh.policy, pattern: `^${pattern}$`, 'apply-to': 'exchanges',
|
|
9
|
+
definition: { 'federation-upstream-set': 'all' }, priority: 0 };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function durable(name) {
|
|
13
|
+
return { vhost: '/', name, durable: true, 'auto_delete': false, arguments: {} };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function binding(source, destination, type, key) {
|
|
17
|
+
return { source, vhost: '/', destination, 'destination_type': type, 'routing_key': key, arguments: {} };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function bindings(nodeId, groups, keys, mesh) {
|
|
21
|
+
const local = new Set(groups.filter((group) => {
|
|
22
|
+
return (group.home ?? group.preference[0]) === nodeId || (mesh.originCopies ?? []).includes(nodeId);
|
|
23
|
+
}).flatMap((group) => { return group.keys ?? []; }));
|
|
24
|
+
return [
|
|
25
|
+
...[...local].map((key) => { return binding(mesh.exchange, mesh.meshExchange, 'exchange', key); }),
|
|
26
|
+
...keys.map((key) => { return binding(mesh.meshExchange, mesh.sharedQueue, 'queue', key); }),
|
|
27
|
+
...groups.flatMap((group) => {
|
|
28
|
+
return (group.keys ?? []).map((key) => { return binding(mesh.meshExchange, mesh.groupQueuePrefix + group.id, 'queue', key); });
|
|
29
|
+
}),
|
|
30
|
+
...keys.filter((key) => { return !local.has(key); }).map((key) => {
|
|
31
|
+
return binding(mesh.meshExchange, mesh.exchange, 'exchange', key);
|
|
32
|
+
})
|
|
33
|
+
];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Broker mesh for every declared group, with a local feed for remote keys. */
|
|
37
|
+
export function classifierFederation(nodeId, endpoints, { groups, mesh }) {
|
|
38
|
+
const peers = Object.keys(endpoints).filter((id) => { return id !== nodeId && endpoints[id]; });
|
|
39
|
+
const keys = [...new Set(groups.flatMap((group) => { return group.keys ?? []; }))];
|
|
40
|
+
return {
|
|
41
|
+
parameters: peers.map((peer) => { return upstream(peer, endpoints[peer], mesh); }),
|
|
42
|
+
policies: peers.length ? [policy(mesh)] : [],
|
|
43
|
+
exchanges: keys.length ? [{ ...durable(mesh.meshExchange), type: 'topic' }] : [],
|
|
44
|
+
queues: keys.length ? [durable(mesh.sharedQueue), ...groups.map((group) => {
|
|
45
|
+
return durable(mesh.groupQueuePrefix + group.id);
|
|
46
|
+
})] : [],
|
|
47
|
+
bindings: bindings(nodeId, groups, keys, mesh)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Limit pruning to the declared mesh's upstreams and policy. */
|
|
52
|
+
export function federationOwnership({ mesh }) {
|
|
53
|
+
return {
|
|
54
|
+
ownsUpstream(row) { return row.name.startsWith(mesh.upstreamPrefix); },
|
|
55
|
+
ownsPolicy(row) { return row.name === mesh.policy; }
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chooses the one node allowed to calculate and the local deployment steps.
|
|
3
|
+
*
|
|
4
|
+
* Store beats a surviving spool, and a spool beats any Ready supervisor. A
|
|
5
|
+
* missing report is a dead node. Failover changes the machine set on the
|
|
6
|
+
* already running writer, never the replica count. Failback waits until the
|
|
7
|
+
* restored home has live observations covering a real replicated segment.
|
|
8
|
+
*
|
|
9
|
+
* {{{
|
|
10
|
+
* decide({}, ['preferred', 'standby'], [], 0, { replacementDelayMs: 30, clockSkewMs: 5 })
|
|
11
|
+
* }}}
|
|
12
|
+
*/
|
|
13
|
+
import { restored } from './supervisorReplica.js';
|
|
14
|
+
|
|
15
|
+
/** True when a node report is recent enough to keep its calculator. */
|
|
16
|
+
export function alive(report, now, timing) {
|
|
17
|
+
const at = report?.receivedAt;
|
|
18
|
+
return Number.isFinite(at) && at <= now + timing.clockSkewMs && now - at <= timing.replacementDelayMs;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function capable(id, found, now, options) {
|
|
22
|
+
const mark = found.get(id);
|
|
23
|
+
if (!Number.isSafeInteger(mark?.observationMs) || !Number.isSafeInteger(mark?.segmentEndMs)) { return true; }
|
|
24
|
+
return restored(mark, now, options);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function handoff(desired, active, silent, ready, released) {
|
|
28
|
+
if (desired === active || silent) { return { active: silent ? desired : active, pending: null }; }
|
|
29
|
+
if (!ready) { return { active, pending: null }; }
|
|
30
|
+
return released ? { active: desired, pending: null } : { active, pending: desired };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function rankOf(id, stores, near) {
|
|
34
|
+
if (stores.includes(id)) { return 2; }
|
|
35
|
+
if (near.includes(id)) { return 1; }
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Next classifier record for one group. */
|
|
40
|
+
export function decide(record, preference, reports, now, options) {
|
|
41
|
+
const found = new Map(reports.map((row) => { return [row.nodeId, row]; }));
|
|
42
|
+
const stores = options.stores ?? [preference[0]];
|
|
43
|
+
const near = options.near ?? preference.slice(1, 2);
|
|
44
|
+
const ready = preference.filter((id) => { return alive(found.get(id), now, options); });
|
|
45
|
+
const ranked = [...ready].sort((left, right) => {
|
|
46
|
+
return rankOf(right, stores, near) - rankOf(left, stores, near) || preference.indexOf(left) - preference.indexOf(right);
|
|
47
|
+
});
|
|
48
|
+
const inside = preference.includes(record.active);
|
|
49
|
+
const desired = ranked.find((id) => { return capable(id, found, now, options); }) ?? ranked[0] ?? (inside ? record.active : undefined) ?? preference[0];
|
|
50
|
+
const active = inside ? record.active : preference[0];
|
|
51
|
+
const silent = !inside || !alive(found.get(record.active), now, options);
|
|
52
|
+
const released = Boolean(record.pending && options.ack?.pending === record.pending
|
|
53
|
+
&& Number(options.ack.revision) > Number(options.revision));
|
|
54
|
+
return handoff(desired, active, silent, capable(desired, found, now, options), released);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Run the active node, arm the incoming node, wait otherwise. */
|
|
58
|
+
export function permit(nodeId, record) {
|
|
59
|
+
if (record?.active === nodeId) { return 'run'; }
|
|
60
|
+
return record?.pending === nodeId ? 'arm' : 'wait';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Ordered local changes. The warm writer stays at one replica. */
|
|
64
|
+
export function steps(nodeId, local, record = {}) {
|
|
65
|
+
const role = permit(nodeId, record);
|
|
66
|
+
const lease = role === 'run' || role === 'arm' ? 'present' : 'absent';
|
|
67
|
+
return local.map((row) => { return { name: row.name, replicas: 1, lease }; });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function merge(deploys, name, group, owned) {
|
|
71
|
+
const current = deploys.get(name) ?? { name, replicas: 1, lease: 'absent', groups: '', role: 'standby' };
|
|
72
|
+
if (owned) {
|
|
73
|
+
current.lease = 'present';
|
|
74
|
+
current.role = 'leader';
|
|
75
|
+
current.groups = current.groups ? `${current.groups},${group}` : group;
|
|
76
|
+
}
|
|
77
|
+
deploys.set(name, current);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One step per Deployment: lease present if any owned group shares that writer. */
|
|
81
|
+
export function writers(nodeId, local, record = {}) {
|
|
82
|
+
const deploys = new Map();
|
|
83
|
+
Object.entries(local).forEach(([group, rows]) => {
|
|
84
|
+
const role = permit(nodeId, record[group]);
|
|
85
|
+
const owned = role === 'run' || role === 'arm';
|
|
86
|
+
rows.forEach((row) => { merge(deploys, row.name, group, owned); });
|
|
87
|
+
});
|
|
88
|
+
return [...deploys.values()];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Hide classifier keys from the collector scheduler. */
|
|
92
|
+
export function visible(view) {
|
|
93
|
+
const assignments = Object.fromEntries(Object.entries(view.assignments ?? {}).filter(([id]) => { return !id.startsWith('classify-'); }));
|
|
94
|
+
const revisions = Object.fromEntries(Object.entries(view.revisions ?? {}).filter(([key]) => { return !key.startsWith('assignments/classify-'); }));
|
|
95
|
+
return { ...view, assignments, revisions };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** True when the writer lease is held, the group is in env, and the rollout has finished. */
|
|
99
|
+
export function prepared(body, group) {
|
|
100
|
+
const env = body.spec?.template?.spec?.containers?.[0]?.env ?? [];
|
|
101
|
+
const lease = env.find((row) => { return row.name === 'SUPERVISOR_LEASE_URL' || row.name === 'SUPERVISOR_LEASE_URL_HELD'; });
|
|
102
|
+
const groups = env.find((row) => { return row.name === 'CLASSIFY_GROUP'; })?.value ?? '';
|
|
103
|
+
const want = body.spec?.replicas ?? 0;
|
|
104
|
+
return lease?.name === 'SUPERVISOR_LEASE_URL' && !env.some((row) => { return row.name === 'SUPERVISOR_LEASE_URL_HELD'; })
|
|
105
|
+
&& groups.split(',').includes(group) && body.status?.updatedReplicas === want;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Ready note from the node that is arming the group. */
|
|
109
|
+
export function groupAck(assignments, group, pending, revisions = {}) {
|
|
110
|
+
if (!pending) { return null; }
|
|
111
|
+
const id = `classify-ready~${pending}~${group}`;
|
|
112
|
+
const value = assignments[id];
|
|
113
|
+
return value ? { pending: value.pending, revision: revisions[`assignments/${id}`] } : null;
|
|
114
|
+
}
|