Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(cli): --json output on read-only admin CLI verbs

Juan Denis9be1ebf8bb10
diff --git a/backend/cli.py b/backend/cli.py
index 6d34e0bf..47894bcf 100644
--- a/backend/cli.py
+++ b/backend/cli.py
@@ -3,6 +3,7 @@
import os
import click
+import json
import secrets
import sys
from pathlib import Path
@@ -55,6 +56,11 @@ def cli(ctx, debug):
click.echo(f"Loaded environment from: {_env_loaded}")
+def _echo_json(payload):
+ """Machine-readable output for the --json flags (stdout only)."""
+ click.echo(json.dumps(payload, indent=2, default=str))
+
+
@cli.command()
@click.option('--email', prompt=True, help='Admin email address')
@click.option('--username', prompt=True, help='Admin username')
@@ -175,12 +181,27 @@ def activate_user(email):
@cli.command()
-def list_users():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def list_users(as_json):
"""List all users."""
app = create_app()
with app.app_context():
users = User.query.all()
+ if as_json:
+ _echo_json({'users': [
+ {
+ 'id': user.id,
+ 'username': user.username,
+ 'email': user.email,
+ 'role': user.role,
+ 'is_active': user.is_active,
+ 'is_locked': user.is_locked,
+ }
+ for user in users
+ ]})
+ return
+
if not users:
click.echo('No users found.')
return
@@ -223,13 +244,18 @@ def init_db():
@cli.command()
-def db_status():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def db_status(as_json):
"""Show current database migration status."""
app = create_app()
with app.app_context():
from app.services.migration_service import MigrationService
status = MigrationService.get_status()
+ if as_json:
+ _echo_json(status)
+ return
+
click.echo(f"\nCurrent revision: {status['current_revision'] or 'none'}")
click.echo(f"Head revision: {status['head_revision'] or 'none'}")
click.echo(f"Pending: {status['pending_count']}")
@@ -586,15 +612,34 @@ def factory_reset():
@cli.command()
@click.option('--all', 'show_all', is_flag=True, help='Also show Docker container status')
-def list_apps(show_all):
[email protected]('--json', 'as_json', is_flag=True,
+ help='Output machine-readable JSON (not combinable with --all)')
+def list_apps(show_all, as_json):
"""List all user applications (excludes ServerKit infrastructure)."""
import subprocess
from app.models import Application
+ if as_json and show_all:
+ _fail('--json cannot be combined with --all (the Docker section is table-only).')
+
app = create_app()
with app.app_context():
apps = Application.query.all()
+ if as_json:
+ _echo_json({'apps': [
+ {
+ 'id': application.id,
+ 'name': application.name,
+ 'app_type': application.app_type,
+ 'status': application.status,
+ 'port': application.port,
+ 'root_path': application.root_path,
+ }
+ for application in apps
+ ]})
+ return
+
click.echo('\n' + '=' * 90)
click.echo(' USER APPLICATIONS')
click.echo('=' * 90)
@@ -648,13 +693,17 @@ def list_apps(show_all):
@cli.command('list-servers')
-def list_servers():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def list_servers(as_json):
"""List deployment targets."""
app = create_app()
with app.app_context():
from app.services.remote_docker_service import RemoteDockerService
servers = RemoteDockerService.get_available_servers()
+ if as_json:
+ _echo_json({'servers': servers})
+ return
click.echo(f"\n{'ID':<38} {'Name':<28} {'Status':<12} {'Target'}")
click.echo('-' * 90)
for server in servers:
@@ -718,7 +767,8 @@ def deploy_template(template_id, app_name, server_id, variables, wait):
@cli.command('deployment-status')
@click.argument('job_id')
@click.option('--logs', is_flag=True, help='Show job logs')
-def deployment_status(job_id, logs):
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def deployment_status(job_id, logs, as_json):
"""Show deployment job status."""
app = create_app()
with app.app_context():
@@ -729,6 +779,10 @@ def deployment_status(job_id, logs):
click.echo(click.style('Deployment job not found', fg='red'))
sys.exit(1)
+ if as_json:
+ _echo_json({'job': job})
+ return
+
click.echo(f"\nJob: {job['id']}")
click.echo(f"Kind: {job['kind']}")
click.echo(f"Status: {job['status']} ({job['progress_percent']}%)")
@@ -792,7 +846,8 @@ def _echo_table(headers, rows):
@cli.command()
-def status():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def status(as_json):
"""Show panel health and version."""
from app.utils.version import get_panel_version
from app.services.cli_api_client import CliApiError
@@ -804,6 +859,10 @@ def status():
except CliApiError as exc:
_fail(str(exc))
+ if as_json:
+ _echo_json({'version': version, 'health': health})
+ return
+
rows = [
('Panel version', version),
('API status', health.get('status', 'unknown')),
@@ -821,7 +880,8 @@ def services():
@services.command('list')
-def services_list():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def services_list(as_json):
"""List monitored system services."""
from app.services.cli_api_client import CliApiError
@@ -831,6 +891,9 @@ def services_list():
_fail(str(exc))
entries = data.get('services', [])
+ if as_json:
+ _echo_json({'services': entries})
+ return
if not entries:
click.echo('No services reported.')
return
@@ -857,7 +920,8 @@ def apps():
@apps.command('list')
-def apps_list():
[email protected]('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
+def apps_list(as_json):
"""List applications known to the panel."""
from app.services.cli_api_client import CliApiError
@@ -867,6 +931,9 @@ def apps_list():
_fail(str(exc))
entries = data.get('apps', [])
+ if as_json:
+ _echo_json({'apps': entries})
+ return
if not entries:
click.echo('No applications found.')
return
@@ -920,16 +987,25 @@ def login_url(ttl, ip, user_ref):
@cli.command()
@click.option('--repair', 'do_repair', is_flag=True, help='Repair all repairable findings')
@click.option('--yes', is_flag=True, help='Skip the repair confirmation prompt')
-def doctor(do_repair, yes):
[email protected]('--json', 'as_json', is_flag=True,
+ help='Output the report as JSON (not combinable with --repair)')
+def doctor(do_repair, yes, as_json):
"""Run panel diagnostics (and optionally repair findings)."""
from app.services.cli_api_client import CliApiError
+ if as_json and do_repair:
+ _fail('--json cannot be combined with --repair (JSON mode is read-only).')
+
try:
client = _api_client()
data = client.post('/doctor/run')
except CliApiError as exc:
_fail(str(exc))
+ if as_json:
+ _echo_json(data.get('report') or {})
+ return
+
checks = (data.get('report') or {}).get('checks', [])
if not checks:
click.echo('Doctor reported no checks.')
@@ -1035,7 +1111,8 @@ def manifest():
@click.option('--project', 'project_id', type=int, required=True, help='Project id')
@click.option('--file', 'file_path', type=click.Path(exists=True), default=None,
help='Manifest file to plan (defaults to the stored manifest)')
-def manifest_plan(project_id, file_path):
[email protected]('--json', 'as_json', is_flag=True, help='Output the plan as JSON')
+def manifest_plan(project_id, file_path, as_json):
"""Compute the change plan for a project's manifest (dry run)."""
from app.services.cli_api_client import CliApiError
@@ -1045,6 +1122,9 @@ def manifest_plan(project_id, file_path):
_fail(str(exc))
plan = data.get('plan') or {}
+ if as_json:
+ _echo_json(plan)
+ return
steps = plan.get('steps') or []
_echo_plan_steps(steps)
_echo_plan_issues(plan.get('issues'))
diff --git a/backend/tests/test_cli_json.py b/backend/tests/test_cli_json.py
new file mode 100644
index 00000000..31cc9e13
--- /dev/null
+++ b/backend/tests/test_cli_json.py
@@ -0,0 +1,184 @@
+"""--json output on the read-only CLI verbs: every listed command must emit
+parseable JSON on stdout (scriptable/monitorable CLI), and the two flags that
+conflict with table-only extras must refuse loudly."""
+import json
+
+import pytest
+from click.testing import CliRunner
+
+import cli as serverkit_cli
+
+
+def _all_output(result):
+ out = result.output
+ try:
+ out += result.stderr
+ except (ValueError, AttributeError):
+ pass
+ return out
+
+
+def _json_out(result):
+ assert result.exit_code == 0, _all_output(result)
+ return json.loads(result.output)
+
+
+class FakeClient:
+ def __init__(self, responses):
+ self.responses = responses
+ self.calls = []
+
+ def get(self, path):
+ self.calls.append(('GET', path, None))
+ return self.responses[path]
+
+ def post(self, path, json_body=None):
+ self.calls.append(('POST', path, json_body))
+ return self.responses[path]
+
+
+def fake_api(monkeypatch):
+ def _install(responses):
+ fake = FakeClient(responses)
+ monkeypatch.setattr(serverkit_cli, '_api_client', lambda with_token=True: fake)
+ return fake
+ return _install
+
+
+# ── API-backed verbs ─────────────────────────────────────────────────────────
+
+def test_status_json(fake_api):
+ fake_api({'/system/health': {'status': 'ok', 'service': 'serverkit'}})
+ result = CliRunner().invoke(serverkit_cli.cli, ['status', '--json'])
+ data = _json_out(result)
+ assert data['health']['status'] == 'ok'
+ assert data['version']
+
+
+def test_doctor_json_emits_raw_report(fake_api):
+ fake_api({'/doctor/run': {'report': {'checks': [
+ {'key': 'nginx', 'title': 'Nginx config', 'status': 'ok', 'detail': ''},
+ {'key': 'ssl', 'title': 'SSL cert', 'status': 'fail', 'detail': 'expired'},
+ ]}}})
+ result = CliRunner().invoke(serverkit_cli.cli, ['doctor', '--json'])
+ data = _json_out(result)
+ assert [c['key'] for c in data['checks']] == ['nginx', 'ssl']
+
+
+def test_doctor_json_refuses_repair(fake_api):
+ fake_api({})
+ result = CliRunner().invoke(serverkit_cli.cli, ['doctor', '--json', '--repair'])
+ assert result.exit_code == 1
+ assert '--repair' in _all_output(result)
+
+
+def test_services_list_json(fake_api):
+ fake_api({'/processes/services': {'services': [
+ {'name': 'nginx', 'status': 'running', 'pid': 123},
+ ]}})
+ result = CliRunner().invoke(serverkit_cli.cli, ['services', 'list', '--json'])
+ data = _json_out(result)
+ assert data['services'][0]['name'] == 'nginx'
+
+
+def test_apps_list_json(fake_api):
+ fake_api({'/apps': {'apps': [
+ {'name': 'blog', 'app_type': 'wordpress', 'status': 'running'},
+ ]}})
+ result = CliRunner().invoke(serverkit_cli.cli, ['apps', 'list', '--json'])
+ data = _json_out(result)
+ assert data['apps'][0]['app_type'] == 'wordpress'
+
+
+def test_manifest_plan_json(fake_api):
+ fake = fake_api({'/manifests/plan': {'plan': {
+ 'steps': [{'type': 'create', 'service': 'web', 'description': 'create app web'}],
+ 'step_count': 1,
+ 'summary': '1 change planned',
+ 'issues': [],
+ }}})
+ result = CliRunner().invoke(
+ serverkit_cli.cli, ['manifest', 'plan', '--project', '7', '--json'])
+ data = _json_out(result)
+ assert ('POST', '/manifests/plan', {'project_id': 7}) in fake.calls
+ assert data['step_count'] == 1
+ assert data['steps'][0]['service'] == 'web'
+
+
+# ── DIRECT (in-process) verbs ────────────────────────────────────────────────
+
+def test_list_users_json(app):
+ from app import db
+ from app.models import User
+
+ user = User(email='[email protected]', username='juan', role='admin', is_active=True)
+ user.set_password('x')
+ db.session.add(user)
+ db.session.commit()
+
+ result = CliRunner().invoke(serverkit_cli.cli, ['list-users', '--json'])
+ data = _json_out(result)
+ assert data['users'] == [{
+ 'id': user.id,
+ 'username': 'juan',
+ 'email': '[email protected]',
+ 'role': 'admin',
+ 'is_active': True,
+ 'is_locked': False,
+ }]
+
+
+def test_list_apps_json_empty(app):
+ result = CliRunner().invoke(serverkit_cli.cli, ['list-apps', '--json'])
+ data = _json_out(result)
+ assert data == {'apps': []}
+
+
+def test_list_apps_json_refuses_all(app):
+ result = CliRunner().invoke(serverkit_cli.cli, ['list-apps', '--json', '--all'])
+ assert result.exit_code == 1
+ assert '--all' in _all_output(result)
+
+
+def test_list_servers_json(app, monkeypatch):
+ from app.services.remote_docker_service import RemoteDockerService
+
+ monkeypatch.setattr(
+ RemoteDockerService, 'get_available_servers',
+ staticmethod(lambda: [{'id': 'local', 'name': 'This server',
+ 'status': 'online', 'is_local': True}]),
+ )
+ result = CliRunner().invoke(serverkit_cli.cli, ['list-servers', '--json'])
+ data = _json_out(result)
+ assert data['servers'][0]['id'] == 'local'
+
+
+def test_db_status_json(app, monkeypatch):
+ from app.services.migration_service import MigrationService
+
+ monkeypatch.setattr(
+ MigrationService, 'get_status',
+ staticmethod(lambda: {'current_revision': '074', 'head_revision': '074',
+ 'pending_count': 0, 'pending_migrations': [],
+ 'needs_migration': False}),
+ )
+ result = CliRunner().invoke(serverkit_cli.cli, ['db-status', '--json'])
+ data = _json_out(result)
+ assert data['current_revision'] == '074'
+ assert data['pending_count'] == 0
+
+
+def test_deployment_status_json(app, monkeypatch):
+ from app.services.deployment_job_service import DeploymentJobService
+
+ job = {'id': 'j-1', 'kind': 'template.install', 'status': 'succeeded',
+ 'progress_percent': 100, 'target_server_name': 'local'}
+ monkeypatch.setattr(
+ DeploymentJobService, 'get_job',
+ staticmethod(lambda job_id, include_logs=False: job),
+ )
+ result = CliRunner().invoke(
+ serverkit_cli.cli, ['deployment-status', 'j-1', '--json'])
+ data = _json_out(result)
+ assert data['job']['status'] == 'succeeded'