292 lines
9.5 KiB
Python
Executable File
292 lines
9.5 KiB
Python
Executable File
"""Command line interface: assign, remove, list, sync, watch, doctor, init."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import time
|
|
|
|
from . import __version__
|
|
from .config import load_config
|
|
from .errors import ConfigError, ProxdomainError
|
|
from .service import DomainService, ServiceReport
|
|
|
|
_STATUS = {
|
|
"ok": "ok",
|
|
"changed": "done",
|
|
"planned": "plan",
|
|
"warning": "warn",
|
|
"skipped": "skip",
|
|
"error": "FAIL",
|
|
}
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
common = argparse.ArgumentParser(add_help=False)
|
|
common.add_argument(
|
|
"-c",
|
|
"--config",
|
|
default=argparse.SUPPRESS,
|
|
help="path to proxdomain.toml (default: ./proxdomain.toml or /etc/proxdomain/config.toml)",
|
|
)
|
|
common.add_argument(
|
|
"--json",
|
|
action="store_true",
|
|
default=argparse.SUPPRESS,
|
|
help="print machine-readable JSON",
|
|
)
|
|
|
|
parser = argparse.ArgumentParser(
|
|
prog="proxdomain",
|
|
description=(
|
|
"Give a Proxmox VM/CT a public domain: creates the Cloudflare DNS "
|
|
"record and the reverse-proxy entry on the Proxmox host."
|
|
),
|
|
parents=[common],
|
|
)
|
|
parser.add_argument("--version", action="version", version=f"proxdomain {__version__}")
|
|
sub = parser.add_subparsers(dest="command", metavar="command")
|
|
|
|
assign = sub.add_parser(
|
|
"assign",
|
|
parents=[common],
|
|
help="assign a domain to a VM/CT and wire up DNS + reverse proxy",
|
|
description=(
|
|
"Resolve the guest, pick its IP, create or update the Cloudflare "
|
|
"A/AAAA record and write the web server config. Safe to re-run."
|
|
),
|
|
)
|
|
target = assign.add_mutually_exclusive_group(required=True)
|
|
target.add_argument("--vmid", type=int, help="Proxmox guest ID")
|
|
target.add_argument("--name", help="Proxmox guest name (exact, then substring)")
|
|
assign.add_argument(
|
|
"--subdomain",
|
|
help="subdomain label (app) or full name (app.example.com); default: from domain_template",
|
|
)
|
|
assign.add_argument("--port", type=int, help="backend port on the guest (default: general.default_port)")
|
|
assign.add_argument("--ip", help="override the discovered guest IP")
|
|
assign.add_argument(
|
|
"--proxied",
|
|
dest="proxied",
|
|
action=argparse.BooleanOptionalAction,
|
|
default=None,
|
|
help="Cloudflare orange cloud (default: cloudflare.proxied)",
|
|
)
|
|
assign.add_argument("--force", action="store_true", help="take over a domain owned by another guest")
|
|
assign.add_argument("--dry-run", action="store_true", help="show what would change, touch nothing")
|
|
|
|
remove = sub.add_parser(
|
|
"remove",
|
|
parents=[common],
|
|
help="remove the DNS record and proxy config for an assignment",
|
|
)
|
|
which = remove.add_mutually_exclusive_group(required=True)
|
|
which.add_argument("--fqdn", help="domain to remove")
|
|
which.add_argument("--vmid", type=int, help="guest whose assignment should be removed")
|
|
remove.add_argument("--yes", action="store_true", help="confirm the deletion")
|
|
remove.add_argument("--dry-run", action="store_true", help="show what would be removed")
|
|
|
|
sub.add_parser(
|
|
"list",
|
|
parents=[common],
|
|
help="list managed domains",
|
|
)
|
|
|
|
sync = sub.add_parser(
|
|
"sync",
|
|
parents=[common],
|
|
help="re-apply DNS + config for every managed domain (after IP or config changes)",
|
|
)
|
|
sync.add_argument("--dry-run", action="store_true")
|
|
|
|
watch = sub.add_parser(
|
|
"watch",
|
|
parents=[common],
|
|
help="assign domains to newly created guests (cron/systemd or long-running)",
|
|
)
|
|
watch.add_argument("--once", action="store_true", help="single pass, then exit")
|
|
watch.add_argument("--interval", type=int, help="seconds between passes")
|
|
watch.add_argument("--tag", help="only guests carrying this Proxmox tag")
|
|
watch.add_argument("--all-new", action="store_true", help="ignore tags, consider every new guest")
|
|
watch.add_argument(
|
|
"--auto-assign",
|
|
action="store_true",
|
|
help="actually assign; without it watch only lists candidates",
|
|
)
|
|
watch.add_argument("--dry-run", action="store_true", help="plan every assignment")
|
|
|
|
sub.add_parser(
|
|
"doctor",
|
|
parents=[common],
|
|
help="check config, Proxmox, Cloudflare and web server access",
|
|
)
|
|
|
|
init = sub.add_parser(
|
|
"init",
|
|
parents=[common],
|
|
help="create the managed config directory and the web server include",
|
|
)
|
|
init.add_argument("--dry-run", action="store_true")
|
|
|
|
return parser
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = build_parser()
|
|
args = parser.parse_args(argv)
|
|
command = args.command
|
|
if command is None:
|
|
parser.print_help()
|
|
return 2
|
|
|
|
json_output = bool(getattr(args, "json", False))
|
|
try:
|
|
config = load_config(getattr(args, "config", None))
|
|
except ConfigError as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
try:
|
|
service = DomainService(config)
|
|
except (ConfigError, ProxdomainError) as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
try:
|
|
if command == "assign":
|
|
report = service.assign(
|
|
vmid=args.vmid,
|
|
name=args.name,
|
|
subdomain=args.subdomain,
|
|
port=args.port,
|
|
ip=args.ip,
|
|
proxied=args.proxied,
|
|
force=args.force,
|
|
dry_run=args.dry_run,
|
|
)
|
|
return _finish(report, json_output)
|
|
|
|
if command == "remove":
|
|
report = service.remove(
|
|
fqdn=args.fqdn,
|
|
vmid=args.vmid,
|
|
confirm=args.yes,
|
|
dry_run=args.dry_run,
|
|
)
|
|
return _finish(report, json_output)
|
|
|
|
if command == "list":
|
|
return _list(service, json_output)
|
|
|
|
if command == "sync":
|
|
return _finish(service.sync(dry_run=args.dry_run), json_output)
|
|
|
|
if command == "watch":
|
|
return _watch(service, args, json_output)
|
|
|
|
if command == "doctor":
|
|
return _finish(service.doctor(), json_output)
|
|
|
|
if command == "init":
|
|
return _finish(service.init(dry_run=args.dry_run), json_output)
|
|
|
|
parser.print_help()
|
|
return 2
|
|
except ProxdomainError as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 1
|
|
except KeyboardInterrupt:
|
|
print("interrupted", file=sys.stderr)
|
|
return 130
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
def _finish(report: ServiceReport, json_output: bool) -> int:
|
|
print_report(report, json_output=json_output)
|
|
return 0 if report.ok else 1
|
|
|
|
|
|
def print_report(report: ServiceReport, *, json_output: bool = False) -> None:
|
|
if json_output:
|
|
print(json.dumps(report.to_dict(), indent=2))
|
|
return
|
|
print(f"{report.action}: {'ok' if report.ok else 'FAILED'}")
|
|
for step in report.steps:
|
|
label = _STATUS.get(step.status, step.status)
|
|
print(f" [{label:<4}] {step.name:<12} {step.detail}")
|
|
|
|
|
|
def _list(service: DomainService, json_output: bool) -> int:
|
|
items = service.state.all()
|
|
if json_output:
|
|
print(json.dumps([item.to_dict() for item in items], indent=2))
|
|
return 0
|
|
if not items:
|
|
print("no managed domains yet (run: proxdomain assign --vmid <id>)")
|
|
return 0
|
|
|
|
headers = ("FQDN", "VMID", "NODE", "IP", "PORT", "DNS")
|
|
rows = [
|
|
(
|
|
item.fqdn,
|
|
str(item.vmid),
|
|
item.node,
|
|
item.ip or "-",
|
|
str(item.port),
|
|
"yes" if item.record_id else "-",
|
|
)
|
|
for item in items
|
|
]
|
|
widths = [len(header) for header in headers]
|
|
for row in rows:
|
|
for index, value in enumerate(row):
|
|
widths[index] = max(widths[index], len(value))
|
|
print(" ".join(header.ljust(widths[i]) for i, header in enumerate(headers)))
|
|
print(" ".join("-" * width for width in widths))
|
|
for row in rows:
|
|
print(" ".join(value.ljust(widths[i]) for i, value in enumerate(row)))
|
|
return 0
|
|
|
|
|
|
def _watch(service: DomainService, args: argparse.Namespace, json_output: bool) -> int:
|
|
auto = bool(args.auto_assign or service.config.watch.auto_assign)
|
|
interval = args.interval or service.config.watch.interval
|
|
tag = "" if args.all_new else (args.tag if args.tag is not None else None)
|
|
failures = 0
|
|
|
|
while True:
|
|
try:
|
|
candidates = service.watch_candidates(
|
|
tag=tag, require_running=service.config.watch.require_running
|
|
)
|
|
except ProxdomainError as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
if args.once:
|
|
return 1
|
|
candidates = []
|
|
failures += 1
|
|
|
|
if not candidates:
|
|
print("[ok ] no new guests to assign")
|
|
for guest in candidates:
|
|
if not auto:
|
|
tags = ",".join(guest.tags) or "-"
|
|
print(
|
|
f"[new ] {guest.label} tags={tags} -> "
|
|
f"proxdomain assign --vmid {guest.vmid}"
|
|
)
|
|
continue
|
|
report = service.assign(vmid=guest.vmid, dry_run=args.dry_run)
|
|
print_report(report, json_output=json_output)
|
|
if not report.ok:
|
|
failures += 1
|
|
|
|
if args.once:
|
|
break
|
|
try:
|
|
time.sleep(max(5, interval))
|
|
except KeyboardInterrupt:
|
|
break
|
|
return 0 if failures == 0 else 1
|