mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-01 20:55:16 +09:00
Add serverkit adopt-site
Lists the sites host nginx serves, shows what adopting one would record, and registers it with --apply. list-sites now names a PHP-FPM site instead of calling it "port static". Part of #269.
This commit is contained in:
1 parent
4ba435243f
commit
933216e911
4 files changed
+217
-8
No files matched your search
+116
@@ -854,6 +854,122 @@ def _api_client(with_token=True):
|
||||
return ApiClient(token=token)
|
||||
|
||||
|
||||
@cli.command('adopt-site')
|
||||
@click.argument('site', required=False)
|
||||
@click.option('--apply', 'apply_', is_flag=True,
|
||||
help='Register the site. Without it, only show what would be recorded.')
|
||||
@click.option('--name', default=None, help='Service name (default: derived from the domain)')
|
||||
@click.option('--json', 'as_json', is_flag=True, help='Output machine-readable JSON')
|
||||
def adopt_site(site, apply_, name, as_json):
|
||||
"""Register a site that already runs on this server.
|
||||
|
||||
With no SITE, lists every site host nginx serves and whether ServerKit
|
||||
manages it. With a SITE (a domain or a vhost file name), shows what
|
||||
adopting it would record: a dry run. Add --apply to register it.
|
||||
|
||||
Nothing on the server is rewritten either way: adopting records the
|
||||
running nginx vhost, PHP-FPM pool, database and certificate as they are.
|
||||
"""
|
||||
from app.services import site_adoption_service
|
||||
from app.services.site_adoption_service import SiteAdoptionError
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
if not site:
|
||||
if apply_:
|
||||
_fail('--apply needs a site: serverkit adopt-site <domain> --apply')
|
||||
sites = site_adoption_service.discover()
|
||||
if as_json:
|
||||
_echo_json({'sites': sites})
|
||||
return
|
||||
if not sites:
|
||||
click.echo('\n Host nginx is not serving any sites.\n')
|
||||
return
|
||||
click.echo(f"\n{'Domain':<34} {'Type':<10} {'PHP':<6} {'SSL':<4} {'State'}")
|
||||
click.echo('-' * 90)
|
||||
for found in sites:
|
||||
if found['linked_app']:
|
||||
state = f"managed as {found['linked_app']['name']}"
|
||||
elif found['adoptable']:
|
||||
state = 'not managed (adoptable)'
|
||||
else:
|
||||
state = f"not managed: {found['reason']}"
|
||||
click.echo(
|
||||
f"{found['primary_domain']:<34} "
|
||||
f"{(found['app_type'] or found['kind']):<10} "
|
||||
f"{((found['php'] or {}).get('version') or '-'):<6} "
|
||||
f"{('yes' if found['ssl']['enabled'] else 'no'):<4} "
|
||||
f"{state}"
|
||||
)
|
||||
adoptable = sum(1 for found in sites if found['adoptable'])
|
||||
click.echo(f"\n{adoptable} site(s) can be adopted: serverkit adopt-site <domain>\n")
|
||||
return
|
||||
|
||||
found = site_adoption_service.find(site)
|
||||
if found is None:
|
||||
_fail(f'No site served by host nginx matches "{site}". '
|
||||
"Run 'serverkit adopt-site' to list them.")
|
||||
plan = site_adoption_service.plan(found, name)
|
||||
|
||||
if not apply_:
|
||||
if as_json:
|
||||
_echo_json({'dry_run': True, 'adoptable': found['adoptable'],
|
||||
'reason': found['reason'], 'plan': plan})
|
||||
return
|
||||
_print_adoption_plan(found, plan)
|
||||
if found['adoptable']:
|
||||
click.echo(f"\nDry run. Nothing was changed. To register it:\n"
|
||||
f" serverkit adopt-site {site} --apply\n")
|
||||
else:
|
||||
click.echo(click.style(f"\nCannot adopt: {found['reason']}\n", fg='yellow'))
|
||||
return
|
||||
|
||||
owner = User.query.filter_by(role='admin', is_active=True).order_by(User.id).first()
|
||||
if owner is None:
|
||||
_fail("No active admin user to own the service. Run 'serverkit create-admin' first.")
|
||||
try:
|
||||
application, plan = site_adoption_service.adopt(site, owner, name=name)
|
||||
except SiteAdoptionError as exc:
|
||||
_fail(str(exc))
|
||||
if as_json:
|
||||
_echo_json({'dry_run': False, 'plan': plan, 'app': application.to_dict()})
|
||||
return
|
||||
_print_adoption_plan(found, plan)
|
||||
click.echo(click.style(
|
||||
f"\nAdopted as \"{application.name}\" (id {application.id}). "
|
||||
'No file on the server was changed.\n', fg='green'))
|
||||
|
||||
|
||||
def _print_adoption_plan(site, plan):
|
||||
php = site['php'] or {}
|
||||
click.echo(f"\nSite: {site['primary_domain']}")
|
||||
click.echo(f" vhost {site['vhost_file']}")
|
||||
click.echo(f" domains {', '.join(site['domains'])}")
|
||||
click.echo(f" root {site['root'] or '-'}")
|
||||
if php:
|
||||
pool = f" (pool {php['pool']})" if php.get('pool') else ''
|
||||
click.echo(f" PHP-FPM {php.get('version') or 'unknown version'}{pool} at {php['listen']}")
|
||||
if site['ssl']['enabled']:
|
||||
expires = site['ssl']['expires_at'] or 'expiry unknown'
|
||||
click.echo(f" certificate {site['ssl']['certificate']} ({expires})")
|
||||
else:
|
||||
click.echo(' certificate none')
|
||||
if site['database']:
|
||||
click.echo(f" database {site['database']['name']} on {site['database']['host']}")
|
||||
click.echo('\nWould record:' if site['adoptable'] else '\nWould have recorded:')
|
||||
application = plan['application']
|
||||
click.echo(f" service {application['name']} ({application['app_type']}, "
|
||||
f"managed by {application['managed_by']})")
|
||||
click.echo(f" domains {len(plan['domains'])}")
|
||||
if plan['wordpress_site'] is not None:
|
||||
click.echo(f" WordPress version {plan['wordpress_site']['wp_version'] or 'unknown'}")
|
||||
if plan['database'] is not None:
|
||||
click.echo(f" database linked to the service")
|
||||
click.echo('\nLeft exactly as it is:')
|
||||
for path in plan['untouched']:
|
||||
click.echo(f" {path}")
|
||||
|
||||
|
||||
def _fail(message):
|
||||
click.echo(click.style(f'Error: {message}', fg='red'), err=True)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""`serverkit adopt-site` — the CLI face of site adoption (issue #269).
|
||||
|
||||
Dry run by default: naming a site prints what would be recorded and changes
|
||||
nothing; only `--apply` registers it. The host fixture and the "nothing on
|
||||
the host changed" snapshot come from test_site_adoption.py.
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
from factories import make_user
|
||||
from test_site_adoption import _snapshot, host # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run(app, monkeypatch):
|
||||
"""Invoke the Click command against the test app instead of a fresh one."""
|
||||
import cli
|
||||
monkeypatch.setattr(cli, 'create_app', lambda *args, **kwargs: app)
|
||||
|
||||
def invoke(*args):
|
||||
return CliRunner().invoke(cli.cli, ['adopt-site', *args], catch_exceptions=False)
|
||||
return invoke
|
||||
|
||||
|
||||
def test_no_argument_lists_sites_with_their_state(run, host): # noqa: F811
|
||||
result = run()
|
||||
assert result.exit_code == 0, result.output
|
||||
assert 'shop.example.com' in result.output and 'wordpress' in result.output
|
||||
assert 'not managed (adoptable)' in result.output
|
||||
assert '2 site(s) can be adopted' in result.output
|
||||
listed = json.loads(run('--json').output)['sites']
|
||||
assert {site['primary_domain'] for site in listed} == {
|
||||
'shop.example.com', 'docs.example.com', 'api.example.com'}
|
||||
|
||||
|
||||
def test_naming_a_site_is_a_dry_run(run, host): # noqa: F811
|
||||
from app.models.application import Application
|
||||
before = _snapshot(host['root'])
|
||||
result = run('shop.example.com')
|
||||
assert result.exit_code == 0, result.output
|
||||
assert 'Dry run. Nothing was changed.' in result.output
|
||||
assert 'serverkit adopt-site shop.example.com --apply' in result.output
|
||||
assert 'Left exactly as it is:' in result.output
|
||||
assert Application.query.filter_by(name='shop-example-com').first() is None
|
||||
assert _snapshot(host['root']) == before
|
||||
|
||||
|
||||
def test_apply_registers_the_site_and_leaves_the_host_alone(run, host, app): # noqa: F811
|
||||
from app import db
|
||||
from app.models.application import Application
|
||||
make_user(db, 'cli_adopt_admin', 'admin')
|
||||
before = _snapshot(host['root'])
|
||||
result = run('docs.example.com', '--apply', '--name', 'docs-site')
|
||||
assert result.exit_code == 0, result.output
|
||||
assert 'Adopted as "docs-site"' in result.output
|
||||
row = Application.query_active().filter_by(name='docs-site').one()
|
||||
assert (row.managed_by, row.app_type, row.status) == ('host', 'static', 'running')
|
||||
assert _snapshot(host['root']) == before
|
||||
|
||||
|
||||
def test_refusals_exit_non_zero_and_register_nothing(run, host, app): # noqa: F811
|
||||
from app import db
|
||||
from app.models.application import Application
|
||||
make_user(db, 'cli_adopt_admin2', 'admin')
|
||||
count = Application.query.count()
|
||||
assert run('nope.example.com').exit_code == 1
|
||||
# A proxied process is described, but --apply refuses it.
|
||||
assert run('api.example.com').exit_code == 0
|
||||
assert run('api.example.com', '--apply').exit_code == 1
|
||||
assert run('--apply').exit_code == 1
|
||||
assert Application.query.count() == count
|
||||
@@ -600,6 +600,15 @@ server {
|
||||
root /var/www/static;
|
||||
}
|
||||
EOF
|
||||
cat > "$t/nginx/sites-enabled/php-site.conf" <<'EOF'
|
||||
server {
|
||||
server_name php.example.com;
|
||||
root /var/www/php-site;
|
||||
location ~ \.php$ {
|
||||
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
cat > "$t/rhel/conf.d/confd.conf" <<'EOF'
|
||||
server {
|
||||
server_name confd.example.com;
|
||||
@@ -614,9 +623,11 @@ out2="$( set -Eeuo pipefail; NGINX_DIR="$t/rhel"; cmd_list_sites 2>&1 )"
|
||||
rc2=$?
|
||||
if [ "$rc" -eq 0 ] && [ "$rc2" -eq 0 ] \
|
||||
&& printf '%s' "$out" | grep 'proxied.example.com' | grep -q 'port 4100' \
|
||||
&& printf '%s' "$out" | grep 'static.example.com' | grep -q 'port static' \
|
||||
&& printf '%s' "$out" | grep 'static.example.com' | grep -q 'static files' \
|
||||
&& printf '%s' "$out" | grep 'php.example.com' | grep -q 'php-fpm 8.3' \
|
||||
&& ! printf '%s' "$out" | grep -q 'port static' \
|
||||
&& printf '%s' "$out2" | grep 'confd.example.com' | grep -q 'port 4200'; then
|
||||
ok "list-sites extracts ports portably and lists conf.d layouts"
|
||||
ok "list-sites extracts ports portably, names PHP-FPM sites, and lists conf.d layouts"
|
||||
else
|
||||
bad "list-sites broken: rc=$rc/$rc2 out=[$out] out2=[$out2]"
|
||||
fi
|
||||
@@ -725,7 +736,7 @@ fi
|
||||
t="$WORK/t18"; mkdir -p "$t/install"
|
||||
unknown=""
|
||||
for c in manifest services apps repair login-url support-bundle \
|
||||
db-migrate db-status db-history panel-status panel-doctor; do
|
||||
db-migrate db-status db-history panel-status panel-doctor adopt-site; do
|
||||
out="$(SERVERKIT_DIR="$t/install" bash "$CLI" "$c" 2>&1)" || true
|
||||
if printf '%s' "$out" | grep -q 'Unknown command'; then
|
||||
unknown="$unknown $c"
|
||||
@@ -829,6 +840,7 @@ check_args 'services list --json' services list --json
|
||||
check_args 'status --json' panel-status --json
|
||||
check_args 'doctor --repair --yes' panel-doctor --repair --yes
|
||||
check_args 'connect status --json' connect status --json
|
||||
check_args 'adopt-site example.com --apply --json' adopt-site example.com --apply --json
|
||||
if [ -z "$t20_fail" ]; then
|
||||
ok "executed-mode flag passthrough: wrapper commands reach cli.py verbatim"
|
||||
else
|
||||
|
||||
@@ -326,6 +326,7 @@ cmd_help() {
|
||||
echo "Site Management:"
|
||||
echo " setup-proxy Setup host nginx as reverse proxy (run once)"
|
||||
echo " add-site Add a new site/domain"
|
||||
echo " adopt-site Register a site already running here (adopt-site [domain] [--apply])"
|
||||
echo " list-sites List all configured sites"
|
||||
echo " remove-site Remove a site"
|
||||
echo ""
|
||||
@@ -372,7 +373,7 @@ cmd_completion() {
|
||||
_serverkit() {
|
||||
local cur commands
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
commands="help start stop restart status logs update branch version check-update uninstall create-admin reset-password setup-code unlock-user list-users make-admin deactivate-user activate-user init-db migrate-db db-migrate db-status db-history backup-db restore-db disk cleanup-apps factory-reset generate-keys config setup-proxy create-app deploy-template list-servers deployment-status list-apps start-app stop-app app-logs add-site list-sites remove-site doctor manifest services apps repair login-url support-bundle connect panel-status panel-doctor completion"
|
||||
commands="help start stop restart status logs update branch version check-update uninstall create-admin reset-password setup-code unlock-user list-users make-admin deactivate-user activate-user init-db migrate-db db-migrate db-status db-history backup-db restore-db disk cleanup-apps factory-reset generate-keys config setup-proxy create-app deploy-template list-servers deployment-status list-apps start-app stop-app app-logs add-site adopt-site list-sites remove-site doctor manifest services apps repair login-url support-bundle connect panel-status panel-doctor completion"
|
||||
|
||||
if [ "$COMP_CWORD" -eq 1 ]; then
|
||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||
@@ -392,6 +393,7 @@ _serverkit() {
|
||||
disk) COMPREPLY=( $(compgen -W "--safe --all --only --days --keep --older-than --dry-run --allow-restart --yes --json" -- "$cur") ) ;;
|
||||
cleanup-apps) COMPREPLY=( $(compgen -W "--delete-volumes --keep-db" -- "$cur") ) ;;
|
||||
list-apps) COMPREPLY=( $(compgen -W "--all --json" -- "$cur") ) ;;
|
||||
adopt-site) COMPREPLY=( $(compgen -W "--apply --name --json" -- "$cur") ) ;;
|
||||
deployment-status) COMPREPLY=( $(compgen -W "--logs --json" -- "$cur") ) ;;
|
||||
db-migrate|migrate-db) COMPREPLY=( $(compgen -W "--no-backup" -- "$cur") ) ;;
|
||||
login-url) COMPREPLY=( $(compgen -W "--ttl --ip --user" -- "$cur") ) ;;
|
||||
@@ -1205,11 +1207,17 @@ cmd_list_sites() {
|
||||
DOMAIN=$(grep -m1 "server_name" "$site" | awk '{print $2}' | tr -d ';' || true)
|
||||
# Portable port extraction (GNU-only `grep -oP` broke busybox)
|
||||
PORT=$(grep -m1 "proxy_pass" "$site" | sed -n 's/.*:\([0-9][0-9]*\).*/\1/p' || true)
|
||||
if [ -z "$PORT" ]; then
|
||||
PORT="static"
|
||||
if [ -n "$PORT" ]; then
|
||||
TARGET="port $PORT"
|
||||
elif grep -q "fastcgi_pass" "$site" 2>/dev/null; then
|
||||
# A host PHP-FPM site has no port: name what serves it.
|
||||
PHP_VER=$(grep -m1 "fastcgi_pass" "$site" | sed -n 's/.*php-\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' || true)
|
||||
TARGET="php-fpm${PHP_VER:+ $PHP_VER}"
|
||||
else
|
||||
TARGET="static files"
|
||||
fi
|
||||
ENABLED="✓"
|
||||
printf " %s %-35s → port %s\n" "$ENABLED" "$DOMAIN" "$PORT"
|
||||
printf " %s %-35s → %s\n" "$ENABLED" "$DOMAIN" "$TARGET"
|
||||
fi
|
||||
done
|
||||
else
|
||||
@@ -1719,7 +1727,7 @@ case "${1:-help}" in
|
||||
migrate-db)
|
||||
cmd_migrate_db
|
||||
;;
|
||||
manifest|services|apps|repair|login-url|support-bundle|connect|db-migrate|db-status|db-history)
|
||||
manifest|services|apps|repair|login-url|support-bundle|connect|db-migrate|db-status|db-history|adopt-site)
|
||||
cmd_panel_cli "$@"
|
||||
;;
|
||||
panel-status)
|
||||
|
||||
Reference in new issue
Block a user