diff --git a/.changeset/list-running-containers.md b/.changeset/list-running-containers.md new file mode 100644 index 0000000..20df16d --- /dev/null +++ b/.changeset/list-running-containers.md @@ -0,0 +1,5 @@ +--- +"@mieweb/cli": minor +--- + +Add `mieweb containers list` to show running containers on the connected opensource-server Manager, with `--json` for scripts. diff --git a/README.md b/README.md index aabb8c1..cdb5349 100644 --- a/README.md +++ b/README.md @@ -50,12 +50,14 @@ Packages, split by *what a consumer must install*, not by module: ## Using the `mieweb` CLI Requires Node.js 22.18 or newer. By default, `mieweb login` opens the -os.mieweb.org Manager in your browser. Check your identity with `whoami`, then -run `deploy` from your project directory. +os.mieweb.org Manager in your browser. Check your identity with `whoami` and +use `containers list` to see the running containers your account can access. +Run `deploy` from your project directory. ```sh npx mieweb login npx mieweb whoami +npx mieweb containers list npx mieweb deploy ``` @@ -65,12 +67,13 @@ Or install once and use the command directly: npm install -g mieweb mieweb login mieweb whoami +mieweb containers list mieweb deploy ``` Commands that use a target print its name to standard error. For commands that contact an opensource-server Manager, the same line includes its URL. -Deploy, tail and destroy also show the site ID when one is configured. +Deploy, tail, destroy and `containers list` also show the site ID when one is configured. Wrangler commands show the named environment selected with `--env` or `CLOUDFLARE_ENV`. diff --git a/packages/cli/README.md b/packages/cli/README.md index c35ef55..3c64fc5 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -25,6 +25,25 @@ Select `--target cloudflare` to use Wrangler. The CLI uses in that order. Any target can override its deploy provider with `targets..provider` in `mieweb.jsonc`. +## List running containers + +On the default `mieweb` target, run this command from any directory to see +the running containers your account can access on the selected Manager. + +```sh +mieweb containers list +mieweb containers list --json +``` + +The table shows the site ID, container ID, hostname, node and status. +The command uses the same Manager and credentials as `mieweb whoami`. +`MIEWEB_OS_SITE_ID` selects a single site and takes precedence over +`targets.mieweb.siteId` in the project configuration. With neither set, +the command lists running containers across all sites visible to your account. + +On the Cloudflare target, `mieweb --target cloudflare containers list` +forwards to Wrangler and lists Cloudflare container applications. + ## Images (Cloudflare Containers) Build container images once, distribute them with **skopeo** diff --git a/packages/cli/src/containers.mjs b/packages/cli/src/containers.mjs new file mode 100644 index 0000000..a784738 --- /dev/null +++ b/packages/cli/src/containers.mjs @@ -0,0 +1,100 @@ +import { readFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import { configuredSiteId, managerUrl } from './provider.mjs'; + +const usage = 'Usage: mieweb containers list [--json]'; +const loginHint = 'Run `mieweb login` or set MIEWEB_OS_TOKEN.'; + +/** Read the OS provider's login for this exact Manager, using the same CI override as deploy. */ +async function managerToken(manager, env) { + const token = env.MIEWEB_OS_TOKEN?.trim(); + if (token) return token; + const file = env.MIEWEB_OS_CREDENTIALS?.trim() || join(env.HOME?.trim() || homedir(), '.mieweb', 'os.json'); + try { + const cache = JSON.parse(await readFile(file, 'utf8')); + const saved = cache?.instances?.[manager]?.token; + if (typeof saved === 'string' && saved.trim()) return saved; + } catch (err) { + if (err instanceof SyntaxError) throw new Error(`Invalid Manager login file at ${file}. ${loginHint}`); + if (err.code !== 'ENOENT') throw err; + } + throw new Error(`No credentials for ${manager}. ${loginHint}`); +} + +async function getList(manager, token, path) { + const response = await fetch(`${manager}/api/v1/${path}`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' }, + redirect: 'manual', + signal: AbortSignal.timeout(30_000), + }); + if (response.status === 401) throw new Error(`Manager rejected the credentials. ${loginHint}`); + if (!response.ok) throw new Error(`Manager request for ${path} failed (HTTP ${response.status}).`); + const body = await response.json().catch(() => null); + if (!Array.isArray(body?.data)) throw new Error(`Expected a list from the Manager at ${path}.`); + return body.data; +} + +async function listRunningContainers(config) { + const manager = managerUrl(config, process.env); + if (!manager) throw new Error('Invalid Manager URL. Use HTTPS or a loopback HTTP address.'); + const selected = configuredSiteId(config, process.env); + if (selected === null) throw new Error('The selected Manager site ID must be a positive integer.'); + const token = await managerToken(manager, process.env); + const sites = selected === undefined ? await getList(manager, token, 'sites') : [{ id: selected }]; + const running = []; + for (const site of sites) { + const siteId = site?.id; + if (!Number.isSafeInteger(siteId) || siteId <= 0) throw new Error('Manager returned an invalid site ID.'); + // The Manager defaults to caller-owned containers. The wildcard includes + // shared containers and keeps the authenticated account's visibility rules. + const containers = await getList(manager, token, `sites/${siteId}/containers?user[0]=*`); + for (const container of containers) { + if (typeof container?.status !== 'string') throw new Error(`Missing container status from site ${siteId}.`); + if (container.status !== 'running') continue; + // Container records can contain deployment secrets. Project only the inventory columns. + const { id, hostname, nodeName, status } = container; + if (!Number.isSafeInteger(id) || typeof hostname !== 'string' || (nodeName != null && typeof nodeName !== 'string')) { + throw new Error(`Invalid running container record from site ${siteId}.`); + } + running.push({ siteId, id, hostname, nodeName: nodeName ?? null, status }); + } + } + return running.sort((a, b) => a.siteId - b.siteId || a.id - b.id); +} + +function formatTable(rows) { + if (rows.length === 0) return 'No running containers.'; + const lines = [['SITE ID', 'ID', 'HOSTNAME', 'NODE', 'STATUS']]; + for (const { siteId, id, hostname, nodeName, status } of rows) { + // Keep Manager-supplied names on one terminal line. + const cells = [siteId, id, hostname, nodeName ?? '-', status]; + lines.push(cells.map((value) => JSON.stringify(String(value)).slice(1, -1))); + } + const widths = lines[0].map((_, i) => lines.reduce((max, row) => Math.max(max, row[i].length), 0)); + return lines.map((row) => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n'); +} + +/** @param {string[]} args @param {import('./config.mjs').MiewebConfig} config */ +export async function runContainersCommand(args, config) { + if (args.includes('--help') || args.includes('-h')) { + console.log(usage); + return 0; + } + if (args[0] !== 'list' || args.slice(1).some((arg) => arg !== '--json')) { + console.error(usage); + return 1; + } + try { + const rows = await listRunningContainers(config); + const output = args.includes('--json') ? JSON.stringify(rows, null, 2) : formatTable(rows); + // The CLI exits explicitly. Wait for large inventories piped to stdout to drain. + await new Promise((resolve, reject) => { + process.stdout.write(output + '\n', (err) => err ? reject(err) : resolve()); + }); + return 0; + } catch (err) { + console.error(`mieweb containers: ${err.message}`); + return 1; + } +} diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs index 497bcb8..fd45d2e 100755 --- a/packages/cli/src/index.mjs +++ b/packages/cli/src/index.mjs @@ -23,6 +23,7 @@ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { loadConfig } from './config.mjs'; import { delegateToWrangler } from './cloudflare.mjs'; +import { runContainersCommand } from './containers.mjs'; import { runHostTarget } from './local.mjs'; import { runInit } from './init.mjs'; import { runImagesCommand, runRegistryCommand } from './images.mjs'; @@ -80,6 +81,10 @@ async function main(argv) { const config = loadConfig({ overrideTarget }); process.stderr.write(`[mieweb] Target: ${formatEnvironment(config, args)}\n`); + if (args[0] === 'containers' && usesOpensourceServer(config)) { + return runContainersCommand(args.slice(1), config); + } + // Container image plumbing (build once, skopeo copy — container-plan.md M2). // `images push` on the cloudflare target delegates to wrangler's managed // registry; every other target goes through skopeo to its own registry. @@ -158,6 +163,7 @@ function printHelp() { " mieweb login Authenticate the active target's provider.", " mieweb logout Clear the provider's stored session.", " mieweb whoami Show the provider's auth status.", + ' mieweb containers list [--json] List running containers on the connected Manager.', ' mieweb dev Start a dev server for the active target.', " mieweb deploy Deploy via the active target's provider.", ' mieweb tail Stream logs from the deployed worker.', diff --git a/packages/cli/src/provider.mjs b/packages/cli/src/provider.mjs index 5b2dd8b..038f227 100644 --- a/packages/cli/src/provider.mjs +++ b/packages/cli/src/provider.mjs @@ -2,6 +2,7 @@ import { pathToFileURL } from 'node:url'; import { resolve, join, isAbsolute } from 'node:path'; import { createRequire } from 'node:module'; +import { isIPv4 } from 'node:net'; import { resolve as resolveFrom } from 'import-meta-resolve'; import { existsSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; @@ -103,31 +104,54 @@ export function formatEnvironment(config, args, env = process.env) { return namedEnv ? `${target} (env ${JSON.stringify(namedEnv).slice(1, -1)})` : target; } - if (!providerVerb || verb === 'dev' || !usesOpensourceServer(config)) return target; + const listContainers = verb === 'containers' && args[1] === 'list'; + if ((!providerVerb && !listContainers) || verb === 'dev' || !usesOpensourceServer(config)) return target; // The OS provider accepts --instance for interactive auth only. Its other // verbs all resolve the Manager from the environment and then target config. const instanceArg = verb === 'login' || verb === 'logout' ? optionValues(args, ['--instance'])[0] : undefined; + const manager = managerUrl(config, env, instanceArg); + if (!manager) return target; + if (listContainers || verb === 'deploy' || verb === 'destroy' || verb === 'tail') { + const site = configuredSiteId(config, env); + if (site) return `${target} (${manager}, site ${site})`; + } + return `${target} (${manager})`; +} + +/** Canonical Manager base URL and login-cache key, or null for an invalid URL. + * @param {MiewebConfig} config + * @param {NodeJS.ProcessEnv} env + * @param {string} [instanceArg] + */ +export function managerUrl(config, env, instanceArg) { const raw = instanceArg ?? (env.MIEWEB_OS_URL?.trim() || sanitizeTargetConfig(config).instanceUrl); - if (typeof raw !== 'string') return target; + if (typeof raw !== 'string') return null; let url; try { url = new URL(raw.trim()); } catch { - return target; + return null; } - if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return target; - if (url.protocol === 'http:' && url.hostname !== 'localhost' && url.hostname !== '[::1]' && !url.hostname.startsWith('127.')) { - return target; + if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return null; + const loopback = url.hostname === 'localhost' || url.hostname === '[::1]' || (isIPv4(url.hostname) && url.hostname.startsWith('127.')); + if (url.protocol === 'http:' && !loopback) { + return null; } // Match the Manager's base path, discarding query and fragment data. const path = url.pathname.replace(/\/+$/, '').replace(/\/api\/v1$/, ''); - const manager = url.origin + path; - if (verb === 'deploy' || verb === 'destroy' || verb === 'tail') { - const value = env.MIEWEB_OS_SITE_ID?.trim() || config.targetConfig?.siteId; - const site = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value; - if (Number.isSafeInteger(site) && site > 0) return `${target} (${manager}, site ${site})`; - } - return `${target} (${manager})`; + return url.origin + path; +} + +/** Undefined when no site was selected, null when the selection is invalid. + * @param {MiewebConfig} config + * @param {NodeJS.ProcessEnv} env + * @returns {number|null|undefined} + */ +export function configuredSiteId(config, env) { + const value = env.MIEWEB_OS_SITE_ID?.trim() || config.targetConfig?.siteId; + if (value == null || value === '') return undefined; + const site = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value; + return Number.isSafeInteger(site) && site > 0 ? site : null; } /** diff --git a/packages/cli/test/command-output.test.mjs b/packages/cli/test/command-output.test.mjs index b42467e..28630d2 100644 --- a/packages/cli/test/command-output.test.mjs +++ b/packages/cli/test/command-output.test.mjs @@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; const exec = promisify(execFile); +const managerToken = 'inventory-token'; const cli = fileURLToPath(new URL('../src/index.mjs', import.meta.url)); function project(t) { @@ -18,28 +19,129 @@ function project(t) { delete env.MIEWEB_TARGET; delete env.MIEWEB_OS_URL; delete env.MIEWEB_OS_TOKEN; + delete env.MIEWEB_OS_SITE_ID; delete env.CLOUDFLARE_ENV; env.MIEWEB_OS_CREDENTIALS = join(cwd, 'credentials.json'); return { cwd, env }; } -test('whoami names the Manager used for the saved login and keeps the account on stdout', async (t) => { - const options = project(t); +async function fakeManager(t, resources) { + const requests = []; const server = createServer((req, res) => { - const valid = req.url === '/team/api/v1/session' && req.headers.authorization === 'Bearer fixture'; - res.writeHead(valid ? 200 : 403, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ data: { user: 'demo' } })); + const url = new URL(req.url, 'http://localhost'); + const resource = url.pathname.replace(/^\/team\/api\/v1\//, ''); + requests.push(resource); + const data = resources[resource]; + let status = 200; + if (req.headers.authorization !== `Bearer ${managerToken}`) status = 401; + else if (req.method !== 'GET' || data === undefined) status = 404; + else if (resource.endsWith('/containers') && url.searchParams.get('user[0]') !== '*') status = 400; + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(status === 200 ? { data } : { error: { message: 'Manager request failed' } })); }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); t.after(() => new Promise((resolve) => server.close(resolve))); - const manager = `http://127.0.0.1:${server.address().port}/team`; + return { manager: `http://127.0.0.1:${server.address().port}/team`, requests }; +} + +test('whoami names the Manager used for the saved login and keeps the account on stdout', async (t) => { + const options = project(t); + const { manager } = await fakeManager(t, { session: { user: 'demo' } }); options.env.MIEWEB_OS_URL = manager; - writeFileSync(options.env.MIEWEB_OS_CREDENTIALS, JSON.stringify({ instances: { [manager]: { token: 'fixture' } } })); + writeFileSync(options.env.MIEWEB_OS_CREDENTIALS, JSON.stringify({ instances: { [manager]: { token: managerToken } } })); const { stdout, stderr } = await exec(process.execPath, [cli, 'whoami'], options); assert.equal(stdout.trim(), 'Authenticated as demo (login) — provider "opensource-server".'); assert.equal(stderr.trim(), `[mieweb] Target: mieweb (${manager})`); }); +test('containers list reads every site on the selected Manager using its saved login', async (t) => { + const options = project(t); + const web = { id: 27, hostname: 'shared-web', nodeName: 'node-a', status: 'running' }; + const db = { id: 37, hostname: 'db', nodeName: 'node-b', status: 'running' }; + const { manager } = await fakeManager(t, { + sites: [{ id: 2, name: 'alpha' }, { id: 3, name: 'beta' }], + 'sites/2/containers': [ + { ...web, environmentVars: { PASSWORD: 'private-env-marker' } }, + { id: 29, hostname: 'offline-web', nodeName: 'node-a', status: 'offline' }, + ], + 'sites/3/containers': [ + { id: 36, hostname: 'pending-db', nodeName: 'node-b', status: 'creating' }, + db, + ], + }); + writeFileSync(join(options.cwd, 'mieweb.jsonc'), JSON.stringify({ targets: { mieweb: { instanceUrl: manager + '/api/v1/' } } })); + writeFileSync(options.env.MIEWEB_OS_CREDENTIALS, JSON.stringify({ instances: { + 'https://another-manager.example': { token: 'different-token' }, + [manager]: { token: managerToken }, + } })); + const { stdout, stderr } = await exec(process.execPath, [cli, 'containers', 'list', '--json'], options); + assert.deepEqual(JSON.parse(stdout).sort((a, b) => a.id - b.id), [{ siteId: 2, ...web }, { siteId: 3, ...db }]); + assert.equal(stderr.trim(), `[mieweb] Target: mieweb (${manager})`); + const table = await exec(process.execPath, [cli, 'containers', 'list'], options); + assert.match(table.stdout, /HOSTNAME/); + assert.match(table.stdout, /shared-web/); + assert.match(table.stdout, /\bdb\b/); + assert.doesNotMatch(table.stdout + table.stderr, /offline-web|pending-db|private-env-marker|inventory-token/); +}); + +test('containers list restricts inventory to the configured site or its environment override', async (t) => { + const options = project(t); + const { manager, requests } = await fakeManager(t, { + 'sites/4/containers': [{ id: 41, hostname: 'offline', nodeName: null, status: 'offline' }], + 'sites/8/containers': [], + }); + options.env.MIEWEB_OS_TOKEN = managerToken; + writeFileSync(join(options.cwd, 'mieweb.jsonc'), JSON.stringify({ targets: { mieweb: { instanceUrl: manager, siteId: 4 } } })); + const list = (...flags) => exec(process.execPath, [cli, 'containers', 'list', ...flags], options); + assert.deepEqual(JSON.parse((await list('--json')).stdout), []); + assert.match((await list()).stdout, /no running containers/i); + options.env.MIEWEB_OS_SITE_ID = '8'; + assert.deepEqual(JSON.parse((await list('--json')).stdout), []); + options.env.MIEWEB_OS_SITE_ID = 'invalid'; + await assert.rejects(list('--json'), (err) => err.code === 1 && /site ID/.test(err.stderr) && err.stdout === ''); + assert.deepEqual(requests, ['sites/4/containers', 'sites/4/containers', 'sites/8/containers']); +}); + +test('containers list fails on Manager errors without printing a partial inventory or credentials', async (t) => { + const options = project(t); + const { manager, requests } = await fakeManager(t, { + sites: [{ id: 1 }, { id: 2 }], + 'sites/1/containers': [{ id: 11, hostname: 'partial', nodeName: 'node-a', status: 'running' }], + }); + options.env.MIEWEB_OS_URL = manager; + writeFileSync(options.env.MIEWEB_OS_CREDENTIALS, JSON.stringify({ instances: { + 'https://another-manager.example': { token: managerToken }, + } })); + await assert.rejects(exec(process.execPath, [cli, 'containers', 'list'], options), (err) => { + assert.equal(err.stdout, ''); + assert.match(err.stderr, /mieweb login/); + return err.code === 1; + }); + assert.deepEqual(requests, []); + for (const token of ['expired-token', managerToken]) { + options.env.MIEWEB_OS_TOKEN = token; + await assert.rejects(exec(process.execPath, [cli, 'containers', 'list', '--json'], options), (err) => { + assert.equal(err.code, 1); + assert.equal(err.stdout, ''); + assert.doesNotMatch(err.stderr, /expired-token|inventory-token/); + assert.ok(err.stderr.trim().split('\n').length > 1); + return true; + }); + } + assert.deepEqual(requests.sort(), ['sites', 'sites', 'sites/1/containers', 'sites/2/containers']); +}); + +test('Cloudflare container subcommands and options are forwarded to Wrangler unchanged', async (t) => { + const options = project(t); + const wrangler = join(options.cwd, 'wrangler'); + writeFileSync(wrangler, '#!/usr/bin/env node\nconsole.log(JSON.stringify(process.argv.slice(2)))\n', { mode: 0o755 }); + options.env.MIEWEB_REAL_WRANGLER = wrangler; + for (const args of [['containers', 'list'], ['containers', 'instances', 'app-id', '--json']]) { + const { stdout } = await exec(process.execPath, [cli, '--target', 'cloudflare', ...args], options); + assert.deepEqual(JSON.parse(stdout), args); + } +}); + test('Wrangler passthrough leaves redirected JSON parseable', async (t) => { const options = project(t); const wrangler = join(options.cwd, 'wrangler');