@yarkivaev/scada 2.6.42 → 2.7.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/package.json +3 -2
- package/src/application/management/management.js +57 -0
- package/src/bin/scada.js +122 -0
- package/src/infrastructure/management/command.js +18 -0
- package/src/infrastructure/management/inventory.js +63 -0
- package/src/infrastructure/management/kubernetes.js +90 -0
- package/src/infrastructure/management/protocol.js +67 -0
- package/src/infrastructure/management/remote.js +31 -0
- package/src/infrastructure/management/server.js +83 -0
- package/src/infrastructure/management/serverSideRelease.js +25 -0
- package/src/infrastructure/management/systemd.js +49 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yarkivaev/scada",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.0",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
|
|
27
27
|
"supervisor-sink": "./src/bin/supervisor-sink.js",
|
|
28
28
|
"scada-collector": "./src/bin/collector.js",
|
|
29
|
-
"scada-controller": "./src/bin/controller.js"
|
|
29
|
+
"scada-controller": "./src/bin/controller.js",
|
|
30
|
+
"scada": "./src/bin/scada.js"
|
|
30
31
|
},
|
|
31
32
|
"scripts": {
|
|
32
33
|
"test": "mocha --exit 'test/**/test*.js'",
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime port: components(), logs(id, tail), plan(), apply().
|
|
3
|
+
* The application only knows context names and normalized results.
|
|
4
|
+
*/
|
|
5
|
+
export default function management(targets) {
|
|
6
|
+
const applying = new Set();
|
|
7
|
+
|
|
8
|
+
function targetOf(name, forwarded) {
|
|
9
|
+
const target = targets.get(name);
|
|
10
|
+
if (!target) {
|
|
11
|
+
throw new Error('unknown context');
|
|
12
|
+
}
|
|
13
|
+
if (forwarded && target.forwards) {
|
|
14
|
+
throw new Error('remote contexts support one forwarding hop');
|
|
15
|
+
}
|
|
16
|
+
return target;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function describe(name, forwarded) {
|
|
20
|
+
try {
|
|
21
|
+
return { name, components: await targetOf(name, forwarded).adapter.components() };
|
|
22
|
+
} catch (error) {
|
|
23
|
+
return { name, error: error.message };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function apply({ adapter, locks }) {
|
|
28
|
+
if (locks.some((key) => { return applying.has(key); })) {
|
|
29
|
+
throw new Error('apply already in progress for this target');
|
|
30
|
+
}
|
|
31
|
+
locks.forEach((key) => { applying.add(key); });
|
|
32
|
+
try {
|
|
33
|
+
return await adapter.apply();
|
|
34
|
+
} finally {
|
|
35
|
+
locks.forEach((key) => { applying.delete(key); });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function execute({ action, context, component, tail, forwarded }) {
|
|
40
|
+
if (action === 'contexts') {
|
|
41
|
+
return { contexts: Array.from(targets, ([name, target]) => {
|
|
42
|
+
return { name, runtime: target.runtime };
|
|
43
|
+
}) };
|
|
44
|
+
}
|
|
45
|
+
if (action === 'components') {
|
|
46
|
+
const names = context ? [context] : Array.from(targets.keys());
|
|
47
|
+
return { contexts: await Promise.all(names.map((name) => { return describe(name, forwarded); })) };
|
|
48
|
+
}
|
|
49
|
+
const target = targetOf(context, forwarded);
|
|
50
|
+
if (action === 'logs') {
|
|
51
|
+
return { logs: await target.adapter.logs(component, tail) };
|
|
52
|
+
}
|
|
53
|
+
return action === 'plan' ? target.adapter.plan() : apply(target);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { execute };
|
|
57
|
+
}
|
package/src/bin/scada.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import management from '../application/management/management.js';
|
|
5
|
+
import readInventory from '../infrastructure/management/inventory.js';
|
|
6
|
+
import managementServer from '../infrastructure/management/server.js';
|
|
7
|
+
import { request, send } from '../infrastructure/management/protocol.js';
|
|
8
|
+
|
|
9
|
+
const usage = `Usage:
|
|
10
|
+
scada contexts
|
|
11
|
+
scada status [--context NAME]
|
|
12
|
+
scada get components [--context NAME]
|
|
13
|
+
scada logs COMPONENT --context NAME [--tail LINES]
|
|
14
|
+
scada plan --context NAME
|
|
15
|
+
scada apply --context NAME
|
|
16
|
+
|
|
17
|
+
Client options: --server URL (or SCADA_SERVER), --output text|json
|
|
18
|
+
Client credential: SCADA_TOKEN
|
|
19
|
+
|
|
20
|
+
scada serve --config PATH [--host HOST] [--port PORT] [--cert PATH --key PATH]
|
|
21
|
+
|
|
22
|
+
Server credentials: SCADA_TOKEN (read/write), SCADA_READ_TOKEN (read only)
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
const clientOptions = {
|
|
26
|
+
server: { type: 'string' },
|
|
27
|
+
context: { type: 'string' },
|
|
28
|
+
output: { type: 'string', default: 'text' },
|
|
29
|
+
tail: { type: 'string' }
|
|
30
|
+
};
|
|
31
|
+
const serverOptions = {
|
|
32
|
+
config: { type: 'string' },
|
|
33
|
+
host: { type: 'string', default: '127.0.0.1' },
|
|
34
|
+
port: { type: 'string', default: '8080' },
|
|
35
|
+
cert: { type: 'string' },
|
|
36
|
+
key: { type: 'string' }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function commandOf([verb, arg, ...rest], { context, tail }) {
|
|
40
|
+
if (rest.length || (verb === 'get' && arg !== 'components') ||
|
|
41
|
+
(arg !== undefined && !['logs', 'get'].includes(verb)) || (tail !== undefined && verb !== 'logs') ||
|
|
42
|
+
(verb === 'contexts' && context !== undefined)) {
|
|
43
|
+
throw new Error('invalid command arguments; see scada --help');
|
|
44
|
+
}
|
|
45
|
+
const action = ['get', 'status'].includes(verb) ? 'components' : verb;
|
|
46
|
+
const result = request.safeParse({
|
|
47
|
+
action,
|
|
48
|
+
...(context !== undefined && { context }),
|
|
49
|
+
...(verb === 'logs' && { component: arg, tail: tail === undefined ? undefined : Number(tail) })
|
|
50
|
+
});
|
|
51
|
+
if (!result.success) {
|
|
52
|
+
throw new Error('invalid command arguments; see scada --help');
|
|
53
|
+
}
|
|
54
|
+
return result.data;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function textOf({ contexts, changes, logs }) {
|
|
58
|
+
if (contexts) {
|
|
59
|
+
return contexts.flatMap(({ name, runtime, components, error }) => {
|
|
60
|
+
if (components?.length) {
|
|
61
|
+
return components.map(({ id, state }) => { return `${name}\t${id}\t${state}`; });
|
|
62
|
+
}
|
|
63
|
+
return [`${name}\t${runtime ?? error ?? 'no components'}`];
|
|
64
|
+
}).join('\n');
|
|
65
|
+
}
|
|
66
|
+
if (changes) {
|
|
67
|
+
return changes.length ? changes.map(({ id, action }) => { return `${id}\t${action}`; }).join('\n') : 'no changes';
|
|
68
|
+
}
|
|
69
|
+
return logs;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function unhealthy({ error, components }) {
|
|
73
|
+
return Boolean(error) || !components.length || components.some(({ state }) => { return state !== 'ready'; });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function client(args) {
|
|
77
|
+
const { positionals, values } = parseArgs({ args, allowPositionals: true, options: clientOptions });
|
|
78
|
+
const command = commandOf(positionals, values);
|
|
79
|
+
const url = values.server ?? process.env.SCADA_SERVER;
|
|
80
|
+
const { SCADA_TOKEN: token } = process.env;
|
|
81
|
+
if (!url || !token || !['text', 'json'].includes(values.output)) {
|
|
82
|
+
throw new Error('set --server (or SCADA_SERVER), SCADA_TOKEN and use text or json output');
|
|
83
|
+
}
|
|
84
|
+
const result = await send(url, token, command);
|
|
85
|
+
const text = values.output === 'json' ? JSON.stringify(result) : textOf(result);
|
|
86
|
+
process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
|
|
87
|
+
if (positionals[0] === 'status' && result.contexts.some(unhealthy)) {
|
|
88
|
+
process.exitCode = 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function serve(args) {
|
|
93
|
+
const { values: { config, host, port, cert, key } } = parseArgs({ args, options: serverOptions });
|
|
94
|
+
if (!config || Boolean(cert) !== Boolean(key) || !/^\d{1,5}$/u.test(port) || Number(port) > 65535) {
|
|
95
|
+
throw new Error('serve requires --config and accepts --port 0-65535 and a --cert/--key pair');
|
|
96
|
+
}
|
|
97
|
+
const targets = await readInventory(config, process.env);
|
|
98
|
+
const tls = cert ? { cert: await readFile(cert), key: await readFile(key) } : undefined;
|
|
99
|
+
const { address, server } = await managementServer(management(targets), {
|
|
100
|
+
host, port: Number(port), tls, token: process.env.SCADA_TOKEN, readToken: process.env.SCADA_READ_TOKEN
|
|
101
|
+
});
|
|
102
|
+
function close() {
|
|
103
|
+
server.close();
|
|
104
|
+
}
|
|
105
|
+
process.once('SIGTERM', close);
|
|
106
|
+
process.once('SIGINT', close);
|
|
107
|
+
process.stdout.write(`${address}\n`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const args = process.argv.slice(2);
|
|
111
|
+
try {
|
|
112
|
+
if (args.length === 0 || args.includes('--help') || args[0] === 'help') {
|
|
113
|
+
process.stdout.write(usage);
|
|
114
|
+
} else if (args[0] === 'serve') {
|
|
115
|
+
await serve(args.slice(1));
|
|
116
|
+
} else {
|
|
117
|
+
await client(args);
|
|
118
|
+
}
|
|
119
|
+
} catch (error) {
|
|
120
|
+
process.stderr.write(`scada: ${error.message}\n`);
|
|
121
|
+
process.exitCode = 1;
|
|
122
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Invoke a trusted binary without a shell. Keep subprocess diagnostics out of
|
|
5
|
+
* API responses because tools may include runtime credentials or rendered values.
|
|
6
|
+
*/
|
|
7
|
+
export default function command(binary, args, timeout = 30000, env = process.env) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
execFile(binary, args, { timeout, env, maxBuffer: 4 * 1024 * 1024 },
|
|
10
|
+
(error, stdout) => {
|
|
11
|
+
if (error) {
|
|
12
|
+
reject(new Error(`${binary} ${args[0]} failed (${error.code ?? error.signal ?? 'runtime error'})`));
|
|
13
|
+
} else {
|
|
14
|
+
resolve(stdout);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Load the host-owned inventory and compose its runtime adapters. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import kubernetes from './kubernetes.js';
|
|
6
|
+
import systemd from './systemd.js';
|
|
7
|
+
import remote from './remote.js';
|
|
8
|
+
import { contextName, urlOf } from './protocol.js';
|
|
9
|
+
|
|
10
|
+
const name = z.string().regex(/^[a-z0-9][a-z0-9.-]{0,62}$/u);
|
|
11
|
+
const unit = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.@:-]*\.service$/u);
|
|
12
|
+
const target = z.discriminatedUnion('runtime', [
|
|
13
|
+
z.strictObject({
|
|
14
|
+
runtime: z.literal('kubernetes'), kubeContext: z.string().min(1), namespace: name, release: name,
|
|
15
|
+
values: z.string().min(1).optional(), releasePlan: z.string().min(1).optional()
|
|
16
|
+
}).refine(({ values, releasePlan }) => { return !values || !releasePlan; }),
|
|
17
|
+
z.strictObject({ runtime: z.literal('systemd'), units: z.record(unit, z.literal('running')) }),
|
|
18
|
+
z.strictObject({
|
|
19
|
+
runtime: z.literal('remote'), server: z.string(), context: contextName,
|
|
20
|
+
tokenEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/u)
|
|
21
|
+
})
|
|
22
|
+
]);
|
|
23
|
+
const inventory = z.strictObject({ contexts: z.record(contextName, target) });
|
|
24
|
+
|
|
25
|
+
function adapter(config, directory, env) {
|
|
26
|
+
if (config.runtime === 'systemd') {
|
|
27
|
+
return systemd(config);
|
|
28
|
+
}
|
|
29
|
+
if (config.runtime === 'kubernetes') {
|
|
30
|
+
return kubernetes({
|
|
31
|
+
...config, values: config.values && resolve(directory, config.values),
|
|
32
|
+
releasePlan: config.releasePlan && resolve(directory, config.releasePlan)
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const token = env[config.tokenEnv];
|
|
36
|
+
if (!token) {
|
|
37
|
+
throw new Error(`missing credential ${config.tokenEnv}`);
|
|
38
|
+
}
|
|
39
|
+
return remote({ ...config, token });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function writeLocks(config) {
|
|
43
|
+
if (config.runtime === 'systemd') {
|
|
44
|
+
return Object.keys(config.units).map((id) => { return `systemd:${id}`; });
|
|
45
|
+
}
|
|
46
|
+
if (config.runtime === 'kubernetes') {
|
|
47
|
+
return [JSON.stringify(['kubernetes', config.kubeContext, config.namespace])];
|
|
48
|
+
}
|
|
49
|
+
return [JSON.stringify(['remote', urlOf(config.server).origin, config.context])];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default async function readInventory(path, env) {
|
|
53
|
+
const result = inventory.safeParse(JSON.parse(await readFile(path, 'utf8')));
|
|
54
|
+
if (!result.success) {
|
|
55
|
+
throw new Error(`invalid inventory at ${result.error.issues[0].path.join('.') || 'root'}`);
|
|
56
|
+
}
|
|
57
|
+
return new Map(Object.entries(result.data.contexts).map(([id, config]) => {
|
|
58
|
+
return [id, {
|
|
59
|
+
runtime: config.runtime, forwards: config.runtime === 'remote', locks: writeLocks(config),
|
|
60
|
+
adapter: adapter(config, dirname(resolve(path)), env)
|
|
61
|
+
}];
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Kubernetes inspection and reconciliation for one configured release. */
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import command from './command.js';
|
|
4
|
+
|
|
5
|
+
const chart = fileURLToPath(new URL('../../../charts/scada', import.meta.url));
|
|
6
|
+
const worker = fileURLToPath(new URL('./serverSideRelease.js', import.meta.url));
|
|
7
|
+
const workloads = 'deployments,statefulsets,daemonsets,jobs';
|
|
8
|
+
|
|
9
|
+
function jobState(status) {
|
|
10
|
+
function active(type) {
|
|
11
|
+
return status.conditions?.some((item) => {
|
|
12
|
+
return item.type === type && item.status === 'True';
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
if (active('Failed')) {
|
|
16
|
+
return 'failed';
|
|
17
|
+
}
|
|
18
|
+
return active('Complete') ? 'ready' : 'pending';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function workloadState({ kind, metadata, spec = {}, status = {} }) {
|
|
22
|
+
if (kind === 'Job') {
|
|
23
|
+
return jobState(status);
|
|
24
|
+
}
|
|
25
|
+
if ((status.observedGeneration ?? 0) < metadata.generation) {
|
|
26
|
+
return 'pending';
|
|
27
|
+
}
|
|
28
|
+
const daemon = kind === 'DaemonSet';
|
|
29
|
+
const desired = daemon ? status.desiredNumberScheduled : spec.replicas ?? 1;
|
|
30
|
+
const available = daemon ? status.numberAvailable : status.availableReplicas ?? status.readyReplicas;
|
|
31
|
+
if (desired === 0) {
|
|
32
|
+
return 'stopped';
|
|
33
|
+
}
|
|
34
|
+
const updated = daemon ? status.updatedNumberScheduled : status.updatedReplicas;
|
|
35
|
+
if (kind === 'Deployment' && (status.replicas ?? 0) > (updated ?? 0)) {
|
|
36
|
+
return 'pending';
|
|
37
|
+
}
|
|
38
|
+
const complete = (available ?? 0) >= desired && (updated ?? 0) >= desired;
|
|
39
|
+
return complete ? 'ready' : 'pending';
|
|
40
|
+
}
|
|
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]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
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) };
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function logs(component, tail) {
|
|
56
|
+
if (!(await components()).some(({ id }) => { return id === component; })) {
|
|
57
|
+
throw new Error('unknown component');
|
|
58
|
+
}
|
|
59
|
+
return kubectl('logs', [component, `--tail=${tail}`, '--all-containers=true']);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function helm(options, timeout) {
|
|
63
|
+
if (!values) {
|
|
64
|
+
throw new Error('this context has no desired release values');
|
|
65
|
+
}
|
|
66
|
+
// Even with --kube-context, Helm honors environment overrides for its API server and TLS settings.
|
|
67
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => {
|
|
68
|
+
return !key.startsWith('HELM_KUBE');
|
|
69
|
+
}));
|
|
70
|
+
await command('helm', ['upgrade', '--install', release, chart, `--kube-context=${kubeContext}`,
|
|
71
|
+
`--namespace=${namespace}`, `--values=${values}`, '--timeout=5m', ...options], timeout, env);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function reconcile(action, options, timeout) {
|
|
75
|
+
if (releasePlan) {
|
|
76
|
+
// The executor bounds each subprocess. Wait for the worker to settle before releasing the write lock.
|
|
77
|
+
await command(process.execPath, [worker, action, releasePlan, kubeContext, namespace, release], 0)
|
|
78
|
+
.catch(() => { throw new Error('Kubernetes server-side release failed'); });
|
|
79
|
+
} else {
|
|
80
|
+
await helm(options, timeout);
|
|
81
|
+
}
|
|
82
|
+
return { changes: [{ id: release, action: 'reconcile' }] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
components, logs,
|
|
87
|
+
plan() { return reconcile('check', ['--dry-run=server', '--hide-secret'], 30000); },
|
|
88
|
+
apply() { return reconcile('apply', ['--atomic'], 660000); }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** Versioned management protocol shared by the server, CLI and forwarding runtime. */
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
export const endpoint = '/api/management/v1/command';
|
|
5
|
+
export const contextName = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/u);
|
|
6
|
+
const scope = { forwarded: z.boolean().optional() };
|
|
7
|
+
export const request = z.discriminatedUnion('action', [
|
|
8
|
+
z.strictObject({ action: z.literal('contexts') }),
|
|
9
|
+
z.strictObject({ action: z.literal('components'), context: contextName.optional(), ...scope }),
|
|
10
|
+
z.strictObject({
|
|
11
|
+
action: z.literal('logs'), context: contextName, ...scope,
|
|
12
|
+
component: z.string().min(1).max(300), tail: z.int().min(1).max(1000).default(100)
|
|
13
|
+
}),
|
|
14
|
+
z.strictObject({ action: z.literal('plan'), context: contextName, ...scope }),
|
|
15
|
+
z.strictObject({ action: z.literal('apply'), context: contextName, ...scope })
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
export function loopback(host) {
|
|
19
|
+
return ['127.0.0.1', '::1', '[::1]'].includes(host);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function urlOf(value) {
|
|
23
|
+
const url = new URL(value);
|
|
24
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback(url.hostname))) ||
|
|
25
|
+
url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
|
26
|
+
throw new Error('management server must be an HTTPS origin (HTTP is allowed on loopback)');
|
|
27
|
+
}
|
|
28
|
+
if (url.protocol === 'https:' && process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0') {
|
|
29
|
+
throw new Error('HTTPS management requires TLS certificate verification');
|
|
30
|
+
}
|
|
31
|
+
return new URL(endpoint, url);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const component = z.object({
|
|
35
|
+
id: z.string(), state: z.enum(['ready', 'stopped', 'pending', 'failed'])
|
|
36
|
+
});
|
|
37
|
+
const changes = z.object({ changes: z.array(z.object({ id: z.string(), action: z.string() })) });
|
|
38
|
+
const results = {
|
|
39
|
+
contexts: z.object({ contexts: z.array(z.object({ name: contextName, runtime: z.string() })) }),
|
|
40
|
+
components: z.object({ contexts: z.array(z.union([
|
|
41
|
+
z.object({ name: contextName, components: z.array(component) }),
|
|
42
|
+
z.object({ name: contextName, error: z.string() })
|
|
43
|
+
])) }),
|
|
44
|
+
logs: z.object({ logs: z.string() }),
|
|
45
|
+
plan: changes,
|
|
46
|
+
apply: changes
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export async function send(server, token, command) {
|
|
50
|
+
const url = urlOf(server);
|
|
51
|
+
const response = await fetch(url, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
54
|
+
body: JSON.stringify(command),
|
|
55
|
+
redirect: 'error',
|
|
56
|
+
signal: AbortSignal.timeout(command.action === 'apply' ? 720000 : 90000)
|
|
57
|
+
});
|
|
58
|
+
const data = await response.json().catch(() => { return null; });
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
throw new Error(typeof data?.error === 'string' ? data.error : `management HTTP ${response.status}`);
|
|
61
|
+
}
|
|
62
|
+
const result = results[command.action].safeParse(data);
|
|
63
|
+
if (!result.success) {
|
|
64
|
+
throw new Error('invalid response from management server');
|
|
65
|
+
}
|
|
66
|
+
return result.data;
|
|
67
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Expose a concrete context on another management endpoint as a local runtime. */
|
|
2
|
+
import { send } from './protocol.js';
|
|
3
|
+
|
|
4
|
+
export default function remote({ server, token, context }) {
|
|
5
|
+
function request(action, options = {}) {
|
|
6
|
+
return send(server, token, { action, context, forwarded: true, ...options });
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async function components() {
|
|
10
|
+
const { contexts } = await request('components');
|
|
11
|
+
const target = contexts.find(({ name }) => { return name === context; });
|
|
12
|
+
if (!target) {
|
|
13
|
+
throw new Error('remote server did not return the requested context');
|
|
14
|
+
}
|
|
15
|
+
if (target.error) {
|
|
16
|
+
throw new Error(target.error);
|
|
17
|
+
}
|
|
18
|
+
return target.components;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function logs(component, tail) {
|
|
22
|
+
const result = await request('logs', { component, tail });
|
|
23
|
+
return result.logs;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
components, logs,
|
|
28
|
+
plan() { return request('plan'); },
|
|
29
|
+
apply() { return request('apply'); }
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/** Authenticated HTTP transport for the management application. */
|
|
2
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { createServer as httpServer } from 'node:http';
|
|
5
|
+
import { createServer as httpsServer } from 'node:https';
|
|
6
|
+
import { endpoint, loopback, request } from './protocol.js';
|
|
7
|
+
|
|
8
|
+
const maxBodyBytes = 8192;
|
|
9
|
+
|
|
10
|
+
function matches(value, token) {
|
|
11
|
+
const actual = Buffer.from(value ?? '');
|
|
12
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
13
|
+
return Boolean(token) && actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function reply(res, status, data) {
|
|
17
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
18
|
+
res.end(JSON.stringify(data));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function readCommand(req) {
|
|
22
|
+
const chunks = [];
|
|
23
|
+
let bytes = 0;
|
|
24
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
25
|
+
bytes += chunk.length;
|
|
26
|
+
if (bytes > maxBodyBytes) {
|
|
27
|
+
req.resume();
|
|
28
|
+
throw new Error('request too large');
|
|
29
|
+
}
|
|
30
|
+
chunks.push(chunk);
|
|
31
|
+
}
|
|
32
|
+
return request.parse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function execute(res, service, command) {
|
|
36
|
+
try {
|
|
37
|
+
reply(res, 200, await service.execute(command));
|
|
38
|
+
} catch (error) {
|
|
39
|
+
reply(res, 422, { error: error.message });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function accept(req, res, service, credentials) {
|
|
44
|
+
if (req.url !== endpoint || req.method !== 'POST') {
|
|
45
|
+
reply(res, 404, { error: 'unknown management endpoint' });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const admin = matches(req.headers.authorization, credentials.token);
|
|
49
|
+
if (!admin && !matches(req.headers.authorization, credentials.readToken)) {
|
|
50
|
+
reply(res, 401, { error: 'unauthorized' });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const command = await readCommand(req).catch(() => { return null; });
|
|
54
|
+
if (!command) {
|
|
55
|
+
reply(res, 400, { error: 'invalid management command' });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (command.action === 'apply' && !admin) {
|
|
59
|
+
reply(res, 403, { error: 'forbidden' });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
await execute(res, service, command);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export default async function managementServer(service, { host, port, tls, token, readToken }) {
|
|
66
|
+
if (!tls && !loopback(host)) {
|
|
67
|
+
throw new Error('a non-loopback listener requires --cert and --key');
|
|
68
|
+
}
|
|
69
|
+
if (!token && !readToken) {
|
|
70
|
+
throw new Error('set SCADA_TOKEN or SCADA_READ_TOKEN for the management server');
|
|
71
|
+
}
|
|
72
|
+
if (token && token === readToken) {
|
|
73
|
+
throw new Error('read and write credentials must differ');
|
|
74
|
+
}
|
|
75
|
+
const options = { requestTimeout: 15000, headersTimeout: 10000 };
|
|
76
|
+
const server = tls ? httpsServer({ ...options, ...tls }) : httpServer(options);
|
|
77
|
+
server.on('request', (req, res) => { void accept(req, res, service, { token, readToken }); });
|
|
78
|
+
server.listen(port, host);
|
|
79
|
+
await once(server, 'listening');
|
|
80
|
+
const { address } = server.address();
|
|
81
|
+
const hostname = address.includes(':') ? `[${address}]` : address;
|
|
82
|
+
return { server, address: `${tls ? 'https' : 'http'}://${hostname}:${server.address().port}` };
|
|
83
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Run the synchronous deployment executor outside the HTTP process.
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import executeRelease from '../deploy/executeRelease.js';
|
|
6
|
+
|
|
7
|
+
const [, , action, planPath, context, namespace, release] = process.argv;
|
|
8
|
+
const { values, fieldManager, prerequisites, workloads, retirements, podsAbsentBeforeApply } =
|
|
9
|
+
JSON.parse(readFileSync(planPath, 'utf8'));
|
|
10
|
+
const chart = fileURLToPath(new URL('../../../charts/scada', import.meta.url));
|
|
11
|
+
|
|
12
|
+
function execute(binary, args, options) {
|
|
13
|
+
const stdout = !options.stdio || options.stdio[1] === 'pipe' ? 'pipe' : 'ignore';
|
|
14
|
+
return execFileSync(binary, args, {
|
|
15
|
+
...options, stdio: ['pipe', stdout, 'ignore'], maxBuffer: 4 * 1024 * 1024,
|
|
16
|
+
timeout: action === 'check' ? 30000 : 310000, killSignal: 'SIGKILL'
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
try {
|
|
21
|
+
executeRelease({ chart, release, context, namespace, values, fieldManager, prerequisites,
|
|
22
|
+
workloads, retirements, podsAbsentBeforeApply }, action, execute);
|
|
23
|
+
} catch {
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Read and start explicitly managed systemd services on this host. */
|
|
2
|
+
import command from './command.js';
|
|
3
|
+
|
|
4
|
+
function unitState(text) {
|
|
5
|
+
const active = /^ActiveState=(?<state>[^\n]+)$/mu.exec(text)?.groups.state;
|
|
6
|
+
const load = /^LoadState=(?<state>[^\n]+)$/mu.exec(text)?.groups.state;
|
|
7
|
+
if (load !== 'loaded') {
|
|
8
|
+
return 'failed';
|
|
9
|
+
}
|
|
10
|
+
const states = new Map([['active', 'ready'], ['inactive', 'stopped'], ['failed', 'failed']]);
|
|
11
|
+
return states.get(active) ?? 'pending';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export default function systemd({ units }) {
|
|
15
|
+
function components() {
|
|
16
|
+
return Promise.all(Object.keys(units).map(async (id) => {
|
|
17
|
+
const text = await command('systemctl', ['show', '--property=LoadState,ActiveState', '--', id]);
|
|
18
|
+
return { id, state: unitState(text) };
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function logs(id, tail) {
|
|
23
|
+
if (!Object.hasOwn(units, id)) {
|
|
24
|
+
throw new Error('unknown component');
|
|
25
|
+
}
|
|
26
|
+
return command('journalctl', ['--no-pager', '--unit', id, '--lines', String(tail)]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function plan() {
|
|
30
|
+
const changes = (await components()).flatMap(({ id, state }) => {
|
|
31
|
+
if (units[id] === 'running' && state !== 'ready') {
|
|
32
|
+
return [{ id, action: 'start' }];
|
|
33
|
+
}
|
|
34
|
+
return [];
|
|
35
|
+
});
|
|
36
|
+
return { changes };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function apply() {
|
|
40
|
+
const result = await plan();
|
|
41
|
+
const ids = result.changes.map(({ id }) => { return id; });
|
|
42
|
+
if (ids.length > 0) {
|
|
43
|
+
await command('systemctl', ['start', '--', ...ids], 300000);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return { components, logs, plan, apply };
|
|
49
|
+
}
|