Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

self-hosting: openpanel CLI entry point with doctor and compose commands

Carl-Gerhard Lindesvärd8245ec6e9147
diff --git a/self-hosting/cli/src/commands/compose.ts b/self-hosting/cli/src/commands/compose.ts
new file mode 100644
index 000000000..85270e438
--- /dev/null
+++ b/self-hosting/cli/src/commands/compose.ts
@@ -0,0 +1,31 @@
+import { run } from '../run';
+
+const ARGS = {
+ up: ['up', '-d'],
+ down: ['down'],
+ restart: ['up', '-d', '--force-recreate'],
+ logs: ['logs', '-f', '--tail', '200'],
+ status: ['ps'],
+} as const;
+
+export type ComposeCommand = keyof typeof ARGS;
+
+export const isComposeCommand = (name: string): name is ComposeCommand =>
+ name in ARGS;
+
+// `restart` recreates so a changed .env is picked up; plain `docker compose
+// restart` keeps the old environment, which is what bit ./restart before.
+export const compose = async (
+ command: ComposeCommand,
+ dir: string,
+ extra: string[] = []
+): Promise<number> => {
+ const { code } = await run(
+ ['docker', 'compose', ...ARGS[command], ...extra],
+ {
+ cwd: dir,
+ inherit: true,
+ }
+ );
+ return code;
+};
diff --git a/self-hosting/cli/src/commands/doctor.ts b/self-hosting/cli/src/commands/doctor.ts
new file mode 100644
index 000000000..1a0f0a420
--- /dev/null
+++ b/self-hosting/cli/src/commands/doctor.ts
@@ -0,0 +1,83 @@
+import { applyFixes, type Finding, runDoctor } from '../doctor';
+import { checkHost } from '../host';
+import { isInstallDir, loadInstall, writeInstall } from '../install';
+import { bold, dim, green, log, red, SEVERITY_LABEL } from '../ui';
+
+interface DoctorOptions {
+ dir: string;
+ fix: boolean;
+ check: boolean;
+}
+
+const printFinding = (finding: Finding) => {
+ log(`${SEVERITY_LABEL[finding.severity]} ${bold(finding.title)}`);
+ log(` ${dim(finding.detail)}`);
+ const action = finding.fix ? green('fixable with --fix') : finding.manual;
+ if (action) {
+ log(` ${dim('→')} ${action}`);
+ }
+};
+
+const printHost = async (): Promise<boolean> => {
+ const results = await checkHost();
+ for (const result of results) {
+ log(`${result.ok ? green('ok') : red('!!')} ${result.title}`);
+ if (!result.ok && result.hint) {
+ log(` ${dim(result.hint)}`);
+ }
+ }
+ return results.every((result) => result.ok);
+};
+
+export const doctor = async ({
+ dir,
+ fix,
+ check,
+}: DoctorOptions): Promise<number> => {
+ log(bold('Host'));
+ const hostOk = await printHost();
+ log();
+
+ if (!isInstallDir(dir)) {
+ log(`No install found in ${dir}. Run \`openpanel init\` to create one.`);
+ return hostOk ? 0 : 1;
+ }
+
+ const install = loadInstall(dir);
+ const findings = runDoctor(install);
+ log(bold(`Install (${dir})`));
+ if (findings.length === 0) {
+ log(`${green('ok')} Nothing to fix.`);
+ return hostOk ? 0 : 1;
+ }
+ for (const finding of findings) {
+ printFinding(finding);
+ }
+ log();
+
+ const fixable = findings.filter((finding) => finding.fix);
+ const blocking = findings.filter((finding) => finding.severity === 'error');
+
+ if (!fix) {
+ log(
+ fixable.length > 0
+ ? `Run \`openpanel doctor --fix\` to repair ${fixable.length} of ${findings.length}.`
+ : 'Nothing here can be fixed automatically.'
+ );
+ return check && blocking.length > 0 ? 1 : 0;
+ }
+
+ applyFixes(install);
+ const written = await writeInstall(dir, install);
+ log(
+ green(`Fixed ${fixable.length}. Wrote ${written.join(', ') || 'nothing'}.`)
+ );
+ if (written.length > 0) {
+ log(dim('Originals saved next to each file as <name>.bak.'));
+ }
+ const manual = findings.filter((finding) => !finding.fix);
+ if (manual.length > 0) {
+ log(`${manual.length} item(s) still need you — see above.`);
+ }
+ return 0;
+};
diff --git a/self-hosting/cli/src/host.ts b/self-hosting/cli/src/host.ts
new file mode 100644
index 000000000..ddc9fb321
--- /dev/null
+++ b/self-hosting/cli/src/host.ts
@@ -0,0 +1,69 @@
+import { totalmem } from 'node:os';
+import { run } from './run';
+
+const BYTES_PER_GIB = 1024 ** 3;
+// Redpanda is pinned to 2G of its own; the rest of the stack needs headroom.
+const MIN_RAM_GIB = 4;
+
+export interface HostCheck {
+ id: string;
+ ok: boolean;
+ title: string;
+ hint?: string;
+}
+
+const DOCKER_INSTALL_HINT =
+ 'Install Docker: https://docs.docker.com/engine/install/ (Linux: `curl -fsSL https://get.docker.com | sh`)';
+
+export const checkHost = async (): Promise<HostCheck[]> => {
+ const docker = await run(['docker', '--version']);
+ if (docker.code !== 0) {
+ return [
+ {
+ id: 'host/docker',
+ ok: false,
+ title: 'Docker is not installed',
+ hint: DOCKER_INSTALL_HINT,
+ },
+ ];
+ }
+
+ const compose = await run(['docker', 'compose', 'version']);
+ const daemon = await run(['docker', 'info']);
+ const ramGiB = totalmem() / BYTES_PER_GIB;
+
+ return [
+ { id: 'host/docker', ok: true, title: docker.stdout.trim() },
+ {
+ id: 'host/compose',
+ ok: compose.code === 0,
+ title:
+ compose.code === 0
+ ? compose.stdout.trim()
+ : 'Docker Compose v2 is missing',
+ hint: 'Install the compose plugin: https://docs.docker.com/compose/install/',
+ },
+ {
+ id: 'host/daemon',
+ ok: daemon.code === 0,
+ title:
+ daemon.code === 0
+ ? 'Docker daemon is reachable'
+ : 'Cannot reach the Docker daemon',
+ hint: 'Start Docker, or add your user to the docker group: `sudo usermod -aG docker $USER` and log in again.',
+ },
+ {
+ id: 'host/memory',
+ ok: ramGiB >= MIN_RAM_GIB,
+ title: `${ramGiB.toFixed(1)} GiB RAM (need ${MIN_RAM_GIB}+)`,
+ hint: 'Redpanda, ClickHouse and Postgres together need at least 4 GiB.',
+ },
+ ];
+};
+
+// Offered only on Linux: Docker's own script, shown to the user before it runs.
+export const DOCKER_INSTALL_COMMAND = [
+ 'sh',
+ '-c',
+ 'curl -fsSL https://get.docker.com | sh',
+];
diff --git a/self-hosting/cli/src/main.ts b/self-hosting/cli/src/main.ts
new file mode 100644
index 000000000..33f8f0b7d
--- /dev/null
+++ b/self-hosting/cli/src/main.ts
@@ -0,0 +1,75 @@
+import { homedir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { parseArgs } from 'node:util';
+import { compose, isComposeCommand } from './commands/compose';
+import { doctor } from './commands/doctor';
+import { isInstallDir } from './install';
+import { log } from './ui';
+
+const VERSION = '0.1.0';
+const DEFAULT_DIR = join(homedir(), 'openpanel');
+
+const HELP = `openpanel ${VERSION} — run and maintain a self-hosted OpenPanel
+
+Usage: openpanel <command> [options]
+
+Commands:
+ doctor [--fix] [--check] Check the host and your install; --fix repairs it
+ up | down | restart Start, stop, or recreate the stack
+ logs [service] Follow logs
+ status Show running services
+
+Options:
+ --dir <path> Install directory (default: current dir if it has
+ a docker-compose.yml, else ~/openpanel)
+ -h, --help Show this help
+ -v, --version Show the version
+`;
+
+// A user standing in their install dir should not have to say so.
+const resolveDir = (flag: string | undefined): string => {
+ if (flag) {
+ return resolve(flag);
+ }
+ if (process.env.OPENPANEL_DIR) {
+ return resolve(process.env.OPENPANEL_DIR);
+ }
+ return isInstallDir(process.cwd()) ? process.cwd() : DEFAULT_DIR;
+};
+
+const main = async (): Promise<number> => {
+ const { values, positionals } = parseArgs({
+ args: process.argv.slice(2),
+ allowPositionals: true,
+ options: {
+ dir: { type: 'string' },
+ fix: { type: 'boolean', default: false },
+ check: { type: 'boolean', default: false },
+ help: { type: 'boolean', short: 'h', default: false },
+ version: { type: 'boolean', short: 'v', default: false },
+ },
+ });
+ const [command, ...rest] = positionals;
+
+ if (values.version) {
+ log(VERSION);
+ return 0;
+ }
+ if (values.help || !command) {
+ log(HELP);
+ return 0;
+ }
+
+ const dir = resolveDir(values.dir);
+ if (command === 'doctor') {
+ return doctor({ dir, fix: values.fix, check: values.check });
+ }
+ if (isComposeCommand(command)) {
+ return compose(command, dir, rest);
+ }
+
+ log(`Unknown command "${command}".\n\n${HELP}`);
+ return 1;
+};
+
+process.exit(await main());
diff --git a/self-hosting/cli/src/run.ts b/self-hosting/cli/src/run.ts
new file mode 100644
index 000000000..5dba3e89e
--- /dev/null
+++ b/self-hosting/cli/src/run.ts
@@ -0,0 +1,29 @@
+import { spawn } from 'node:child_process';
+
+export interface RunResult {
+ code: number;
+ stdout: string;
+}
+
+const MISSING_BINARY_CODE = 127;
+
+// `inherit` streams straight to the terminal (up, logs); otherwise output is
+// captured for the caller to inspect. A missing binary resolves like a failed
+// command instead of throwing, so host checks can report it.
+export const run = (
+ command: string[],
+ options: { cwd?: string; inherit?: boolean } = {}
+): Promise<RunResult> =>
+ new Promise((resolve) => {
+ const [binary = '', ...args] = command;
+ const child = spawn(binary, args, {
+ cwd: options.cwd,
+ stdio: options.inherit ? 'inherit' : ['ignore', 'pipe', 'ignore'],
+ });
+ let stdout = '';
+ child.stdout?.on('data', (chunk) => {
+ stdout += chunk;
+ });
+ child.on('error', () => resolve({ code: MISSING_BINARY_CODE, stdout }));
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout }));
+ });
diff --git a/self-hosting/cli/src/ui.ts b/self-hosting/cli/src/ui.ts
new file mode 100644
index 000000000..29dd10232
--- /dev/null
+++ b/self-hosting/cli/src/ui.ts
@@ -0,0 +1,18 @@
+const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
+const paint = (code: number) => (text: string) =>
+ useColor ? `\u001b[${code}m${text}\u001b[0m` : text;
+
+export const bold = paint(1);
+export const dim = paint(2);
+export const red = paint(31);
+export const green = paint(32);
+export const yellow = paint(33);
+export const cyan = paint(36);
+
+export const SEVERITY_LABEL = {
+ error: red('error'),
+ warn: yellow('warn '),
+ info: cyan('info '),
+} as const;
+
+export const log = (line = '') => console.log(line);