diff --git a/compose.yaml b/compose.yaml index f8c290d..a804e81 100644 --- a/compose.yaml +++ b/compose.yaml @@ -174,6 +174,7 @@ services: PROJECT_DIR: /project LLAMA_MODELS_DIR: /project/gpu/llama_models NODE_INSTANCE: ${TAILSCALE_HOSTNAME:-gpu-node} + TAILSCALE_HOSTNAME: ${TAILSCALE_HOSTNAME:-gpu-node} networks: - gpu-node restart: always diff --git a/dashboard/src/app/api/debug/route.ts b/dashboard/src/app/api/debug/route.ts index 935bb02..6c868c0 100644 --- a/dashboard/src/app/api/debug/route.ts +++ b/dashboard/src/app/api/debug/route.ts @@ -6,8 +6,10 @@ import { HOST_PROJECT_PATH, LLAMA_MODELS_DIR, NODE_INSTANCE, + TAILSCALE_HOSTNAME, ENV_FILE_PATH, DASHBOARD_CONFIG_PATH, + validateComposeEnv, } from "@/lib/docker"; export const dynamic = "force-dynamic"; @@ -21,6 +23,7 @@ export const runtime = "nodejs"; * - Whether key paths exist * - Directory listings of PROJECT_DIR and LLAMA_MODELS_DIR * - Contents of .env (if present) — useful for verifying HOST_PROJECT_PATH was set + * - Validation result: are all env vars needed by `docker compose` actually set? * * Useful for diagnosing "models not visible" type issues. */ @@ -58,7 +61,20 @@ export async function GET() { entries: await listDirSafe(comfyModelsDir), }); - // 4. .env file + // 4. Comfy subdirs (model types) + let comfyTypes: string[] = []; + if (await isDirSafe(comfyModelsDir)) { + try { + const entries = await fs.readdir(comfyModelsDir, { withFileTypes: true }); + comfyTypes = entries + .filter((e) => e.isDirectory() && !e.isSymbolicLink()) + .map((e) => e.name); + } catch { + /* ignore */ + } + } + + // 5. .env file (raw contents + parsed) const envExists = await existsSafe(ENV_FILE_PATH); let envContents: string | null = null; if (envExists) { @@ -69,15 +85,19 @@ export async function GET() { } } - // 5. Dashboard config + // 6. Dashboard config const configExists = await existsSafe(DASHBOARD_CONFIG_PATH); + // 7. Validate env — are all vars needed by docker compose actually set? + const envError = await validateComposeEnv(); + return NextResponse.json({ env: { PROJECT_DIR, HOST_PROJECT_PATH, LLAMA_MODELS_DIR, NODE_INSTANCE, + TAILSCALE_HOSTNAME, ENV_FILE_PATH, DASHBOARD_CONFIG_PATH, // Also expose relevant process.env for debugging @@ -91,8 +111,15 @@ export async function GET() { }, }, checks, - envFile: envExists ? { exists: true, contents: envContents } : { exists: false }, + comfyTypes, + envFile: envExists + ? { exists: true, contents: envContents } + : { exists: false }, dashboardConfig: { exists: configExists, path: DASHBOARD_CONFIG_PATH }, + envValidation: { + ok: envError === null, + error: envError, + }, timestamp: new Date().toISOString(), }); } @@ -123,3 +150,4 @@ async function listDirSafe(p: string): Promise { return [`[error: ${(err as Error).message}]`]; } } + diff --git a/dashboard/src/lib/docker.ts b/dashboard/src/lib/docker.ts index 2da069d..e85487e 100644 --- a/dashboard/src/lib/docker.ts +++ b/dashboard/src/lib/docker.ts @@ -1,6 +1,6 @@ import { exec, spawn, type ExecOptions } from "node:child_process"; import { promisify } from "node:util"; -import { promises as fs } from "node:fs"; +import { promises as fs, existsSync } from "node:fs"; import path from "node:path"; const execAsync = promisify(exec); @@ -14,13 +14,109 @@ const execAsync = promisify(exec); */ export const PROJECT_DIR = process.env.PROJECT_DIR || "/project"; +/** + * Path to the project's .env file. We parse it ourselves to ensure compose + * always gets the right HOST_PROJECT_PATH / TAILSCALE_HOSTNAME, regardless + * of how the dashboard container itself was started. + */ +export const ENV_FILE_PATH = path.join(PROJECT_DIR, ".env"); + +/** + * Parsed contents of the .env file. Read once at startup, cached. + * Falls back to {} if the file doesn't exist (only happens on dev machines). + */ +let _envCache: Record | null = null; + +async function loadEnvFile(): Promise> { + if (_envCache !== null) return _envCache; + const out: Record = {}; + try { + const raw = await fs.readFile(ENV_FILE_PATH, "utf-8"); + for (const line of raw.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eq = trimmed.indexOf("="); + if (eq < 0) continue; + const key = trimmed.slice(0, eq).trim(); + let val = trimmed.slice(eq + 1).trim(); + // Strip surrounding quotes + if ( + (val.startsWith('"') && val.endsWith('"')) || + (val.startsWith("'") && val.endsWith("'")) + ) { + val = val.slice(1, -1); + } + out[key] = val; + } + } catch { + /* .env doesn't exist — fall through with empty out */ + } + _envCache = out; + return out; +} + +/** + * Sync version (uses cache populated by loadEnvFile, or reads file on first + * call). Used in places that can't be async (e.g. module-level exports). + */ +function readEnvSync(): Record { + if (_envCache !== null) return _envCache; + const out: Record = {}; + if (existsSync(ENV_FILE_PATH)) { + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const raw = require("node:fs").readFileSync(ENV_FILE_PATH, "utf-8"); + for (const line of raw.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eq = trimmed.indexOf("="); + if (eq < 0) continue; + const key = trimmed.slice(0, eq).trim(); + let val = trimmed.slice(eq + 1).trim(); + if ( + (val.startsWith('"') && val.endsWith('"')) || + (val.startsWith("'") && val.endsWith("'")) + ) { + val = val.slice(1, -1); + } + out[key] = val; + } + } catch { + /* ignore */ + } + } + _envCache = out; + return out; +} + +/** + * Resolve an env value: process.env first (set by compose.yaml), then .env + * file, then the given default. + */ +function envOrFile(key: string, fallback: string = ""): string { + const fromProcess = process.env[key]; + if (fromProcess && fromProcess.length > 0) return fromProcess; + const fromFile = readEnvSync()[key]; + if (fromFile && fromFile.length > 0) return fromFile; + return fallback; +} + /** * Host-side absolute path of the GPU-Node project. Required so that when the * dashboard spawns `docker compose`, the compose file's relative volume mounts * resolve correctly on the host (where Docker daemon actually runs). + * + * Reads from env first, then .env file. If neither is set, returns "/project" + * (the internal mount) as a last-resort fallback — but operations that need + * the real host path will fail with a clear error. */ -export const HOST_PROJECT_PATH = - process.env.HOST_PROJECT_PATH || "/project"; +export const HOST_PROJECT_PATH = envOrFile("HOST_PROJECT_PATH", "/project"); + +/** + * Tailscale hostname — used for container_name and NODE_INSTANCE labels. + * Read from env / .env so we always match what the rest of the stack is using. + */ +export const TAILSCALE_HOSTNAME = envOrFile("TAILSCALE_HOSTNAME", "gpu-node"); /** * Internal mount of the llama_models directory. @@ -32,7 +128,7 @@ export const LLAMA_MODELS_DIR = * Node instance name (used for filtering containers by label). */ export const NODE_INSTANCE = - process.env.NODE_INSTANCE || process.env.TAILSCALE_HOSTNAME || "gpu-node"; + envOrFile("NODE_INSTANCE", "") || TAILSCALE_HOSTNAME; /** * Compose file path (relative to PROJECT_DIR). @@ -49,12 +145,6 @@ export const DASHBOARD_CONFIG_PATH = path.join( "config.json" ); -/** - * Path to the project's .env file (used to persist LLAMA_MODEL/LLAMA_EXTRA_ARGS - * so users can still inspect the .env if they prefer). - */ -export const ENV_FILE_PATH = path.join(PROJECT_DIR, ".env"); - // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- @@ -307,6 +397,10 @@ export async function writeEnvLlamaConfig( if (!hasExtra) out.push(`LLAMA_EXTRA_ARGS=${extraArgs}`); await fs.writeFile(ENV_FILE_PATH, out.join("\n").replace(/\n+$/, "\n"), "utf-8"); + + // Invalidate the in-memory .env cache so the next composeEnv() call picks + // up the new values. + _envCache = null; } // --------------------------------------------------------------------------- @@ -349,11 +443,70 @@ function humanSize(bytes: number): string { // Docker / Compose control // --------------------------------------------------------------------------- +/** + * Validate that the env vars needed by `docker compose` are actually set. + * Returns null if all good, or an error message describing the first missing + * var. Mirrors what `gpuctl` does via `require_host_project_path` etc. + */ +export async function validateComposeEnv(): Promise { + // Make sure .env is loaded + await loadEnvFile(); + + if (!HOST_PROJECT_PATH || HOST_PROJECT_PATH === "/project") { + // /project is the internal mount — compose needs the actual host path + return ( + "HOST_PROJECT_PATH is not set. Set it in /project/.env to the absolute " + + "path of the GPU-Node directory on the host (e.g. " + + "/home/operator/projects/GPU-Node). Without it, compose will resolve " + + "${HOST_PROJECT_PATH:-./} to './' relative to the dashboard container's " + + "CWD — but the resulting path doesn't exist on the host." + ); + } + if (!TAILSCALE_HOSTNAME) { + return "TAILSCALE_HOSTNAME is not set in env or .env file"; + } + return null; +} + +/** + * Build the env for `docker compose` subprocess. + * + * IMPORTANT: we explicitly set every variable that compose.yaml references, + * pulling from process.env (set by the dashboard container's own + * environment: line in compose.yaml) and falling back to the .env file + * parsed at startup. This mirrors how `gpuctl` shells pass `HOST_PROJECT_PATH=...` + * before `docker compose`. + * + * The full list comes from the .env.example: + * - TAILSCALE_HOSTNAME (used in container_name) + * - TS_AUTHKEY (needed by tailscale service) + * - WEBDAV_USER, WEBDAV_PASS (needed by webdav service) + * - HOST_PROJECT_PATH (used in all volume mounts) + * - LLAMA_MODEL, LLAMA_EXTRA_ARGS (used by llama service command) + * - COMFY_RUN_HOST, COMFY_BASE_HOST (used by comfyui service) + * - COMFY_EXTRA_ARGS (used by comfyui service) + * - NODE_INSTANCE (set by dashboard service in compose.yaml) + */ function composeEnv(extra: Record = {}): NodeJS.ProcessEnv { + // Start from .env file contents (lowest precedence) + const fileEnv = readEnvSync(); + return { + // Inherit the dashboard container's own process env (PATH, HOME, etc.) ...process.env, + + // .env file vars (these are also what compose would read if we didn't + // pass them explicitly, but explicit is better — compose's --env-file + // behaviour depends on CWD which may differ) + ...fileEnv, + + // Explicit overrides for variables we know compose needs + TAILSCALE_HOSTNAME, HOST_PROJECT_PATH, NODE_INSTANCE, + LLAMA_MODELS_DIR: undefined, // unset to avoid leaking internal mount + + // Caller-provided overrides (e.g. LLAMA_MODEL, LLAMA_EXTRA_ARGS for `up`) ...extra, }; } @@ -362,6 +515,24 @@ async function runCompose( args: string[], env: Record = {} ): Promise<{ stdout: string; stderr: string; code: number }> { + // Pre-validate env for `up`/`start` operations — fail fast with a clear + // error instead of letting compose silently resolve ${HOST_PROJECT_PATH:-./} + // to './' and then fail with a cryptic volume mount error. + const isUp = args.some((a) => a === "up" || a === "start" || a === "create"); + if (isUp) { + const err = await validateComposeEnv(); + if (err) { + return { + stdout: "", + stderr: `[dashboard] ${err}`, + code: 1, + }; + } + } + + // Make sure .env is loaded (no-op if already cached) + await loadEnvFile(); + const opts: ExecOptions = { cwd: PROJECT_DIR, env: composeEnv(env),