Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

15.4 KB
Raw Blame
// Copyright 2026 Ix Infrastructure Inc.

import { Command } from "commander";
import { execFileSync, spawn } from "child_process";
import { createInterface } from "readline";
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { stampBackendVersionAfterPull } from "./upgrade.js";
import { clearLocalToken, ensureLocalToken } from "../config.js";
import { ixHome } from "../ix-home.js";
import { createClient } from "../../client/factory.js";
import { backendComposeArgs, composeSupportsLocalToken, handSetLocalToken, parseArangoHealth } from "../backend-compose.js";

// Functions, not consts, so they follow IX_HOME as it is when a command runs
// rather than when this module was imported -- see `ixHome()`.
const composeDir = (): string => join(ixHome(), "backend");
const localCompose = (): string => join(composeDir(), "docker-compose.yml");
const HEALTH_URL = "http://localhost:8090/v1/health";

/**
 * The compose file this CLI release ships. `npm run build` copies the repo's
 * docker-compose.standalone.yml to dist/, which the release tarball carries;
 * a source checkout also finds it at the repo root, four levels above this
 * file. Both are located from the CLI's own install, never from the cwd.
 */
function bundledComposeFile(): string | null {
  if (process.env.NODE_ENV === "test" && process.env.IX_BUNDLED_COMPOSE !== undefined) {
    return process.env.IX_BUNDLED_COMPOSE && existsSync(process.env.IX_BUNDLED_COMPOSE)
      ? process.env.IX_BUNDLED_COMPOSE
      : null;
  }
  const here = dirname(fileURLToPath(import.meta.url));
  for (const candidate of [
    join(here, "..", "..", "docker-compose.standalone.yml"),
    join(here, "..", "..", "..", "..", "docker-compose.standalone.yml"),
  ]) {
    if (existsSync(candidate)) return candidate;
  }
  return null;
}

/**
 * The backend's compose file, ~/.ix/backend/docker-compose.yml, written from
 * the copy this CLI ships when it is missing. Never a docker-compose.yml from
 * the working directory: `ix docker start` inside an untrusted repository
 * would otherwise run whatever services that repository's compose file
 * declares. And never a download from the `main` branch, which may not match
 * the installed CLI.
 */
function findComposeFile(): string | null {
  const local = localCompose();
  if (existsSync(local)) return local;
  const bundled = bundledComposeFile();
  if (!bundled) return null;
  try {
    mkdirSync(composeDir(), { recursive: true });
    copyFileSync(bundled, local);
    return local;
  } catch {
    return null;
  }
}

function arangoHealth(composeFile: string | null): ReturnType<typeof parseArangoHealth> | "unknown" {
  if (!composeFile) return "unknown";
  try {
    const out = execFileSync("docker", [...backendComposeArgs(composeFile), "ps", "--format", "json", "arangodb"], {
      encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000,
    });
    return parseArangoHealth(out);
  } catch {
    return "unknown";
  }
}

function reportMissingCompose(): void {
  console.error(`[error] No backend compose file at ${localCompose()}, and this CLI install does not ship one.`);
  console.error("  Reinstall or run 'ix upgrade' to restore it.");
}

/** Compose projects whose volumes are Ix backend data: ix docker's own, and a repo checkout run directly. */
const IX_COMPOSE_PROJECTS = new Set(["backend", "ix"]);

/**
 * Is this volume an Ix backend's ArangoDB data? Exact compose project and
 * volume names. The previous test (project starting with "ix", volume
 * containing "arango") also matched other stacks' databases on the same
 * machine (ix-bench, a personal or test backend), which --remove-all-data
 * then deleted.
 */
export function isIxArangoVolume(labels: Map<string, string>): boolean {
  return (
    IX_COMPOSE_PROJECTS.has(labels.get("com.docker.compose.project") ?? "") &&
    labels.get("com.docker.compose.volume") === "arangodb-data"
  );
}

function findIxArangoVolumes(): string[] {
  try {
    const output = execFileSync(
      "docker",
      ["volume", "ls", "--format", "{{.Name}}|{{.Labels}}"],
      { encoding: "utf-8", timeout: 10000 }
    ).trim();
    if (!output) return [];

    return output.split("\n").filter((line) => {
      const [name, labels] = line.split("|", 2);
      if (!name || !labels) return false;

      const labelMap = new Map<string, string>();
      for (const pair of labels.split(",")) {
        const eq = pair.indexOf("=");
        if (eq > 0) labelMap.set(pair.slice(0, eq), pair.slice(eq + 1));
      }

      return isIxArangoVolume(labelMap);
    }).map((line) => line.split("|", 1)[0]);
  } catch {
    return [];
  }
}

function askConfirmation(prompt: string): Promise<boolean> {
  const rl = createInterface({ input: process.stdin, output: process.stderr });
  return new Promise((resolve) => {
    rl.question(prompt, (answer) => {
      rl.close();
      resolve(answer.toLowerCase() === "y");
    });
  });
}

function memoryLayerResponds(timeout = 5000): boolean {
  try {
    execFileSync("curl", ["-sf", HEALTH_URL], { stdio: "ignore", timeout });
    return true;
  } catch {
    return false;
  }
}

/**
 * The memory layer answers its health route (which reports 503 while it cannot
 * reach ArangoDB), and this project's arangodb container, if it runs one, is
 * not unhealthy. ArangoDB is no longer probed on a host port: the compose file
 * does not publish one. A backend served by some other stack ("absent",
 * "unknown") is judged by the memory layer alone, as before.
 */
function isHealthy(composeFile: string | null): boolean {
  if (!memoryLayerResponds()) return false;
  const arango = arangoHealth(composeFile);
  return arango !== "unhealthy" && arango !== "starting";
}

/** One line on whether the running backend requires the local token. Best-effort. */
async function reportLocalAuth(): Promise<void> {
  try {
    const caps = await createClient({ endpoint: "http://localhost:8090" }).fetchCapabilities();
    if (caps.local_auth === undefined) {
      console.log("  Local token:  not supported by this backend image (run 'ix upgrade')");
    } else {
      console.log(`  Local token:  ${caps.local_auth_enforcing ? "required" : "off"}`);
    }
  } catch (err) {
    if ((err as Error)?.name === "LocalTokenRequiredError") {
      console.log("  Local token:  required, and this CLI's token was refused (run 'ix docker start --local-token')");
    }
  }
}

function dockerAvailable(): boolean {
  try {
    execFileSync("docker", ["info"], { stdio: "ignore", timeout: 10000 });
    return true;
  } catch {
    return false;
  }
}

export function registerDockerCommand(program: Command): void {
  const docker = program
    .command("docker")
    .description("Manage the IX backend Docker containers");

  docker
    .command("start")
    .alias("up")
    .description("Start the IX backend (ArangoDB + Memory Layer)")
    .option("--local-token", "Require a bearer token on the backend; the CLI stores and sends it")
    .option("--no-local-token", "Stop requiring the token and forget the stored one")
    .action(async (opts: { localToken?: boolean }) => {
      // Written before anything else, so stop/restart/logs work from any directory.
      const composeFile = findComposeFile();

      // Opt-in until a release turns the token on by default. Changing it means
      // recreating memory-layer with the new environment, so a healthy backend
      // is not left as it is.
      const changeToken = opts.localToken !== undefined;
      if (opts.localToken === true) {
        let composeText = "";
        try { composeText = composeFile ? readFileSync(composeFile, "utf-8") : ""; } catch { /* reported below */ }
        if (!composeSupportsLocalToken(composeText)) {
          console.error(`[error] ${composeFile ?? localCompose()} does not pass IX_LOCAL_TOKEN to the backend.`);
          console.error("  It predates token support, and 'ix upgrade' does not replace it. Move it aside and");
          console.error("  run this again: 'ix docker start' then writes the compose file this CLI ships.");
          console.error(`    mv ${localCompose()} ${localCompose()}.old`);
          process.exit(1);
        }
        // A token already set by hand in .env is adopted rather than replaced,
        // so whatever else was given it (IX_TOKEN, another client) keeps working.
        ensureLocalToken(handSetLocalToken());
      } else if (opts.localToken === false) {
        clearLocalToken();
      }

      if (!changeToken && isHealthy(composeFile)) {
        console.log("[ok] Backend is already running and healthy");
        console.log("  Memory Layer: http://localhost:8090");
        await reportLocalAuth();
        return;
      }

      if (!dockerAvailable()) {
        console.error("[error] Docker is not running.");
        console.error("  Start Docker Desktop and try again.");
        process.exit(1);
      }

      if (!composeFile) {
        reportMissingCompose();
        process.exit(1);
      }

      console.log("Starting backend services...");
      try {
        // Only `up` writes .env: it is what hands the container a changed token.
        const composeArgs = backendComposeArgs(composeFile, { writeEnv: true, clearToken: opts.localToken === false });
        execFileSync("docker", [...composeArgs, "up", "-d", "--pull", "always"], {
          stdio: "inherit",
        });
      } catch {
        console.error("[error] Failed to start Docker containers.");
        process.exit(1);
      }

      // `--pull always` just fetched the images this compose names, so if it
      // tracks `:latest` the container is now running the current backend
      // release — record it. Without this the tracked version only ever moves
      // when `ix upgrade` runs, so starting the backend any other way leaves a
      // file naming an older release and the update notice fires on every
      // command for ever. The compose file is passed because it decides whether
      // that premise holds at all: a user may have edited it to pin a tag, a
      // digest, or a local build.
      // Awaited so the stamp is on disk before the command returns, and it
      // cannot fail the start: the helper swallows its own errors.
      await stampBackendVersionAfterPull(composeFile);

      console.log("Waiting for services to become healthy...");
      for (let i = 0; i < 30; i++) {
        if (isHealthy(composeFile)) {
          console.log("");
          console.log("[ok] Backend is ready!");
          console.log("  Memory Layer: http://localhost:8090");
          if (changeToken) await reportLocalAuth();
          return;
        }
        process.stdout.write(".");
        await new Promise((r) => setTimeout(r, 2000));
      }

      console.log("");
      console.error("[!!] Health check timed out. Check: ix docker logs");
      process.exit(1);
    });

  docker
    .command("stop")
    .alias("down")
    .description("Stop the IX backend containers")
    .option("--remove-data", "Also remove the current project's ArangoDB data volume")
    .option("--remove-all-data", "Remove all local Ix ArangoDB data volumes across repos")
    .option("--yes", "Skip confirmation prompt (for use with --remove-all-data)")
    .action(async (opts) => {
      const composeFile = findComposeFile();
      if (!composeFile) {
        reportMissingCompose();
        process.exit(1);
      }

      const removeLocal = opts.removeData || opts.removeAllData;
      const args = [...backendComposeArgs(composeFile), "down"];
      if (removeLocal) args.push("-v");

      try {
        execFileSync("docker", args, { stdio: "inherit" });
      } catch {
        console.error("[error] Failed to stop containers.");
        process.exit(1);
      }

      if (opts.removeAllData) {
        const volumes = findIxArangoVolumes();
        if (volumes.length === 0) {
          console.log("[ok] Backend stopped. No additional Ix data volumes found.");
          return;
        }

        if (!opts.yes) {
          console.log("");
          console.log("This will remove all local Ix ArangoDB data volumes across repos:");
          for (const v of volumes) console.log(`  ${v}`);
          console.log("");
          const confirmed = await askConfirmation("Continue? [y/N] ");
          if (!confirmed) {
            console.log("Aborted.");
            return;
          }
        }

        const removed: string[] = [];
        const failed: string[] = [];
        for (const v of volumes) {
          try {
            execFileSync("docker", ["volume", "rm", v], { stdio: "ignore", timeout: 10000 });
            removed.push(v);
          } catch {
            failed.push(v);
          }
        }

        if (failed.length > 0) {
          console.error("");
          console.error("[error] Failed to remove one or more Ix data volumes.");
          for (const v of failed) console.error(`  ${v}`);
          console.error("");
          console.error("  Volumes may be in use. Stop all Ix containers first.");
          process.exitCode = 1;
        }

        if (removed.length > 0) {
          console.log("");
          console.log("[ok] Backend stopped and all local Ix data volumes removed.");
          console.log("");
          console.log("Removed:");
          for (const v of removed) console.log(`  ${v}`);
        }
      } else if (opts.removeData) {
        console.log("[ok] Backend stopped and data volume removed.");
      } else {
        console.log("[ok] Backend stopped. Data volume preserved.");
        console.log("  Use 'ix docker stop --remove-data' to also delete data.");
      }
    });

  docker
    .command("status")
    .description("Show backend container and health status")
    .action(async () => {
      const composeFile = findComposeFile();
      if (composeFile) {
        try {
          execFileSync("docker", [...backendComposeArgs(composeFile), "ps"], {
            stdio: "inherit",
          });
        } catch {
          // compose ps failed, that's ok
        }
      }
      console.log("");
      if (isHealthy(composeFile)) {
        console.log("[ok] Backend is healthy");
        console.log("  Memory Layer: http://localhost:8090");
        await reportLocalAuth();
      } else {
        console.log("[!!] Backend is not healthy");
        console.log(`  Memory Layer: ${memoryLayerResponds(3000) ? "responding" : "not responding"}`);
        const arango = arangoHealth(composeFile);
        console.log(`  ArangoDB: ${arango === "absent" ? "no container" : arango === "unknown" ? "container state unknown" : arango}`);
      }
    });

  docker
    .command("logs")
    .description("Tail backend container logs")
    .option("-f, --follow", "Follow log output", true)
    .action((opts) => {
      const composeFile = findComposeFile();
      if (!composeFile) {
        reportMissingCompose();
        process.exit(1);
      }

      const args = [...backendComposeArgs(composeFile), "logs"];
      if (opts.follow) args.push("-f");
      const child = spawn("docker", args, { stdio: "inherit" });
      child.on("exit", (code) => process.exit(code || 0));
    });

  docker
    .command("restart")
    .description("Restart the IX backend containers")
    .action(() => {
      const composeFile = findComposeFile();
      if (!composeFile) {
        reportMissingCompose();
        process.exit(1);
      }

      try {
        execFileSync("docker", [...backendComposeArgs(composeFile), "restart"], {
          stdio: "inherit",
        });
        console.log("[ok] Backend restarted.");
      } catch {
        console.error("[error] Failed to restart containers.");
        process.exit(1);
      }
    });
}