first commit

This commit is contained in:
leo committed 2026-11-20 15:16:41 +02:00
commit dd50a0d05e
31 files changed
+5299

No files matched your search

+597
View File
@@ -0,0 +1,597 @@
"""Orchestration: guest -> domain -> Cloudflare record -> reverse proxy config."""
from __future__ import annotations
import ipaddress
import re
from dataclasses import dataclass, field
from .cloudflare import CloudflareClient, Zone
from .config import Config
from .errors import ConfigError, ProxdomainError
from .proxmox import Guest, ProxmoxClient
from .runner import build_runner
from .state import Assignment, StateStore
from .webserver import FQDN_RE, SiteSpec, WebServerManager
_HOSTNAME_STRIP = re.compile(r"[^a-z0-9]+")
_DASHES = re.compile(r"-{2,}")
@dataclass
class Step:
name: str
status: str # ok | changed | planned | warning | skipped | error
detail: str = ""
@dataclass
class ServiceReport:
action: str
steps: list[Step] = field(default_factory=list)
assignment: Assignment | None = None
@property
def ok(self) -> bool:
return not any(step.status == "error" for step in self.steps)
def add(self, name: str, status: str, detail: str = "") -> "ServiceReport":
self.steps.append(Step(name, status, detail))
return self
def fail(self, name: str, detail: str) -> "ServiceReport":
return self.add(name, "error", detail)
def to_dict(self) -> dict:
return {
"action": self.action,
"ok": self.ok,
"steps": [step.__dict__ for step in self.steps],
"assignment": self.assignment.to_dict() if self.assignment else None,
}
class DomainService:
def __init__(
self,
config: Config,
*,
proxmox: ProxmoxClient | None = None,
cloudflare: CloudflareClient | None = None,
webserver: WebServerManager | None = None,
state: StateStore | None = None,
) -> None:
self.config = config
self.state = state or StateStore(
config.state.path,
audit_path=config.state.resolved_audit_path(),
lock_timeout=config.state.lock_timeout,
)
self.state.load()
self._proxmox = proxmox
self._cloudflare = cloudflare
self._webserver = webserver
# -- lazy clients (so `list` works without API credentials) ---------
@property
def proxmox(self) -> ProxmoxClient:
if self._proxmox is None:
self._proxmox = ProxmoxClient(self.config.proxmox)
return self._proxmox
@property
def cloudflare(self) -> CloudflareClient:
if self._cloudflare is None:
self._cloudflare = CloudflareClient(self.config.cloudflare)
return self._cloudflare
@property
def webserver(self) -> WebServerManager:
if self._webserver is None:
self._webserver = WebServerManager(
self.config.webserver, build_runner(self.config.webserver)
)
return self._webserver
# -- main workflow --------------------------------------------------
def assign(
self,
*,
vmid: int | None = None,
name: str | None = None,
subdomain: str | None = None,
port: int | None = None,
ip: str | None = None,
proxied: bool | None = None,
force: bool = False,
dry_run: bool = False,
) -> ServiceReport:
report = ServiceReport("assign")
try:
guest = self.proxmox.find_guest(vmid=vmid, name=name)
except ProxdomainError as exc:
return report.fail("guest", str(exc))
report.add("guest", "ok", guest.label)
if not guest.is_running:
report.add("guest", "warning", "guest is not running; the proxy target may be down")
try:
fqdn = self._resolve_fqdn(guest, subdomain)
except ProxdomainError as exc:
return report.fail("domain", str(exc))
try:
address = ip or self.proxmox.guest_ip(guest)
except ProxdomainError as exc:
return report.fail("address", str(exc))
if not address:
return report.fail(
"address",
f"no usable IP address found for {guest.label}; pass --ip, install "
"qemu-guest-agent in the VM, or set a static ip= in the guest config",
)
try:
parsed_ip = ipaddress.ip_address(address)
except ValueError:
return report.fail("address", f"{address!r} is not a valid IP address")
report.add("address", "ok", f"{address} ({'argument' if ip else 'discovered'})")
report.add("domain", "ok", fqdn)
target_port = int(port or self.config.general.default_port)
if not 1 <= target_port <= 65535:
return report.fail("port", f"{target_port} is not a valid TCP port")
existing = self.state.get(fqdn)
if existing is not None and existing.vmid != guest.vmid and not force:
return report.fail(
"state",
f"{fqdn} is already assigned to {existing.kind} {existing.vmid}; "
"pass --force to take it over",
)
zone = self._find_zone(report, fqdn, dry_run=dry_run)
if zone is None and not dry_run:
return report
effective_proxied = self.config.cloudflare.proxied if proxied is None else proxied
proxy_note = ""
if effective_proxied and not parsed_ip.is_global:
effective_proxied = False
proxy_note = (
f"{address} is not a public address, so the Cloudflare proxy "
"(orange cloud) was disabled; only the DNS record is created"
)
spec = self._site_spec(guest, fqdn, address, target_port)
try:
applied = self.webserver.apply(spec, dry_run=dry_run)
except ProxdomainError as exc:
return report.fail("web-config", str(exc))
if dry_run:
status = "planned"
elif applied.changed:
status = "changed"
else:
status = "ok"
report.add(
"web-config",
status,
"; ".join(applied.messages) or applied.path,
)
if proxy_note:
report.add("dns", "warning", proxy_note)
assignment = existing or Assignment(
fqdn=fqdn, vmid=guest.vmid, node=guest.node, kind=guest.kind
)
assignment.name = guest.name
assignment.vmid = guest.vmid
assignment.ip = address
assignment.port = target_port
assignment.node = guest.node
assignment.kind = guest.kind
assignment.webserver = self.config.webserver.kind
assignment.site_file = applied.path
if zone is not None:
assignment.zone_id = zone.id
assignment.zone_name = zone.name
record_type = "A" if parsed_ip.version == 4 else "AAAA"
if not dry_run:
self._save(assignment)
self.state.audit(
"assign.web-config",
fqdn=fqdn,
vmid=guest.vmid,
address=address,
port=target_port,
path=applied.path,
)
if zone is None:
report.add("dns", "skipped", "no zone resolved; DNS not touched in this dry run")
report.assignment = assignment
return report
if dry_run:
self._preview_dns(report, zone, fqdn, address, record_type, effective_proxied)
report.add("result", "planned", "dry run: nothing was changed")
report.assignment = assignment
return report
try:
upsert = self.cloudflare.upsert_address_record(
zone.id,
fqdn,
address,
proxied=effective_proxied,
)
except ProxdomainError as exc:
report.fail("dns", str(exc))
report.add(
"result",
"warning",
"the web server config is in place; fix the DNS error and re-run "
"assign (it is idempotent)",
)
report.assignment = assignment
return report
assignment.record_type = upsert.record.type or record_type
assignment.record_id = upsert.record.id
self._save(assignment)
self.state.audit(
"assign.dns",
fqdn=fqdn,
record_id=upsert.record.id,
action=upsert.action,
content=address,
proxied=effective_proxied,
)
report.add(
"dns",
"changed" if upsert.changed else "ok",
f"{upsert.action} {record_type} {fqdn} -> {address} "
f"(proxied={'yes' if effective_proxied else 'no'})",
)
report.add("result", "ok", f"{fqdn} -> {spec.target}")
report.assignment = assignment
return report
def remove(
self,
*,
fqdn: str | None = None,
vmid: int | None = None,
confirm: bool = False,
dry_run: bool = False,
) -> ServiceReport:
report = ServiceReport("remove")
if not fqdn and vmid is None:
return report.fail("state", "specify --fqdn or --vmid")
if vmid is not None and not fqdn:
matches = self.state.find(vmid=vmid)
if len(matches) > 1:
listing = ", ".join(item.fqdn for item in matches)
return report.fail("state", f"vmid {vmid} has several assignments: {listing}")
else:
matches = self.state.find(fqdn=fqdn)
if not matches:
target = fqdn or f"vmid {vmid}"
return report.fail("state", f"no managed assignment found for {target}")
assignment = matches[0]
report.add(
"state",
"ok",
f"{assignment.fqdn} -> {assignment.kind} {assignment.vmid} on {assignment.node}",
)
if not confirm and not dry_run:
return report.fail(
"confirm",
f"this deletes the DNS record and proxy config for {assignment.fqdn}; "
"re-run with --yes to proceed",
)
try:
result = self.webserver.remove(assignment.fqdn, dry_run=dry_run)
except ProxdomainError as exc:
return report.fail("web-config", str(exc))
report.add(
"web-config",
"planned" if dry_run else ("changed" if result.changed else "ok"),
"; ".join(result.messages) or assignment.site_file,
)
if not assignment.has_dns_record:
report.add("dns", "skipped", "no Cloudflare record id recorded for this assignment")
elif dry_run:
report.add(
"dns",
"planned",
f"would delete {assignment.record_type} {assignment.fqdn} "
f"(zone {assignment.zone_name or assignment.zone_id})",
)
else:
try:
self.cloudflare.delete_record(assignment.zone_id, assignment.record_id or "")
except ProxdomainError as exc:
report.fail("dns", str(exc))
report.add(
"result",
"warning",
"the proxy config was removed but the assignment is kept in state; "
"fix the DNS error and re-run remove",
)
return report
report.add(
"dns",
"changed",
f"deleted {assignment.record_type} {assignment.fqdn}",
)
assignment.record_id = None
if not dry_run:
with self.state.locked():
self.state.load()
self.state.remove(assignment.fqdn)
self.state.flush()
self.state.audit("remove", fqdn=assignment.fqdn, vmid=assignment.vmid)
report.add(
"result",
"planned" if dry_run else "ok",
f"{assignment.fqdn} is no longer managed",
)
return report
def sync(self, *, dry_run: bool = False) -> ServiceReport:
report = ServiceReport("sync")
assignments = self.state.all()
if not assignments:
return report.add("state", "ok", "no assignments to sync")
changed = 0
for assignment in assignments:
try:
guest = self.proxmox.find_guest(vmid=assignment.vmid)
except ProxdomainError as exc:
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
continue
try:
address = self.proxmox.guest_ip(guest) or assignment.ip
except ProxdomainError as exc:
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
continue
if not address:
report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP")
continue
spec = self._site_spec(guest, assignment.fqdn, address, assignment.port)
try:
result = self.webserver.apply(spec, dry_run=dry_run)
except ProxdomainError as exc:
report.fail("web-config", f"{assignment.fqdn}: {exc}")
continue
if result.changed:
changed += 1
report.add(
"web-config",
"planned" if dry_run else ("changed" if result.changed else "ok"),
f"{assignment.fqdn}: {'; '.join(result.messages) or 'up to date'}",
)
if dry_run or not assignment.zone_id:
continue
try:
upsert = self.cloudflare.upsert_address_record(
assignment.zone_id, assignment.fqdn, address
)
except ProxdomainError as exc:
report.fail("dns", f"{assignment.fqdn}: {exc}")
continue
assignment.ip = address
assignment.record_type = upsert.record.type or assignment.record_type
assignment.record_id = upsert.record.id
if upsert.changed:
changed += 1
report.add("dns", "changed", f"{assignment.fqdn}: {upsert.action} -> {address}")
self._save(assignment)
report.add(
"result",
"planned" if dry_run else "ok",
f"{len(assignments)} assignment(s) checked, {changed} change(s)",
)
return report
# -- discovery / diagnostics ---------------------------------------
def watch_candidates(
self, *, tag: str | None = None, require_running: bool = True
) -> list[Guest]:
wanted_tag = self.config.watch.tag if tag is None else tag
tracked = {item.vmid for item in self.state.all()}
candidates = []
for guest in self.proxmox.list_guests():
if guest.vmid in tracked:
continue
if wanted_tag and wanted_tag not in guest.tags:
continue
if require_running and not guest.is_running:
continue
candidates.append(guest)
return candidates
def doctor(self) -> ServiceReport:
report = ServiceReport("doctor")
if self.config.source is not None:
report.add("config", "ok", str(self.config.source))
try:
guests = self.proxmox.list_guests()
report.add(
"proxmox",
"ok",
f"{len(guests)} guest(s) visible via {self.config.proxmox.api_url}",
)
except (ProxdomainError, ConfigError) as exc:
report.fail(
"proxmox",
f"{exc} (the token needs at least VM.Audit on /vms)",
)
try:
status = self.cloudflare.verify_token()
zones = self.cloudflare.list_zones()
names = ", ".join(zone.name for zone in zones[:5]) or "none"
report.add("cloudflare", "ok", f"token {status}; {len(zones)} zone(s): {names}")
except (ProxdomainError, ConfigError) as exc:
report.fail(
"cloudflare",
f"{exc} (the token needs Zone:Read and DNS:Edit)",
)
report.add(
"web-server",
"ok",
f"{self.config.webserver.kind} via {self.webserver.runner.describe()}, "
f"managed dir {self.config.webserver.manage_dir}",
)
try:
present = self.webserver.runner.exists(self.config.webserver.manage_dir)
report.add(
"web-server",
"ok" if present else "warning",
"managed directory exists"
if present
else "managed directory is missing; run `proxdomain init`",
)
except ProxdomainError as exc:
report.fail("web-server", str(exc))
try:
validated = self.webserver.validate()
report.add(
"web-server",
"ok" if validated else "skipped",
"configuration test passed"
if validated
else "no test command configured for this web server",
)
except ProxdomainError as exc:
report.fail("web-server", str(exc))
try:
items = self.state.all()
report.add("state", "ok", f"{len(items)} assignment(s) in {self.state.path}")
except ProxdomainError as exc:
report.fail("state", str(exc))
return report
def init(self, *, dry_run: bool = False) -> ServiceReport:
report = ServiceReport("init")
try:
steps = self.webserver.bootstrap(dry_run=dry_run)
except ProxdomainError as exc:
return report.fail("bootstrap", str(exc))
for status, detail in steps:
report.add("bootstrap", status, detail)
report.add(
"result",
"planned" if dry_run else "ok",
"bootstrap finished" if not dry_run else "dry run: nothing was changed",
)
return report
# -- internals ------------------------------------------------------
def _resolve_fqdn(self, guest: Guest, subdomain: str | None) -> str:
if subdomain and subdomain.strip():
value = subdomain.strip().lower().rstrip(".")
if "." in value:
fqdn = value
else:
fqdn = f"{value}.{self.config.general.base_domain}"
else:
hostname = sanitize_hostname(guest.name, guest.vmid)
try:
fqdn = self.config.general.domain_template.format(
hostname=hostname,
vmid=guest.vmid,
node=guest.node,
kind=guest.kind,
base_domain=self.config.general.base_domain,
)
except KeyError as exc:
raise ProxdomainError(
f"general.domain_template uses an unknown placeholder {exc}"
) from exc
fqdn = fqdn.strip().lower().rstrip(".")
if not FQDN_RE.match(fqdn):
raise ProxdomainError(f"{fqdn!r} is not a valid DNS name")
return fqdn
def _site_spec(
self, guest: Guest, fqdn: str, address: str, port: int
) -> SiteSpec:
return SiteSpec(
fqdn=fqdn,
address=address,
port=port,
vmid=guest.vmid,
node=guest.node,
kind=guest.kind,
webserver=self.config.webserver.kind,
tls_mode=self.config.webserver.tls.mode,
cert_dir=self.config.webserver.tls.cert_dir,
webroot=self.config.webserver.tls.webroot,
cert_resolver=self.config.webserver.cert_resolver,
)
def _find_zone(
self, report: ServiceReport, fqdn: str, *, dry_run: bool
) -> Zone | None:
try:
zone = self.cloudflare.find_zone(fqdn, self.config.general.base_domain)
except (ProxdomainError, ConfigError) as exc:
if dry_run:
report.add("zone", "warning", f"{exc} (dry run: skipping DNS preview)")
return None
report.fail("zone", str(exc))
return None
report.add("zone", "ok", f"{zone.name} ({zone.id})")
return zone
def _preview_dns(
self,
report: ServiceReport,
zone: Zone,
fqdn: str,
address: str,
record_type: str,
proxied: bool,
) -> None:
try:
records = self.cloudflare.list_records(zone.id, name=fqdn, rtype=record_type)
except ProxdomainError as exc:
report.add("dns", "warning", f"could not preview the record: {exc}")
return
action = "create" if not records else (
"keep" if records[0].content == address and records[0].proxied == proxied else "update"
)
report.add(
"dns",
"planned",
f"would {action} {record_type} {fqdn} -> {address} "
f"(proxied={'yes' if proxied else 'no'})",
)
def _save(self, assignment: Assignment) -> None:
with self.state.locked():
self.state.load()
self.state.upsert(assignment)
self.state.flush()
def sanitize_hostname(name: str, vmid: int) -> str:
value = _HOSTNAME_STRIP.sub("-", (name or "").strip().lower()).strip("-")
value = _DASHES.sub("-", value)
value = value[:40].strip("-")
return value or f"vm{vmid}"