SPB Git

Repository Public

mlstore.ts 9.2 KB 125 lines typescript

1#!/usr/bin/env node2/**3 * =============================================================================4 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : MacLustr Storage Node9 * File             : server/bin/mlstore.ts10 * Description      : Admin CLI for the storage coordinator (same /admin/v1 API11 *                    as the dashboard). Token: MSC_ADMIN_TOKEN, or the file12 *                    ~/.config/maclustr-storage/admin.token. URL: MSC_URL13 *                    (default https://storage.spboucher.ai).14 * Module           : server15 * Repository       : https://git.spboucher.ai/maclustr-storage-ios16 * Project Website  : https://storage.spboucher.ai17 * Created          : 2026-12-0118 * Last Modified    : 2026-12-0119 *20 * Author           : Simon-Pierre Boucher21 * Position         : Professor of Finance22 * Institution      : Université du Québec en Outaouais (UQO)23 * Organization     : SP Boucher24 * Website          : https://spboucher.ai25 * Git              : https://git.spboucher.ai26 *27 * Preferred Contact: admin@spboucher.ai28 * Technical Contact: dev@spboucher.ai29 * Security/Admin   : admin@spboucher.ai30 *31 * Copyright (c) 202632 * Simon-Pierre Boucher33 * All rights reserved where applicable. This file is governed by the34 * applicable project license, copyright notices and relevant law.35 * Existing third-party rights and notices remain unaffected.36 *37 * License          : None specified (no license file in this repository)38 *39 * Do not embed credentials, private keys, access tokens,40 * certificates or confidential personal information.41 *42 * =============================================================================43 * END OF SP BOUCHER SOURCE HEADER44 * =============================================================================45 */4647import { createReadStream, createWriteStream, existsSync, readFileSync, statSync } from "node:fs";48import { createHash } from "node:crypto";49import { homedir } from "node:os";50import { basename, join } from "node:path";51import { Readable } from "node:stream";52import { pipeline } from "node:stream/promises";5354const tokenFile = join(process.env.MSC_SECRET_DIR || join(homedir(), ".config", "maclustr-storage"), "admin.token");55const token = process.env.MSC_ADMIN_TOKEN || (existsSync(tokenFile) ? readFileSync(tokenFile, "utf8").trim() : "");56const base = (process.env.MSC_URL || (existsSync(tokenFile) && !process.env.MSC_ADMIN_TOKEN ? `http://127.0.0.1:${process.env.MSC_PORT || 8870}` : "https://storage.spboucher.ai")).replace(/\/$/, "");57if (!token) { console.error("no admin token (MSC_ADMIN_TOKEN or " + tokenFile + ")"); process.exit(2); }5859async function api(method: string, route: string, body?: unknown): Promise<any> {60  const r = await fetch(`${base}/admin/v1/${route}`, { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });61  const j = await r.json().catch(() => ({}));62  if (!r.ok) { console.error(`${method} ${route} -> ${r.status} ${JSON.stringify(j)}`); process.exit(1); }63  return j;64}65const gb = (n: number | null | undefined) => n == null ? "—" : n >= 2 ** 30 ? (n / 2 ** 30).toFixed(2) + " GiB" : (n / 2 ** 20).toFixed(1) + " MiB";66const pct = (x: number | null | undefined) => x == null ? "—" : (x * 100).toFixed(1) + " %";67const ago = (t: number) => t ? Math.max(0, Math.floor(Date.now() / 1000) - t) + " s ago" : "never";68const [cmd, ...args] = process.argv.slice(2);6970switch (cmd) {71  case "status": case "nodes": {72    const o = await api("GET", "overview");73    if (args.includes("--json")) { console.log(JSON.stringify(o, null, 1)); break; }74    const t = o.totals, s = o.stable;75    console.log(`coordinator ${o.coordinator.version} ${o.coordinator.protocol} · fragment ${gb(o.coordinator.fragment_size)} · mobile replicas target ${o.coordinator.mobile_replicas_target}`);76    console.log(`stable store : ${s.objects} objects, ${gb(s.object_bytes)}, ${s.fragments} fragments (${s.fragments_unhealthy} unhealthy), disk free ${gb(s.disk_free)}`);77    console.log(`mobile nodes : ${t.nodes_online}/${t.nodes} online · registered ${gb(t.capacity_registered)} · accessible ${gb(t.capacity_accessible)} · offline ${gb(t.capacity_offline)} · writable now ${gb(t.capacity_available_now)}`);78    console.log(`               used ${gb(t.used)} · redundant ${gb(t.redundant_bytes)} · sent ${gb(t.transferred_to_devices)} · received ${gb(t.transferred_from_devices)} · availability 24 h ${pct(t.availability_24h)} · integrity ${pct(t.integrity_rate)} (${t.integrity_checks} checks)`);79    for (const n of o.nodes) console.log(`  ${n.id}  ${String(n.name).padEnd(22)} ${String(n.health).padEnd(9)} ${String(n.model ?? "").padEnd(14)} iOS ${String(n.os_version ?? "").padEnd(6)} alloc ${gb(n.capacity.allocated).padStart(10)} used ${gb(n.capacity.used).padStart(10)} frags ${String(n.fragments).padStart(5)}  seen ${ago(n.last_seen)} via ${n.last_via ?? "—"}`);80    break;81  }82  case "node": console.log(JSON.stringify(await api("GET", "nodes/" + encodeURIComponent(args[0])), null, 1)); break;83  case "pair": {84    const p = await api("POST", "pairing", { label: args[0] ?? "", ttl_seconds: Number(args[1]) || undefined });85    console.log(`pairing code : ${p.code}\nexpires in   : ${p.ttl_seconds} s (single use)\nQR payload   : ${p.qr_payload}`);86    break;87  }88  case "codes": console.table((await api("GET", "pairing")).codes); break;89  case "unpair-code": console.log(await api("DELETE", "pairing/" + args[0])); break;90  case "revoke": case "suspend": case "resume": case "verify": console.log(JSON.stringify((await api("POST", `nodes/${encodeURIComponent(args[0])}/${cmd}`, {})), null, 1).slice(0, 600)); break;91  case "forget": console.log(await api("DELETE", "nodes/" + encodeURIComponent(args[0]))); break;92  case "drain": console.log(JSON.stringify((await api("POST", `nodes/${encodeURIComponent(args[0])}/drain`, { remove: args.includes("--remove") })).node.drain)); break;93  case "retrieve": console.log(JSON.stringify(await api("POST", `nodes/${encodeURIComponent(args[0])}/retrieve`, { count: Number(args[1]) || 1 }), null, 1)); break;94  case "put": {95    const file = args[0]; const size = statSync(file).size;96    const name = args[1] ?? basename(file);97    const klass = (args.find(a => a.startsWith("--class=")) ?? "--class=archive").slice(8);98    const t0 = Date.now();99    const r = await fetch(`${base}/admin/v1/objects?name=${encodeURIComponent(name)}&class=${encodeURIComponent(klass)}`, { method: "PUT", headers: { Authorization: `Bearer ${token}`, "Content-Length": String(size) }, body: Readable.toWeb(createReadStream(file, { highWaterMark: 1 << 20 })) as any, duplex: "half" } as any);100    const j = await r.json();101    if (!r.ok) { console.error(r.status, j); process.exit(1); }102    console.log(`object ${j.id}  ${gb(j.size)}  ${j.fragments} fragments (${j.new_fragments} new, ${j.deduplicated} deduplicated)  sha256 ${j.sha256}  ${((Date.now() - t0) / 1000).toFixed(1)} s`);103    break;104  }105  case "get": {106    const r = await fetch(`${base}/admin/v1/objects/${args[0]}/content`, { headers: { Authorization: `Bearer ${token}` } });107    if (!r.ok) { console.error(r.status, await r.text()); process.exit(1); }108    const h = createHash("sha256");109    const src = Readable.fromWeb(r.body as any);110    src.on("data", c => h.update(c));111    await pipeline(src, createWriteStream(args[1]));112    const got = h.digest("hex"), want = r.headers.get("x-object-sha256");113    console.log(`${args[1]}  sha256 ${got}  ${got === want ? "matches the catalog" : "DOES NOT MATCH " + want}`);114    if (got !== want) process.exit(1);115    break;116  }117  case "ls": for (const o of (await api("GET", "objects")).objects) console.log(`${o.id}  ${gb(o.size).padStart(11)}  ${String(o.fragments).padStart(5)} frags  on mobile ${o.mobile.covered}/${o.fragments} (${o.mobile.copies} copies)  ${o.class.padEnd(8)} ${o.name}`); break;118  case "show": console.log(JSON.stringify(await api("GET", "objects/" + args[0]), null, 1)); break;119  case "rm": console.log(await api("DELETE", "objects/" + args[0])); break;120  case "events": for (const e of (await api("GET", "events?limit=" + (Number(args[0]) || 40))).events.reverse()) console.log(`${new Date(e.ts * 1000).toISOString().slice(0, 19)}  ${String(e.device_name ?? "—").padEnd(18)} ${e.kind.padEnd(28)} ${JSON.stringify(e.detail)}`); break;121  case "transfers": for (const t of (await api("GET", "transfers?limit=" + (Number(args[0]) || 40))).transfers.reverse()) console.log(`${new Date(t.ts * 1000).toISOString().slice(0, 19)}  ${String(t.device_name).padEnd(18)} ${t.direction.padEnd(11)} ${gb(t.bytes).padStart(10)} ${String(t.ms).padStart(7)} ms  ${t.ms ? (t.bytes / 2 ** 20 / (t.ms / 1000)).toFixed(1).padStart(7) : "      —"} MiB/s  ${t.via.padEnd(7)} ${t.ok ? "ok" : "interrupted"}${t.resumed_from ? " resumed@" + t.resumed_from : ""}`); break;122  default:123    console.log("usage: mlstore status [--json] | node <id|name> | pair [label] [ttl] | codes | unpair-code <id> | put <file> [name] [--class=x] | get <object> <out> | ls | show <object> | rm <object>\n       | revoke|suspend|resume|verify|forget <node> | drain <node> [--remove] | retrieve <node> [count] | events [n] | transfers [n]");124}125
Files main
Menu

Theme