"""Orchestration: guest -> domain -> Cloudflare record -> reverse proxy config.""" from __future__ import annotations import ipaddress import re from dataclasses import dataclass, field from .addressing import PublicAddressResolver 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, dns_resolver: PublicAddressResolver | 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 self._dns_resolver = dns_resolver # -- 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 @property def dns_resolver(self) -> PublicAddressResolver: if self._dns_resolver is None: self._dns_resolver = PublicAddressResolver( self.config.dns, preference=self.config.proxmox.ip_preference ) return self._dns_resolver # -- 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, address: 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: guest_address = ip or self.proxmox.guest_ip(guest) except ProxdomainError as exc: return report.fail("address", str(exc)) if not guest_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: ipaddress.ip_address(guest_address) except ValueError: return report.fail("address", f"{guest_address!r} is not a valid IP address") report.add( "address", "ok", f"guest {guest_address} ({'argument' if ip else 'discovered'})", ) try: published = self.dns_resolver.resolve( guest_address=guest_address, override=address ) except ProxdomainError as exc: return report.fail("dns-address", str(exc)) report.add("dns-address", "ok", f"{published.address} ({published.source})") report.add("domain", "ok", fqdn) 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", ) try: target_port, port_source = self._resolve_port(guest, port, existing) except ProxdomainError as exc: return report.fail("port", str(exc)) report.add("port", "ok", f"{target_port} ({port_source})") 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 parsed_dns = ipaddress.ip_address(published.address) proxy_note = "" if effective_proxied and not parsed_dns.is_global: effective_proxied = False proxy_note = ( f"{published.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, guest_address, target_port) record_type = "A" if parsed_dns.version == 4 else "AAAA" # Ordering: ACME needs the name to resolve to this host before it can # validate, so a certificate that is still missing forces DNS to be # published first (Caddy starts ACME as soon as it reloads, so it always # goes first there). Everywhere else the vhost is written first, so a # failing DNS call cannot advertise a name that nothing answers for. dns_first = zone is not None and not dry_run and self._dns_before_config(spec) upsert = None if dns_first: try: upsert = self.cloudflare.upsert_address_record( zone.id, fqdn, published.address, proxied=effective_proxied ) except ProxdomainError as exc: report.fail("dns", str(exc)) report.add( "result", "warning", "a Let's Encrypt certificate needs this name to resolve first, " "so nothing was changed; fix the DNS error and re-run assign", ) return report report.add( "dns", "changed" if upsert.changed else "ok", f"{upsert.action} {record_type} {fqdn} -> {published.address} " f"(proxied={'yes' if effective_proxied else 'no'}; " "published before the certificate request)", ) try: applied = self.webserver.apply(spec, dry_run=dry_run) except ProxdomainError as exc: if upsert is not None: self.state.audit( "assign.dns-only", fqdn=fqdn, vmid=guest.vmid, content=published.address, ) 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, ) tls_step = self._tls_step(spec) if tls_step is not None: report.add(*tls_step) 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 = guest_address assignment.dns_ip = published.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_dns.version == 4 else "AAAA" if not dry_run: self._save(assignment) self.state.audit( "assign.web-config", fqdn=fqdn, vmid=guest.vmid, guest_address=guest_address, dns_address=published.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, published.address, record_type, effective_proxied ) report.add("result", "planned", "dry run: nothing was changed") report.assignment = assignment return report if upsert is None: try: upsert = self.cloudflare.upsert_address_record( zone.id, fqdn, published.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 assignment.tls = self.config.webserver.tls.mode self._save(assignment) self.state.audit( "assign.dns", fqdn=fqdn, record_id=upsert.record.id, action=upsert.action, content=published.address, guest_address=guest_address, proxied=effective_proxied, ) if not dns_first: report.add( "dns", "changed" if upsert.changed else "ok", f"{upsert.action} {record_type} {fqdn} -> {published.address} " f"(proxied={'yes' if effective_proxied else 'no'})", ) report.add( "result", "ok", f"{fqdn} -> {spec.target} (published {published.address})", ) 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: guest_address = self.proxmox.guest_ip(guest) or assignment.ip except ProxdomainError as exc: report.add("guest", "warning", f"{assignment.fqdn}: {exc}") continue if not guest_address: report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP") continue try: published = self.dns_resolver.resolve(guest_address=guest_address) except ProxdomainError as exc: report.fail("dns-address", f"{assignment.fqdn}: {exc}") continue if published.address != assignment.dns_ip: report.add( "dns-address", "planned" if dry_run else "changed", f"{assignment.fqdn}: {assignment.dns_ip or '-'} -> " f"{published.address} ({published.source})", ) try: declared_port, port_source = self.proxmox.guest_port(guest) except ProxdomainError as exc: report.fail("port", f"{assignment.fqdn}: {exc}") continue target_port = declared_port or assignment.port if target_port != assignment.port: report.add( "port", "planned" if dry_run else "changed", f"{assignment.fqdn}: {assignment.port} -> {target_port} ({port_source})", ) spec = self._site_spec(guest, assignment.fqdn, guest_address, target_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 assignment.port = target_port 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: assignment.ip = guest_address assignment.dns_ip = published.address continue try: upsert = self.cloudflare.upsert_address_record( assignment.zone_id, assignment.fqdn, published.address ) except ProxdomainError as exc: report.fail("dns", f"{assignment.fqdn}: {exc}") continue assignment.ip = guest_address assignment.dns_ip = published.address assignment.tls = self.config.webserver.tls.mode 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} -> {published.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)", ) if self.config.dns.target == "guest": report.add( "dns-target", "ok", "guest: each record publishes the guest's own address", ) else: try: resolved = self.dns_resolver.resolve(guest_address="") report.add( "dns-target", "ok", f"target {self.config.dns.target}: {resolved.address} " f"({resolved.source})", ) except ProxdomainError as exc: report.fail("dns-target", str(exc)) 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)) report.add(*self._doctor_tls()) 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)) items = [] if items and self.config.webserver.tls.mode in ("letsencrypt", "certbot"): report.add(*self._doctor_certificates(items)) return report def _doctor_tls(self) -> tuple[str, str, str]: tls = self.config.webserver.tls kind = self.config.webserver.kind if tls.mode == "none": return ( "tls", "skipped", "not managed (webserver.tls.mode = 'none'); set 'letsencrypt' for " "automatic HTTPS", ) if tls.mode == "files": present = self.webserver.runner.exists(tls.cert_dir) return ( "tls", "ok" if present else "warning", f"files mode: reading certificates from {tls.cert_dir}" if present else f"files mode, but {tls.cert_dir} does not exist", ) if kind == "caddy": return ( "tls", "ok", f"letsencrypt: Caddy's ACME issuer requests certificates on demand " f"({tls.email}) and renews them automatically", ) if kind == "traefik": return ( "tls", "ok", f"letsencrypt: Traefik certResolver " f"{self.config.webserver.cert_resolver} (must be defined in the " "static config with an ACME configuration)", ) try: binary = (tls.certbot_command or ("certbot",))[0] probe = self.webserver.runner.run([binary, "--version"]) except ProxdomainError as exc: return ("tls", "warning", f"cannot run certbot: {exc}") if not probe.ok: return ( "tls", "warning", f"{binary} is not installed or not executable; install certbot " "(apt install certbot) so proxdomain can issue Let's Encrypt " "certificates", ) version = probe.stdout.strip() or probe.output(limit=60) return ( "tls", "ok", f"letsencrypt via {binary} ({version}); webroot {tls.webroot}, " f"renew hook '{self.webserver.renew_hook or '-'}'", ) def _doctor_certificates(self, items: list[Assignment]) -> tuple[str, str, str]: if self.config.webserver.kind != "nginx": return ( "tls-certs", "ok", f"{len(items)} site(s) handled by " f"{self.config.webserver.kind}, which renews certificates itself", ) cert_dir = self.config.webserver.tls.cert_dir missing = [ item.fqdn for item in items if not self.webserver.runner.exists(f"{cert_dir}/{item.fqdn}/fullchain.pem") ] if not missing: return ( "tls-certs", "ok", f"a certificate exists for all {len(items)} managed site(s)", ) return ( "tls-certs", "warning", f"no certificate for {', '.join(missing)}; re-run assign for those guests", ) 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 _resolve_port( self, guest: Guest, port: int | None, existing: Assignment | None, ) -> tuple[int, str]: """Pick the backend port: explicit flag, guest declaration, stored, default.""" if port is not None: return _valid_port(int(port), "--port"), "command line" declared, source = self.proxmox.guest_port(guest) if declared is not None: return declared, source if existing is not None and existing.port: # Re-running assign must not silently reset a custom port. return _valid_port(existing.port, "the stored assignment"), "previous assignment" return _valid_port(self.config.general.default_port, "general.default_port"), ( "general.default_port" ) def _dns_before_config(self, spec: SiteSpec) -> bool: """True when ACME needs the public record in place before the vhost.""" webserver = self.config.webserver if webserver.tls.mode != "letsencrypt" and webserver.tls.mode != "certbot": return False if webserver.kind == "caddy": # Caddy starts issuing the moment the new site block is loaded. return True return self._certificate_missing(spec) def _certificate_missing(self, spec: SiteSpec) -> bool: """True when a certificate must still be obtained before TLS can serve.""" return self.webserver.issues_certificates and not self.webserver.certificate_present(spec) def _tls_step(self, spec: SiteSpec) -> tuple[str, str, str] | None: mode = self.config.webserver.tls.mode kind = self.config.webserver.kind if mode == "none": return ( "tls", "skipped", "tls.mode = 'none'; set webserver.tls.mode = 'letsencrypt' for HTTPS", ) if mode == "files": if self.webserver.certificate_present(spec): return ("tls", "ok", f"certificate files present in {spec.cert_dir}") return ( "tls", "warning", f"no certificate at {spec.certificate}; the vhost will fail to load " "once nginx is reloaded", ) if kind == "caddy": return ( "tls", "ok", "Caddy requests and renews a Let's Encrypt certificate for this site", ) if kind == "traefik": return ( "tls", "ok", f"Traefik obtains the certificate through certResolver " f"{self.config.webserver.cert_resolver}", ) if self.webserver.certificate_present(spec): expiry = self.webserver.certificate_expiry(spec) detail = f"Let's Encrypt certificate present ({spec.certificate})" if expiry: detail = f"Let's Encrypt certificate valid until {expiry}" return ("tls", "ok", detail) return ("tls", "warning", "no certificate yet; run assign again to finish issuance") 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, tls_email=self.config.webserver.tls.email, acme_ca=self.config.webserver.tls.acme_ca, renew_hook=self.webserver.renew_hook, ) 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 _valid_port(port: int, source: str) -> int: if not 1 <= port <= 65535: raise ProxdomainError( f"{port} is not a valid TCP port (1-65535); it came from {source}" ) return port 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}"