// HU-5223: what kj runs on this machine now: its containers and daemons. Collecting only reads. import { readdirSync, readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { parseInspect } from "../sonar/own-container.js"; import { getKarajanHome, getOllamaComposePath, getSonarComposePath } from "../utils/paths.js"; import { runCommand } from "../utils/process.js"; const KJ_NAMES = new Set(["karajan-sonarqube", "karajan-sonarqube-db", "kj-ollama"]); const here = (file) => path.resolve(import.meta.dirname, file); const OWN_INSTALL = { execPath: process.execPath, board: here("../../packages/hu-board/src/server.js"), scripts: [here("../../bin/kj.js"), here("../cli.js")] }; const literal = RegExp.escape ?? ((text) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`)); function daemonCommands({ execPath, board, scripts }) { // runtime, flags, then kj's script; exact paths allow spaces const runBy = String.raw`^(?:(?:\S*[\\/])?(?:node|bun)(?:\.exe)?|${literal(execPath)})(?:\s+-\S*)*\s+(?!-)`; const cli = String.raw`(?:\S*[\\/])?kj(?:\.js)?|\S*[\\/]src[\\/]cli\.js|${scripts.map(literal).join("|")}`; return { board: new RegExp(String.raw`${runBy}(?:\S*[\\/]hu-board[\\/]src[\\/]server\.js|${literal(board)})(?:\s|$)`), watcher: new RegExp(String.raw`(?:${runBy}(?:${cli})|^(?:\S*[\\/])?kj)\s+watch\s+start(?:\s|$)`), }; } async function inspectAll(run) { // null: docker is absent or does not answer const docker = (...args) => run("docker", args, { timeout: 10_000 }); const listed = await docker("ps", "-aq", "--no-trunc"); if (listed.exitCode !== 0) return null; const ids = listed.stdout.split(/\s+/).filter(Boolean); if (ids.length === 0) return []; const inspected = await docker("inspect", ...ids); return inspected.exitCode === 0 ? parseInspect(inspected.stdout) : null; } async function removeContainer(run, id) { const res = await run("docker", ["rm", "-f", id], { timeout: 60_000 }); if (res.exitCode !== 0) throw new Error(res.stderr.trim() || `docker rm exited ${res.exitCode}`); } async function addContainers({ items, left }, run) { const all = await inspectAll(run); if (!all) { left.push({ what: "docker containers", why: "docker is absent or not answering: none looked at" }); return; } const composes = new Set([getSonarComposePath(), getOllamaComposePath()]); const volumes = new Set(); for (const { Id, Name, Config, Mounts } of all) { const name = Name.replace(/^\//, ""); if (composes.has(Config?.Labels?.["com.docker.compose.project.config_files"])) { items.push({ kind: "container", action: "remove", what: `container ${name} (${Id})`, apply: () => removeContainer(run, Id) }); for (const mount of Mounts ?? []) if (mount.Type === "volume") volumes.add(mount.Name); } else if (KJ_NAMES.has(name)) left.push({ what: `container ${name}`, why: "not from kj's compose file" }); } const names = [...volumes].join(" "); if (names) left.push({ what: `volumes ${names}`, why: `data; by hand: docker volume rm ${names}` }); } const isAlive = (pid, signal) => { try { signal(pid, 0); return true; } catch { return false; } }; async function ownerOf(pid, command, { run, signal }) { // a pid file outlives its process: pids are reused if (!Number.isInteger(pid) || pid <= 1 || !isAlive(pid, signal)) return "dead"; const res = await run("ps", ["-ww", "-o", "command=", "-p", String(pid)]); return res.exitCode === 0 && command.test(res.stdout.trim()) ? "kj" : "foreign"; } const readPid = (file) => Number(readFileSync(file, "utf8").trim()); function dropPidFile(file, pid) { // only while it still names the stopped process try { if (readPid(file) === pid) rmSync(file, { force: true }); } catch (error) { if (error.code !== "ENOENT") throw error; } } async function addDaemon({ items, left }, { label, file, command }, deps) { let pid; try { pid = readPid(file); } catch (error) { if (error.code !== "ENOENT") left.push({ what: file, why: `not read (${error.code})` }); return; } const owner = await ownerOf(pid, command, deps); if (owner === "foreign") left.push({ what: `pid ${pid} in ${file}`, why: "its command line is not kj's, or cannot be read" }); if (owner !== "kj") return; const apply = async () => { if (await ownerOf(pid, command, deps) !== "kj") throw new Error(`pid ${pid} is no longer kj's`); deps.signal(pid, "SIGTERM"); dropPidFile(file, pid); }; items.push({ kind: "daemon", action: "stop", what: `${label} (pid ${pid})`, apply }); } function pidFiles(dir) { try { return readdirSync(dir).filter((f) => f.endsWith(".pid")).map((f) => path.join(dir, f)); } catch (error) { if (error.code === "ENOENT") return []; throw error; } } export async function collectRuntime({ run = runCommand, signal = process.kill.bind(process), install = OWN_INSTALL } = {}) { const plan = { items: [], left: [] }; await addContainers(plan, run); const deps = { run, signal }; const commands = daemonCommands(install); await addDaemon(plan, { label: "HU Board", file: path.join(getKarajanHome(), "hu-board.pid"), command: commands.board }, deps); for (const file of pidFiles(path.join(getKarajanHome(), "watchers"))) { await addDaemon(plan, { label: "project watcher", file, command: commands.watcher }, deps); } return plan; }