mapsource-node 0.1.1 → 0.1.3
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/README.md +37 -14
- package/bin/mapsource-node.mjs +1 -2
- package/package.json +1 -1
- package/src/capability.mjs +2 -1
- package/src/commands.mjs +115 -50
- package/src/enrollment-screen-test.ts +64 -0
- package/src/enrollment-screen.ts +249 -0
- package/src/index.ts +15 -3
- package/src/interface.ts +49 -20
- package/src/service-management.mjs +172 -0
- package/src/service-screen-test.ts +41 -0
- package/src/service-screen.ts +101 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Mapsource Node provides a terminal dashboard for Mapsource infrastructure and
|
|
|
4
4
|
an enrollment client for compatible Linux read-engine hosts.
|
|
5
5
|
|
|
6
6
|
```sh
|
|
7
|
-
npm install --global mapsource-node
|
|
7
|
+
npm install --global mapsource-node
|
|
8
8
|
mapsource-node
|
|
9
9
|
```
|
|
10
10
|
|
|
@@ -14,21 +14,44 @@ engine constraints, pass `--engine-strict=false` when installing this release.
|
|
|
14
14
|
|
|
15
15
|
Use `mapsource-node --json` for a read-only telemetry snapshot. The Services
|
|
16
16
|
tab shows recent queue depth and latency when the local controller measures
|
|
17
|
-
them.
|
|
18
|
-
authority to see the available service profiles.
|
|
17
|
+
them.
|
|
19
18
|
|
|
20
|
-
|
|
21
|
-
mapsource-node invite --node new-node --services search,routing --out ./sync-key
|
|
22
|
-
mapsource-node setup --key-file ./sync-key
|
|
23
|
-
mapsource-node status
|
|
24
|
-
```
|
|
19
|
+
## Enroll a node
|
|
25
20
|
|
|
26
|
-
|
|
27
|
-
the
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
the
|
|
21
|
+
1. On Primary, open `mapsource-node` and choose **Enrollment → Create sync key**.
|
|
22
|
+
Enter the new node's name. Select the services it may install or leave the
|
|
23
|
+
selection empty to allow every service currently offered. Admins can also
|
|
24
|
+
create a key under **Enrollment** in the Mapsource site dashboard.
|
|
25
|
+
2. On the new host, install the package and open `mapsource-node`. The Enrollment
|
|
26
|
+
screen opens automatically. Paste the short-lived key to see the offered
|
|
27
|
+
services and local disk usage.
|
|
28
|
+
3. Choose the services to install, review available storage and required space,
|
|
29
|
+
then confirm. Run the console as the intended node service account with
|
|
30
|
+
noninteractive sudo. If the session is interrupted, reopen the console and
|
|
31
|
+
use **Resume enrollment**. If the claim is pending, paste the original key.
|
|
32
|
+
4. Watch the status screen for the registered Cloudflare peer endpoint, dataset
|
|
33
|
+
synchronization, and engine verification. Serving traffic requires separate
|
|
34
|
+
fleet admission. Use `disable` or `retire` to preview the services affected by
|
|
35
|
+
either operation.
|
|
32
36
|
|
|
33
37
|
Use `mapsource-node --help` for the CLI and [RELEASING.md](RELEASING.md) for
|
|
34
38
|
publishing.
|
|
39
|
+
# Local intelligence services
|
|
40
|
+
|
|
41
|
+
Open **Services** in `mapsource-node` to inspect installed intelligence
|
|
42
|
+
workers and the selected worker's active dataset path. Use **E** to start and
|
|
43
|
+
enable the systemd unit at boot or to stop and disable it. Disable retains the
|
|
44
|
+
dataset. Use **M** to enter a directory on another mounted filesystem and
|
|
45
|
+
confirm the move. The directory must already exist and be writable by the
|
|
46
|
+
service user, with enough free space for the copy and filesystem reserve.
|
|
47
|
+
|
|
48
|
+
The move verifies the destination against the source checksum and restarts
|
|
49
|
+
an active worker. A failed readiness check restores the prior settings.
|
|
50
|
+
The original copy remains available for rollback. For a stopped unit, the
|
|
51
|
+
copy is verified and the next start uses the new path.
|
|
52
|
+
|
|
53
|
+
`mapsource-node retire --services ID[,ID]` previews reclaimable enrollment
|
|
54
|
+
data. Adding `--apply` requires an interactive review, a yes confirmation
|
|
55
|
+
and the exact retirement phrase before requesting deletion. The enrollment
|
|
56
|
+
authority also checks for a current preview and confirms there is a verified
|
|
57
|
+
surviving source copy.
|
package/bin/mapsource-node.mjs
CHANGED
|
@@ -11,7 +11,6 @@ const [command, ...args] = process.argv.slice(2);
|
|
|
11
11
|
try {
|
|
12
12
|
if (command === "--version" && !args.length) console.log(`mapsource-node ${pkg.version}`);
|
|
13
13
|
else if (command === undefined || command === "--self-test" || command === "--json") {
|
|
14
|
-
if (command === undefined && await (await import("../src/commands.mjs")).firstRun()) process.exit(0);
|
|
15
14
|
const candidates = { x64: "@oven/bun-linux-x64-baseline", arm64: "@oven/bun-linux-aarch64" };
|
|
16
15
|
const platform = candidates[process.arch];
|
|
17
16
|
if (process.platform !== "linux" || !platform) throw new Error("The terminal interface requires Linux x64 or ARM64.");
|
|
@@ -19,7 +18,7 @@ try {
|
|
|
19
18
|
const entrypoint = fileURLToPath(new URL("../src/index.ts", import.meta.url));
|
|
20
19
|
const child = spawn(executable, ["--no-env-file", entrypoint, ...process.argv.slice(2)], {
|
|
21
20
|
stdio: "inherit",
|
|
22
|
-
env: { ...process.env, OPENTUI_LIBC: "glibc", MAPSOURCE_NODE_BUILD: pkg.version },
|
|
21
|
+
env: { ...process.env, OPENTUI_LIBC: "glibc", MAPSOURCE_NODE_BUILD: pkg.version, MAPSOURCE_NODE_BOOTSTRAP_EXEC: process.execPath },
|
|
23
22
|
});
|
|
24
23
|
const signalChild = () => child.kill("SIGTERM");
|
|
25
24
|
process.once("SIGTERM", signalChild);
|
package/package.json
CHANGED
package/src/capability.mjs
CHANGED
|
@@ -51,7 +51,8 @@ export async function measureHost(targets) {
|
|
|
51
51
|
for (const [id, target] of Object.entries(targets)) {
|
|
52
52
|
const directory = await nearestMount(target);
|
|
53
53
|
const [volume, metadata] = await Promise.all([statfs(directory), stat(directory)]);
|
|
54
|
-
mounts[id] = { path: target, device: metadata.dev, bytes: volume.bavail * volume.bsize,
|
|
54
|
+
mounts[id] = { path: target, device: metadata.dev, bytes: volume.bavail * volume.bsize,
|
|
55
|
+
percentUsed: volume.blocks > 0 ? Math.round(100 * (volume.blocks - volume.bfree) / volume.blocks) : null, inodes: volume.ffree };
|
|
55
56
|
}
|
|
56
57
|
const memory = /^MemAvailable:\s+(\d+) kB$/m.exec(await readFile("/proc/meminfo", "utf8").catch(() => ""));
|
|
57
58
|
const os = /^ID="?([a-z0-9-]+)"?$/m.exec(await readFile("/etc/os-release", "utf8").catch(() => ""))?.[1] ?? "unknown";
|
package/src/commands.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
2
|
import { access, mkdir, open, rm } from "node:fs/promises";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { createInterface } from "node:readline/promises";
|
|
6
|
-
import { parseArgs } from "node:util";
|
|
6
|
+
import { parseArgs, promisify } from "node:util";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { measureHost, planServices, validateCatalog } from "./capability.mjs";
|
|
9
|
+
import { installedServices, moveServiceDataset, setServiceEnabled } from "./service-management.mjs";
|
|
9
10
|
import { catalogDigest, enrollmentRequest, localIdentity, operatorRequest, readEnrollment, readInvitation, saveEnrollment, secretInput } from "./enrollment.mjs";
|
|
10
11
|
|
|
11
12
|
const mirrorRoot = "/srv/mapsource-mirror";
|
|
@@ -18,12 +19,23 @@ const show = value => console.log(JSON.stringify(value, null, 2));
|
|
|
18
19
|
const servicesOption = { services: { type: "string" } };
|
|
19
20
|
const flags = (args, options) => parseArgs({ args, options }).values;
|
|
20
21
|
const ids = value => value.split(",").map(item => item.trim()).filter(Boolean);
|
|
22
|
+
const run = promisify(execFile);
|
|
23
|
+
export const localCapacity = () => measureHost(targets);
|
|
24
|
+
export const savedEnrollment = () => readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
25
|
+
export async function hasMesh() {
|
|
26
|
+
const paths = ["/etc/mapsource-cd/node-v5.json", "/etc/systemd/system/mapsource-mesh-tunnel.service"];
|
|
27
|
+
return (await Promise.all(paths.map(file => access(file).then(() => true, () => false)))).some(Boolean);
|
|
28
|
+
}
|
|
21
29
|
const usage = `Mapsource Node
|
|
22
30
|
|
|
23
31
|
mapsource-node Open the terminal dashboard
|
|
24
32
|
mapsource-node --json Read current fleet telemetry
|
|
25
33
|
mapsource-node services List profiles offered by the local authority
|
|
26
|
-
mapsource-node
|
|
34
|
+
mapsource-node local-services List installed intelligence units and dataset locations
|
|
35
|
+
mapsource-node service enable ID Enable and start one local unit
|
|
36
|
+
mapsource-node service disable ID Disable and stop one local unit
|
|
37
|
+
mapsource-node service move ID DIRECTORY Copy, verify and switch an installed dataset
|
|
38
|
+
mapsource-node invite --node NAME [--services ID[,ID]] [--out FILE]
|
|
27
39
|
mapsource-node revoke --node NAME Revoke an unused sync key
|
|
28
40
|
mapsource-node setup [--key-file FILE | --key-stdin] [--services ID[,ID]] [--apply]
|
|
29
41
|
mapsource-node resume Resume an authorized enrollment and deploy
|
|
@@ -65,8 +77,14 @@ async function localMesh(configuration) {
|
|
|
65
77
|
} finally { await file.close(); }
|
|
66
78
|
// Only the reviewed, npm-pinned bootstrap code is executable. The authority
|
|
67
79
|
// supplies the scoped connector credential and node identity as data.
|
|
68
|
-
const text =
|
|
69
|
-
|
|
80
|
+
const text = await new Promise((resolve, reject) => {
|
|
81
|
+
const node = process.env.MAPSOURCE_NODE_BOOTSTRAP_EXEC || process.execPath;
|
|
82
|
+
const child = execFile(node, [bootstrap, "--execute"], { encoding: "utf8", timeout: 180_000 }, (error, stdout) => {
|
|
83
|
+
if (error) reject(new Error("Local peer setup failed. Check the service user's sudo access and the SSH and tunnel services."));
|
|
84
|
+
else resolve(stdout);
|
|
85
|
+
});
|
|
86
|
+
child.stdin?.on("error", () => {});
|
|
87
|
+
child.stdin?.end(JSON.stringify(payload));
|
|
70
88
|
});
|
|
71
89
|
const installed = JSON.parse(text.trim().split("\n").at(-1));
|
|
72
90
|
if (installed.installed !== true || installed.node !== payload.node || installed.machineId !== payload.machineId) {
|
|
@@ -76,68 +94,107 @@ async function localMesh(configuration) {
|
|
|
76
94
|
}
|
|
77
95
|
|
|
78
96
|
async function localPrivileges(services, catalog) {
|
|
79
|
-
|
|
97
|
+
await run("/usr/bin/sudo", ["-n", "true"], { timeout: 5000 }).catch(() => { throw new Error("Setup requires noninteractive sudo for this service user."); });
|
|
80
98
|
if (catalog.services.some(service => services.includes(service.id) && service.tools.includes("docker"))) {
|
|
81
|
-
|
|
82
|
-
|
|
99
|
+
await run("docker", ["info", "--format", "{{.ServerVersion}}"], { timeout: 8000 }).catch(() => { throw new Error("Setup requires access to the running Docker daemon."); });
|
|
100
|
+
await run("docker", ["compose", "version", "--short"], { timeout: 8000 }).catch(() => { throw new Error("Setup requires Docker Compose."); });
|
|
83
101
|
}
|
|
84
102
|
}
|
|
85
103
|
|
|
86
|
-
async function
|
|
104
|
+
async function authorizedCall(saved) {
|
|
105
|
+
const identity = await localIdentity();
|
|
106
|
+
return (operation, value = {}) => enrollmentRequest(saved.endpoint, operation, { node: saved.node, ...value }, { identity });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function enrollmentStatus() {
|
|
110
|
+
const saved = await readEnrollment();
|
|
111
|
+
if (saved.pendingClaim) return { node: saved.node, phase: "awaiting-key" };
|
|
112
|
+
return (await authorizedCall(saved))("status");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {(message: string) => void} onStage */
|
|
116
|
+
export async function resume(onStage = (_message) => {}) {
|
|
87
117
|
const saved = await readEnrollment();
|
|
88
118
|
if (saved.pendingClaim) throw new Error("Re-enter the same sync key with setup to resume the authorized selection.");
|
|
89
|
-
const
|
|
90
|
-
const call = (operation, value = {}) => enrollmentRequest(saved.endpoint, operation, { node: saved.node, ...value }, { identity });
|
|
119
|
+
const call = await authorizedCall(saved);
|
|
91
120
|
let result = await call("status");
|
|
92
121
|
if (["authorized", "tunnel-issued"].includes(result.phase)) {
|
|
122
|
+
onStage("Installing the named Cloudflare connector…");
|
|
93
123
|
const peer = await call("bootstrap");
|
|
94
124
|
const identityProof = await localMesh(peer);
|
|
125
|
+
onStage("Verifying the node through its tunnel…");
|
|
95
126
|
result = await call("register", identityProof);
|
|
96
127
|
}
|
|
97
128
|
if (["registered", "failed"].includes(result.phase)) {
|
|
98
129
|
const host = await measureHost(targets);
|
|
99
130
|
const plan = planServices(saved.catalog, host, saved.services);
|
|
100
|
-
if (!plan.eligible)
|
|
131
|
+
if (!plan.eligible) throw new Error(plan.errors.join(" "));
|
|
101
132
|
await localPrivileges(saved.services, saved.catalog);
|
|
133
|
+
onStage("Requesting the dataset sync…");
|
|
102
134
|
result = await call("deploy");
|
|
103
135
|
}
|
|
104
136
|
return result;
|
|
105
137
|
}
|
|
106
138
|
|
|
139
|
+
export async function inspectSyncKey(raw) {
|
|
140
|
+
const invitation = readInvitation(raw), saved = await savedEnrollment();
|
|
141
|
+
if (saved && !saved.pendingClaim) throw new Error("This node already has an enrollment. Open its status to continue.");
|
|
142
|
+
if (saved && saved.endpoint !== invitation.endpoint) throw new Error("Resume with the original sync key.");
|
|
143
|
+
const grant = saved
|
|
144
|
+
? { node: saved.node, allowed: saved.services, catalog: saved.catalog }
|
|
145
|
+
: await enrollmentRequest(invitation.endpoint, "catalog", {}, { invitation });
|
|
146
|
+
validateCatalog(grant.catalog);
|
|
147
|
+
const host = await measureHost(targets);
|
|
148
|
+
const services = grant.catalog.services.filter(service => grant.allowed.includes(service.id));
|
|
149
|
+
return { invitation, saved, grant, host, services };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** @param {(message: string) => void} onStage */
|
|
153
|
+
export async function applySyncKey(review, selection, onStage = (_message) => {}) {
|
|
154
|
+
const { invitation, grant } = review;
|
|
155
|
+
const services = [...new Set(selection)].sort();
|
|
156
|
+
if (!services.length || !services.every(id => grant.allowed.includes(id))) throw new Error("Select services permitted by this sync key.");
|
|
157
|
+
const current = await savedEnrollment();
|
|
158
|
+
if (current && !current.pendingClaim) return resume(onStage);
|
|
159
|
+
if (current && (current.node !== grant.node || current.endpoint !== invitation.endpoint ||
|
|
160
|
+
JSON.stringify(current.services) !== JSON.stringify(services))) throw new Error("Resume the pending enrollment with its original selection.");
|
|
161
|
+
const plan = planServices(grant.catalog, await measureHost(targets), services);
|
|
162
|
+
if (!plan.eligible) throw new Error(plan.errors.join(" "));
|
|
163
|
+
await localPrivileges(services, grant.catalog);
|
|
164
|
+
const saved = { node: grant.node, endpoint: invitation.endpoint, services, catalog: grant.catalog, pendingClaim: true };
|
|
165
|
+
await saveEnrollment(saved);
|
|
166
|
+
onStage("Claiming the sync key…");
|
|
167
|
+
const identity = await localIdentity();
|
|
168
|
+
const receipt = await enrollmentRequest(saved.endpoint, "claim", {
|
|
169
|
+
machineId: identity.machineId, username: identity.username, services, catalogDigest: catalogDigest(saved.catalog),
|
|
170
|
+
}, { invitation, identity });
|
|
171
|
+
if (receipt.node !== saved.node) throw new Error("The claimed identity does not match the enrollment.");
|
|
172
|
+
await saveEnrollment({ ...saved, pendingClaim: false });
|
|
173
|
+
return resume(onStage);
|
|
174
|
+
}
|
|
175
|
+
|
|
107
176
|
async function setup(args) {
|
|
108
177
|
const options = flags(args, { ...servicesOption, "key-file": { type: "string" }, "key-stdin": { type: "boolean" }, apply: { type: "boolean" } });
|
|
109
178
|
if (options["key-file"] && options["key-stdin"]) throw new Error("Choose one sync key input.");
|
|
110
|
-
|
|
179
|
+
const saved = await savedEnrollment();
|
|
111
180
|
if (saved && !saved.pendingClaim) { show(await resume()); return; }
|
|
112
|
-
const
|
|
113
|
-
|
|
181
|
+
const review = await inspectSyncKey(await secretInput({ fromFile: options["key-file"], fromStdin: options["key-stdin"] }));
|
|
182
|
+
const { grant: { catalog }, host, services } = review;
|
|
114
183
|
if (!saved) {
|
|
115
|
-
const grant = await enrollmentRequest(invitation.endpoint, "catalog", {}, { invitation });
|
|
116
|
-
const catalog = grant.catalog;
|
|
117
|
-
validateCatalog(catalog);
|
|
118
|
-
const host = await measureHost(targets);
|
|
119
184
|
console.log(`${host.os} ${host.architecture} · ${host.cpu} threads · ${gib(host.memoryBytes)} available · CUDA device ${host.cuda ? "detected" : "absent"}`);
|
|
120
|
-
for (const service of
|
|
185
|
+
for (const service of services) {
|
|
121
186
|
const { errors, eligible } = planServices(catalog, host, [service.id]);
|
|
122
187
|
console.log(` ${service.id} ${printable(service.label)} · ${eligible ? "compatible" : printable(errors[0])}`);
|
|
123
188
|
}
|
|
124
|
-
|
|
125
|
-
|
|
189
|
+
}
|
|
190
|
+
const selection = saved?.services ?? ids(options.services ?? await input("Select service IDs separated by commas: "));
|
|
191
|
+
if (!saved) {
|
|
126
192
|
const plan = planServices(catalog, host, selection);
|
|
127
193
|
showPlan(plan);
|
|
128
194
|
if (!plan.eligible) throw new Error("The selection exceeds this host’s capacity.");
|
|
129
195
|
if (!options.apply && (!process.stdin.isTTY || (await input("Apply this plan? [y/N] ")).toLowerCase() !== "y")) return;
|
|
130
|
-
await localPrivileges(selection, catalog);
|
|
131
|
-
saved = { node: grant.node, endpoint: invitation.endpoint, services: [...new Set(selection)].sort(), catalog, pendingClaim: true };
|
|
132
|
-
await saveEnrollment(saved);
|
|
133
196
|
}
|
|
134
|
-
|
|
135
|
-
const receipt = await enrollmentRequest(saved.endpoint, "claim", {
|
|
136
|
-
machineId: identity.machineId, username: identity.username, services: saved.services, catalogDigest: catalogDigest(saved.catalog),
|
|
137
|
-
}, { invitation, identity });
|
|
138
|
-
if (receipt.node !== saved.node) throw new Error("The claimed identity does not match the enrollment.");
|
|
139
|
-
await saveEnrollment({ ...saved, pendingClaim: false });
|
|
140
|
-
show(await resume());
|
|
197
|
+
show(await applySyncKey(review, selection));
|
|
141
198
|
}
|
|
142
199
|
|
|
143
200
|
export async function main(command, args) {
|
|
@@ -145,23 +202,30 @@ export async function main(command, args) {
|
|
|
145
202
|
if (command === "setup") { await setup(args); return; }
|
|
146
203
|
if (command === "resume" && !args.length) { show(await resume()); return; }
|
|
147
204
|
if (command === "services" && !args.length) { show((await operatorRequest("catalog", {})).catalog.services); return; }
|
|
205
|
+
if (command === "local-services" && !args.length) { show(await installedServices()); return; }
|
|
206
|
+
if (command === "service") {
|
|
207
|
+
const [action, id, directory] = args;
|
|
208
|
+
if (["enable", "disable"].includes(action) && id && args.length === 2) { await setServiceEnabled(id, action === "enable"); return; }
|
|
209
|
+
if (action === "move" && id && directory && args.length === 3) { show(await moveServiceDataset(id, directory)); return; }
|
|
210
|
+
throw new Error("Use service enable ID, service disable ID or service move ID DIRECTORY.");
|
|
211
|
+
}
|
|
148
212
|
if (command === "invite" || command === "revoke") {
|
|
149
213
|
const options = flags(args, command === "invite" ? { node: { type: "string" }, out: { type: "string" }, ...servicesOption } : { node: { type: "string" } });
|
|
150
214
|
if (!options.node) throw new Error("Pass --node NAME.");
|
|
151
215
|
if (command === "revoke") { show(await operatorRequest(command, { node: options.node })); return; }
|
|
152
|
-
|
|
216
|
+
const request = { node: options.node, ...(options.services && { services: ids(options.services) }) };
|
|
153
217
|
if (options.out) {
|
|
154
218
|
const fd = await open(options.out, "wx", 0o600);
|
|
155
219
|
let complete = false;
|
|
156
220
|
try {
|
|
157
|
-
const result = await operatorRequest(command,
|
|
221
|
+
const result = await operatorRequest(command, request);
|
|
158
222
|
await fd.writeFile(result.key + "\n"); await fd.sync();
|
|
159
223
|
complete = true;
|
|
160
224
|
show({ node: result.node, expiresAt: result.expiresAt, keyFile: options.out });
|
|
161
225
|
} finally { await fd.close(); if (!complete) await rm(options.out); }
|
|
162
226
|
} else {
|
|
163
227
|
if (!process.stdout.isTTY) throw new Error("Use --out FILE to avoid printing a key into logs or a pipeline.");
|
|
164
|
-
const result = await operatorRequest(command,
|
|
228
|
+
const result = await operatorRequest(command, request);
|
|
165
229
|
console.log(result.key);
|
|
166
230
|
console.log("Expires " + new Date(result.expiresAt).toISOString());
|
|
167
231
|
}
|
|
@@ -171,22 +235,23 @@ export async function main(command, args) {
|
|
|
171
235
|
const options = flags(args, command === "status" ? {} : { ...servicesOption, apply: { type: "boolean" } });
|
|
172
236
|
const saved = await readEnrollment();
|
|
173
237
|
if (saved.pendingClaim) throw new Error("Waiting for sync key confirmation. Run mapsource-node setup.");
|
|
174
|
-
|
|
175
|
-
|
|
238
|
+
const services = options.services ? [...new Set(ids(options.services))].sort() : undefined;
|
|
239
|
+
const identity = await localIdentity();
|
|
240
|
+
const invoke = (preview, approval = {}) => enrollmentRequest(saved.endpoint, command, { node: saved.node, preview,
|
|
241
|
+
...(services && { services }), ...approval }, { identity });
|
|
242
|
+
if (command === "retire" && options.apply) {
|
|
243
|
+
if (!services?.length || !process.stdin.isTTY) throw new Error("Retirement requires an interactive terminal and explicit service IDs.");
|
|
244
|
+
const { confirmation, expiresAt, ...plan } = await invoke(true);
|
|
245
|
+
show(plan);
|
|
246
|
+
if ((await input("Remove these services and their exclusive dataset copies? [y/N] ")).toLowerCase() !== "y") return;
|
|
247
|
+
const phrase = "RETIRE " + services.join(",");
|
|
248
|
+
if (await input("Type " + phrase + " to confirm: ") !== phrase) return;
|
|
249
|
+
if (expiresAt && expiresAt <= Date.now()) throw new Error("The reviewed retirement plan expired. Review it again.");
|
|
250
|
+
show(await invoke(false, { confirmation, confirm: phrase }));
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
show(await invoke(!options.apply));
|
|
176
254
|
return;
|
|
177
255
|
}
|
|
178
256
|
throw new Error("Unknown command. Run mapsource-node --help.");
|
|
179
257
|
}
|
|
180
|
-
|
|
181
|
-
export async function firstRun() {
|
|
182
|
-
const enrolled = await Promise.all(["/etc/mapsource-cd/node-v5.json", "/etc/systemd/system/mapsource-mesh-tunnel.service"]
|
|
183
|
-
.map(file => access(file).then(() => true, () => false)));
|
|
184
|
-
if (enrolled.some(Boolean)) return false;
|
|
185
|
-
const state = await readEnrollment().catch(error => { if (error.code !== "ENOENT") throw error; });
|
|
186
|
-
if (state && !state.pendingClaim) return false;
|
|
187
|
-
if (!process.stdin.isTTY) return false;
|
|
188
|
-
console.log("Mapsource Node · First-time setup");
|
|
189
|
-
console.log("Create a sync key on an enrolled host with mapsource-node invite.");
|
|
190
|
-
await setup([]);
|
|
191
|
-
return true;
|
|
192
|
-
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import type { createTestRenderer } from "@opentui/core/testing";
|
|
3
|
+
import type { CliRenderer } from "@opentui/core";
|
|
4
|
+
import { nodeInterface } from "./interface.ts";
|
|
5
|
+
import type { enrollmentActions } from "./enrollment-screen.ts";
|
|
6
|
+
|
|
7
|
+
const services = [{ id: "tiles", label: "Raster and vector tiles" }];
|
|
8
|
+
const secret = "mps-sync1:mapsource-enroll-primary.mapsource.io:" + "a".repeat(32) + ":" + "b".repeat(43);
|
|
9
|
+
const host = {
|
|
10
|
+
platform: "linux" as const, os: "debian", architecture: "x64" as const, cpu: 4, memoryBytes: 8 * 1024 ** 3, tools: [], cuda: false,
|
|
11
|
+
mounts: { data: { path: "/srv/mapsource-mirror", device: 1, bytes: 500 * 1024 ** 3, inodes: 4000, percentUsed: 32 } },
|
|
12
|
+
};
|
|
13
|
+
type Actions = typeof enrollmentActions;
|
|
14
|
+
type BindKeys = (renderer: CliRenderer, ui: ReturnType<typeof nodeInterface>, refresh: () => void) => void;
|
|
15
|
+
|
|
16
|
+
export async function testEnrollmentScreen(bind: BindKeys, testRenderer: typeof createTestRenderer) {
|
|
17
|
+
const calls: unknown[] = [];
|
|
18
|
+
const base: Actions = {
|
|
19
|
+
hasMesh: async () => true, savedEnrollment: async () => undefined, capacity: async () => host,
|
|
20
|
+
inspect: async () => ({ invitation: {} as Awaited<ReturnType<Actions["inspect"]>>["invitation"], saved: undefined,
|
|
21
|
+
grant: { node: "test-node", allowed: ["tiles"], catalog: {} }, host, services }),
|
|
22
|
+
apply: async (_review, selected) => { calls.push(selected); return { node: "test-node", phase: "copying" }; },
|
|
23
|
+
plan: () => ({ eligible: true, services, requiredCpu: 1, requiredMemory: 2 ** 30, disks: [], errors: [] }),
|
|
24
|
+
status: async () => ({ node: "test-node", phase: "copying" }),
|
|
25
|
+
resume: async () => ({ node: "test-node", phase: "copying" }),
|
|
26
|
+
catalog: async () => services,
|
|
27
|
+
invite: async (node, allowed) => { calls.push({ node, allowed }); return { node, key: secret, expiresAt: Date.now() + 600_000 }; },
|
|
28
|
+
revoke: async () => ({ revoked: true }),
|
|
29
|
+
};
|
|
30
|
+
for (const fresh of [false, true]) {
|
|
31
|
+
const { renderer, mockInput, renderOnce, captureCharFrame } = await testRenderer({ width: 100, height: 30 });
|
|
32
|
+
try {
|
|
33
|
+
const ui = nodeInterface(renderer, "test", { ...base, hasMesh: async () => !fresh });
|
|
34
|
+
bind(renderer, ui, () => {});
|
|
35
|
+
const frame = async () => { await new Promise(resolve => setTimeout(resolve, 10)); await renderOnce(); return captureCharFrame(); };
|
|
36
|
+
await mockInput.pressKey("4");
|
|
37
|
+
if (fresh) {
|
|
38
|
+
assert.match(await frame(), /32% used/);
|
|
39
|
+
await mockInput.pasteBracketedText(secret);
|
|
40
|
+
assert.doesNotMatch(await frame(), /mps-sync1/);
|
|
41
|
+
mockInput.pressEnter();
|
|
42
|
+
assert.match(await frame(), /Raster and vector tiles/);
|
|
43
|
+
mockInput.pressKey(" ");
|
|
44
|
+
assert.match(await frame(), /Plan · 1 threads/);
|
|
45
|
+
assert.equal(calls.length, 1);
|
|
46
|
+
mockInput.pressEnter();
|
|
47
|
+
assert.match(await frame(), /Copying datasets/);
|
|
48
|
+
assert.deepEqual(calls[1], ["tiles"]);
|
|
49
|
+
} else {
|
|
50
|
+
assert.match(await frame(), /Key issuer · Primary · connected/);
|
|
51
|
+
await mockInput.pressKey("g");
|
|
52
|
+
await mockInput.typeText("test-node");
|
|
53
|
+
mockInput.pressEnter();
|
|
54
|
+
assert.match(await frame(), /An empty selection allows all/);
|
|
55
|
+
mockInput.pressEnter();
|
|
56
|
+
assert.match(await frame(), /SYNC KEY CREATED/);
|
|
57
|
+
assert.deepEqual(calls[0], { node: "test-node", allowed: [] });
|
|
58
|
+
assert.doesNotMatch(await frame(), /mps-sync1/);
|
|
59
|
+
await mockInput.pressKey("v");
|
|
60
|
+
assert.match(await frame(), /mps-sync1/);
|
|
61
|
+
}
|
|
62
|
+
} finally { renderer.destroy(); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import type { KeyEvent } from "@opentui/core";
|
|
2
|
+
import { applySyncKey, enrollmentStatus, hasMesh, inspectSyncKey, localCapacity, resume, savedEnrollment } from "./commands.mjs";
|
|
3
|
+
import { planServices } from "./capability.mjs";
|
|
4
|
+
import { operatorRequest } from "./enrollment.mjs";
|
|
5
|
+
|
|
6
|
+
type Profile = { id: string; label: string };
|
|
7
|
+
type Key = { node: string; key: string; expiresAt: number };
|
|
8
|
+
type Job = { phase: string; node: string; endpoint?: string; message?: string; services?: (string | { id: string; phase: string })[] };
|
|
9
|
+
type Line = { text: string; action?: () => void; tone?: "action" | "muted" };
|
|
10
|
+
type Mode = "home" | "name" | "allow" | "issued" | "key" | "choose" | "status" | "revoke";
|
|
11
|
+
const safe = (value: unknown) => String(value).replace(/[\p{Cc}\p{Cf}]/gu, "").slice(0, 600);
|
|
12
|
+
const gib = (bytes: number) => (bytes / 1024 ** 3).toFixed(1) + " GiB";
|
|
13
|
+
const phaseLabels: Record<string, string> = {
|
|
14
|
+
"awaiting-key": "Waiting for the original sync key",
|
|
15
|
+
authorized: "Authorized", "tunnel-issued": "Connector issued", registered: "Peer registered", copying: "Copying datasets",
|
|
16
|
+
verified: "Engines verified · awaiting fleet admission", serving: "Serving", failed: "Sync needs attention",
|
|
17
|
+
disabled: "Disabled", retiring: "Retiring services", retired: "Retired",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const enrollmentActions = {
|
|
21
|
+
hasMesh, savedEnrollment, capacity: localCapacity, inspect: inspectSyncKey, apply: applySyncKey,
|
|
22
|
+
plan: planServices,
|
|
23
|
+
status: enrollmentStatus as () => Promise<Job>,
|
|
24
|
+
resume: resume as (stage: (message: string) => void) => Promise<Job>,
|
|
25
|
+
catalog: async () => (await operatorRequest("catalog", {}) as { catalog: { services: Profile[] } }).catalog.services,
|
|
26
|
+
invite: (node: string, services: string[]) => operatorRequest("invite", { node, ...(services.length ? { services } : {}) }) as Promise<Key>,
|
|
27
|
+
revoke: (node: string) => operatorRequest("revoke", { node }) as Promise<{ revoked: boolean }>,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export function enrollmentScreen(draw: () => void, clipboard: (text: string) => boolean, api = enrollmentActions) {
|
|
31
|
+
let mode: Mode = "home";
|
|
32
|
+
let initialized = false, mesh = false, enrolled = false, awaitingKey = false, reveal = false;
|
|
33
|
+
let busy = "", notice = "", input = "", target = "";
|
|
34
|
+
let authority: Profile[] | null = null;
|
|
35
|
+
let host: Awaited<ReturnType<typeof localCapacity>> | undefined;
|
|
36
|
+
let review: Awaited<ReturnType<typeof inspectSyncKey>> | undefined;
|
|
37
|
+
let issued: Key | undefined, job: Job | undefined;
|
|
38
|
+
let cursor = 0;
|
|
39
|
+
const choices = new Set<string>();
|
|
40
|
+
const selection = () => Array.from(choices);
|
|
41
|
+
const setMode = (value: Mode) => { mode = value; input = ""; notice = ""; cursor = 0; draw(); };
|
|
42
|
+
|
|
43
|
+
async function act(label: string, action: () => Promise<void>) {
|
|
44
|
+
if (busy) return;
|
|
45
|
+
busy = label; notice = ""; draw();
|
|
46
|
+
try { await action(); }
|
|
47
|
+
catch (cause) { notice = safe(cause instanceof Error ? cause.message : "Enrollment request failed."); }
|
|
48
|
+
finally { busy = ""; draw(); }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function refresh() {
|
|
52
|
+
return act("Checking enrollment…", async () => {
|
|
53
|
+
const [local, saved, capacity, offered] = await Promise.all([
|
|
54
|
+
api.hasMesh(), api.savedEnrollment(), api.capacity(), api.catalog().catch(() => null),
|
|
55
|
+
]);
|
|
56
|
+
mesh = local; enrolled = !!saved; awaitingKey = !!saved?.pendingClaim; host = capacity; authority = offered;
|
|
57
|
+
if (!initialized) {
|
|
58
|
+
initialized = true;
|
|
59
|
+
if (enrolled && !awaitingKey) mode = "status";
|
|
60
|
+
else if (!mesh || awaitingKey) mode = "key";
|
|
61
|
+
}
|
|
62
|
+
if (mode === "status") job = await api.status();
|
|
63
|
+
if (mode === "choose" && review) review = { ...review, host: capacity };
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function showStatus() {
|
|
68
|
+
setMode("status");
|
|
69
|
+
void refresh();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function submit() {
|
|
73
|
+
if (mode === "name") {
|
|
74
|
+
if (!/^[a-z][a-z0-9-]{0,31}$/.test(input)) { notice = "Use a lowercase node name with letters, digits or dashes."; draw(); return; }
|
|
75
|
+
target = input; choices.clear(); setMode("allow");
|
|
76
|
+
} else if (mode === "allow") {
|
|
77
|
+
void act("Creating a sync key…", async () => { issued = await api.invite(target, selection()); reveal = false; setMode("issued"); });
|
|
78
|
+
} else if (mode === "key") {
|
|
79
|
+
const key = input;
|
|
80
|
+
input = "";
|
|
81
|
+
void act("Checking the sync key and local capacity…", async () => {
|
|
82
|
+
review = await api.inspect(key);
|
|
83
|
+
host = review.host;
|
|
84
|
+
choices.clear();
|
|
85
|
+
for (const service of review.saved?.services ?? []) choices.add(service);
|
|
86
|
+
setMode("choose");
|
|
87
|
+
});
|
|
88
|
+
} else if (mode === "choose" && review) {
|
|
89
|
+
if (!selection().length) { notice = "Select at least one service."; draw(); return; }
|
|
90
|
+
const selected = api.plan(review.grant.catalog, review.host, selection());
|
|
91
|
+
if (!selected.eligible) { notice = "Adjust the service selection to meet the capacity checks."; draw(); return; }
|
|
92
|
+
const confirmed = review;
|
|
93
|
+
void act("Preparing enrollment…", async () => {
|
|
94
|
+
try { job = await api.apply(confirmed, selection(), stage => { busy = stage; draw(); }) as Job; }
|
|
95
|
+
finally {
|
|
96
|
+
// A failed request may have committed the claim. Consult the saved
|
|
97
|
+
// identity before offering another plan or consuming a different key.
|
|
98
|
+
const saved = await api.savedEnrollment();
|
|
99
|
+
enrolled = !!saved; awaitingKey = !!saved?.pendingClaim;
|
|
100
|
+
if (saved) { review = undefined; setMode(awaitingKey ? "key" : "status"); }
|
|
101
|
+
}
|
|
102
|
+
review = undefined; enrolled = true; setMode("status");
|
|
103
|
+
});
|
|
104
|
+
} else if (mode === "revoke") {
|
|
105
|
+
if (!/^[a-z][a-z0-9-]{0,31}$/.test(input)) { notice = "Enter the node name to revoke its unused key."; draw(); return; }
|
|
106
|
+
const name = input;
|
|
107
|
+
void act("Revoking the unused key…", async () => {
|
|
108
|
+
const result = await api.revoke(name);
|
|
109
|
+
if (issued?.node === name) issued = undefined;
|
|
110
|
+
setMode("home");
|
|
111
|
+
notice = result.revoked ? `Unused key revoked for ${name}.` : `No unused key was found for ${name}.`;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function copy() {
|
|
117
|
+
if (!issued || issued.expiresAt <= Date.now()) return;
|
|
118
|
+
notice = clipboard(issued.key) ? "Copy sent to your terminal clipboard." : "Clipboard unavailable here. Use Reveal to copy the key.";
|
|
119
|
+
draw();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function continueSync() {
|
|
123
|
+
void act("Checking the saved enrollment…", async () => {
|
|
124
|
+
job = await api.resume(stage => { busy = stage; draw(); });
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function cancel() {
|
|
129
|
+
review = undefined; issued = undefined; reveal = false; choices.clear();
|
|
130
|
+
setMode("home");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const typing = () => ["name", "key", "revoke"].includes(mode);
|
|
134
|
+
function paste(value: string) {
|
|
135
|
+
if (busy || !typing()) return;
|
|
136
|
+
input = (input + value.trim().replace(/[^a-zA-Z0-9_.:-]/g, "")).slice(0, mode === "key" ? 180 : 32);
|
|
137
|
+
draw();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function profiles(): Profile[] { return mode === "allow" ? authority ?? [] : review?.services ?? []; }
|
|
141
|
+
function toggle(id: string) {
|
|
142
|
+
if (busy || review?.saved) return;
|
|
143
|
+
if (choices.has(id)) choices.delete(id); else choices.add(id);
|
|
144
|
+
draw();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function keypress(key: KeyEvent): boolean {
|
|
148
|
+
const name = key.name;
|
|
149
|
+
if (name === "escape" && mode !== "home") { if (!busy) cancel(); return true; }
|
|
150
|
+
if (busy) return name !== "q";
|
|
151
|
+
if (typing()) {
|
|
152
|
+
if (name === "return") submit();
|
|
153
|
+
else if (name === "backspace") { input = input.slice(0, -1); draw(); }
|
|
154
|
+
else if (!key.ctrl && !key.meta && /^[a-zA-Z0-9_.:-]$/.test(key.sequence)) paste(key.sequence);
|
|
155
|
+
else return !["tab", "pageup", "pagedown"].includes(name);
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
if (mode === "allow" || mode === "choose") {
|
|
159
|
+
const allowed = profiles();
|
|
160
|
+
if (name === "up" || name === "down") {
|
|
161
|
+
cursor = Math.max(0, Math.min(allowed.length - 1, cursor + (name === "up" ? -1 : 1))); draw();
|
|
162
|
+
} else if (name === "space") { if (allowed[cursor]) toggle(allowed[cursor].id); }
|
|
163
|
+
else if (name === "return") submit();
|
|
164
|
+
else if (mode === "allow" && name === "a") { choices.clear(); draw(); }
|
|
165
|
+
else return false;
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
if (mode === "issued" && name === "c") { copy(); return true; }
|
|
169
|
+
if (mode === "issued" && name === "v") { reveal = !reveal; draw(); return true; }
|
|
170
|
+
if (mode === "status" && name === "s") { continueSync(); return true; }
|
|
171
|
+
if (mode === "home" && name === "g" && authority) { setMode("name"); return true; }
|
|
172
|
+
if (mode === "home" && name === "x" && authority) { setMode("revoke"); return true; }
|
|
173
|
+
if (mode === "home" && name === "e" && (!mesh || awaitingKey) && (!enrolled || awaitingKey)) { setMode("key"); return true; }
|
|
174
|
+
if (mode === "home" && name === "s" && enrolled) { showStatus(); return true; }
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function view(width: number): { title: string; lines: Line[] } {
|
|
179
|
+
const lines: Line[] = [];
|
|
180
|
+
const add = (text: string, tone?: Line["tone"]) => lines.push({ text, tone });
|
|
181
|
+
const button = (text: string, action: () => void) => lines.push({ text, action: () => { if (!busy) action(); }, tone: "action" });
|
|
182
|
+
let title = "ENROLLMENT";
|
|
183
|
+
if (mode === "home") {
|
|
184
|
+
add(authority ? "Key issuer · Primary · connected" : "Key issuer · Primary");
|
|
185
|
+
if (authority) {
|
|
186
|
+
button("[G] Create sync key", () => setMode("name"));
|
|
187
|
+
button("[X] Revoke unused key", () => setMode("revoke"));
|
|
188
|
+
} else if (mesh && !enrolled) add("Create a key on Primary or under Enrollment in the site admin.", "muted");
|
|
189
|
+
if ((!mesh || awaitingKey) && (!enrolled || awaitingKey)) button("[E] Enroll this node", () => setMode("key"));
|
|
190
|
+
if (enrolled) button("[S] View enrollment status", showStatus);
|
|
191
|
+
} else if (typing()) {
|
|
192
|
+
title = mode === "key" ? "ENROLL THIS NODE" : mode === "name" ? "CREATE SYNC KEY" : "REVOKE UNUSED KEY";
|
|
193
|
+
add(mode === "key" ? "Paste a sync key from Primary or the site admin." : "Node name");
|
|
194
|
+
add("› " + (mode === "key" && input ? "●".repeat(Math.min(24, input.length)) : input) + "▏");
|
|
195
|
+
button(mode === "name" ? "[Enter] Choose key permissions" : mode === "key" ? "[Enter] Check sync key" : "[Enter] Revoke unused key", submit);
|
|
196
|
+
} else if (mode === "allow" || mode === "choose") {
|
|
197
|
+
title = mode === "allow" ? "ALLOW SERVICES" : "CHOOSE SERVICES TO INSTALL";
|
|
198
|
+
add(`Node · ${safe(mode === "allow" ? target : review?.grant.node)}`);
|
|
199
|
+
add(mode === "allow" ? "An empty selection allows all offered services." : "↑↓ Select · Space Toggle · Enter Confirm", "muted");
|
|
200
|
+
for (const [index, service] of profiles().entries()) {
|
|
201
|
+
const check = review && api.plan(review.grant.catalog, review.host, [service.id]);
|
|
202
|
+
button(`${index === cursor ? "›" : " "} [${choices.has(service.id) ? "x" : " "}] ${safe(service.label)}${check ? check.eligible ? " · Ready" : " · Check capacity" : ""}`, () => { cursor = index; toggle(service.id); });
|
|
203
|
+
}
|
|
204
|
+
if (mode === "allow") button("[A] Allow all offered services", () => { choices.clear(); draw(); });
|
|
205
|
+
if (mode === "choose" && review && choices.size) {
|
|
206
|
+
const result = api.plan(review.grant.catalog, review.host, selection());
|
|
207
|
+
add(`Plan · ${result.requiredCpu} threads · ${gib(result.requiredMemory)} memory`);
|
|
208
|
+
for (const disk of result.disks) add(`${gib(disk.peakBytes)} peak + ${gib(disk.reserveBytes)} reserve · ${gib(disk.availableBytes)} free`, "muted");
|
|
209
|
+
for (const error of result.errors) add(safe(error));
|
|
210
|
+
}
|
|
211
|
+
button(mode === "allow" ? "[Enter] Create sync key" : "[Enter] Confirm and start enrollment", submit);
|
|
212
|
+
} else if (mode === "issued" && issued) {
|
|
213
|
+
title = "SYNC KEY CREATED";
|
|
214
|
+
add(`Node · ${safe(issued.node)}`);
|
|
215
|
+
add(`Expires · ${new Date(issued.expiresAt).toISOString().slice(11, 16)} UTC`);
|
|
216
|
+
if (issued.expiresAt <= Date.now()) add("This key has expired.");
|
|
217
|
+
else {
|
|
218
|
+
button("[C] Copy sync key", copy);
|
|
219
|
+
button(reveal ? "[V] Hide sync key" : "[V] Reveal sync key", () => { reveal = !reveal; draw(); });
|
|
220
|
+
if (reveal) {
|
|
221
|
+
const key = safe(issued.key), columns = Math.max(16, width - 10);
|
|
222
|
+
for (let offset = 0; offset < key.length; offset += columns) add(key.slice(offset, offset + columns));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
} else if (mode === "status") {
|
|
226
|
+
title = "ENROLLMENT STATUS";
|
|
227
|
+
if (job) {
|
|
228
|
+
add(`${safe(job.node)} · ${safe(phaseLabels[job.phase] ?? job.phase)}`);
|
|
229
|
+
if (job.endpoint) add(safe(job.endpoint), "muted");
|
|
230
|
+
for (const service of job.services ?? []) add(typeof service === "string" ? safe(service) : `${safe(service.id)} · ${safe(service.phase)}`);
|
|
231
|
+
if (job.message) add(safe(job.message), "muted");
|
|
232
|
+
}
|
|
233
|
+
if (!job || ["failed", "authorized", "registered", "tunnel-issued"].includes(job.phase)) button("[S] Resume enrollment", continueSync);
|
|
234
|
+
}
|
|
235
|
+
if (host && ["home", "key", "choose", "status"].includes(mode)) {
|
|
236
|
+
add(`Local capacity · ${host.os} ${host.architecture} · ${host.cpu} threads · ${gib(host.memoryBytes)} free memory`, "muted");
|
|
237
|
+
for (const mount of Object.values(host.mounts)) {
|
|
238
|
+
add(`${mount.path} · ${mount.percentUsed === null ? "Usage unknown" : mount.percentUsed + "% used"} · ${gib(mount.bytes)} available`, "muted");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (mode !== "home") button("[Esc] Back", cancel);
|
|
242
|
+
if (busy || notice) add(busy || notice);
|
|
243
|
+
return { title, lines };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return { refresh, view, keypress, paste, clearSecret() { issued = undefined; input = ""; review = undefined; if (mode === "issued" || mode === "choose") mode = "home"; },
|
|
247
|
+
poll() { if (mode === "status" && !busy) void act("Checking sync progress…", async () => { job = await api.status(); }); },
|
|
248
|
+
};
|
|
249
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -3,22 +3,29 @@ import type { CliRenderer } from "@opentui/core";
|
|
|
3
3
|
import { mapsourcePalette } from "./palette.ts";
|
|
4
4
|
import { nodeInterface } from "./interface.ts";
|
|
5
5
|
import { readTelemetry } from "./telemetry.ts";
|
|
6
|
+
import { hasMesh } from "./commands.mjs";
|
|
6
7
|
|
|
7
8
|
const version = process.env.MAPSOURCE_NODE_BUILD ?? "development";
|
|
8
9
|
const usage = "Mapsource Admin\n\n mapsource-node Open the terminal dashboard\n mapsource-node --json Print one read-only telemetry snapshot\n mapsource-node --version Print the installed release\n";
|
|
9
10
|
const [arg, ...remaining] = process.argv.slice(2);
|
|
10
11
|
|
|
11
12
|
function bindKeys(renderer: CliRenderer, ui: ReturnType<typeof nodeInterface>, refresh: () => void) {
|
|
13
|
+
renderer.keyInput.on("paste", event => {
|
|
14
|
+
if (ui.tab() === 3) { event.preventDefault(); ui.enrollment.paste(new TextDecoder().decode(event.bytes)); }
|
|
15
|
+
if (ui.tab() === 2) { event.preventDefault(); ui.management.paste(new TextDecoder().decode(event.bytes)); }
|
|
16
|
+
});
|
|
12
17
|
renderer.keyInput.on("keypress", key => {
|
|
18
|
+
if (ui.tab() === 3 && ui.enrollment.keypress(key)) { key.preventDefault(); return; }
|
|
19
|
+
if (ui.tab() === 2 && ui.management.keypress(key)) { key.preventDefault(); return; }
|
|
13
20
|
if (key.name === "q" || key.name === "escape") renderer.destroy();
|
|
14
|
-
else if (key.name === "r") refresh();
|
|
21
|
+
else if (key.name === "r") { if (ui.tab() === 3) void ui.enrollment.refresh(); else refresh(); }
|
|
15
22
|
else if (key.name === "left") ui.navigate(ui.tab() - 1);
|
|
16
23
|
else if (key.name === "right" || key.name === "tab") ui.navigate(ui.tab() + 1);
|
|
17
24
|
else if (key.name === "up") ui.scroll(-1);
|
|
18
25
|
else if (key.name === "down") ui.scroll(1);
|
|
19
26
|
else if (key.name === "pageup") ui.scroll(-10);
|
|
20
27
|
else if (key.name === "pagedown") ui.scroll(10);
|
|
21
|
-
else if (["1", "2", "3"].includes(key.name)) ui.navigate(Number(key.name) - 1);
|
|
28
|
+
else if (["1", "2", "3", "4"].includes(key.name)) ui.navigate(Number(key.name) - 1);
|
|
22
29
|
});
|
|
23
30
|
}
|
|
24
31
|
|
|
@@ -42,6 +49,7 @@ async function launch() {
|
|
|
42
49
|
const timer = setInterval(() => void refresh(), 5000);
|
|
43
50
|
renderer.once("destroy", () => { closed = true; clearInterval(timer); });
|
|
44
51
|
ui.paint();
|
|
52
|
+
if (!await hasMesh()) ui.navigate(3);
|
|
45
53
|
void refresh();
|
|
46
54
|
}
|
|
47
55
|
|
|
@@ -62,8 +70,12 @@ else if (arg === "--self-test" && !remaining.length) {
|
|
|
62
70
|
mockInput.pressArrow("right");
|
|
63
71
|
await renderOnce();
|
|
64
72
|
if (view.tab() !== 2 || !captureCharFrame().includes("Q Quit")) throw new Error("OpenTUI navigation verification failed");
|
|
65
|
-
console.log("mapsource-node self-test " + version);
|
|
66
73
|
} finally { renderer.destroy(); }
|
|
74
|
+
const { testEnrollmentScreen } = await import("./enrollment-screen-test.ts");
|
|
75
|
+
await testEnrollmentScreen(bindKeys, createTestRenderer);
|
|
76
|
+
const { testServiceScreen } = await import("./service-screen-test.ts");
|
|
77
|
+
await testServiceScreen();
|
|
78
|
+
console.log("mapsource-node self-test " + version);
|
|
67
79
|
} else if (arg !== undefined || !process.stdin.isTTY || !process.stdout.isTTY) {
|
|
68
80
|
process.stderr.write(arg === undefined ? "A terminal is required. SSH with -t or use mapsource-node --json.\n" : usage);
|
|
69
81
|
process.exitCode = 2;
|
package/src/interface.ts
CHANGED
|
@@ -2,9 +2,11 @@ import { BoxRenderable, ScrollBoxRenderable, TextAttributes, TextRenderable } fr
|
|
|
2
2
|
import type { CliRenderer, RenderContext } from "@opentui/core";
|
|
3
3
|
import { mapsourcePalette as palette } from "./palette.ts";
|
|
4
4
|
import type { Telemetry } from "./telemetry.ts";
|
|
5
|
+
import { enrollmentScreen, type enrollmentActions } from "./enrollment-screen.ts";
|
|
6
|
+
import { serviceScreen, type serviceActions } from "./service-screen.ts";
|
|
5
7
|
|
|
6
|
-
const tabs = ["Overview", "Fleet", "Services"] as const;
|
|
7
|
-
const compactTabs = ["Node", "Fleet", "Svc"] as const;
|
|
8
|
+
const tabs = ["Overview", "Fleet", "Services", "Enrollment"] as const;
|
|
9
|
+
const compactTabs = ["Node", "Fleet", "Svc", "Enroll"] as const;
|
|
8
10
|
const good = palette.focus, muted = palette.muted, amber = "#eac684", red = "#ef9990";
|
|
9
11
|
const dash = "—";
|
|
10
12
|
const percent = (value: number | null | undefined) => value == null ? dash : value.toFixed(1) + "%";
|
|
@@ -26,8 +28,12 @@ const stateColor = (state: string) => {
|
|
|
26
28
|
return value.includes("unavailable") ? red : amber;
|
|
27
29
|
};
|
|
28
30
|
|
|
29
|
-
export function nodeInterface(renderer: CliRenderer, version: string) {
|
|
31
|
+
export function nodeInterface(renderer: CliRenderer, version: string, actions?: typeof enrollmentActions, manager?: typeof serviceActions) {
|
|
30
32
|
let selected = 0, snapshot: Telemetry | null = null;
|
|
33
|
+
let closed = false;
|
|
34
|
+
renderer.once("destroy", () => { closed = true; });
|
|
35
|
+
const enrollment = enrollmentScreen(() => { if (selected === 3 && !closed) paint(); }, value => renderer.copyToClipboardOSC52(value), actions);
|
|
36
|
+
const management = serviceScreen(() => { if (selected === 2 && !closed) paint(); }, manager);
|
|
31
37
|
const history = new Map<string, { latency: (number | null)[]; queued: (number | null)[] }>();
|
|
32
38
|
// OpenTUI's renderer getter types omit undefined on optional context fields.
|
|
33
39
|
const context = renderer as unknown as RenderContext;
|
|
@@ -42,7 +48,7 @@ export function nodeInterface(renderer: CliRenderer, version: string) {
|
|
|
42
48
|
header.add(heading);
|
|
43
49
|
const navigation = box({ flexDirection: "row", height: 2, flexShrink: 0, gap: 1, paddingX: 1 });
|
|
44
50
|
const navText = tabs.map((tab, index) => text(` ${index + 1} ${tab} `, muted, false, { width: tab.length + 4 }));
|
|
45
|
-
navText.forEach(item => navigation.add(item));
|
|
51
|
+
navText.forEach((item, index) => { item.onMouseUp = () => navigate(index); navigation.add(item); });
|
|
46
52
|
const viewport = new ScrollBoxRenderable(context, {
|
|
47
53
|
flexGrow: 1, flexShrink: 1, minHeight: 0, scrollX: false, scrollY: true, viewportCulling: true,
|
|
48
54
|
contentOptions: { paddingX: 1, paddingBottom: 1 },
|
|
@@ -130,11 +136,6 @@ export function nodeInterface(renderer: CliRenderer, version: string) {
|
|
|
130
136
|
for (const service of data.services) row(local, service.name, service.state, stateColor(service.state));
|
|
131
137
|
if (!data.services.length) local.add(text("Controller telemetry unavailable.", amber));
|
|
132
138
|
viewport.add(local);
|
|
133
|
-
const tools = panel("ENROLLMENT");
|
|
134
|
-
tools.add(text("Run mapsource-node services to list profiles.", muted));
|
|
135
|
-
tools.add(text("Run mapsource-node invite to create a sync key.", muted));
|
|
136
|
-
tools.add(text("Run mapsource-node status for enrollment progress.", muted));
|
|
137
|
-
viewport.add(tools);
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
function paint() {
|
|
@@ -142,21 +143,51 @@ export function nodeInterface(renderer: CliRenderer, version: string) {
|
|
|
142
143
|
for (const child of viewport.getChildren()) child.destroyRecursively();
|
|
143
144
|
heading.content = snapshot ? `MAPSOURCE ADMIN / ${snapshot.node.toUpperCase()}` : "MAPSOURCE ADMIN";
|
|
144
145
|
navText.forEach((item, index) => {
|
|
145
|
-
const name = (renderer.width <
|
|
146
|
+
const name = (renderer.width < 58 ? compactTabs : tabs)[index] ?? "";
|
|
146
147
|
item.content = ` ${index + 1} ${name} `;
|
|
147
148
|
item.width = name.length + 4;
|
|
148
149
|
item.fg = index === selected ? palette.ink : muted;
|
|
149
150
|
item.bg = index === selected ? good : palette.ink;
|
|
150
151
|
});
|
|
151
|
-
keys.content = renderer.width < 65 ? "1–
|
|
152
|
-
`1–
|
|
153
|
-
if (
|
|
152
|
+
keys.content = renderer.width < 65 ? "1–4 View · ↑↓ Scroll · R Refresh · Q Quit" :
|
|
153
|
+
`1–4 / ← → View ↑ ↓ Scroll R Refresh Q Quit · ${version.slice(0, 12)}`;
|
|
154
|
+
if (selected === 3) {
|
|
155
|
+
const view = enrollment.view(renderer.width);
|
|
156
|
+
const section = panel(view.title);
|
|
157
|
+
for (const line of view.lines) {
|
|
158
|
+
// Standard wrapping keeps endpoint names and capacity explanations
|
|
159
|
+
// readable on a narrow terminal or SSH window.
|
|
160
|
+
const entry = new TextRenderable(context, { content: line.text,
|
|
161
|
+
fg: line.tone === "action" ? good : line.tone === "muted" ? muted : palette.paper,
|
|
162
|
+
wrapMode: "char", flexShrink: 0, ...(line.action && { onMouseUp: line.action }) });
|
|
163
|
+
section.add(entry);
|
|
164
|
+
}
|
|
165
|
+
viewport.add(section);
|
|
166
|
+
} else if (selected === 2) {
|
|
167
|
+
const section = panel("MANAGE LOCAL SERVICES");
|
|
168
|
+
for (const line of management.view()) {
|
|
169
|
+
section.add(new TextRenderable(context, { content: line.text, fg: line.action ? good : palette.paper,
|
|
170
|
+
wrapMode: "char", flexShrink: 0, ...(line.action && { onMouseUp: line.action }) }));
|
|
171
|
+
}
|
|
172
|
+
viewport.add(section);
|
|
173
|
+
if (snapshot) services(snapshot);
|
|
174
|
+
} else if (!snapshot) viewport.add(text("Reading node, fleet, and public status…", muted));
|
|
154
175
|
else if (selected === 0) overview(snapshot);
|
|
155
176
|
else if (selected === 1) fleet(snapshot);
|
|
156
|
-
else services(snapshot);
|
|
157
177
|
viewport.scrollTop = oldOffset;
|
|
158
178
|
}
|
|
159
179
|
|
|
180
|
+
function navigate(next: number) {
|
|
181
|
+
const tab = (next + tabs.length) % tabs.length;
|
|
182
|
+
if (tab === selected) return;
|
|
183
|
+
if (selected === 3) enrollment.clearSecret();
|
|
184
|
+
selected = tab;
|
|
185
|
+
viewport.scrollTop = 0;
|
|
186
|
+
paint();
|
|
187
|
+
if (selected === 3) void enrollment.refresh();
|
|
188
|
+
if (selected === 2) void management.refresh();
|
|
189
|
+
}
|
|
190
|
+
|
|
160
191
|
return {
|
|
161
192
|
paint,
|
|
162
193
|
update(data: Telemetry) {
|
|
@@ -168,13 +199,11 @@ export function nodeInterface(renderer: CliRenderer, version: string) {
|
|
|
168
199
|
if (series.latency.length > 30) { series.latency.shift(); series.queued.shift(); }
|
|
169
200
|
history.set(engine.name, series);
|
|
170
201
|
}
|
|
171
|
-
paint();
|
|
172
|
-
},
|
|
173
|
-
navigate(next: number) {
|
|
174
|
-
selected = (next + tabs.length) % tabs.length;
|
|
175
|
-
viewport.scrollTop = 0;
|
|
176
|
-
paint();
|
|
202
|
+
if (selected === 3) enrollment.poll(); else paint();
|
|
177
203
|
},
|
|
204
|
+
navigate,
|
|
205
|
+
enrollment,
|
|
206
|
+
management,
|
|
178
207
|
tab: () => selected,
|
|
179
208
|
scroll(lines: number) { viewport.scrollBy(lines); },
|
|
180
209
|
};
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { constants, createReadStream } from "node:fs";
|
|
4
|
+
import { copyFile, link, lstat, mkdtemp, open, readFile, readdir, realpath, rm, statfs, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir, userInfo } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { setTimeout as pause } from "node:timers/promises";
|
|
8
|
+
import { parseEnv, promisify } from "node:util";
|
|
9
|
+
|
|
10
|
+
const run = promisify(execFile);
|
|
11
|
+
const configRoot = "/etc/mapsource-intelligence";
|
|
12
|
+
const systemdRoot = "/etc/systemd/system";
|
|
13
|
+
const safeRole = /^[a-z][a-z0-9-]{0,47}$/;
|
|
14
|
+
const safePath = /^\/[A-Za-z0-9_./-]+$/;
|
|
15
|
+
const protectedRoots = ["/srv/geo", "/media/roko/sdb1/noclip-maps/openfreemap", "/media/roko/sdb1/noclip-maps/tileserver"];
|
|
16
|
+
const within = (file, root) => file === root || file.startsWith(root + "/");
|
|
17
|
+
const unitName = role => `mapsource-intelligence@${role}.service`;
|
|
18
|
+
const serviceControl = (action, unit) => run("/usr/bin/sudo", ["-n", "/usr/bin/systemctl", ...action, unit], { timeout: 40_000 });
|
|
19
|
+
|
|
20
|
+
async function readService(role) {
|
|
21
|
+
if (!safeRole.test(role)) throw Error("Use a managed Mapsource service ID.");
|
|
22
|
+
const unit = unitName(role);
|
|
23
|
+
const configFile = path.join(configRoot, role + ".env");
|
|
24
|
+
const [config, result] = await Promise.all([
|
|
25
|
+
readFile(configFile, "utf8"),
|
|
26
|
+
run("/usr/bin/systemctl", ["show", unit, "--property=LoadState,ActiveState,UnitFileState,User"], { timeout: 6000 }),
|
|
27
|
+
]);
|
|
28
|
+
const env = parseEnv(config), status = parseEnv(result.stdout);
|
|
29
|
+
const { MAPSOURCE_INTELLIGENCE_ROLE: name, MAPSOURCE_INTELLIGENCE_DATABASE: database, MAPSOURCE_INTELLIGENCE_BUNDLE: bundle,
|
|
30
|
+
MAPSOURCE_INTELLIGENCE_SOCKET: socket } = env;
|
|
31
|
+
if (name !== role || status.LoadState !== "loaded" || !safePath.test(database ?? "") || !safePath.test(bundle ?? "")
|
|
32
|
+
|| socket !== `/run/mapsource-intelligence-${role}/read.sock`) throw Error("The local unit does not expose managed dataset settings.");
|
|
33
|
+
return { role, unit, configFile, config, env, database, bundle, socket, user: status.User,
|
|
34
|
+
active: status.ActiveState === "active", enabled: status.UnitFileState === "enabled", state: status.ActiveState };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function installedServices() {
|
|
38
|
+
const files = await readdir(configRoot).catch(error => {
|
|
39
|
+
if (error.code === "ENOENT") return [];
|
|
40
|
+
throw error;
|
|
41
|
+
});
|
|
42
|
+
const roles = files.filter(file => file.endsWith(".env") && safeRole.test(file.slice(0, -4))).map(file => file.slice(0, -4)).sort();
|
|
43
|
+
return Promise.all(roles.map(async role => {
|
|
44
|
+
try {
|
|
45
|
+
const { role: id, database, active, enabled, state } = await readService(role);
|
|
46
|
+
return { id, database, active, enabled, state };
|
|
47
|
+
} catch {
|
|
48
|
+
return { id: role, database: null, active: false, enabled: false, state: "unverified" };
|
|
49
|
+
}
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function ready(socket) {
|
|
54
|
+
for (let attempt = 0; attempt < 12; attempt++) {
|
|
55
|
+
try {
|
|
56
|
+
const result = await run("/usr/bin/curl", ["--fail", "--silent", "--max-time", "2", "--unix-socket", socket, "http://localhost/ready"],
|
|
57
|
+
{ timeout: 2500, maxBuffer: 200_000 });
|
|
58
|
+
const value = JSON.parse(result.stdout);
|
|
59
|
+
if (value.ready && typeof value.dataset?.release === "string") return value.dataset.release;
|
|
60
|
+
} catch { /* A restarting unit may need a moment to open its socket. */ }
|
|
61
|
+
await pause(450);
|
|
62
|
+
}
|
|
63
|
+
throw Error("The worker did not verify its dataset through the readiness socket.");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function setServiceEnabled(role, enabled) {
|
|
67
|
+
const service = await readService(role);
|
|
68
|
+
await serviceControl([enabled ? "enable" : "disable", "--now"], service.unit);
|
|
69
|
+
try {
|
|
70
|
+
if (enabled) await ready(service.socket);
|
|
71
|
+
const status = await readService(role);
|
|
72
|
+
if (status.enabled !== enabled || status.active !== enabled) throw Error("systemd did not reach the requested service state.");
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (enabled && !service.enabled) await serviceControl(["disable", ...(service.active ? [] : ["--now"])], service.unit);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function writableDataDirectory(value) {
|
|
80
|
+
if (!safePath.test(value) || path.resolve(value) !== value || value === "/" || value.startsWith("/etc/")
|
|
81
|
+
|| protectedRoots.some(root => within(value, root))) throw Error("Use an existing absolute directory on the destination data volume.");
|
|
82
|
+
if (await realpath(value) !== value) throw Error("Choose the real directory path without symbolic links.");
|
|
83
|
+
const info = await lstat(value);
|
|
84
|
+
if (!info.isDirectory() || info.uid !== process.getuid() || info.mode & 0o022) {
|
|
85
|
+
throw Error("The destination must belong to the service user and be private to that user for writes.");
|
|
86
|
+
}
|
|
87
|
+
const { stdout } = await run("/usr/bin/findmnt", ["--json", "--target", value, "--output", "TARGET,FSROOT,OPTIONS"], { timeout: 5000 });
|
|
88
|
+
const mount = JSON.parse(stdout).filesystems?.[0];
|
|
89
|
+
if (!mount || mount.fsroot !== "/" || mount.options.split(",").includes("ro")) {
|
|
90
|
+
throw Error("Use a writable data volume with a direct filesystem mount.");
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function hash(file) {
|
|
96
|
+
const digest = createHash("sha256");
|
|
97
|
+
for await (const chunk of createReadStream(file)) digest.update(chunk);
|
|
98
|
+
return digest.digest("hex");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Copy an immutable release, then switch only this systemd unit. */
|
|
102
|
+
export async function moveServiceDataset(role, directory) {
|
|
103
|
+
const service = await readService(role);
|
|
104
|
+
if (service.user !== userInfo().username || service.user === "root") throw Error("Run Mapsource Node as the local service user.");
|
|
105
|
+
const target = await writableDataDirectory(directory);
|
|
106
|
+
const source = String(await realpath(service.database));
|
|
107
|
+
const sourceInfo = await lstat(source);
|
|
108
|
+
if (protectedRoots.some(root => within(source, root)) || !sourceInfo.isFile() || sourceInfo.uid !== process.getuid()
|
|
109
|
+
|| sourceInfo.mode & 0o222 || !/^[a-z0-9-]+\.sqlite$/.test(path.basename(source))) {
|
|
110
|
+
throw Error("The active path must be an operator-owned, immutable Mapsource dataset.");
|
|
111
|
+
}
|
|
112
|
+
const nextDatabase = path.join(target, path.basename(source));
|
|
113
|
+
if (nextDatabase === source) throw Error("The dataset is already in this directory.");
|
|
114
|
+
const [disk, existing] = await Promise.all([statfs(target), lstat(nextDatabase).catch(error => {
|
|
115
|
+
if (error.code !== "ENOENT") throw error;
|
|
116
|
+
return null;
|
|
117
|
+
})]);
|
|
118
|
+
const free = disk.bsize * disk.bavail;
|
|
119
|
+
if (!existing && (disk.ffree < 8 || free - sourceInfo.size < disk.bsize * disk.blocks * 0.25)) {
|
|
120
|
+
throw Error("The dataset copy would exceed the destination's available storage.");
|
|
121
|
+
}
|
|
122
|
+
const priorRelease = service.active ? await ready(service.socket) : null;
|
|
123
|
+
const identityFile = path.join(systemdRoot, unitName(role) + ".d", "identity.conf");
|
|
124
|
+
const identity = await readFile(identityFile, "utf8");
|
|
125
|
+
const mounts = /^RequiresMountsFor=\/[^\r\n]+$/m;
|
|
126
|
+
if (!mounts.test(identity)) throw Error("The installed unit does not declare a dataset mount.");
|
|
127
|
+
const scratch = await mkdtemp(path.join(target, "mapsource-move-"));
|
|
128
|
+
try {
|
|
129
|
+
const digest = await hash(source);
|
|
130
|
+
if (!existing) {
|
|
131
|
+
const staged = path.join(scratch, "dataset.sqlite");
|
|
132
|
+
await copyFile(source, staged, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
|
|
133
|
+
if (await hash(staged) !== digest) throw Error("The copy failed checksum verification.");
|
|
134
|
+
const file = await open(staged, "r");
|
|
135
|
+
try { await file.sync(); } finally { await file.close(); }
|
|
136
|
+
await link(staged, nextDatabase);
|
|
137
|
+
const parent = await open(target, "r");
|
|
138
|
+
try { await parent.sync(); } finally { await parent.close(); }
|
|
139
|
+
} else if (!existing.isFile() || existing.uid !== process.getuid() || existing.mode & 0o222 || await hash(nextDatabase) !== digest) {
|
|
140
|
+
throw Error("The destination already contains a different dataset.");
|
|
141
|
+
}
|
|
142
|
+
if ((await readService(role)).config !== service.config) throw Error("The service changed while the dataset was being copied.");
|
|
143
|
+
const local = await mkdtemp(path.join(tmpdir(), "mapsource-service-config-"));
|
|
144
|
+
async function install(name, targetFile, contents) {
|
|
145
|
+
const file = path.join(local, name);
|
|
146
|
+
const pending = targetFile + ".mapsource-" + randomUUID();
|
|
147
|
+
await writeFile(file, contents, { mode: 0o600 });
|
|
148
|
+
await run("/usr/bin/sudo", ["-n", "/usr/bin/install", "-m", "0644", "--", file, pending], { timeout: 6000 });
|
|
149
|
+
await run("/usr/bin/sudo", ["-n", "/usr/bin/mv", "-T", "--", pending, targetFile], { timeout: 6000 });
|
|
150
|
+
}
|
|
151
|
+
async function configure(config, dropin) {
|
|
152
|
+
await install("identity.conf", identityFile, dropin);
|
|
153
|
+
await install("service.env", service.configFile, config);
|
|
154
|
+
await run("/usr/bin/sudo", ["-n", "/usr/bin/systemctl", "daemon-reload"], { timeout: 12_000 });
|
|
155
|
+
if (service.active) {
|
|
156
|
+
await serviceControl(["restart"], service.unit);
|
|
157
|
+
if (await ready(service.socket) !== priorRelease) throw Error("The restarted service loaded a different release.");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const config = service.config.replace(/^MAPSOURCE_INTELLIGENCE_DATABASE=.*$/m, `MAPSOURCE_INTELLIGENCE_DATABASE=${nextDatabase}`);
|
|
162
|
+
const dropin = identity.replace(mounts, `RequiresMountsFor=${target} ${path.dirname(service.bundle)}`);
|
|
163
|
+
if (config === service.config || parseEnv(config).MAPSOURCE_INTELLIGENCE_DATABASE !== nextDatabase) throw Error("The dataset setting could not be updated.");
|
|
164
|
+
try { await configure(config, dropin); }
|
|
165
|
+
catch (cause) {
|
|
166
|
+
await configure(service.config, identity).catch(error => { throw new AggregateError([cause, error], "The move failed and automatic rollback needs attention."); });
|
|
167
|
+
throw Error("The move failed and the previous configuration was restored.", { cause });
|
|
168
|
+
}
|
|
169
|
+
} finally { await rm(local, { recursive: true, force: true }); }
|
|
170
|
+
return { role, database: nextDatabase, previous: source, sha256: digest, active: service.active };
|
|
171
|
+
} finally { await rm(scratch, { recursive: true, force: true }); }
|
|
172
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import type { KeyEvent } from "@opentui/core";
|
|
3
|
+
import { serviceScreen } from "./service-screen.ts";
|
|
4
|
+
|
|
5
|
+
export async function testServiceScreen() {
|
|
6
|
+
const calls: unknown[] = [];
|
|
7
|
+
let database = "/srv/data/storm.sqlite", enabled = true;
|
|
8
|
+
const screen = serviceScreen(() => {}, {
|
|
9
|
+
list: async () => [{ id: "historical-weather", database, enabled, active: enabled, state: enabled ? "active" : "inactive" }],
|
|
10
|
+
enable: async (id, requested) => { calls.push({ id, requested }); enabled = requested; },
|
|
11
|
+
move: async (role, directory) => {
|
|
12
|
+
const previous = database;
|
|
13
|
+
database = directory + "/storm.sqlite";
|
|
14
|
+
calls.push({ role, directory });
|
|
15
|
+
return { role, database, previous, sha256: "a".repeat(64), active: enabled };
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
const press = (name: string) => screen.keypress({ name, sequence: name } as KeyEvent);
|
|
19
|
+
const rendered = () => screen.view().map(line => line.text).join("\n");
|
|
20
|
+
const tick = () => new Promise(resolve => setTimeout(resolve, 1));
|
|
21
|
+
await screen.refresh();
|
|
22
|
+
assert.match(rendered(), /Running · Enabled at boot/);
|
|
23
|
+
assert.match(rendered(), /\/srv\/data\/storm.sqlite/);
|
|
24
|
+
assert.equal(press("e"), true);
|
|
25
|
+
await tick();
|
|
26
|
+
assert.match(rendered(), /Stopped · Boot disabled/);
|
|
27
|
+
assert.deepEqual(calls, [{ id: "historical-weather", requested: false }]);
|
|
28
|
+
assert.equal(press("m"), true);
|
|
29
|
+
screen.paste("/mnt/backup");
|
|
30
|
+
press("return");
|
|
31
|
+
assert.match(rendered(), /Confirm destination · \/mnt\/backup/);
|
|
32
|
+
press("escape");
|
|
33
|
+
assert.equal(calls.length, 1);
|
|
34
|
+
press("m");
|
|
35
|
+
screen.paste("/mnt/backup");
|
|
36
|
+
press("return");
|
|
37
|
+
press("return");
|
|
38
|
+
await tick();
|
|
39
|
+
assert.match(rendered(), /Dataset · \/mnt\/backup\/storm.sqlite/);
|
|
40
|
+
assert.deepEqual(calls[1], { role: "historical-weather", directory: "/mnt/backup" });
|
|
41
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { KeyEvent } from "@opentui/core";
|
|
2
|
+
import { installedServices, moveServiceDataset, setServiceEnabled } from "./service-management.mjs";
|
|
3
|
+
|
|
4
|
+
type Service = Awaited<ReturnType<typeof installedServices>>[number];
|
|
5
|
+
export const serviceActions = { list: installedServices, enable: setServiceEnabled, move: moveServiceDataset };
|
|
6
|
+
|
|
7
|
+
export function serviceScreen(draw: () => void, api = serviceActions) {
|
|
8
|
+
let services: Service[] = [], cursor = 0, busy = false;
|
|
9
|
+
let notice = "", directory: string | null = null, confirming = false;
|
|
10
|
+
const selected = () => services[cursor];
|
|
11
|
+
const safe = (message: string) => message.replace(/[\p{Cc}\p{Cf}]/gu, "");
|
|
12
|
+
|
|
13
|
+
async function act(action: () => Promise<string | void>) {
|
|
14
|
+
if (busy) return;
|
|
15
|
+
busy = true; notice = ""; draw();
|
|
16
|
+
try {
|
|
17
|
+
const message = await action();
|
|
18
|
+
services = await api.list();
|
|
19
|
+
cursor = Math.min(cursor, Math.max(0, services.length - 1));
|
|
20
|
+
notice = message ?? "";
|
|
21
|
+
} catch (error) { notice = safe(error instanceof Error ? error.message : "The request failed."); }
|
|
22
|
+
finally { busy = false; draw(); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function toggle() {
|
|
26
|
+
const service = selected();
|
|
27
|
+
if (!service?.database) return;
|
|
28
|
+
const enable = !(service.enabled || service.active);
|
|
29
|
+
void act(async () => {
|
|
30
|
+
await api.enable(service.id, enable);
|
|
31
|
+
return enable ? "Worker started and enabled at boot." : "Worker stopped. Dataset retained.";
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function edit() {
|
|
36
|
+
if (!selected()?.database || busy) return;
|
|
37
|
+
directory = ""; notice = ""; draw();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function submit() {
|
|
41
|
+
const service = selected();
|
|
42
|
+
if (!service || !directory || busy) return;
|
|
43
|
+
if (!confirming) { confirming = true; draw(); return; }
|
|
44
|
+
const destination = directory;
|
|
45
|
+
directory = null; confirming = false;
|
|
46
|
+
void act(async () => {
|
|
47
|
+
await api.move(service.id, destination);
|
|
48
|
+
return "Dataset verified and switched. The prior copy is available for rollback.";
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function paste(value: string) {
|
|
53
|
+
if (directory === null || busy || confirming) return;
|
|
54
|
+
directory = (directory + value.trim().replace(/[^A-Za-z0-9_./-]/g, "")).slice(0, 512);
|
|
55
|
+
draw();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function keypress(key: KeyEvent) {
|
|
59
|
+
if (busy) return key.name !== "q";
|
|
60
|
+
if (directory !== null) {
|
|
61
|
+
if (key.name === "escape") { directory = null; confirming = false; draw(); }
|
|
62
|
+
else if (key.name === "return") submit();
|
|
63
|
+
else if (key.name === "backspace" && !confirming) { directory = directory.slice(0, -1); draw(); }
|
|
64
|
+
else if (!key.ctrl && !key.meta && /^[A-Za-z0-9_./-]$/.test(key.sequence)) paste(key.sequence);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
if (key.name === "r") { void act(async () => {}); return true; }
|
|
68
|
+
if (key.name === "m" && selected()?.database) { edit(); return true; }
|
|
69
|
+
if (key.name === "e" && selected()?.database) { toggle(); return true; }
|
|
70
|
+
if (key.name === "up" || key.name === "down") {
|
|
71
|
+
if (services.length === 0) return false;
|
|
72
|
+
cursor = Math.max(0, Math.min(services.length - 1, cursor + (key.name === "up" ? -1 : 1)));
|
|
73
|
+
draw(); return true;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function view() {
|
|
79
|
+
const lines: { text: string; action?: () => void }[] = [];
|
|
80
|
+
if (!services.length && !busy) lines.push({ text: "No local intelligence workers found. Install services under Enrollment." });
|
|
81
|
+
for (const [index, service] of services.entries()) {
|
|
82
|
+
const state = service.active ? "Running" : service.state === "unverified" ? "Unverified" : "Stopped";
|
|
83
|
+
lines.push({ text: `${index === cursor ? "›" : " "} ${service.id} · ${state} · ${service.enabled ? "Enabled at boot" : "Boot disabled"}`,
|
|
84
|
+
action: () => { if (!busy && directory === null) { cursor = index; draw(); } } });
|
|
85
|
+
}
|
|
86
|
+
const service = selected();
|
|
87
|
+
if (service?.database) lines.push({ text: "Dataset · " + service.database });
|
|
88
|
+
if (directory !== null) {
|
|
89
|
+
lines.push({ text: (confirming ? "Confirm destination · " : "Destination directory · ") + directory });
|
|
90
|
+
if (confirming) lines.push({ text: "This copies the release and switches its systemd configuration. A running worker restarts." });
|
|
91
|
+
lines.push({ text: `[Enter] ${confirming ? "Move dataset" : "Review move"} · [Esc] Cancel`, action: submit });
|
|
92
|
+
} else if (service?.database) {
|
|
93
|
+
lines.push({ text: service.enabled || service.active ? "[E] Disable worker" : "[E] Enable worker", action: toggle });
|
|
94
|
+
lines.push({ text: "[M] Move dataset", action: edit });
|
|
95
|
+
}
|
|
96
|
+
if (busy || notice) lines.push({ text: busy ? "Checking local service or copying dataset…" : notice });
|
|
97
|
+
return lines;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return { view, keypress, paste, refresh: () => act(async () => {}) };
|
|
101
|
+
}
|