@yarkivaev/scada 2.8.0 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/package.json +4 -2
  2. package/src/application/management/loadText.js +37 -0
  3. package/src/application/management/management.js +17 -3
  4. package/src/application/management/networkLoad.js +80 -0
  5. package/src/application/management/terminalLabel.js +6 -0
  6. package/src/application/management/topology.js +36 -0
  7. package/src/application/management/topologyStatus.js +44 -0
  8. package/src/application/management/topologyText.js +28 -0
  9. package/src/bin/scada.js +25 -7
  10. package/src/infrastructure/management/controlLoad.js +33 -0
  11. package/src/infrastructure/management/inventory.js +34 -5
  12. package/src/infrastructure/management/kubernetes.js +35 -11
  13. package/src/infrastructure/management/observations.js +80 -0
  14. package/src/infrastructure/management/prometheusLoad.js +69 -0
  15. package/src/infrastructure/management/protocol.js +51 -5
  16. package/src/infrastructure/management/rabbitmqLoad.js +79 -0
  17. package/src/infrastructure/management/responseJson.js +13 -0
  18. package/stream-processing/dependencies/timeline-segmentation.jar +0 -0
  19. package/stream-processing/src/main/scala/scada/processing/core/Decision.scala +1 -11
  20. package/stream-processing/src/main/scala/scada/processing/core/MachineConfig.scala +1 -0
  21. package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +6 -16
  22. package/stream-processing/src/main/scala/scada/processing/core/Segments.scala +1 -0
  23. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/Checkpoint.scala +1 -0
  24. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +1 -0
  25. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/SupervisorSinkCheckpoint.scala +1 -0
  26. package/stream-processing/src/main/scala/scada/processing/infra/config/AppConfig.scala +2 -2
  27. package/stream-processing/src/main/scala/scada/processing/infra/config/ConfigLoad.scala +1 -0
  28. package/stream-processing/src/main/scala/scada/processing/infra/config/ConfigProfile.scala +0 -1
  29. package/stream-processing/src/main/scala/scada/processing/infra/mqtt/Mqtt.scala +1 -1
  30. package/stream-processing/src/main/scala/scada/processing/infra/state/CheckpointSegments.scala +1 -0
  31. package/stream-processing/src/main/scala/scada/processing/infra/state/SegmentStatePolicy.scala +1 -2
  32. package/stream-processing/src/main/scala/scada/processing/infra/state/Segments.scala +1 -0
  33. package/stream-processing/src/main/scala/scada/processing/infra/stomp/DecisionMessage.scala +2 -2
  34. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SegmentMessage.scala +2 -2
  35. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SegmentWirePolicy.scala +1 -2
  36. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SplitFamily.scala +2 -2
  37. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompMachineDecisions.scala +1 -1
  38. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompReadings.scala +1 -1
  39. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompSegments.scala +1 -0
  40. package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyHistory.scala +2 -1
  41. package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +1 -0
  42. package/stream-processing/src/main/scala/scada/processing/runtime/Close.scala +1 -1
  43. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryBus.scala +1 -0
  44. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +13 -61
  45. package/stream-processing/src/main/scala/scada/processing/runtime/PendingIsland.scala +2 -1
  46. package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala +2 -12
  47. package/stream-processing/src/main/scala/scada/processing/runtime/RuntimeProfile.scala +2 -1
  48. package/stream-processing/src/main/scala/scada/processing/runtime/Seeding.scala +2 -1
  49. package/stream-processing/timeline-segmentation.lock +2 -0
  50. package/stream-processing/src/main/scala/scada/processing/core/Condition.scala +0 -33
  51. package/stream-processing/src/main/scala/scada/processing/core/CyclePhases.scala +0 -65
  52. package/stream-processing/src/main/scala/scada/processing/core/Emission.scala +0 -19
  53. package/stream-processing/src/main/scala/scada/processing/core/Params.scala +0 -15
  54. package/stream-processing/src/main/scala/scada/processing/core/Reading.scala +0 -11
  55. package/stream-processing/src/main/scala/scada/processing/core/Segment.scala +0 -28
  56. package/stream-processing/src/main/scala/scada/processing/core/SegmentDef.scala +0 -14
  57. package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +0 -47
  58. package/stream-processing/src/main/scala/scada/processing/core/SplitFollow.scala +0 -50
  59. package/stream-processing/src/main/scala/scada/processing/core/SplitPieces.scala +0 -102
  60. package/stream-processing/src/main/scala/scada/processing/core/TagDef.scala +0 -12
  61. package/stream-processing/src/main/scala/scada/processing/core/TaggedSegment.scala +0 -19
  62. package/stream-processing/src/main/scala/scada/processing/core/Tagging.scala +0 -42
  63. package/stream-processing/src/main/scala/scada/processing/core/Timestamp.scala +0 -26
  64. package/stream-processing/src/main/scala/scada/processing/core/segmentation/Timeline.scala +0 -43
  65. package/stream-processing/vendor/gaps-and-islands/LICENSE +0 -21
  66. package/stream-processing/vendor/gaps-and-islands/UPSTREAM +0 -4
  67. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -40
  68. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -55
  69. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -127
  70. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -105
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.8.0",
3
+ "version": "2.9.1",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "test": "mocha --exit 'test/**/test*.js'",
34
34
  "test:deep": "mocha --exit 'test/domain/**/test*.js' 'test/infrastructure/ingest/**/test*.js'",
35
35
  "coverage": "c8 --all --src src npm test",
36
- "prepack": "sh stream-processing/resolve-worker.sh",
36
+ "prepack": "sh stream-processing/resolve-dependencies.sh",
37
37
  "lint": "eslint . && node scripts/check-eo-names.mjs",
38
38
  "lint:fix": "eslint . --fix",
39
39
  "lint:eo": "node scripts/check-eo-names.mjs"
@@ -70,6 +70,8 @@
70
70
  "stream-processing/vendor/",
71
71
  "stream-processing/dependencies/stream-worker.jar",
72
72
  "stream-processing/stream-worker.lock",
73
+ "stream-processing/dependencies/timeline-segmentation.jar",
74
+ "stream-processing/timeline-segmentation.lock",
73
75
  "src/"
74
76
  ]
75
77
  }
@@ -0,0 +1,37 @@
1
+ /** Render queue pressure by broker and site, followed by optional site metrics. */
2
+ import terminalLabel from './terminalLabel.js';
3
+
4
+ function sum(queues, field) {
5
+ if (queues.some((queue) => { return queue[field] === undefined; })) {
6
+ return undefined;
7
+ }
8
+ return queues.reduce((total, queue) => { return total + queue[field]; }, 0);
9
+ }
10
+
11
+ function queueText({ name, ready, unacked, consumers, bytes, publishRate, ackRate }) {
12
+ return ` ${terminalLabel(name)}\tready=${ready ?? '?'}\tunacked=${unacked ?? '?'}\tconsumers=${consumers ?? '?'}` +
13
+ `\tbytes=${bytes ?? '?'}\tpub/s=${publishRate ?? '?'}\tack/s=${ackRate ?? '?'}`;
14
+ }
15
+
16
+ function brokerText({ name, site, queues, error }) {
17
+ if (error) {
18
+ return [`Queues ${site}/${name}\t${error}`];
19
+ }
20
+ return [`Queues ${site}/${name}\tready=${sum(queues, 'ready') ?? '?'}\tunacked=${sum(queues, 'unacked') ?? '?'}`,
21
+ ...queues.map(queueText)];
22
+ }
23
+
24
+ function metricsText({ name, site, metrics, error }) {
25
+ if (error) {
26
+ return [`Metrics ${site}/${name}\t${error}`];
27
+ }
28
+ return [`Metrics ${site}/${name}`, ...metrics.map(({ name: metric, resource, value, unit, error: issue }) => {
29
+ const id = resource ? `${metric}/${resource}` : metric;
30
+ return ` ${terminalLabel(id)}\t${issue ?? `${value} ${unit}`}`;
31
+ })];
32
+ }
33
+
34
+ export default function loadText({ brokers, metrics }) {
35
+ const lines = [...brokers.flatMap(brokerText), ...metrics.flatMap(metricsText)];
36
+ return lines.length ? lines.join('\n') : 'no load sources configured';
37
+ }
@@ -1,8 +1,22 @@
1
+ import topologyStatus from './topologyStatus.js';
2
+
3
+ function presentation(execute, topology, describe, network) {
4
+ return (command) => {
5
+ if (command.action === 'load') {
6
+ return network.load(command.context);
7
+ }
8
+ if (command.action === 'status' && topology) {
9
+ return topologyStatus(topology, describe, command.context, network.traffic);
10
+ }
11
+ return execute(command);
12
+ };
13
+ }
14
+
1
15
  /**
2
16
  * Runtime port: components(), logs(id, tail), plan(), apply().
3
17
  * The application only knows context names and normalized results.
4
18
  */
5
- export default function management(targets) {
19
+ export default function management(targets, topology, network) {
6
20
  const applying = new Set();
7
21
 
8
22
  function targetOf(name, forwarded) {
@@ -42,7 +56,7 @@ export default function management(targets) {
42
56
  return { name, runtime: target.runtime };
43
57
  }) };
44
58
  }
45
- if (action === 'components') {
59
+ if (action === 'components' || action === 'status') {
46
60
  const names = context ? [context] : Array.from(targets.keys());
47
61
  return { contexts: await Promise.all(names.map((name) => { return describe(name, forwarded); })) };
48
62
  }
@@ -53,5 +67,5 @@ export default function management(targets) {
53
67
  return action === 'plan' ? target.adapter.plan() : apply(target);
54
68
  }
55
69
 
56
- return { execute };
70
+ return { execute: presentation(execute, topology, describe, network) };
57
71
  }
@@ -0,0 +1,80 @@
1
+ /** Combine queue snapshots and configured acknowledgement evidence. */
2
+ function compareQueues(left, right) {
3
+ return (right.ready ?? 0) + (right.unacked ?? 0) - (left.ready ?? 0) - (left.unacked ?? 0) ||
4
+ left.name.localeCompare(right.name);
5
+ }
6
+
7
+ async function observe(name, source, field) {
8
+ try {
9
+ const data = await source.sample();
10
+ return { name, site: source.site, [field]: field === 'queues' ? data.toSorted(compareQueues) : data };
11
+ } catch (error) {
12
+ return { name, site: source.site, error: error.message };
13
+ }
14
+ }
15
+
16
+ function observations(sources, field, select) {
17
+ return Promise.all(Array.from(sources).filter(([name, source]) => {
18
+ return select(name, source);
19
+ }).map(([name, source]) => { return observe(name, source, field); }));
20
+ }
21
+
22
+ function trafficOf({ broker, queue, stream }, snapshots) {
23
+ const data = snapshots.find(({ name }) => { return name === broker; })?.queues?.find(({ name }) => {
24
+ return name === queue;
25
+ });
26
+ const rate = data?.consumers === 1 ? data.ackRate : undefined;
27
+ if (rate === undefined) {
28
+ return { broker, queue, stream, traffic: 'unknown' };
29
+ }
30
+ return { broker, queue, stream, traffic: rate > 0 ? 'flowing' : 'idle', ackRate: rate };
31
+ }
32
+
33
+ function sameRoute(left, right) {
34
+ return left.from === right.from && left.to === right.to;
35
+ }
36
+
37
+ function withObservations(flow, links, snapshots) {
38
+ const evidence = links.filter((link) => { return sameRoute(link, flow); }).map((link) => {
39
+ return trafficOf(link, snapshots);
40
+ });
41
+ if (evidence.some(({ traffic }) => { return traffic === 'flowing'; })) {
42
+ return { ...flow, evidence, traffic: 'flowing' };
43
+ }
44
+ const idle = evidence.length > 0 && evidence.every(({ traffic }) => { return traffic === 'idle'; });
45
+ return { ...flow, evidence, traffic: idle ? 'idle' : 'unknown' };
46
+ }
47
+
48
+ function matchingLinks(links, sites) {
49
+ return sites ? links.filter(({ from, to }) => { return sites.has(from) || sites.has(to); }) : links;
50
+ }
51
+
52
+ export default function networkLoad(brokers, metrics, links) {
53
+ async function load(scope) {
54
+ function selected(name, { site }) {
55
+ return !scope || name === scope || site === scope;
56
+ }
57
+ const [queueSources, metricSources] = await Promise.all([
58
+ observations(brokers, 'queues', selected), observations(metrics, 'metrics', selected)
59
+ ]);
60
+ if (scope && !queueSources.length && !metricSources.length) {
61
+ throw new Error('no load sources for this site or source name');
62
+ }
63
+ return { load: { brokers: queueSources, metrics: metricSources } };
64
+ }
65
+
66
+ async function traffic(flows, sites) {
67
+ const relevant = matchingLinks(links, sites);
68
+ const targets = new Set(relevant.map(({ broker }) => { return broker; }));
69
+ const snapshots = await observations(brokers, 'queues', (name) => { return targets.has(name); });
70
+ const routes = [...flows];
71
+ relevant.forEach(({ from, to }) => {
72
+ if (!routes.some((flow) => { return sameRoute(flow, { from, to }); })) {
73
+ routes.push({ from, to, streams: [], declared: false });
74
+ }
75
+ });
76
+ return routes.map((flow) => { return withObservations(flow, relevant, snapshots); });
77
+ }
78
+
79
+ return { load, traffic };
80
+ }
@@ -0,0 +1,6 @@
1
+ /** Preserve identifiers in JSON and make nonprinting characters visible in terminal reports. */
2
+ export default function terminalLabel(value) {
3
+ return value.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (character) => {
4
+ return `\\u{${character.codePointAt(0).toString(16)}}`;
5
+ });
6
+ }
@@ -0,0 +1,36 @@
1
+ /** Project the system document into a topology that can be shared with operators. */
2
+ import expand from '../deploy/expand.js';
3
+ import { treePaths } from '../deploy/expandNamespace.js';
4
+ import { isAddress } from '../deploy/expandPattern.js';
5
+ import { edgesOf } from '../deploy/releaseEdges.js';
6
+ import { asPath } from '../deploy/releaseNodes.js';
7
+
8
+ function siteOf(server, bindings, targets) {
9
+ const { id: name } = server;
10
+ const fallback = targets.has(name) ? [name] : [];
11
+ const contexts = Object.hasOwn(bindings, name) ? bindings[name] : fallback;
12
+ const objects = [...new Set([...(server.objects || []), ...(server.ownership || [])].map(asPath))];
13
+ const localStreams = [...new Set((server.fan_in || []).filter(({ from }) => {
14
+ return isAddress(from);
15
+ }).map(({ name: stream }) => { return stream; }))];
16
+ return { name, contexts, objects, localStreams };
17
+ }
18
+
19
+ export default function topology(document, bindings, targets) {
20
+ const system = expand(document);
21
+ const sites = system.servers.map((server) => { return siteOf(server, bindings, targets); });
22
+ Object.entries(bindings).forEach(([site, contexts]) => {
23
+ if (!sites.some(({ name }) => { return name === site; })) {
24
+ throw new Error(`unknown system site ${site}`);
25
+ }
26
+ contexts.forEach((context) => {
27
+ if (!targets.has(context)) {
28
+ throw new Error(`unknown management context ${context} bound to ${site}`);
29
+ }
30
+ });
31
+ });
32
+ const flows = edgesOf(system).map(({ from, to, streams }) => {
33
+ return { from, to, streams: Array.from(streams.keys()) };
34
+ });
35
+ return { namespace: treePaths(system.namespace), sites, flows };
36
+ }
@@ -0,0 +1,44 @@
1
+ /** Add runtime evidence to declared sites without interpreting it as stream health. */
2
+ function contextState(result) {
3
+ if (!result.components?.length) {
4
+ return 'unknown';
5
+ }
6
+ return result.components.every(({ state }) => { return state === 'ready'; }) ? 'ready' : 'degraded';
7
+ }
8
+
9
+ function aggregate(states) {
10
+ if (states.includes('degraded')) {
11
+ return 'degraded';
12
+ }
13
+ return states.length > 0 && states.every((state) => { return state === 'ready'; }) ? 'ready' : 'unknown';
14
+ }
15
+
16
+ function scopeOf(model, context) {
17
+ if (!context) {
18
+ return model;
19
+ }
20
+ const sites = model.sites.filter(({ name, contexts }) => { return name === context || contexts.includes(context); });
21
+ if (sites.length === 0) {
22
+ throw new Error('unknown production site or bound context');
23
+ }
24
+ const names = new Set(sites.map(({ name }) => { return name; }));
25
+ const flows = model.flows.filter(({ from, to }) => { return names.has(from) || names.has(to); });
26
+ return { ...model, sites, flows };
27
+ }
28
+
29
+ export default async function topologyStatus(topology, describe, context, traffic) {
30
+ const model = scopeOf(topology, context);
31
+ const selected = new Set(model.sites.flatMap(({ contexts }) => { return contexts; }));
32
+ const scope = context ? new Set(model.sites.map(({ name }) => { return name; })) : undefined;
33
+ const [statesByContext, flows] = await Promise.all([
34
+ Promise.all(Array.from(selected, async (name) => { return [name, contextState(await describe(name))]; })),
35
+ traffic(model.flows, scope)
36
+ ]);
37
+ const observations = new Map(statesByContext);
38
+ const sites = model.sites.map((site) => {
39
+ const states = site.contexts.map((name) => { return observations.get(name); });
40
+ return { ...site, state: aggregate(states) };
41
+ });
42
+ const state = aggregate(sites.map((site) => { return site.state; }));
43
+ return { topology: { ...model, sites, state, flows } };
44
+ }
@@ -0,0 +1,28 @@
1
+ /** Format the production overview using logical names and flow directions. */
2
+ import terminalLabel from './terminalLabel.js';
3
+
4
+ function siteText(site) {
5
+ return [` ${terminalLabel(site.name)}\t${site.state}`,
6
+ ...site.objects.map((path) => { return ` ${terminalLabel(path)}`; }),
7
+ ...(site.localStreams.length ? [` Local streams: ${site.localStreams.length}`] : [])];
8
+ }
9
+
10
+ function flowText({ from, to, streams, declared, traffic, evidence }) {
11
+ const scope = declared === false ? 'observed route' : `streams=${streams.length}`;
12
+ return [` ${terminalLabel(from)} -> ${terminalLabel(to)}\t${scope}\t${traffic}`, ...evidence.map((item) => {
13
+ const stream = item.stream ? `${terminalLabel(item.stream)} ` : '';
14
+ return ` ${stream}${item.broker}/${terminalLabel(item.queue)}\t${item.traffic}\tack/s=${item.ackRate ?? '?'}`;
15
+ })];
16
+ }
17
+
18
+ export default function topologyText({ namespace, sites, flows, state }) {
19
+ const groups = namespace.filter((path) => { return path.split('/').length <= 3; });
20
+ return [
21
+ `Production ${state}`,
22
+ ...groups.map((path) => { return ` ${terminalLabel(path)}`; }),
23
+ 'Sites',
24
+ ...sites.flatMap(siteText),
25
+ 'Flows',
26
+ ...flows.flatMap(flowText)
27
+ ].join('\n');
28
+ }
package/src/bin/scada.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { parseArgs } from 'node:util';
4
+ import loadText from '../application/management/loadText.js';
5
+ import topologyText from '../application/management/topologyText.js';
4
6
  import management from '../application/management/management.js';
5
7
  import readInventory from '../infrastructure/management/inventory.js';
6
8
  import managementServer from '../infrastructure/management/server.js';
@@ -9,6 +11,7 @@ import { request, send } from '../infrastructure/management/protocol.js';
9
11
  const usage = `Usage:
10
12
  scada contexts
11
13
  scada status [--context NAME]
14
+ scada load [--context SITE]
12
15
  scada get components [--context NAME]
13
16
  scada logs COMPONENT --context NAME [--tail LINES]
14
17
  scada plan --context NAME
@@ -42,7 +45,7 @@ function commandOf([verb, arg, ...rest], { context, tail }) {
42
45
  (verb === 'contexts' && context !== undefined)) {
43
46
  throw new Error('invalid command arguments; see scada --help');
44
47
  }
45
- const action = ['get', 'status'].includes(verb) ? 'components' : verb;
48
+ const action = verb === 'get' ? 'components' : verb;
46
49
  const result = request.safeParse({
47
50
  action,
48
51
  ...(context !== undefined && { context }),
@@ -54,7 +57,13 @@ function commandOf([verb, arg, ...rest], { context, tail }) {
54
57
  return result.data;
55
58
  }
56
59
 
57
- function textOf({ contexts, changes, logs }) {
60
+ function textOf({ contexts, changes, logs, topology, load }) {
61
+ if (topology) {
62
+ return topologyText(topology);
63
+ }
64
+ if (load) {
65
+ return loadText(load);
66
+ }
58
67
  if (contexts) {
59
68
  return contexts.flatMap(({ name, runtime, components, error }) => {
60
69
  if (components?.length) {
@@ -69,8 +78,17 @@ function textOf({ contexts, changes, logs }) {
69
78
  return logs;
70
79
  }
71
80
 
72
- function unhealthy({ error, components }) {
73
- return Boolean(error) || !components.length || components.some(({ state }) => { return state !== 'ready'; });
81
+ function contextUnhealthy({ error, components }) {
82
+ return Boolean(error) || !components?.length || components.some(({ state }) => { return state !== 'ready'; });
83
+ }
84
+
85
+ function unhealthy(result) {
86
+ return result.topology ? result.topology.state !== 'ready' : result.contexts.some(contextUnhealthy);
87
+ }
88
+
89
+ function incompleteLoad({ brokers, metrics }) {
90
+ return brokers.some(({ error }) => { return Boolean(error); }) ||
91
+ metrics.some((source) => { return source.error || source.metrics.some(({ error }) => { return Boolean(error); }); });
74
92
  }
75
93
 
76
94
  async function client(args) {
@@ -84,7 +102,7 @@ async function client(args) {
84
102
  const result = await send(url, token, command);
85
103
  const text = values.output === 'json' ? JSON.stringify(result) : textOf(result);
86
104
  process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
87
- if (positionals[0] === 'status' && result.contexts.some(unhealthy)) {
105
+ if ((command.action === 'status' && unhealthy(result)) || (result.load && incompleteLoad(result.load))) {
88
106
  process.exitCode = 1;
89
107
  }
90
108
  }
@@ -94,9 +112,9 @@ async function serve(args) {
94
112
  if (!config || Boolean(cert) !== Boolean(key) || !/^\d{1,5}$/u.test(port) || Number(port) > 65535) {
95
113
  throw new Error('serve requires --config and accepts --port 0-65535 and a --cert/--key pair');
96
114
  }
97
- const targets = await readInventory(config, process.env);
115
+ const { targets, topology, network } = await readInventory(config, process.env);
98
116
  const tls = cert ? { cert: await readFile(cert), key: await readFile(key) } : undefined;
99
- const { address, server } = await managementServer(management(targets), {
117
+ const { address, server } = await managementServer(management(targets, topology, network), {
100
118
  host, port: Number(port), tls, token: process.env.SCADA_TOKEN, readToken: process.env.SCADA_READ_TOKEN
101
119
  });
102
120
  function close() {
@@ -0,0 +1,33 @@
1
+ /** Read desired collector placement and node capacity from the quorum store. */
2
+ import { clientFromEnv } from '../../application/control/controlClient.js';
3
+ import controlStore from '../../application/control/controlStore.js';
4
+ import { urlOf } from './protocol.js';
5
+
6
+ function placement({ catalog, assignments }) {
7
+ if (!Array.isArray(catalog?.nodes) || !Array.isArray(catalog.tasks)) {
8
+ throw new Error('quorum controller has no catalog');
9
+ }
10
+ const costs = new Map(catalog.tasks.map(({ taskId, cost }) => { return [taskId, cost ?? 1]; }));
11
+ return catalog.nodes.flatMap(({ id: resource, capacity }) => {
12
+ const desired = Object.hasOwn(assignments, resource) ? assignments[resource].assignments : undefined;
13
+ const limit = { name: 'capacity', resource, unit: 'cost', value: capacity };
14
+ if (!Array.isArray(desired)) {
15
+ return [{ name: 'assigned-tasks', resource, unit: 'tasks', error: 'no assignment snapshot' }, limit];
16
+ }
17
+ const cost = desired.reduce((total, { taskId }) => { return total + (costs.get(taskId) ?? 1); }, 0);
18
+ return [
19
+ { name: 'assigned-tasks', resource, unit: 'tasks', value: desired.length },
20
+ { name: 'assigned-cost', resource, unit: 'cost', value: cost }, limit
21
+ ];
22
+ });
23
+ }
24
+
25
+ export default function controlLoad({ site, envPrefix, keyPrefix }, env) {
26
+ const endpoints = (env[`${envPrefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean);
27
+ endpoints.forEach((endpoint) => { urlOf(endpoint); });
28
+ const store = controlStore(clientFromEnv(env, envPrefix), keyPrefix);
29
+ return { site, async sample() {
30
+ const view = await store.read().catch(() => { throw new Error('quorum controller read failed'); });
31
+ return placement(view);
32
+ } };
33
+ }
@@ -1,7 +1,11 @@
1
1
  /** Load the host-owned inventory and compose its runtime adapters. */
2
2
  import { z } from 'zod';
3
+ import { readFileSync } from 'node:fs';
3
4
  import { readFile } from 'node:fs/promises';
4
5
  import { dirname, resolve } from 'node:path';
6
+ import readDocument from '../../application/deploy/readDocument.js';
7
+ import topology from '../../application/management/topology.js';
8
+ import readObservations, { observationConfig } from './observations.js';
5
9
  import kubernetes from './kubernetes.js';
6
10
  import systemd from './systemd.js';
7
11
  import remote from './remote.js';
@@ -9,18 +13,29 @@ import { contextName, urlOf } from './protocol.js';
9
13
 
10
14
  const name = z.string().regex(/^[a-z0-9][a-z0-9.-]{0,62}$/u);
11
15
  const unit = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.@:-]*\.service$/u);
16
+ const workload = z.string().regex(/^(?:deployment|statefulset|daemonset|job)\/[a-z0-9][a-z0-9.-]{0,252}$/u);
12
17
  const target = z.discriminatedUnion('runtime', [
13
18
  z.strictObject({
14
- runtime: z.literal('kubernetes'), kubeContext: z.string().min(1), namespace: name, release: name,
19
+ runtime: z.literal('kubernetes'), kubeContext: z.string().min(1), namespace: name, release: name.optional(),
20
+ workloads: z.array(workload).min(1).max(100).optional(),
15
21
  values: z.string().min(1).optional(), releasePlan: z.string().min(1).optional()
16
- }).refine(({ values, releasePlan }) => { return !values || !releasePlan; }),
22
+ }).refine(({ values, releasePlan, release, workloads }) => {
23
+ return (!values || !releasePlan) && Boolean(release || (workloads && !values && !releasePlan));
24
+ }),
17
25
  z.strictObject({ runtime: z.literal('systemd'), units: z.record(unit, z.literal('running')) }),
18
26
  z.strictObject({
19
27
  runtime: z.literal('remote'), server: z.string(), context: contextName,
20
28
  tokenEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/u)
21
29
  })
22
30
  ]);
23
- const inventory = z.strictObject({ contexts: z.record(contextName, target) });
31
+ const inventory = z.strictObject({
32
+ contexts: z.record(contextName, target),
33
+ observations: observationConfig,
34
+ system: z.strictObject({
35
+ file: z.string().min(1),
36
+ sites: z.record(contextName, z.array(contextName)).default({})
37
+ }).optional()
38
+ });
24
39
 
25
40
  function adapter(config, directory, env) {
26
41
  if (config.runtime === 'systemd') {
@@ -49,15 +64,29 @@ function writeLocks(config) {
49
64
  return [JSON.stringify(['remote', urlOf(config.server).origin, config.context])];
50
65
  }
51
66
 
67
+ function readSystem(system, directory, targets) {
68
+ if (!system) {
69
+ return undefined;
70
+ }
71
+ const file = resolve(directory, system.file);
72
+ const document = readDocument(readFileSync(file, 'utf8'), (include) => {
73
+ return readFileSync(resolve(dirname(file), include), 'utf8');
74
+ });
75
+ return topology(document, system.sites, targets);
76
+ }
77
+
52
78
  export default async function readInventory(path, env) {
53
79
  const result = inventory.safeParse(JSON.parse(await readFile(path, 'utf8')));
54
80
  if (!result.success) {
55
81
  throw new Error(`invalid inventory at ${result.error.issues[0].path.join('.') || 'root'}`);
56
82
  }
57
- return new Map(Object.entries(result.data.contexts).map(([id, config]) => {
83
+ const directory = dirname(resolve(path));
84
+ const targets = new Map(Object.entries(result.data.contexts).map(([id, config]) => {
58
85
  return [id, {
59
86
  runtime: config.runtime, forwards: config.runtime === 'remote', locks: writeLocks(config),
60
- adapter: adapter(config, dirname(resolve(path)), env)
87
+ adapter: adapter(config, directory, env)
61
88
  }];
62
89
  }));
90
+ const production = readSystem(result.data.system, directory, targets);
91
+ return { targets, topology: production, network: readObservations(result.data.observations, production, env) };
63
92
  }
@@ -1,10 +1,10 @@
1
- /** Kubernetes inspection and reconciliation for one configured release. */
1
+ /** Kubernetes inspection and reconciliation for one configured target. */
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import command from './command.js';
4
4
 
5
5
  const chart = fileURLToPath(new URL('../../../charts/scada', import.meta.url));
6
6
  const worker = fileURLToPath(new URL('./serverSideRelease.js', import.meta.url));
7
- const workloads = 'deployments,statefulsets,daemonsets,jobs';
7
+ const workloadKinds = 'deployments,statefulsets,daemonsets,jobs';
8
8
 
9
9
  function jobState(status) {
10
10
  function active(type) {
@@ -39,26 +39,50 @@ function workloadState({ kind, metadata, spec = {}, status = {} }) {
39
39
  return complete ? 'ready' : 'pending';
40
40
  }
41
41
 
42
- export default function kubernetes({ kubeContext, namespace, release, values, releasePlan }) {
43
- function kubectl(action, args) {
44
- return command('kubectl', [action, `--context=${kubeContext}`, `--namespace=${namespace}`, ...args]);
42
+ function workloadId(item) {
43
+ return `${item.kind.toLowerCase()}/${item.metadata.name}`;
44
+ }
45
+
46
+ function workloadInspection(kubectl, release, expected) {
47
+ async function observed() {
48
+ if (expected) {
49
+ const output = await kubectl('get', [...expected, '--ignore-not-found', '-o', 'json']);
50
+ if (!output.trim()) {
51
+ return [];
52
+ }
53
+ const response = JSON.parse(output);
54
+ return response.kind === 'List' ? response.items : [response];
55
+ }
56
+ const selector = `app.kubernetes.io/name=scada,app.kubernetes.io/instance=${release}`;
57
+ const { items } = JSON.parse(await kubectl('get', [workloadKinds, '--selector', selector, '-o', 'json']));
58
+ return items;
45
59
  }
46
60
 
47
61
  async function components() {
48
- const selector = `app.kubernetes.io/name=scada,app.kubernetes.io/instance=${release}`;
49
- const { items } = JSON.parse(await kubectl('get', [workloads, '--selector', selector, '-o', 'json']));
50
- return items.map((item) => {
51
- return { id: `${item.kind.toLowerCase()}/${item.metadata.name}`, state: workloadState(item) };
62
+ const states = new Map((await observed()).map((item) => {
63
+ return [workloadId(item), workloadState(item)];
64
+ }));
65
+ return (expected ?? Array.from(states.keys())).map((id) => {
66
+ return { id, state: states.get(id) ?? 'failed' };
52
67
  });
53
68
  }
54
69
 
55
70
  async function logs(component, tail) {
56
- if (!(await components()).some(({ id }) => { return id === component; })) {
71
+ if ((expected && !expected.includes(component)) ||
72
+ !(await observed()).some((item) => { return workloadId(item) === component; })) {
57
73
  throw new Error('unknown component');
58
74
  }
59
75
  return kubectl('logs', [component, `--tail=${tail}`, '--all-containers=true']);
60
76
  }
61
77
 
78
+ return { components, logs };
79
+ }
80
+
81
+ export default function kubernetes({ kubeContext, namespace, release, values, releasePlan, workloads }) {
82
+ function kubectl(action, args) {
83
+ return command('kubectl', [action, `--context=${kubeContext}`, `--namespace=${namespace}`, ...args]);
84
+ }
85
+
62
86
  async function helm(options, timeout) {
63
87
  if (!values) {
64
88
  throw new Error('this context has no desired release values');
@@ -83,7 +107,7 @@ export default function kubernetes({ kubeContext, namespace, release, values, re
83
107
  }
84
108
 
85
109
  return {
86
- components, logs,
110
+ ...workloadInspection(kubectl, release, workloads),
87
111
  plan() { return reconcile('check', ['--dry-run=server', '--hide-secret'], 30000); },
88
112
  apply() { return reconcile('apply', ['--atomic'], 660000); }
89
113
  };
@@ -0,0 +1,80 @@
1
+ /** Bind trusted monitoring sources and exclusive route queues at gateway startup. */
2
+ import { z } from 'zod';
3
+ import networkLoad from '../../application/management/networkLoad.js';
4
+ import controlLoad from './controlLoad.js';
5
+ import { contextName } from './protocol.js';
6
+ import prometheusLoad from './prometheusLoad.js';
7
+ import rabbitmqLoad from './rabbitmqLoad.js';
8
+
9
+ const credential = z.string().regex(/^[A-Z_][A-Z0-9_]*$/u);
10
+ const queueName = z.string().min(1).max(300);
11
+ const rabbitmq = z.strictObject({
12
+ site: contextName, url: z.string().min(1), vhost: z.string().min(1).default('/'),
13
+ prefix: z.string().max(150).optional(), username: z.string().min(1).optional(), passwordEnv: credential.optional()
14
+ }).refine(({ username, passwordEnv }) => { return Boolean(username) === Boolean(passwordEnv); });
15
+ const metric = z.strictObject({
16
+ name: contextName, query: z.string().min(1).max(5000), unit: z.string().max(40),
17
+ resourceLabel: z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/u).optional()
18
+ });
19
+ const prometheus = z.strictObject({
20
+ site: contextName, url: z.string().min(1), tokenEnv: credential.optional(), metrics: z.array(metric).min(1).max(30)
21
+ });
22
+ const control = z.strictObject({
23
+ site: contextName, envPrefix: credential.default('CONTROL'),
24
+ keyPrefix: z.string().min(1).max(200).optional()
25
+ });
26
+ const link = z.strictObject({
27
+ from: contextName, to: contextName, broker: contextName, queue: queueName, stream: queueName.optional()
28
+ });
29
+ export const observationConfig = z.strictObject({
30
+ rabbitmq: z.record(contextName, rabbitmq).default({}),
31
+ prometheus: z.record(contextName, prometheus).default({}),
32
+ control: z.record(contextName, control).default({}),
33
+ links: z.array(link).default([])
34
+ }).default({ rabbitmq: {}, prometheus: {}, control: {}, links: [] });
35
+
36
+ function validateLinks(links, brokers, topology) {
37
+ const sites = new Set(topology?.sites.map(({ name }) => { return name; }));
38
+ const seen = new Set();
39
+ links.forEach(({ from, to, broker, queue, stream }) => {
40
+ if (!sites.has(from) || !sites.has(to) || brokers.get(broker)?.site !== from || from === to) {
41
+ throw new Error(`invalid route observation ${from} -> ${to}`);
42
+ }
43
+ const key = JSON.stringify([broker, queue]);
44
+ if (seen.has(key)) {
45
+ throw new Error(`route observation queue ${queue} is already bound`);
46
+ }
47
+ if (stream && !topology.flows.some((flow) => {
48
+ return flow.from === from && flow.to === to && flow.streams.includes(stream);
49
+ })) {
50
+ throw new Error(`unknown stream ${stream} on route ${from} -> ${to}`);
51
+ }
52
+ seen.add(key);
53
+ });
54
+ }
55
+
56
+ function shared(source) {
57
+ let pending;
58
+ function sample() {
59
+ pending ??= source.sample().finally(() => { pending = undefined; });
60
+ return pending;
61
+ }
62
+ return { ...source, sample };
63
+ }
64
+
65
+ export default function readObservations(config, topology, env) {
66
+ const brokers = new Map(Object.entries(config.rabbitmq).map(([name, source]) => {
67
+ return [name, shared(rabbitmqLoad(source, env))];
68
+ }));
69
+ validateLinks(config.links, brokers, topology);
70
+ const metrics = new Map(Object.entries(config.prometheus).map(([name, source]) => {
71
+ return [name, shared(prometheusLoad(source, env))];
72
+ }));
73
+ Object.entries(config.control).forEach(([name, source]) => {
74
+ if (metrics.has(name)) {
75
+ throw new Error(`duplicate metric source ${name}`);
76
+ }
77
+ metrics.set(name, shared(controlLoad(source, env)));
78
+ });
79
+ return networkLoad(brokers, metrics, config.links);
80
+ }