@yarkivaev/scada 2.13.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/charts/scada/templates/processes.yaml +6 -1
- package/charts/scada/values.schema.json +1 -0
- package/index.js +29 -0
- package/package.json +3 -2
- package/src/application/control/agent.js +8 -14
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/executionSnapshot.js +4 -5
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/application/runtime/deliveryOperations.js +6 -3
- package/src/application/runtime/deliveryPublications.js +13 -11
- package/src/application/runtime/deliveryQueue.js +5 -4
- package/src/application/runtime/index.js +0 -1
- package/src/application/runtime/queuedDelivery.js +6 -5
- package/src/application/runtime/runCollector.js +8 -6
- package/src/application/runtime/runtime.js +1 -0
- package/src/application/runtime/runtimeServices.js +6 -26
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
- package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
- package/src/application/control/snapshotFile.js +0 -24
- package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
- package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
- package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
- package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
- package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
- package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
- package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
- package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
- package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { taskSpecHash } from '../../application/runtime/assignment.js';
|
|
2
|
+
|
|
3
|
+
function nodeIdentity(node, namespace, execute) {
|
|
4
|
+
const response = execute('kubectl', ['--context', node, '--namespace', namespace, '--request-timeout=10s', 'get', 'nodes', '-o', 'json'],
|
|
5
|
+
{ encoding: 'utf8', timeout: 15000 });
|
|
6
|
+
const nodes = JSON.parse(response).items;
|
|
7
|
+
if (nodes?.length !== 1 || !nodes[0].metadata?.uid) { throw new Error('Single physical node identity required'); }
|
|
8
|
+
return nodes[0];
|
|
9
|
+
}
|
|
10
|
+
function distinct(local, remote) {
|
|
11
|
+
const ips = local.status?.addresses?.filter((row) => { return row.type === 'InternalIP'; }).map((row) => { return row.address; }) ?? [];
|
|
12
|
+
if (local.metadata.uid === remote.metadata.uid || remote.status?.addresses?.some((row) => { return row.type === 'InternalIP' && ips.includes(row.address); })) {
|
|
13
|
+
throw new Error('Surviving reader must run on another physical node');
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl }) {
|
|
17
|
+
const program = `const r=await fetch(${JSON.stringify(statusUrl)},{signal:AbortSignal.timeout(2000)});if(!r.ok)throw new Error('Reader unavailable');process.stdout.write(await r.text());`;
|
|
18
|
+
const response = execute('kubectl', ['--context', proof.nodeId, '--namespace', namespace, '--request-timeout=10s',
|
|
19
|
+
'exec', proof.workload, '-c', container, '--', 'node', '--input-type=module', '-e', program], { encoding: 'utf8', timeout: 15000 });
|
|
20
|
+
const status = JSON.parse(response);
|
|
21
|
+
const row = status.tasks?.find((item) => { return item.taskId === task.taskId; });
|
|
22
|
+
const at = now();
|
|
23
|
+
if (status.initialized !== true || status.stopping || status.fatal || row?.state !== 'running'
|
|
24
|
+
|| ['failed', 'degraded'].includes(row.health) || row.specHash !== taskSpecHash(task.spec)
|
|
25
|
+
|| !Number.isFinite(row.lastRead) || row.lastRead > at + clockSkewMs || at - row.lastRead > freshnessMs) {
|
|
26
|
+
throw new Error(`Fresh surviving reader required: ${task.taskId}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Probe a matching controlled collector or temporary static bridge immediately before retirement. */
|
|
30
|
+
export default function verifyCollectorCoverage({ cluster, namespace, tasks, evidence, execute, now = Date.now,
|
|
31
|
+
freshnessMs = 15000, clockSkewMs = 5000, workloads, container = 'collector', statusUrl = 'http://127.0.0.1:9091/status' }) {
|
|
32
|
+
if (!tasks.length) { return; }
|
|
33
|
+
const local = nodeIdentity(cluster, namespace, execute);
|
|
34
|
+
for (const task of tasks) {
|
|
35
|
+
const proof = evidence?.coverage?.find((item) => { return item.taskId === task.taskId; });
|
|
36
|
+
if (!proof || proof.nodeId === cluster || !task.eligibleNodes.includes(proof.nodeId)
|
|
37
|
+
|| !workloads?.includes(proof.workload)) {
|
|
38
|
+
throw new Error(`Live surviving reader coverage required: ${task.taskId}`);
|
|
39
|
+
}
|
|
40
|
+
distinct(local, nodeIdentity(proof.nodeId, namespace, execute));
|
|
41
|
+
liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { readKube } from './deploymentKube.js';
|
|
3
|
+
|
|
4
|
+
/** Bind supplied packet probe evidence to the live broker pod and network policy. */
|
|
5
|
+
export default function verifyPeerBrokerBoundary({ context, policy, allowedPeers, selector, proof, maxAgeMs = 900000 }, kube, now = Date.now()) {
|
|
6
|
+
if (!policy) { return; }
|
|
7
|
+
const verifiedAt = Date.parse(proof?.verifiedAt);
|
|
8
|
+
if (!proof || proof.cluster !== context || !proof.networkPolicyEnforced
|
|
9
|
+
|| !isDeepStrictEqual(proof.allowedPeers, [...allowedPeers].sort()) || !proof.deniedSources?.length
|
|
10
|
+
|| proof.deniedSources.some((source) => { return allowedPeers.includes(source); })
|
|
11
|
+
|| !(verifiedAt <= now && verifiedAt > now - maxAgeMs)) {
|
|
12
|
+
throw new Error('Fresh verified peer broker perimeter coverage evidence required');
|
|
13
|
+
}
|
|
14
|
+
const live = JSON.parse(readKube(kube, `networkpolicy/${policy.metadata.name}`));
|
|
15
|
+
if (live.metadata.uid !== proof.policyUID || live.metadata.resourceVersion !== proof.policyResourceVersion
|
|
16
|
+
|| !isDeepStrictEqual(live.spec, policy.spec)) {
|
|
17
|
+
throw new Error('Peer broker perimeter policy changed after packet probes');
|
|
18
|
+
}
|
|
19
|
+
const { items: pods } = JSON.parse(kube(['get', 'pods', '-l', selector, '-o', 'json'], undefined, true));
|
|
20
|
+
if (pods.length !== 1 || pods[0].metadata.uid !== proof.brokerPodUID
|
|
21
|
+
|| !pods[0].status.containerStatuses?.every((container) => { return container.ready; })) {
|
|
22
|
+
throw new Error('Peer broker identity changed after perimeter packet probes');
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
function fail(state, error) {
|
|
2
|
+
state.failure ??= error;
|
|
3
|
+
clearTimeout(state.timer);
|
|
4
|
+
state.pending = Buffer.alloc(0);
|
|
5
|
+
if (state.job) { state.job.reject(state.failure); state.job = null; }
|
|
6
|
+
}
|
|
7
|
+
function pump(state) {
|
|
8
|
+
if (!state.job || state.pending.length < state.job.need) { return; }
|
|
9
|
+
const current = state.job;
|
|
10
|
+
state.job = null;
|
|
11
|
+
clearTimeout(state.timer);
|
|
12
|
+
const body = state.pending.subarray(0, current.need);
|
|
13
|
+
state.pending = state.pending.subarray(current.need);
|
|
14
|
+
current.resolve(body);
|
|
15
|
+
}
|
|
16
|
+
function bind(socket, state, maxBytes) {
|
|
17
|
+
socket.on('data', (chunk) => {
|
|
18
|
+
if (state.failure) { return; }
|
|
19
|
+
if (state.pending.length + chunk.length > maxBytes) {
|
|
20
|
+
fail(state, new Error('MySQL 4.0 buffer capacity exceeded'));
|
|
21
|
+
socket.destroy?.();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
state.pending = Buffer.concat([state.pending, chunk]);
|
|
25
|
+
pump(state);
|
|
26
|
+
});
|
|
27
|
+
socket.on('error', (error) => { fail(state, error); });
|
|
28
|
+
socket.once('end', () => { fail(state, new Error('MySQL 4.0 socket closed')); });
|
|
29
|
+
socket.once('close', () => { fail(state, new Error('MySQL 4.0 socket closed')); });
|
|
30
|
+
}
|
|
31
|
+
/** Bounded one-packet reader; a failed connection is never reused. */
|
|
32
|
+
export default function socketBytes(socket, { maxBytes = 1048576, timeoutMs = 10000 } = {}) {
|
|
33
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
34
|
+
throw new TypeError('Invalid MySQL 4.0 reader limits');
|
|
35
|
+
}
|
|
36
|
+
const state = { pending: Buffer.alloc(0), job: null, failure: null, timer: null };
|
|
37
|
+
bind(socket, state, maxBytes);
|
|
38
|
+
return function take(need) {
|
|
39
|
+
if (state.failure) { return Promise.reject(state.failure); }
|
|
40
|
+
if (state.job) { return Promise.reject(new Error('MySQL 4.0 read is already waiting')); }
|
|
41
|
+
if (!Number.isSafeInteger(need) || need < 0 || need > maxBytes) { return Promise.reject(new Error('MySQL 4.0 packet capacity exceeded')); }
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
state.job = { need, resolve, reject };
|
|
44
|
+
state.timer = setTimeout(() => {
|
|
45
|
+
fail(state, new Error('MySQL 4.0 read timed out'));
|
|
46
|
+
socket.destroy?.();
|
|
47
|
+
}, timeoutMs);
|
|
48
|
+
pump(state);
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only client for MySQL 4.0.
|
|
3
|
+
*
|
|
4
|
+
* Older servers can close connections that send a 4.1 handshake.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const db = mysql40({ host: '127.0.0.1', port: 3306, user: 'reader', password: 'secret', database: 'monitoring' });
|
|
8
|
+
* await db.query('SELECT 1');
|
|
9
|
+
*/
|
|
10
|
+
import scramble from './scramble.js';
|
|
11
|
+
import resultRows from './resultRows.js';
|
|
12
|
+
import { connect, frame, packet, reader } from './packets.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Client auth packet for protocol 4.0.
|
|
16
|
+
*
|
|
17
|
+
* @param {Buffer} salt - 8-byte scramble
|
|
18
|
+
* @param {object} options - user, password, database
|
|
19
|
+
* @returns {Buffer} handshake response
|
|
20
|
+
*/
|
|
21
|
+
function login(salt, options) {
|
|
22
|
+
const scrambled = scramble(salt, Buffer.from(options.password));
|
|
23
|
+
return Buffer.concat([
|
|
24
|
+
Buffer.from([0x0d, 0x20, 0xff, 0xff, 0xff]),
|
|
25
|
+
Buffer.from(`${options.user}\0`),
|
|
26
|
+
scrambled,
|
|
27
|
+
Buffer.from(`\0${options.database}\0`)
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Salt from a protocol-10 greeting.
|
|
33
|
+
*
|
|
34
|
+
* @param {Buffer} greeting - server greeting
|
|
35
|
+
* @returns {Buffer} 8-byte salt
|
|
36
|
+
*/
|
|
37
|
+
function saltOf(greeting) {
|
|
38
|
+
const end = greeting.indexOf(0, 1);
|
|
39
|
+
return greeting.subarray(end + 5, end + 13);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Collects packets until a short 0xfe marker, then one past it is not included.
|
|
44
|
+
*
|
|
45
|
+
* @param {function(number): Promise<Buffer>} take - byte reader
|
|
46
|
+
* @param {Buffer[]} found - packets so far
|
|
47
|
+
* @param {number} eofs - short 0xfe packets seen
|
|
48
|
+
* @returns {Promise<Buffer[]>} result packets
|
|
49
|
+
*/
|
|
50
|
+
async function gather(take, limits) {
|
|
51
|
+
const found = [];
|
|
52
|
+
let eofs = 0;
|
|
53
|
+
let bytes = 0;
|
|
54
|
+
while (eofs < 2) {
|
|
55
|
+
// Packet order is defined by the MySQL wire protocol.
|
|
56
|
+
// eslint-disable-next-line no-await-in-loop
|
|
57
|
+
const body = await packet(take);
|
|
58
|
+
bytes += body.length;
|
|
59
|
+
if (found.length >= limits.maxPackets || bytes > limits.maxResponseBytes) { throw new Error('MySQL 4.0 response capacity exceeded'); }
|
|
60
|
+
if (body[0] === 255) { throw new Error(`MySQL 4.0 query failed ${body.toString('latin1', 3)}`); }
|
|
61
|
+
if (body.length < 9 && body[0] === 254) { eofs += 1; }
|
|
62
|
+
found.push(body);
|
|
63
|
+
}
|
|
64
|
+
return found;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Authenticates and runs one SELECT.
|
|
69
|
+
*
|
|
70
|
+
* @param {import('node:net').Socket} socket - connected socket
|
|
71
|
+
* @param {object} options - login options
|
|
72
|
+
* @param {string} sql - SELECT statement
|
|
73
|
+
* @returns {Promise<Array<object>>} rows
|
|
74
|
+
*/
|
|
75
|
+
async function ask(socket, options, sql) {
|
|
76
|
+
const take = reader(socket, options);
|
|
77
|
+
const greeting = await packet(take);
|
|
78
|
+
socket.write(frame(1, login(saltOf(greeting), options)));
|
|
79
|
+
const reply = await packet(take);
|
|
80
|
+
if (reply[0] === 255) {
|
|
81
|
+
throw new Error(`MySQL 4.0 login failed ${reply.toString('latin1', 3)}`);
|
|
82
|
+
}
|
|
83
|
+
socket.write(frame(0, Buffer.concat([Buffer.from([3]), Buffer.from(sql)])));
|
|
84
|
+
return resultRows(await gather(take, options));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Opens a short-lived read-only session per query.
|
|
89
|
+
*
|
|
90
|
+
* @param {{ host: string, port: number, user: string, password: string, database: string }} options - connection
|
|
91
|
+
* @returns {{ query: function(string): Promise<Array<object>> }} client
|
|
92
|
+
*/
|
|
93
|
+
export default function mysql40(config) {
|
|
94
|
+
const options = { maxPackets: 10000, maxResponseBytes: 1048576, ...config };
|
|
95
|
+
if (![options.maxPackets, options.maxResponseBytes].every((value) => { return Number.isSafeInteger(value) && value > 0; })) {
|
|
96
|
+
throw new TypeError('Invalid MySQL 4.0 response limits');
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
async query(sql) {
|
|
100
|
+
if (!sql.startsWith('SELECT ')) {
|
|
101
|
+
throw new Error(`MySQL 4.0 query is not a read ${sql.slice(0, 24)}`);
|
|
102
|
+
}
|
|
103
|
+
options.signal?.throwIfAborted();
|
|
104
|
+
const socket = await connect(options.host, options.port, options);
|
|
105
|
+
function abort() { socket.destroy(new Error('MySQL 4.0 aborted')); }
|
|
106
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
107
|
+
try {
|
|
108
|
+
options.signal?.throwIfAborted();
|
|
109
|
+
return await ask(socket, options, sql);
|
|
110
|
+
} finally {
|
|
111
|
+
options.signal?.removeEventListener('abort', abort);
|
|
112
|
+
socket.destroy();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Packet reader for the MySQL 4.0 wire protocol.
|
|
3
|
+
*
|
|
4
|
+
* One read is outstanding at a time. Callers sequence packets
|
|
5
|
+
* with recursion instead of an await loop.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const take = reader(socket);
|
|
9
|
+
* const body = await packet(take);
|
|
10
|
+
*/
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import byteReader from './byteReader.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Opens a TCP connection.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} host - database host
|
|
18
|
+
* @param {number} port - database port
|
|
19
|
+
* @returns {Promise<import('node:net').Socket>} connected socket
|
|
20
|
+
*/
|
|
21
|
+
export function connect(host, port, { signal, timeoutMs = 10000 } = {}) {
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const socket = net.connect({ host, port });
|
|
25
|
+
const timer = setTimeout(() => { socket.destroy(new Error('MySQL 4.0 connect timed out')); }, timeoutMs);
|
|
26
|
+
function abort() { socket.destroy(signal.reason ?? new Error('MySQL 4.0 aborted')); }
|
|
27
|
+
function cleanup() { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
|
|
28
|
+
socket.once('connect', () => { cleanup(); resolve(socket); });
|
|
29
|
+
socket.once('error', (error) => { cleanup(); reject(error); });
|
|
30
|
+
socket.once('close', () => { cleanup(); reject(new Error('MySQL 4.0 closed before connect')); });
|
|
31
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Frames a client packet.
|
|
37
|
+
*
|
|
38
|
+
* @param {number} seq - packet sequence
|
|
39
|
+
* @param {Buffer} body - payload
|
|
40
|
+
* @returns {Buffer} header plus body
|
|
41
|
+
*/
|
|
42
|
+
export function frame(seq, body) {
|
|
43
|
+
const head = Buffer.from([
|
|
44
|
+
body.length % 256,
|
|
45
|
+
Math.floor(body.length / 256) % 256,
|
|
46
|
+
Math.floor(body.length / 65536) % 256,
|
|
47
|
+
seq
|
|
48
|
+
]);
|
|
49
|
+
return Buffer.concat([head, body]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Creates a one-at-a-time byte reader.
|
|
54
|
+
*
|
|
55
|
+
* @param {import('node:net').Socket} socket - open socket
|
|
56
|
+
* @returns {function(number): Promise<Buffer>} take(count)
|
|
57
|
+
*/
|
|
58
|
+
export function reader(socket, options = {}) {
|
|
59
|
+
return byteReader(socket, options);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Reads one length-prefixed packet.
|
|
64
|
+
*
|
|
65
|
+
* @param {function(number): Promise<Buffer>} take - byte reader
|
|
66
|
+
* @returns {Promise<Buffer>} packet body
|
|
67
|
+
*/
|
|
68
|
+
export async function packet(take) {
|
|
69
|
+
const head = await take(4);
|
|
70
|
+
const length = head[0] + (head[1] * 256) + (head[2] * 65536);
|
|
71
|
+
return take(length);
|
|
72
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a MySQL 4.0 text result set.
|
|
3
|
+
*
|
|
4
|
+
* Field names are the second length-coded string. Rows are length-coded
|
|
5
|
+
* strings, and a short 0xfe packet ends the fields and the rows.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* resultRows([Buffer.from([1]), namePacket, Buffer.from([0xfe])]);
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Reads a length-coded integer.
|
|
13
|
+
*
|
|
14
|
+
* @param {Buffer} buf - packet
|
|
15
|
+
* @param {number} index - offset
|
|
16
|
+
* @returns {{ value: number|null, index: number }} decoded value
|
|
17
|
+
*/
|
|
18
|
+
function lenenc(buf, index) {
|
|
19
|
+
const head = buf[index];
|
|
20
|
+
if (head < 251) {
|
|
21
|
+
return { value: head, index: index + 1 };
|
|
22
|
+
}
|
|
23
|
+
if (head === 251) {
|
|
24
|
+
return { value: null, index: index + 1 };
|
|
25
|
+
}
|
|
26
|
+
if (head === 252) {
|
|
27
|
+
return { value: buf[index + 1] + (buf[index + 2] * 256), index: index + 3 };
|
|
28
|
+
}
|
|
29
|
+
const wide = buf[index + 1] + (buf[index + 2] * 256) + (buf[index + 3] * 65536);
|
|
30
|
+
return { value: wide, index: index + 4 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Reads a length-coded string as raw Latin-1 bytes.
|
|
35
|
+
*
|
|
36
|
+
* @param {Buffer} buf - packet
|
|
37
|
+
* @param {number} index - offset
|
|
38
|
+
* @returns {{ value: string|null, index: number }} decoded text
|
|
39
|
+
*/
|
|
40
|
+
function text(buf, index) {
|
|
41
|
+
const size = lenenc(buf, index);
|
|
42
|
+
if (size.value === null) {
|
|
43
|
+
return { value: null, index: size.index };
|
|
44
|
+
}
|
|
45
|
+
const end = size.index + size.value;
|
|
46
|
+
return { value: buf.toString('latin1', size.index, end), index: end };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Field name from a 4.0 column packet.
|
|
51
|
+
*
|
|
52
|
+
* @param {Buffer} packet - column definition
|
|
53
|
+
* @returns {string} column name
|
|
54
|
+
*/
|
|
55
|
+
function fieldName(packet) {
|
|
56
|
+
const table = text(packet, 0);
|
|
57
|
+
return text(packet, table.index).value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether a packet is the end-of-fields or end-of-rows marker.
|
|
62
|
+
*
|
|
63
|
+
* @param {Buffer} packet - protocol packet
|
|
64
|
+
* @returns {boolean} true for a short 0xfe packet
|
|
65
|
+
*/
|
|
66
|
+
function eof(packet) {
|
|
67
|
+
return packet.length < 9 && packet[0] === 254;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Splits packets into column names and row objects.
|
|
72
|
+
*
|
|
73
|
+
* @param {Buffer[]} packets - result packets, field count first
|
|
74
|
+
* @returns {Array<object>} rows
|
|
75
|
+
*/
|
|
76
|
+
export default function resultRows(packets) {
|
|
77
|
+
const head = packets[0];
|
|
78
|
+
if (head[0] === 255) {
|
|
79
|
+
throw new Error(`MySQL 4.0 query failed ${head.toString('latin1', 3)}`);
|
|
80
|
+
}
|
|
81
|
+
const count = head[0];
|
|
82
|
+
const names = packets.slice(1, 1 + count).map(fieldName);
|
|
83
|
+
const body = packets.slice(2 + count);
|
|
84
|
+
return body.filter((packet) => {
|
|
85
|
+
return !eof(packet);
|
|
86
|
+
}).map((packet) => {
|
|
87
|
+
return names.reduce((row, name) => {
|
|
88
|
+
const cell = text(packet, row.index);
|
|
89
|
+
return { index: cell.index, values: { ...row.values, [name]: cell.value } };
|
|
90
|
+
}, { index: 0, values: {} }).values;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MySQL 4.0 old-password scramble.
|
|
3
|
+
*
|
|
4
|
+
* The mix matches the server's 32-bit unsigned arithmetic.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* scramble(Buffer.from('12345678'), Buffer.from('secret'));
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Keeps a value inside unsigned 32 bits.
|
|
12
|
+
*
|
|
13
|
+
* @param {number} value - intermediate mix
|
|
14
|
+
* @returns {number} unsigned 32-bit value
|
|
15
|
+
*/
|
|
16
|
+
function mask(value) {
|
|
17
|
+
const wrapped = value % 4294967296;
|
|
18
|
+
return wrapped < 0 ? wrapped + 4294967296 : wrapped;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Xors two unsigned 32-bit values without bitwise operators.
|
|
23
|
+
*
|
|
24
|
+
* @param {number} left - first value
|
|
25
|
+
* @param {number} right - second value
|
|
26
|
+
* @returns {number} xor
|
|
27
|
+
*/
|
|
28
|
+
function xor(left, right) {
|
|
29
|
+
let out = 0;
|
|
30
|
+
let bit = 1;
|
|
31
|
+
let low = mask(left);
|
|
32
|
+
let high = mask(right);
|
|
33
|
+
for (let i = 0; i < 32; i += 1) {
|
|
34
|
+
if ((low % 2) !== (high % 2)) {
|
|
35
|
+
out += bit;
|
|
36
|
+
}
|
|
37
|
+
low = Math.floor(low / 2);
|
|
38
|
+
high = Math.floor(high / 2);
|
|
39
|
+
bit *= 2;
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Hashes a password or salt the way MySQL 4.0 does.
|
|
46
|
+
*
|
|
47
|
+
* @param {Buffer} password - raw bytes, spaces skipped
|
|
48
|
+
* @returns {number[]} two masked halves
|
|
49
|
+
*/
|
|
50
|
+
function mix(password) {
|
|
51
|
+
let nr = 1345345333;
|
|
52
|
+
let add = 7;
|
|
53
|
+
let nr2 = 305419889;
|
|
54
|
+
for (const byte of password) {
|
|
55
|
+
if (byte !== 32 && byte !== 9) {
|
|
56
|
+
const mixed = mask((((nr % 64) + add) * byte) + mask(nr * 256));
|
|
57
|
+
nr = xor(nr, mixed);
|
|
58
|
+
nr2 = mask(nr2 + xor(mask(nr2 * 256), nr));
|
|
59
|
+
add += byte;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return [nr % 2147483648, nr2 % 2147483648];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Scrambles an 8-byte salt with the account password.
|
|
67
|
+
*
|
|
68
|
+
* @param {Buffer} message - server salt
|
|
69
|
+
* @param {Buffer} password - account password
|
|
70
|
+
* @returns {Buffer} 8-byte reply
|
|
71
|
+
*/
|
|
72
|
+
export default function scramble(message, password) {
|
|
73
|
+
const pass = mix(password);
|
|
74
|
+
const salt = mix(message);
|
|
75
|
+
let seed1 = xor(pass[0], salt[0]) % 1073741824;
|
|
76
|
+
let seed2 = xor(pass[1], salt[1]) % 1073741824;
|
|
77
|
+
const out = [];
|
|
78
|
+
const span = 1073741823;
|
|
79
|
+
for (let i = 0; i < message.length; i += 1) {
|
|
80
|
+
seed1 = ((seed1 * 3) + seed2) % span;
|
|
81
|
+
seed2 = (seed1 + seed2 + 33) % span;
|
|
82
|
+
out.push(Math.floor((seed1 / span) * 31) + 64);
|
|
83
|
+
}
|
|
84
|
+
seed1 = ((seed1 * 3) + seed2) % span;
|
|
85
|
+
const extra = Math.floor((seed1 / span) * 31);
|
|
86
|
+
return Buffer.from(out.map((item) => {
|
|
87
|
+
return xor(item, extra);
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { createClient } from '@clickhouse/client';
|
|
3
|
+
import { openPostgresPool as openPool } from '../../persistence/postgresPool.js';
|
|
4
|
+
import metricsState from '../../persistence/clickhouse/metricsState.js';
|
|
5
|
+
import historyMetrics from './historyTelemetryMetrics.js';
|
|
6
|
+
|
|
7
|
+
function responseFor(inputs, path, response) {
|
|
8
|
+
if (!['/live', '/ready', '/status'].includes(path)) {
|
|
9
|
+
response.writeHead(404).end();
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
const queues = inputs.map((input) => { return input.status(); });
|
|
13
|
+
const ready = queues.every((state) => { return state.ready; });
|
|
14
|
+
const live = queues.every((state) => { return state.live; });
|
|
15
|
+
const status = { ...queues[0], ready, live, queues };
|
|
16
|
+
const unhealthy = (path === '/ready' && !ready) || (path === '/live' && !live);
|
|
17
|
+
response.writeHead(unhealthy ? 503 : 200, { 'content-type': 'application/json' }).end(JSON.stringify(status));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function schemaReady(client) {
|
|
21
|
+
const result = await client.query({
|
|
22
|
+
query: "SELECT count() AS n FROM system.tables WHERE database='scada' AND name='metrics'",
|
|
23
|
+
format: 'JSONEachRow'
|
|
24
|
+
});
|
|
25
|
+
if (Number((await result.json())[0]?.n) !== 1) {
|
|
26
|
+
throw new Error('ClickHouse telemetry schema is not initialized');
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function serve(inputs, resources, { port, host }) {
|
|
31
|
+
const server = createServer((req, res) => { responseFor(inputs, req.url, res); });
|
|
32
|
+
let stopping;
|
|
33
|
+
function stop() {
|
|
34
|
+
stopping ??= Promise.allSettled(inputs.map((input) => { return input.stop(); })).then(async (settled) => {
|
|
35
|
+
const closed = await Promise.allSettled(resources.map((close) => { return close(); }));
|
|
36
|
+
server.close();
|
|
37
|
+
const failure = [...settled, ...closed].find((result) => { return result.status === 'rejected'; });
|
|
38
|
+
if (failure) { throw failure.reason; }
|
|
39
|
+
});
|
|
40
|
+
return stopping;
|
|
41
|
+
}
|
|
42
|
+
function onSignal() {
|
|
43
|
+
void stop().catch((error) => {
|
|
44
|
+
process.stderr.write(`${error.message}\n`);
|
|
45
|
+
process.exitCode = 1;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const signals = ['SIGINT', 'SIGTERM'];
|
|
49
|
+
signals.forEach((signal) => { process.once(signal, onSignal); });
|
|
50
|
+
server.once('close', () => { signals.forEach((signal) => { process.off(signal, onSignal); }); });
|
|
51
|
+
server.listen(port, host);
|
|
52
|
+
return stop;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function sinks(client, spec) {
|
|
56
|
+
const base = metricsState(client);
|
|
57
|
+
const pool = spec.history ? openPool(spec.postgres) : undefined;
|
|
58
|
+
const history = spec.history?.(client, pool);
|
|
59
|
+
return { pool, history, metrics: history ? historyMetrics(base, history) : base };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Opens the local ClickHouse ingest queues and their shared readiness endpoint. */
|
|
63
|
+
export default async function edgeTelemetryRuntime(spec) {
|
|
64
|
+
const { clickhouse, queues, broker, createInput, inputOptions, port = 9093, host = '0.0.0.0' } = spec;
|
|
65
|
+
if (!queues.length || queues.some((queue) => { return typeof queue !== 'string' || !queue; }) ||
|
|
66
|
+
new Set(queues).size !== queues.length) {
|
|
67
|
+
throw new Error('Distinct telemetry queue names required');
|
|
68
|
+
}
|
|
69
|
+
const client = createClient({ 'request_timeout': 40000, 'max_open_connections': 2,
|
|
70
|
+
'clickhouse_settings': { 'async_insert': 0, 'insert_deduplicate': 1 }, ...clickhouse });
|
|
71
|
+
const { pool, history, metrics } = sinks(client, spec);
|
|
72
|
+
const inputs = queues.map((queue) => { return createInput(broker, queue, metrics, inputOptions); });
|
|
73
|
+
const stop = serve(inputs, [() => { return client.close(); }, () => { return pool?.end(); }], { port, host });
|
|
74
|
+
try {
|
|
75
|
+
await schemaReady(client);
|
|
76
|
+
await history?.ready();
|
|
77
|
+
await Promise.all(inputs.map((input) => { return input.start(); }));
|
|
78
|
+
} catch (error) {
|
|
79
|
+
await stop().catch(() => { return undefined; });
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
return { stop };
|
|
83
|
+
}
|