Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/list-running-containers.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand All @@ -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`.

Expand Down
19 changes: 19 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<target>.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**
Expand Down
100 changes: 100 additions & 0 deletions packages/cli/src/containers.mjs
Original file line number Diff line number Diff line change
@@ -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;
}
}
6 changes: 6 additions & 0 deletions packages/cli/src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.',
Expand Down
50 changes: 37 additions & 13 deletions packages/cli/src/provider.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
}

/**
Expand Down
Loading
Loading