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

+11
View File
@@ -0,0 +1,11 @@
"""proxdomain — assign a public domain to Proxmox VMs/containers.
The package is intentionally dependency free (Python 3.11+ standard library):
it speaks the Proxmox VE and Cloudflare v4 HTTP APIs directly and writes
reverse-proxy config for nginx, Caddy or Traefik.
"""
from __future__ import annotations
__version__ = "0.1.0"
__all__ = ["__version__"]
+10
View File
@@ -0,0 +1,10 @@
"""`python -m proxdomain` entry point."""
from __future__ import annotations
import sys
from .cli import main
if __name__ == "__main__":
sys.exit(main())
+291
View File
@@ -0,0 +1,291 @@
"""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
+234
View File
@@ -0,0 +1,234 @@
"""Cloudflare v4 DNS client (A/AAAA records) with zone discovery."""
from __future__ import annotations
import ipaddress
from dataclasses import dataclass
from .config import CloudflareConfig
from .errors import ApiError, ProxdomainError
from .http import JsonClient, Transport, UrllibTransport
@dataclass(frozen=True)
class DnsRecord:
id: str
name: str
type: str
content: str
proxied: bool = False
ttl: int = 1
@classmethod
def from_api(cls, payload: dict) -> "DnsRecord":
return cls(
id=str(payload.get("id") or ""),
name=str(payload.get("name") or ""),
type=str(payload.get("type") or ""),
content=str(payload.get("content") or ""),
proxied=bool(payload.get("proxied") or False),
ttl=int(payload.get("ttl") or 1),
)
@dataclass(frozen=True)
class Zone:
id: str
name: str
@dataclass(frozen=True)
class UpsertResult:
action: str # created | updated | unchanged
record: DnsRecord
previous: DnsRecord | None = None
@property
def changed(self) -> bool:
return self.action != "unchanged"
class CloudflareClient:
def __init__(
self,
config: CloudflareConfig,
*,
http: JsonClient | None = None,
transport: Transport | None = None,
) -> None:
self.config = config
if http is None:
http = JsonClient(
config.api_url,
transport=transport or UrllibTransport(),
timeout=config.timeout,
retries=config.retries,
)
self.http = http
self.http.default_headers["Authorization"] = f"Bearer {config.resolve_token()}"
self._zone_cache: dict[str, Zone | None] = {}
# -- token / zones --------------------------------------------------
def verify_token(self) -> str:
data = self.http.get("/user/tokens/verify")
result = data.get("result") if isinstance(data, dict) else None
return str((result or {}).get("status") or "unknown")
def list_zones(self) -> list[Zone]:
zones: list[Zone] = []
page = 1
while page <= 10:
data = self.http.get("/zones", {"per_page": 50, "page": page})
rows = _result_list(data)
zones.extend(Zone(id=str(z["id"]), name=str(z["name"])) for z in rows if z.get("id"))
info = data.get("result_info") if isinstance(data, dict) else None
total_pages = int((info or {}).get("total_pages") or 1)
if page >= total_pages or not rows:
break
page += 1
return zones
def find_zone(self, fqdn: str, base_domain: str | None = None) -> Zone:
candidates = _zone_candidates(fqdn, base_domain)
for candidate in candidates:
if candidate in self._zone_cache:
cached = self._zone_cache[candidate]
if cached is not None:
return cached
continue
data = self.http.get("/zones", {"name": candidate, "per_page": 50})
rows = _result_list(data)
zone = None
for row in rows:
if str(row.get("name", "")).lower() == candidate.lower() and row.get("id"):
zone = Zone(id=str(row["id"]), name=str(row["name"]))
break
self._zone_cache[candidate] = zone
if zone is not None:
return zone
raise ProxdomainError(
"no Cloudflare zone found for "
f"{fqdn} (tried: {', '.join(candidates)}); "
"check general.base_domain and that the token can read the zone"
)
# -- records --------------------------------------------------------
def list_records(
self, zone_id: str, *, name: str | None = None, rtype: str | None = None
) -> list[DnsRecord]:
params = {"per_page": 100}
if name:
params["name"] = name
if rtype:
params["type"] = rtype
data = self.http.get(f"/zones/{zone_id}/dns_records", params)
records = []
for row in _result_list(data):
if not isinstance(row, dict) or not row.get("id"):
continue
record = DnsRecord.from_api(row)
if name and record.name.lower() != name.lower():
continue
if rtype and record.type.upper() != rtype.upper():
continue
records.append(record)
return records
def upsert_address_record(
self,
zone_id: str,
fqdn: str,
address: str,
*,
proxied: bool | None = None,
ttl: int | None = None,
comment: str | None = None,
) -> UpsertResult:
rtype = _record_type(address)
proxied = self.config.proxied if proxied is None else proxied
ttl = self.config.ttl if ttl is None else ttl
# Cloudflare forces TTL 1 (automatic) on proxied records; compare against
# that value so a configured 300 does not trigger a PATCH on every run.
ttl = 1 if proxied else ttl
comment = self.config.record_comment if comment is None else comment
existing = self.list_records(zone_id, name=fqdn, rtype=rtype)
if existing:
current = existing[0]
same_content = current.content == address
same_proxy = current.proxied == proxied
same_ttl = current.ttl == ttl
if same_content and same_proxy and same_ttl:
return UpsertResult("unchanged", current)
payload = {
"type": rtype,
"name": fqdn,
"content": address,
"ttl": ttl,
"proxied": proxied,
}
if comment:
payload["comment"] = comment
data = self.http.patch(f"/zones/{zone_id}/dns_records/{current.id}", payload)
return UpsertResult("updated", _record_from_response(data, current), current)
payload = {
"type": rtype,
"name": fqdn,
"content": address,
"ttl": ttl,
"proxied": proxied,
}
if comment:
payload["comment"] = comment
data = self.http.post(f"/zones/{zone_id}/dns_records", payload)
return UpsertResult("created", _record_from_response(data, None))
def delete_record(self, zone_id: str, record_id: str) -> bool:
try:
self.http.delete(f"/zones/{zone_id}/dns_records/{record_id}")
except ApiError as exc:
if exc.status == 404:
return False
raise
return True
# ---------------------------------------------------------------------------
def _record_type(address: str) -> str:
try:
version = ipaddress.ip_address(address).version
except ValueError as exc:
raise ProxdomainError(f"not a valid IP address: {address!r}") from exc
return "A" if version == 4 else "AAAA"
def _record_from_response(data: object, previous: DnsRecord | None) -> DnsRecord:
if isinstance(data, dict):
inner = data.get("result", data)
if isinstance(inner, dict) and inner.get("id"):
return DnsRecord.from_api(inner)
if previous is not None:
return previous
raise ProxdomainError("Cloudflare returned an unexpected DNS record payload")
def _result_list(data: object) -> list[dict]:
if isinstance(data, dict) and isinstance(data.get("result"), list):
return [row for row in data["result"] if isinstance(row, dict)]
return []
def _zone_candidates(fqdn: str, base_domain: str | None) -> list[str]:
fqdn = fqdn.strip().lower().rstrip(".")
labels = fqdn.split(".")
suffixes = [".".join(labels[i:]) for i in range(len(labels) - 1)]
ordered: list[str] = []
if base_domain:
base = base_domain.strip().lower().rstrip(".")
if fqdn == base or fqdn.endswith("." + base):
ordered.append(base)
for suffix in reversed(suffixes): # shortest first (closest to the apex)
if suffix not in ordered:
ordered.append(suffix)
return ordered
+475
View File
@@ -0,0 +1,475 @@
"""Configuration loading and validation (TOML, standard library only)."""
from __future__ import annotations
import os
import tomllib
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Mapping
from .errors import ConfigError
ENV_CONFIG = "PROXDOMAIN_CONFIG"
DEFAULT_CONFIG_PATHS = (
Path("proxdomain.toml"),
Path("/etc/proxdomain/config.toml"),
)
WEBSERVER_KINDS = ("nginx", "caddy", "traefik")
WEBSERVER_MODES = ("local", "ssh")
TLS_MODES = ("none", "files", "certbot")
IP_PREFERENCES = ("auto", "ipv4", "ipv6")
# Web server defaults live here so `config.example.toml` and the docs stay honest.
_KIND_DEFAULTS: dict[str, dict[str, Any]] = {
"nginx": {
"manage_dir": "/etc/nginx/conf.d/proxdomain.d",
"test_command": ("nginx", "-t"),
"reload_command": ("systemctl", "reload", "nginx"),
"cert_resolver": "",
},
"caddy": {
"manage_dir": "/etc/caddy/proxdomain.d",
"test_command": ("caddy", "validate", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"),
"reload_command": ("systemctl", "reload", "caddy"),
"cert_resolver": "",
},
"traefik": {
"manage_dir": "/etc/traefik/dynamic",
# The file provider watches its directory; no reload needed.
"test_command": (),
"reload_command": (),
"cert_resolver": "letsencrypt",
},
}
@dataclass(frozen=True)
class GeneralConfig:
base_domain: str
domain_template: str = "{hostname}.{base_domain}"
default_port: int = 80
@dataclass(frozen=True)
class ProxmoxConfig:
api_url: str
token_id: str
token_secret: str | None = None
token_secret_env: str | None = None
token_secret_file: str | None = None
verify_tls: bool = True
timeout: float = 20.0
exclude_networks: tuple[str, ...] = (
"127.0.0.0/8",
"169.254.0.0/16",
"172.17.0.0/16",
)
ip_preference: str = "ipv4"
def resolve_secret(self) -> str:
if self.token_secret_env:
value = os.environ.get(self.token_secret_env, "")
if not value:
raise ConfigError(
f"environment variable {self.token_secret_env} "
"(proxmox.token_secret_env) is empty or unset"
)
return value
if self.token_secret_file:
path = Path(self.token_secret_file).expanduser()
try:
value = path.read_text(encoding="utf-8").strip()
except OSError as exc:
raise ConfigError(f"cannot read proxmox.token_secret_file {path}: {exc}") from exc
if not value:
raise ConfigError(f"proxmox.token_secret_file {path} is empty")
return value
if self.token_secret:
return self.token_secret
raise ConfigError(
"no Proxmox API token secret configured; set proxmox.token_secret_env "
"(recommended), proxmox.token_secret_file or proxmox.token_secret"
)
@dataclass(frozen=True)
class CloudflareConfig:
api_url: str = "https://api.cloudflare.com/client/v4"
api_token: str | None = None
api_token_env: str | None = "PROXDOMAIN_CF_TOKEN"
api_token_file: str | None = None
proxied: bool = True
ttl: int = 1
record_comment: str = "managed by proxdomain"
timeout: float = 20.0
retries: int = 2
def resolve_token(self) -> str:
if self.api_token_env:
value = os.environ.get(self.api_token_env, "")
if not value:
raise ConfigError(
f"environment variable {self.api_token_env} "
"(cloudflare.api_token_env) is empty or unset"
)
return value
if self.api_token_file:
path = Path(self.api_token_file).expanduser()
try:
value = path.read_text(encoding="utf-8").strip()
except OSError as exc:
raise ConfigError(
f"cannot read cloudflare.api_token_file {path}: {exc}"
) from exc
if not value:
raise ConfigError(f"cloudflare.api_token_file {path} is empty")
return value
if self.api_token:
return self.api_token
raise ConfigError(
"no Cloudflare API token configured; set cloudflare.api_token_env "
"(recommended), cloudflare.api_token_file or cloudflare.api_token"
)
@dataclass(frozen=True)
class TlsConfig:
mode: str = "none" # none | files | certbot
cert_dir: str = "/etc/letsencrypt/live"
webroot: str = "/var/www/certbot"
certbot_command: tuple[str, ...] = (
"certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos",
)
email: str = ""
extra_args: tuple[str, ...] = ()
@dataclass(frozen=True)
class WebServerConfig:
kind: str = "nginx"
mode: str = "local" # local | ssh
manage_dir: str = ""
test_command: tuple[str, ...] = ()
reload_command: tuple[str, ...] = ()
ssh_host: str = ""
ssh_port: int = 22
ssh_identity_file: str = ""
ssh_options: tuple[str, ...] = ()
sudo: str = "sudo -n"
cert_resolver: str = ""
tls: TlsConfig = TlsConfig()
def command(self, name: str) -> tuple[str, ...]:
return self.test_command if name == "test" else self.reload_command
@dataclass(frozen=True)
class WatchConfig:
enabled: bool = False
interval: int = 60
tag: str = "proxdomain"
auto_assign: bool = False
require_running: bool = True
@dataclass(frozen=True)
class StateConfig:
path: str = "/var/lib/proxdomain/state.json"
audit_path: str = ""
lock_timeout: float = 10.0
def resolved_audit_path(self) -> str:
if self.audit_path:
return self.audit_path
# POSIX-style join: the state path describes the Proxmox host, so the
# derived path must not depend on the platform running the CLI.
parent = self.path.rsplit("/", 1)[0] if "/" in self.path else "."
return f"{parent}/audit.jsonl"
@dataclass(frozen=True)
class Config:
general: GeneralConfig
proxmox: ProxmoxConfig
cloudflare: CloudflareConfig
webserver: WebServerConfig
watch: WatchConfig = WatchConfig()
state: StateConfig = StateConfig()
source: Path | None = None
# ---------------------------------------------------------------------------
# loading
# ---------------------------------------------------------------------------
def resolve_config_path(explicit: str | os.PathLike[str] | None = None) -> Path:
candidates: list[Path] = []
if explicit:
candidates.append(Path(explicit).expanduser())
elif os.environ.get(ENV_CONFIG):
candidates.append(Path(os.environ[ENV_CONFIG]).expanduser())
else:
candidates.extend(DEFAULT_CONFIG_PATHS)
for candidate in candidates:
if candidate.is_file():
return candidate
searched = ", ".join(str(c) for c in candidates)
raise ConfigError(
f"no configuration file found (searched: {searched}); "
"copy config.example.toml to proxdomain.toml or pass --config"
)
def load_config(path: str | os.PathLike[str] | None = None) -> Config:
config_path = resolve_config_path(path)
try:
with config_path.open("rb") as handle:
raw = tomllib.load(handle)
except OSError as exc:
raise ConfigError(f"cannot read {config_path}: {exc}") from exc
except tomllib.TOMLDecodeError as exc:
raise ConfigError(f"{config_path} is not valid TOML: {exc}") from exc
return parse_config(raw, source=config_path)
def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Config:
if not isinstance(raw, Mapping):
raise ConfigError("configuration root must be a TOML table")
general_raw = _table(raw, "general")
proxmox_raw = _table(raw, "proxmox")
cloudflare_raw = _table(raw, "cloudflare")
webserver_raw = _table(raw, "webserver")
watch_raw = _table(raw, "watch")
state_raw = _table(raw, "state")
tls_raw = _table(webserver_raw, "tls", prefix="webserver")
general = GeneralConfig(
base_domain=_str(general_raw, "base_domain", required=True, prefix="general"),
domain_template=_str(
general_raw, "domain_template", "{hostname}.{base_domain}", prefix="general"
),
default_port=_port(general_raw, "default_port", 80, prefix="general"),
)
if not general.base_domain or "." not in general.base_domain:
raise ConfigError("general.base_domain must be a registrable domain such as example.com")
if "{hostname}" not in general.domain_template and "{vmid}" not in general.domain_template:
raise ConfigError(
"general.domain_template must contain {hostname} or {vmid} so each guest gets a name"
)
proxmox = ProxmoxConfig(
api_url=_str(proxmox_raw, "api_url", required=True, prefix="proxmox"),
token_id=_str(proxmox_raw, "token_id", required=True, prefix="proxmox"),
token_secret=_opt_str(proxmox_raw, "token_secret", prefix="proxmox"),
token_secret_env=_opt_str(proxmox_raw, "token_secret_env", prefix="proxmox"),
token_secret_file=_opt_str(proxmox_raw, "token_secret_file", prefix="proxmox"),
verify_tls=_bool(proxmox_raw, "verify_tls", True, prefix="proxmox"),
timeout=_float(proxmox_raw, "timeout", 20.0, prefix="proxmox"),
exclude_networks=_str_tuple(proxmox_raw, "exclude_networks", prefix="proxmox")
or ProxmoxConfig.exclude_networks,
ip_preference=_choice(
proxmox_raw, "ip_preference", "ipv4", IP_PREFERENCES, prefix="proxmox"
),
)
if "!" not in proxmox.token_id:
raise ConfigError(
"proxmox.token_id must look like 'user@realm!tokenname' "
"(Proxmox API token identifier)"
)
if not proxmox.api_url.startswith(("http://", "https://")):
raise ConfigError("proxmox.api_url must start with http:// or https://")
cloudflare = CloudflareConfig(
api_url=_str(cloudflare_raw, "api_url", CloudflareConfig.api_url, prefix="cloudflare"),
api_token=_opt_str(cloudflare_raw, "api_token", prefix="cloudflare"),
api_token_env=_opt_str(cloudflare_raw, "api_token_env", prefix="cloudflare")
or None,
api_token_file=_opt_str(cloudflare_raw, "api_token_file", prefix="cloudflare"),
proxied=_bool(cloudflare_raw, "proxied", True, prefix="cloudflare"),
ttl=_int(cloudflare_raw, "ttl", 1, prefix="cloudflare"),
record_comment=_str(
cloudflare_raw, "record_comment", "managed by proxdomain", prefix="cloudflare"
),
timeout=_float(cloudflare_raw, "timeout", 20.0, prefix="cloudflare"),
retries=_int(cloudflare_raw, "retries", 2, prefix="cloudflare"),
)
if cloudflare.ttl != 1 and not 60 <= cloudflare.ttl <= 86400:
raise ConfigError("cloudflare.ttl must be 1 (auto) or between 60 and 86400")
kind = _choice(webserver_raw, "kind", "nginx", WEBSERVER_KINDS, prefix="webserver")
defaults = _KIND_DEFAULTS[kind]
mode = _choice(webserver_raw, "mode", "local", WEBSERVER_MODES, prefix="webserver")
manage_dir = _str(webserver_raw, "manage_dir", defaults["manage_dir"], prefix="webserver")
if not manage_dir.startswith("/"):
raise ConfigError("webserver.manage_dir must be an absolute path on the Proxmox host")
test_command = _str_tuple(webserver_raw, "test_command", prefix="webserver")
if "test_command" not in webserver_raw:
test_command = tuple(defaults["test_command"])
reload_command = _str_tuple(webserver_raw, "reload_command", prefix="webserver")
if "reload_command" not in webserver_raw:
reload_command = tuple(defaults["reload_command"])
tls = TlsConfig(
mode=_choice(tls_raw, "mode", "none", TLS_MODES, prefix="webserver.tls"),
cert_dir=_str(tls_raw, "cert_dir", TlsConfig.cert_dir, prefix="webserver.tls"),
webroot=_str(tls_raw, "webroot", TlsConfig.webroot, prefix="webserver.tls"),
certbot_command=_str_tuple(tls_raw, "certbot_command", prefix="webserver.tls")
or TlsConfig.certbot_command,
email=_str(tls_raw, "email", "", prefix="webserver.tls"),
extra_args=_str_tuple(tls_raw, "extra_args", prefix="webserver.tls"),
)
if tls.mode == "certbot" and not tls.email:
raise ConfigError("webserver.tls.email is required when tls.mode = 'certbot'")
webserver = WebServerConfig(
kind=kind,
mode=mode,
manage_dir=manage_dir.rstrip("/"),
test_command=test_command,
reload_command=reload_command,
ssh_host=_str(webserver_raw, "ssh_host", "", prefix="webserver"),
ssh_port=_int(webserver_raw, "ssh_port", 22, prefix="webserver"),
ssh_identity_file=_str(webserver_raw, "ssh_identity_file", "", prefix="webserver"),
ssh_options=_str_tuple(webserver_raw, "ssh_options", prefix="webserver"),
sudo=_str(webserver_raw, "sudo", "sudo -n", prefix="webserver"),
cert_resolver=_str(
webserver_raw, "cert_resolver", defaults["cert_resolver"], prefix="webserver"
),
tls=tls,
)
if webserver.mode == "ssh" and not webserver.ssh_host:
raise ConfigError("webserver.ssh_host is required when webserver.mode = 'ssh'")
if kind != "nginx" and tls.mode == "certbot":
raise ConfigError(
"webserver.tls.mode = 'certbot' is only supported with kind = 'nginx'; "
"use 'none' (Caddy manages certificates itself) or 'files'"
)
if kind == "traefik" and tls.mode == "files":
raise ConfigError(
"webserver.tls.mode = 'files' is not supported with kind = 'traefik'; "
"set webserver.cert_resolver instead"
)
state = StateConfig(
path=_str(state_raw, "path", StateConfig.path, prefix="state"),
audit_path=_str(state_raw, "audit_path", "", prefix="state"),
lock_timeout=_float(state_raw, "lock_timeout", 10.0, prefix="state"),
)
watch = WatchConfig(
enabled=_bool(watch_raw, "enabled", False, prefix="watch"),
interval=max(5, _int(watch_raw, "interval", 60, prefix="watch")),
tag=_str(watch_raw, "tag", "proxdomain", prefix="watch").strip(),
auto_assign=_bool(watch_raw, "auto_assign", False, prefix="watch"),
require_running=_bool(watch_raw, "require_running", True, prefix="watch"),
)
return Config(
general=general,
proxmox=proxmox,
cloudflare=cloudflare,
webserver=webserver,
watch=watch,
state=state,
source=source,
)
def with_overrides(config: Config, **overrides: Any) -> Config:
"""Return a copy with simple top-level field overrides (used by tests/CLI)."""
return replace(config, **overrides)
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def _table(raw: Mapping[str, Any], key: str, *, prefix: str = "") -> Mapping[str, Any]:
value = raw.get(key, {})
if not isinstance(value, Mapping):
raise ConfigError(f"{prefix + '.' if prefix else ''}{key} must be a TOML table")
return value
def _str(
table: Mapping[str, Any], key: str, default: str | None = None, *,
required: bool = False, prefix: str = "",
) -> str:
value = table.get(key, default)
if value is None:
if required:
raise ConfigError(f"missing required setting {_dotted(prefix, key)}")
return ""
if not isinstance(value, str):
raise ConfigError(f"{_dotted(prefix, key)} must be a string")
if required and not value.strip():
raise ConfigError(f"{_dotted(prefix, key)} must not be empty")
return value.strip()
def _opt_str(table: Mapping[str, Any], key: str, *, prefix: str = "") -> str | None:
value = table.get(key)
if value is None:
return None
if not isinstance(value, str):
raise ConfigError(f"{_dotted(prefix, key)} must be a string")
return value.strip() or None
def _bool(table: Mapping[str, Any], key: str, default: bool, *, prefix: str = "") -> bool:
value = table.get(key, default)
if not isinstance(value, bool):
raise ConfigError(f"{_dotted(prefix, key)} must be true or false")
return value
def _int(table: Mapping[str, Any], key: str, default: int, *, prefix: str = "") -> int:
value = table.get(key, default)
if isinstance(value, bool) or not isinstance(value, int):
raise ConfigError(f"{_dotted(prefix, key)} must be an integer")
return value
def _float(table: Mapping[str, Any], key: str, default: float, *, prefix: str = "") -> float:
value = table.get(key, default)
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ConfigError(f"{_dotted(prefix, key)} must be a number")
return float(value)
def _port(table: Mapping[str, Any], key: str, default: int, *, prefix: str = "") -> int:
value = _int(table, key, default, prefix=prefix)
if not 1 <= value <= 65535:
raise ConfigError(f"{_dotted(prefix, key)} must be between 1 and 65535")
return value
def _str_tuple(table: Mapping[str, Any], key: str, *, prefix: str = "") -> tuple[str, ...]:
value = table.get(key)
if value is None:
return ()
if isinstance(value, str):
raise ConfigError(
f"{_dotted(prefix, key)} must be an array of strings, e.g. [\"nginx\", \"-t\"]"
)
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
raise ConfigError(f"{_dotted(prefix, key)} must be an array of strings")
return tuple(value)
def _choice(
table: Mapping[str, Any], key: str, default: str, allowed: tuple[str, ...], *,
prefix: str = "",
) -> str:
value = _str(table, key, default, prefix=prefix)
if value not in allowed:
raise ConfigError(
f"{_dotted(prefix, key)} must be one of: {', '.join(allowed)} (got {value!r})"
)
return value
def _dotted(prefix: str, key: str) -> str:
return f"{prefix}.{key}" if prefix else key
+36
View File
@@ -0,0 +1,36 @@
"""Exception types shared by every proxdomain module."""
from __future__ import annotations
class ProxdomainError(Exception):
"""Base class for all expected, user-facing failures."""
class ConfigError(ProxdomainError):
"""The configuration file is missing, malformed or incomplete."""
class ApiError(ProxdomainError):
"""A remote API (Proxmox VE or Cloudflare) returned an error."""
def __init__(
self,
message: str,
*,
status: int | None = None,
payload: object | None = None,
url: str | None = None,
) -> None:
super().__init__(message)
self.status = status
self.payload = payload
self.url = url
@property
def is_auth_error(self) -> bool:
return self.status in (401, 403)
class WebServerError(ProxdomainError):
"""Writing, validating or reloading the web server configuration failed."""
+203
View File
@@ -0,0 +1,203 @@
"""A very small JSON-over-HTTP client with retries and testable transport."""
from __future__ import annotations
import json
import socket
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from typing import Any, Mapping, Protocol
from .errors import ApiError
RETRY_STATUSES = (429, 502, 503, 504)
# POST is deliberately excluded: retrying a DNS create after a 502 could leave a
# duplicate record behind. Everything else here is safe to replay.
RETRYABLE_METHODS = frozenset({"GET", "HEAD", "PUT", "PATCH", "DELETE"})
@dataclass(frozen=True)
class Response:
status: int
body: bytes
headers: Mapping[str, str] = field(default_factory=dict)
def json(self) -> Any:
try:
return json.loads(self.body.decode("utf-8") or "null")
except (UnicodeDecodeError, json.JSONDecodeError) as exc: # pragma: no cover - defensive
raise ApiError(f"response is not valid JSON: {exc}") from exc
def text(self) -> str:
return self.body.decode("utf-8", errors="replace")
class Transport(Protocol):
def request(
self,
method: str,
url: str,
headers: Mapping[str, str],
body: bytes | None,
timeout: float,
) -> Response: ...
class UrllibTransport:
"""Real network transport built on urllib (no third-party dependencies)."""
def __init__(self, *, verify_tls: bool = True) -> None:
if verify_tls:
self._context: ssl.SSLContext | None = None
else:
self._context = ssl._create_unverified_context() # noqa: SLF001 - documented API gap
def request(
self,
method: str,
url: str,
headers: Mapping[str, str],
body: bytes | None,
timeout: float,
) -> Response:
req = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
try:
with urllib.request.urlopen(req, timeout=timeout, context=self._context) as resp:
return Response(
status=resp.status,
body=resp.read(),
headers={k.lower(): v for k, v in resp.headers.items()},
)
except urllib.error.HTTPError as exc:
# Keep the payload: Cloudflare and Proxmox both put useful detail there.
return Response(
status=exc.code,
body=exc.read() or b"",
headers={k.lower(): v for k, v in (exc.headers or {}).items()},
)
except urllib.error.URLError as exc:
raise ApiError(f"cannot reach {url}: {exc.reason}") from exc
except socket.timeout as exc:
raise ApiError(f"timeout while calling {url}") from exc
class JsonClient:
"""Base URL + auth headers + JSON encoding/decoding + bounded retries."""
def __init__(
self,
base_url: str,
*,
transport: Transport | None = None,
timeout: float = 20.0,
retries: int = 2,
backoff: float = 0.5,
default_headers: Mapping[str, str] | None = None,
sleep=time.sleep,
) -> None:
self.base_url = base_url.rstrip("/")
self.transport = transport or UrllibTransport()
self.timeout = timeout
self.retries = max(0, retries)
self.backoff = backoff
self.default_headers = {"Accept": "application/json", **dict(default_headers or {})}
self._sleep = sleep
# -- public API -----------------------------------------------------
def get(self, path: str, params: Mapping[str, Any] | None = None) -> Any:
return self.request("GET", path, params=params)
def post(self, path: str, body: Any) -> Any:
return self.request("POST", path, json_body=body)
def patch(self, path: str, body: Any) -> Any:
return self.request("PATCH", path, json_body=body)
def put(self, path: str, body: Any) -> Any:
return self.request("PUT", path, json_body=body)
def delete(self, path: str) -> Any:
return self.request("DELETE", path)
def request(
self,
method: str,
path: str,
*,
params: Mapping[str, Any] | None = None,
json_body: Any = None,
headers: Mapping[str, str] | None = None,
) -> Any:
url = self.base_url + path
if params:
query = urllib.parse.urlencode(
{k: v for k, v in params.items() if v is not None}, doseq=True
)
if query:
url = f"{url}?{query}"
body = None if json_body is None else json.dumps(json_body).encode("utf-8")
request_headers = dict(self.default_headers)
if body is not None:
request_headers["Content-Type"] = "application/json"
if headers:
request_headers.update(headers)
attempts = self.retries + 1
last: Response | None = None
for attempt in range(1, attempts + 1):
last = self.transport.request(method, url, request_headers, body, self.timeout)
retryable = last.status == 429 or (
last.status in RETRY_STATUSES and method.upper() in RETRYABLE_METHODS
)
if last.status < 400 or not retryable or attempt == attempts:
break
delay = self.backoff * (2 ** (attempt - 1))
retry_after = last.headers.get("retry-after")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
pass
self._sleep(delay)
assert last is not None
if last.status >= 400:
raise ApiError(
self._error_message(method, url, last),
status=last.status,
payload=_safe_json(last),
url=url,
)
if not last.body:
return None
return last.json()
# -- helpers --------------------------------------------------------
@staticmethod
def _error_message(method: str, url: str, response: Response) -> str:
detail = ""
payload = _safe_json(response)
if isinstance(payload, dict):
errors = payload.get("errors")
if isinstance(errors, list) and errors:
detail = "; ".join(
str(e.get("message") if isinstance(e, dict) else e) for e in errors
)
elif payload.get("message"):
detail = str(payload["message"])
if not detail:
detail = response.text().strip()[:300]
suffix = f": {detail}" if detail else ""
return f"{method} {url} -> HTTP {response.status}{suffix}"
def _safe_json(response: Response) -> Any:
try:
return response.json()
except ApiError:
return None
+258
View File
@@ -0,0 +1,258 @@
"""Proxmox VE API client: guest discovery and IP address resolution."""
from __future__ import annotations
import ipaddress
from dataclasses import dataclass, field
from typing import Iterable
from .config import ProxmoxConfig
from .errors import ApiError, ProxdomainError
from .http import JsonClient, Transport, UrllibTransport
@dataclass(frozen=True)
class Guest:
vmid: int
node: str
name: str
kind: str # "qemu" | "lxc"
status: str = "unknown"
tags: tuple[str, ...] = field(default_factory=tuple)
@property
def ref(self) -> str:
return f"{self.kind}/{self.vmid}"
@property
def label(self) -> str:
return f"{self.name or 'unnamed'} ({self.kind} {self.vmid} on {self.node})"
@property
def is_running(self) -> bool:
return self.status == "running"
class ProxmoxClient:
def __init__(
self,
config: ProxmoxConfig,
*,
http: JsonClient | None = None,
transport: Transport | None = None,
) -> None:
self.config = config
if http is None:
http = JsonClient(
config.api_url,
transport=transport or UrllibTransport(verify_tls=config.verify_tls),
timeout=config.timeout,
retries=1,
)
self.http = http
self._excluded = _parse_networks(config.exclude_networks)
self.http.default_headers["Authorization"] = (
f"PVEAPIToken={config.token_id}={config.resolve_secret()}"
)
# -- inventory ------------------------------------------------------
def list_guests(self) -> list[Guest]:
data = self.http.get("/cluster/resources", {"type": "vm"})
guests: list[Guest] = []
for item in _data_list(data):
if not isinstance(item, dict) or "vmid" not in item:
continue
kind = str(item.get("type") or "")
if kind not in ("qemu", "lxc"):
continue
guests.append(
Guest(
vmid=int(item["vmid"]),
node=str(item.get("node") or ""),
name=str(item.get("name") or ""),
kind=kind,
status=str(item.get("status") or "unknown"),
tags=_split_tags(item.get("tags")),
)
)
guests.sort(key=lambda g: (g.node, g.vmid))
return guests
def find_guest(
self, *, vmid: int | None = None, name: str | None = None
) -> Guest:
if vmid is None and not name:
raise ProxdomainError("specify a guest by --vmid or --name")
guests = self.list_guests()
if vmid is not None:
matches = [g for g in guests if g.vmid == vmid]
else:
needle = (name or "").strip().lower()
matches = [g for g in guests if g.name.lower() == needle]
if not matches:
matches = [g for g in guests if needle and needle in g.name.lower()]
if not matches:
target = f"vmid {vmid}" if vmid is not None else f"name {name!r}"
raise ProxdomainError(f"no guest found for {target}; check the PVE token permissions")
if len(matches) > 1:
listing = ", ".join(f"{g.kind}/{g.vmid} ({g.name})" for g in matches)
raise ProxdomainError(f"{name!r} matches several guests: {listing}; use --vmid")
return matches[0]
def new_guests(self, known_vmids: Iterable[int], *, tag: str = "") -> list[Guest]:
known = set(known_vmids)
result = []
for guest in self.list_guests():
if guest.vmid in known:
continue
if tag and tag not in guest.tags:
continue
result.append(guest)
return result
# -- addressing -----------------------------------------------------
def guest_ip(self, guest: Guest) -> str | None:
want = self.config.ip_preference
candidates: list[str] = []
if guest.kind == "qemu":
candidates.extend(self._agent_ips(guest))
else:
candidates.extend(self._lxc_runtime_ips(guest))
candidates.extend(self._config_ips(guest))
unique: list[str] = []
for address in candidates:
if address and address not in unique:
unique.append(address)
v4 = [a for a in unique if _version(a) == 4 and self._usable(a)]
v6 = [a for a in unique if _version(a) == 6 and self._usable(a)]
if want == "ipv4":
return (v4 or v6 or [None])[0]
if want == "ipv6":
return (v6 or v4 or [None])[0]
return (unique and next((a for a in unique if self._usable(a)), None)) or None
def _usable(self, address: str) -> bool:
try:
ip = ipaddress.ip_address(address)
except ValueError:
return False
if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified:
return False
return not any(ip in network for network in self._excluded)
def _agent_ips(self, guest: Guest) -> list[str]:
path = f"/nodes/{guest.node}/qemu/{guest.vmid}/agent/network-get-interfaces"
try:
data = self.http.get(path)
except ApiError as exc:
if exc.is_auth_error:
raise
return [] # qemu-guest-agent not installed/running: fall back to config
payload = data
if isinstance(payload, dict) and isinstance(payload.get("data"), (dict, list)):
payload = payload["data"]
if isinstance(payload, dict) and isinstance(payload.get("result"), list):
payload = payload["result"]
found: list[str] = []
if isinstance(payload, list):
for iface in payload:
if not isinstance(iface, dict) or iface.get("name") == "lo":
continue
for addr in iface.get("ip-addresses") or []:
if not isinstance(addr, dict):
continue
value = addr.get("ip-address")
kind = addr.get("ip-address-type")
if value and kind in ("ipv4", "ipv6", 4, 6):
found.append(str(value))
return found
def _lxc_runtime_ips(self, guest: Guest) -> list[str]:
path = f"/nodes/{guest.node}/lxc/{guest.vmid}/interfaces"
try:
data = self.http.get(path)
except ApiError as exc:
if exc.is_auth_error:
raise
return []
found: list[str] = []
for item in _data_list(data):
if not isinstance(item, dict):
continue
for key in ("inet", "inet6"):
value = str(item.get(key) or "").split("/")[0].strip()
if value and value != "127.0.0.1":
found.append(value)
return found
def _config_ips(self, guest: Guest) -> list[str]:
endpoint = "qemu" if guest.kind == "qemu" else "lxc"
try:
data = self.http.get(f"/nodes/{guest.node}/{endpoint}/{guest.vmid}/config")
except ApiError as exc:
if exc.is_auth_error:
raise
return []
config = data if isinstance(data, dict) else {}
if "data" in config and isinstance(config["data"], dict):
config = config["data"]
found: list[str] = []
for key, value in sorted(config.items()):
if not (key.startswith("net") or key.startswith("ipconfig")):
continue
if not isinstance(value, str):
continue
for option in value.split(","):
option = option.strip()
if "=" not in option:
continue
name, _, raw = option.partition("=")
if name.strip() not in ("ip", "ip6"):
continue
address = raw.split("/")[0].strip()
if address and address.lower() != "dhcp" and address.lower() != "auto":
found.append(address)
return found
# ---------------------------------------------------------------------------
def _parse_networks(values: Iterable[str]) -> tuple[ipaddress._BaseNetwork, ...]:
networks = []
for value in values:
try:
networks.append(ipaddress.ip_network(value, strict=False))
except ValueError as exc:
raise ProxdomainError(
f"proxmox.exclude_networks contains an invalid network {value!r}: {exc}"
) from exc
return tuple(networks)
def _data_list(data: object) -> list:
if isinstance(data, dict):
inner = data.get("data")
if isinstance(inner, list):
return inner
if inner is None:
return []
return [inner]
if isinstance(data, list):
return data
return []
def _split_tags(value: object) -> tuple[str, ...]:
if not isinstance(value, str):
return ()
normalized = value.replace(",", ";")
return tuple(tag.strip() for tag in normalized.split(";") if tag.strip())
def _version(address: str) -> int:
try:
return ipaddress.ip_address(address).version
except ValueError:
return 0
+287
View File
@@ -0,0 +1,287 @@
"""File and command execution: either on this machine or on the Proxmox host over SSH."""
from __future__ import annotations
import os
import shlex
import subprocess
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Sequence
from .errors import ProxdomainError
@dataclass(frozen=True)
class CommandResult:
argv: tuple[str, ...]
returncode: int
stdout: str = ""
stderr: str = ""
@property
def ok(self) -> bool:
return self.returncode == 0
def output(self, limit: int = 1200) -> str:
text = "\n".join(part.strip() for part in (self.stdout, self.stderr) if part.strip())
return text[-limit:]
class Runner(Protocol):
def run(
self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0
) -> CommandResult: ...
def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: ...
def read_text(self, path: str) -> str | None: ...
def remove(self, path: str) -> bool: ...
def exists(self, path: str) -> bool: ...
def mkdir(self, path: str) -> None: ...
def describe(self) -> str: ...
class LocalRunner:
"""Writes files and runs commands directly (used when proxdomain runs on the PVE host)."""
def __init__(self, *, sleep=time.sleep) -> None:
self._sleep = sleep
def run(
self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0
) -> CommandResult:
argv = tuple(argv)
if not argv:
raise ProxdomainError("refusing to run an empty command")
try:
completed = subprocess.run(
list(argv),
input=input_text,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
)
except FileNotFoundError as exc:
raise ProxdomainError(f"command not found: {argv[0]}") from exc
except subprocess.TimeoutExpired as exc:
raise ProxdomainError(f"command timed out after {timeout}s: {' '.join(argv)}") from exc
return CommandResult(
argv=argv,
returncode=completed.returncode,
stdout=completed.stdout or "",
stderr=completed.stderr or "",
)
def write_text(self, path: str, content: str, mode: int = 0o644) -> bool:
target = Path(path)
current = self.read_text(path)
if current is not None and current == content:
return False
target.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent))
try:
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
if os.name != "nt":
os.chmod(tmp, mode)
os.replace(tmp, target)
except BaseException:
with _suppress_errors():
os.unlink(tmp)
raise
return True
def read_text(self, path: str) -> str | None:
try:
return Path(path).read_text(encoding="utf-8")
except FileNotFoundError:
return None
except IsADirectoryError:
return None
except OSError as exc:
raise ProxdomainError(f"cannot read {path}: {exc}") from exc
def remove(self, path: str) -> bool:
try:
os.unlink(path)
return True
except FileNotFoundError:
return False
except OSError as exc:
raise ProxdomainError(f"cannot remove {path}: {exc}") from exc
def exists(self, path: str) -> bool:
return Path(path).exists()
def mkdir(self, path: str) -> None:
Path(path).mkdir(parents=True, exist_ok=True)
def describe(self) -> str:
return "local"
class SSHRunner:
"""Runs commands and manages files on the Proxmox host through `ssh`.
Uses non-interactive sudo (`sudo -n` by default) so a missing sudo grant fails
fast instead of hanging a cron job or systemd unit.
"""
def __init__(
self,
host: str,
*,
port: int = 22,
identity_file: str = "",
ssh_options: Sequence[str] = (),
sudo: str = "sudo -n",
timeout: float = 120.0,
sleep=time.sleep,
) -> None:
if not host:
raise ProxdomainError("webserver.ssh_host must not be empty")
self.host = host
self.port = port
self.identity_file = identity_file
self.ssh_options = tuple(ssh_options)
self.sudo = sudo.strip()
self.timeout = timeout
self._sleep = sleep
# -- commands -------------------------------------------------------
def run(
self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0
) -> CommandResult:
argv = tuple(argv)
if not argv:
raise ProxdomainError("refusing to run an empty command")
remote = " ".join(shlex.quote(str(part)) for part in argv)
return self._ssh(remote, input_text=input_text, timeout=timeout)
def _ssh(
self, remote_command: str, *, input_text: str | None = None, timeout: float = 120.0
) -> CommandResult:
argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]
if self.port != 22:
argv += ["-p", str(self.port)]
if self.identity_file:
argv += ["-i", self.identity_file]
for option in self.ssh_options:
argv += ["-o", option]
argv += [self.host, remote_command]
try:
completed = subprocess.run(
argv,
input=input_text,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
)
except FileNotFoundError as exc:
raise ProxdomainError("ssh client not found on PATH") from exc
except subprocess.TimeoutExpired as exc:
raise ProxdomainError(
f"ssh to {self.host} timed out after {timeout}s: {remote_command[:200]}"
) from exc
return CommandResult(
argv=tuple(argv),
returncode=completed.returncode,
stdout=completed.stdout or "",
stderr=completed.stderr or "",
)
# -- files ----------------------------------------------------------
def write_text(self, path: str, content: str, mode: int = 0o644) -> bool:
if self.read_text(path) == content:
return False
directory = _posix_dirname(path)
tmp = f"{path}.proxdomain.tmp"
script = " && ".join(
[
self._sudo(f"mkdir -p {shlex.quote(directory)}"),
self._sudo(f"tee {shlex.quote(tmp)} > /dev/null"),
self._sudo(f"chmod {mode:o} {shlex.quote(tmp)}"),
self._sudo(f"mv -f {shlex.quote(tmp)} {shlex.quote(path)}"),
]
)
result = self._ssh(script, input_text=content)
if not result.ok:
raise ProxdomainError(
f"cannot write {path} on {self.host}: {result.output()}"
)
return True
def read_text(self, path: str) -> str | None:
result = self._ssh(self._sudo(f"cat {shlex.quote(path)}"))
if not result.ok:
if "No such file" in result.stderr or "cannot open" in result.stderr:
return None
raise ProxdomainError(f"cannot read {path} on {self.host}: {result.output()}")
return result.stdout
def remove(self, path: str) -> bool:
if not self.exists(path):
return False
result = self._ssh(self._sudo(f"rm -f {shlex.quote(path)}"))
if not result.ok:
raise ProxdomainError(f"cannot remove {path} on {self.host}: {result.output()}")
return True
def exists(self, path: str) -> bool:
result = self._ssh(self._sudo(f"test -e {shlex.quote(path)}"))
return result.ok
def mkdir(self, path: str) -> None:
result = self._ssh(self._sudo(f"mkdir -p {shlex.quote(path)}"))
if not result.ok:
raise ProxdomainError(
f"cannot create directory {path} on {self.host}: {result.output()}"
)
def describe(self) -> str:
return f"ssh://{self.host}"
def _sudo(self, command: str) -> str:
return f"{self.sudo} {command}" if self.sudo else command
def build_runner(config) -> Runner: # config: WebServerConfig
if config.mode == "ssh":
return SSHRunner(
config.ssh_host,
port=config.ssh_port,
identity_file=config.ssh_identity_file,
ssh_options=config.ssh_options,
sudo=config.sudo,
)
return LocalRunner()
def _posix_dirname(path: str) -> str:
trimmed = path.rstrip("/")
if "/" not in trimmed:
return "."
return trimmed.rsplit("/", 1)[0] or "/"
class _suppress_errors:
def __enter__(self) -> None:
return None
def __exit__(self, *exc_info: object) -> bool:
return True
+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}"
+240
View File
@@ -0,0 +1,240 @@
"""Persistent assignment state plus an append-only audit log."""
from __future__ import annotations
import json
import os
import time
from contextlib import contextmanager
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterator
from .errors import ProxdomainError
STATE_VERSION = 1
def utcnow() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
@dataclass
class Assignment:
fqdn: str
vmid: int
node: str
kind: str
name: str = ""
ip: str = ""
port: int = 80
webserver: str = ""
zone_id: str = ""
zone_name: str = ""
record_type: str = ""
record_id: str | None = None
site_file: str = ""
created_at: str = ""
updated_at: str = ""
extra: dict = field(default_factory=dict)
@classmethod
def from_dict(cls, payload: dict) -> "Assignment":
try:
fqdn = str(payload["fqdn"])
vmid = int(payload["vmid"])
node = str(payload["node"])
kind = str(payload["kind"])
except (KeyError, TypeError, ValueError) as exc:
raise ProxdomainError(f"corrupt assignment entry in state file: {exc}") from exc
return cls(
fqdn=fqdn,
vmid=vmid,
node=node,
kind=kind,
name=str(payload.get("name") or ""),
ip=str(payload.get("ip") or ""),
port=int(payload.get("port") or 80),
webserver=str(payload.get("webserver") or ""),
zone_id=str(payload.get("zone_id") or ""),
zone_name=str(payload.get("zone_name") or ""),
record_type=str(payload.get("record_type") or ""),
record_id=(str(payload["record_id"]) if payload.get("record_id") else None),
site_file=str(payload.get("site_file") or ""),
created_at=str(payload.get("created_at") or ""),
updated_at=str(payload.get("updated_at") or ""),
extra=dict(payload.get("extra") or {}),
)
def to_dict(self) -> dict:
return asdict(self)
@property
def has_dns_record(self) -> bool:
return bool(self.record_id and self.zone_id)
class StateStore:
def __init__(
self,
path: str,
*,
audit_path: str | None = None,
lock_timeout: float = 10.0,
) -> None:
self.path = path
self.audit_path = audit_path
self.lock_timeout = lock_timeout
self._items: dict[str, Assignment] = {}
self._loaded = False
# -- persistence ----------------------------------------------------
@property
def memory_only(self) -> bool:
return self.path == ":memory:"
def load(self) -> dict[str, Assignment]:
if self.memory_only:
self._loaded = True
return self._items
file = Path(self.path)
if not file.exists():
self._items = {}
self._loaded = True
return self._items
try:
payload = json.loads(file.read_text(encoding="utf-8") or "{}")
except (OSError, json.JSONDecodeError) as exc:
raise ProxdomainError(
f"cannot read state file {self.path}: {exc}; "
"fix or move it aside before retrying"
) from exc
if not isinstance(payload, dict):
raise ProxdomainError(f"state file {self.path} has an unexpected format")
version = payload.get("version")
if version not in (None, STATE_VERSION):
raise ProxdomainError(
f"state file {self.path} uses version {version}, this build expects {STATE_VERSION}"
)
rows = payload.get("assignments") or {}
if not isinstance(rows, dict):
raise ProxdomainError(f"state file {self.path} has no assignments table")
self._items = {name: Assignment.from_dict(row) for name, row in rows.items()}
self._loaded = True
return self._items
def flush(self) -> None:
if self.memory_only:
return
if not self._loaded:
self.load()
file = Path(self.path)
file.parent.mkdir(parents=True, exist_ok=True)
payload = {
"version": STATE_VERSION,
"updated_at": utcnow(),
"assignments": {
name: item.to_dict() for name, item in sorted(self._items.items())
},
}
tmp = file.with_name(f".{file.name}.tmp")
tmp.write_text(json.dumps(payload, indent=2, sort_keys=False) + "\n", encoding="utf-8")
os.replace(tmp, file)
# -- accessors ------------------------------------------------------
def all(self) -> list[Assignment]:
if not self._loaded:
self.load()
return sorted(self._items.values(), key=lambda item: item.fqdn)
def get(self, fqdn: str) -> Assignment | None:
if not self._loaded:
self.load()
return self._items.get(fqdn.lower())
def find(self, *, fqdn: str | None = None, vmid: int | None = None) -> list[Assignment]:
items = self.all()
if fqdn:
return [item for item in items if item.fqdn == fqdn.lower().strip()]
if vmid is not None:
return [item for item in items if item.vmid == vmid]
return []
def upsert(self, assignment: Assignment) -> Assignment:
if not self._loaded:
self.load()
key = assignment.fqdn.lower()
now = utcnow()
current = self._items.get(key)
if current is not None and not assignment.created_at:
assignment.created_at = current.created_at
if not assignment.created_at:
assignment.created_at = now
assignment.fqdn = key
assignment.updated_at = now
self._items[key] = assignment
return assignment
def remove(self, fqdn: str) -> bool:
if not self._loaded:
self.load()
return self._items.pop(fqdn.lower(), None) is not None
# -- audit ----------------------------------------------------------
def audit(self, event: str, **fields: object) -> None:
if not self.audit_path:
return
path = Path(self.audit_path)
path.parent.mkdir(parents=True, exist_ok=True)
record = {"ts": utcnow(), "event": event, **fields}
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, default=str) + "\n")
# -- locking --------------------------------------------------------
@contextmanager
def locked(self) -> Iterator[None]:
if self.memory_only:
yield
return
path = Path(self.path)
path.parent.mkdir(parents=True, exist_ok=True)
lock_path = path.with_name(path.name + ".lock")
deadline = time.monotonic() + self.lock_timeout
fd: int | None = None
while True:
try:
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.write(fd, str(os.getpid()).encode("ascii", "ignore"))
break
except FileExistsError:
if _is_stale(lock_path, self.lock_timeout):
_try_unlink(lock_path)
continue
if time.monotonic() >= deadline:
raise ProxdomainError(
f"state file is locked by another proxdomain run ({lock_path}); "
"wait for it to finish or delete the lock file if it is stale"
)
time.sleep(0.1)
try:
yield
finally:
if fd is not None:
os.close(fd)
_try_unlink(lock_path)
def _is_stale(lock_path: Path, lock_timeout: float) -> bool:
try:
age = time.time() - lock_path.stat().st_mtime
except OSError:
return False
return age > max(60.0, lock_timeout * 6)
def _try_unlink(path: Path) -> None:
try:
path.unlink()
except OSError:
pass
+462
View File
@@ -0,0 +1,462 @@
"""Reverse-proxy configuration generation and safe activation.
Supports nginx (config file + `nginx -t` + reload), Caddy (snippet + validate +
reload) and Traefik (dynamic file provider, reloaded automatically).
"""
from __future__ import annotations
import posixpath
import re
from dataclasses import dataclass, field
from .config import WebServerConfig
from .errors import ProxdomainError, WebServerError
from .runner import Runner
FQDN_RE = re.compile(
r"^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$"
)
_EXTENSIONS = {"nginx": ".conf", "caddy": ".caddy", "traefik": ".yml"}
@dataclass(frozen=True)
class SiteSpec:
fqdn: str
address: str
port: int
vmid: int
node: str
kind: str # qemu | lxc
webserver: str
tls_mode: str = "none"
cert_dir: str = "/etc/letsencrypt/live"
webroot: str = "/var/www/certbot"
cert_resolver: str = ""
upstream_scheme: str = "http"
@property
def target(self) -> str:
return f"{self.upstream_scheme}://{self.address}:{self.port}"
@property
def certificate(self) -> str:
return posixpath.join(self.cert_dir, self.fqdn, "fullchain.pem")
@property
def private_key(self) -> str:
return posixpath.join(self.cert_dir, self.fqdn, "privkey.pem")
@dataclass
class ApplyResult:
path: str
changed: bool = False
validated: bool = False
reloaded: bool = False
messages: list[str] = field(default_factory=list)
class WebServerManager:
def __init__(self, config: WebServerConfig, runner: Runner) -> None:
self.config = config
self.runner = runner
# -- rendering ------------------------------------------------------
def render(self, spec: SiteSpec) -> str:
if spec.webserver == "nginx":
return render_nginx(spec)
if spec.webserver == "caddy":
return render_caddy(spec)
if spec.webserver == "traefik":
return render_traefik(spec)
raise WebServerError(f"unsupported web server: {spec.webserver!r}")
def site_path(self, fqdn: str) -> str:
if not FQDN_RE.match(fqdn):
raise WebServerError(f"refusing to use {fqdn!r} as a config file name")
extension = _EXTENSIONS.get(self.config.kind)
if extension is None:
raise WebServerError(f"unsupported web server: {self.config.kind!r}")
return f"{self.config.manage_dir}/{fqdn}{extension}"
# -- lifecycle ------------------------------------------------------
def apply(self, spec: SiteSpec, *, dry_run: bool = False) -> ApplyResult:
if spec.webserver != self.config.kind:
raise WebServerError(
f"site spec is for {spec.webserver}, manager is configured for {self.config.kind}"
)
content = self.render(spec)
path = self.site_path(spec.fqdn)
result = ApplyResult(path=path)
if dry_run:
result.changed = self.runner.read_text(path) != content
result.messages.append(
("would write " if result.changed else "would keep ") + path
)
return result
self.runner.mkdir(self.config.manage_dir)
original = self.runner.read_text(path)
bootstrapped = False
if spec.tls_mode == "certbot" and not self.runner.exists(spec.certificate):
try:
self._serve_challenge(spec, path, result)
self._request_certificate(spec, result)
except WebServerError:
if original is None:
self.runner.remove(path)
else:
self.runner.write_text(path, original)
raise
bootstrapped = True
result.changed = self.runner.write_text(path, content) or bootstrapped
if not result.changed:
result.messages.append("config already up to date")
return result
result.messages.append(
("updated " if original is not None else "created ") + path
)
try:
result.validated = self.validate()
except WebServerError as exc:
# Never leave a broken config on disk for the next reload to pick up.
if original is None:
self.runner.remove(path)
else:
self.runner.write_text(path, original)
raise WebServerError(
f"{exc}\nrolled back {path} to its previous content"
) from exc
if self.config.reload_command:
result.reloaded = self._reload()
return result
def remove(self, fqdn: str, *, dry_run: bool = False) -> ApplyResult:
path = self.site_path(fqdn)
result = ApplyResult(path=path)
if not self.runner.exists(path):
result.messages.append("no config file present")
return result
if dry_run:
result.changed = True
result.messages.append(f"would remove {path}")
return result
previous = self.runner.read_text(path)
result.changed = self.runner.remove(path)
result.messages.append(f"removed {path}")
try:
result.validated = self.validate()
except WebServerError as exc:
if previous is not None:
self.runner.write_text(path, previous)
raise WebServerError(
f"{exc}\nrestored {path} after the removal broke validation"
) from exc
if self.config.reload_command:
result.reloaded = self._reload()
return result
def validate(self) -> bool:
if not self.config.test_command:
return False
result = self.runner.run(self.config.test_command)
if not result.ok:
raise WebServerError(
"web server configuration test failed "
f"({' '.join(self.config.test_command)}):\n{result.output()}"
)
return True
def _reload(self) -> bool:
result = self.runner.run(self.config.reload_command)
if not result.ok:
raise WebServerError(
"configuration is valid and written, but reloading the web server "
f"failed ({' '.join(self.config.reload_command)}):\n{result.output()}\n"
"run the reload command manually; the config is already in place"
)
return True
def _serve_challenge(self, spec: SiteSpec, path: str, result: ApplyResult) -> None:
"""Activate an HTTP-only vhost so certbot's webroot plugin can answer."""
self.runner.write_text(path, render_nginx_challenge(spec))
try:
self.validate()
except WebServerError as exc:
raise WebServerError(
f"cannot activate the temporary ACME vhost for {spec.fqdn}:\n{exc}"
) from exc
if self.config.reload_command:
self._reload()
result.messages.append("served the ACME challenge on port 80")
def _request_certificate(self, spec: SiteSpec, result: ApplyResult) -> None:
command = list(self.config.tls.certbot_command) + [
"-d",
spec.fqdn,
"--email",
self.config.tls.email,
]
command.extend(self.config.tls.extra_args)
result.messages.append(f"requesting a certificate for {spec.fqdn}")
completed = self.runner.run(command)
if not completed.ok:
raise WebServerError(
f"certbot failed for {spec.fqdn}:\n{completed.output()}\n"
"the domain must already resolve to this host and port 80 must be "
"reachable from the internet (set the Cloudflare record to grey cloud "
"until the certificate is issued)"
)
result.messages.append(f"issued a certificate for {spec.fqdn}")
# -- one-time bootstrap --------------------------------------------
def bootstrap(self, *, dry_run: bool = False) -> list[tuple[str, str]]:
"""Create the managed directory and the include needed by the web server."""
steps: list[tuple[str, str]] = []
kind = self.config.kind
manage_dir = self.config.manage_dir
if dry_run:
steps.append(("planned", f"create directory {manage_dir}"))
else:
self.runner.mkdir(manage_dir)
steps.append(("ok", f"directory {manage_dir} is ready"))
if kind == "nginx":
steps.extend(self._bootstrap_nginx(manage_dir, dry_run))
elif kind == "caddy":
steps.extend(self._bootstrap_caddy(manage_dir, dry_run))
else:
steps.append(
(
"note",
"Traefik's file provider only watches directories that are already "
"configured in its static config; make sure "
f"{manage_dir} is one of them",
)
)
if self.config.tls.mode == "certbot":
webroot = self.config.tls.webroot
if dry_run:
steps.append(("planned", f"create ACME webroot {webroot}"))
else:
self.runner.mkdir(webroot)
steps.append(("ok", f"ACME webroot {webroot} is ready"))
return steps
def _bootstrap_nginx(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
parent = posixpath.dirname(manage_dir.rstrip("/"))
include_file = f"{manage_dir}.conf"
if posixpath.basename(parent) != "conf.d":
return [
(
"note",
f"{manage_dir} is not inside an nginx conf.d directory; add "
f"'include {manage_dir}/*.conf;' to the http{{}} block manually",
)
]
include_line = f"include {manage_dir}/*.conf;"
if _directory_has_include(self.runner, parent, include_line):
return [("ok", f"nginx already includes {manage_dir}/*.conf")]
content = (
"# Managed by proxdomain: pulls in generated virtual hosts.\n"
f"{include_line}\n"
)
if dry_run:
return [("planned", f"write {include_file} with '{include_line}'")]
self.runner.write_text(include_file, content)
return [
("ok", f"wrote {include_file} with '{include_line}'"),
("next", "run: nginx -t && systemctl reload nginx"),
]
def _bootstrap_caddy(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
caddyfile = "/etc/caddy/Caddyfile"
import_line = f"import {manage_dir}/*.caddy"
current = self.runner.read_text(caddyfile)
if current is None:
return [
(
"note",
f"{caddyfile} not found; add '{import_line}' to your Caddyfile manually",
)
]
if import_line in current:
return [("ok", f"Caddyfile already imports {manage_dir}/*.caddy")]
updated = current.rstrip("\n") + f"\n\n# proxdomain managed sites\n{import_line}\n"
if dry_run:
return [("planned", f"append '{import_line}' to {caddyfile}")]
self.runner.write_text(caddyfile, updated)
return [
("ok", f"appended '{import_line}' to {caddyfile}"),
("next", "run: caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy"),
]
# ---------------------------------------------------------------------------
# renderers
# ---------------------------------------------------------------------------
def render_nginx(spec: SiteSpec) -> str:
header = [
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
"",
]
if spec.tls_mode == "none":
body = [
"server {",
" listen 80;",
" listen [::]:80;",
f" server_name {spec.fqdn};",
"",
_nginx_proxy(spec, indent=" "),
"}",
]
return "\n".join(header + body) + "\n"
body = [
"server {",
" listen 80;",
" listen [::]:80;",
f" server_name {spec.fqdn};",
"",
" location /.well-known/acme-challenge/ {",
f" root {spec.webroot};",
" }",
"",
" location / {",
" return 301 https://$host$request_uri;",
" }",
"}",
"",
"server {",
" listen 443 ssl;",
" listen [::]:443 ssl;",
f" server_name {spec.fqdn};",
"",
f" ssl_certificate {spec.certificate};",
f" ssl_certificate_key {spec.private_key};",
" ssl_protocols TLSv1.2 TLSv1.3;",
" ssl_session_cache shared:SSL:10m;",
" ssl_session_timeout 1h;",
"",
_nginx_proxy(spec, indent=" "),
"}",
]
return "\n".join(header + body) + "\n"
def render_nginx_challenge(spec: SiteSpec) -> str:
"""HTTP-only vhost used while waiting for the first certificate."""
header = [
"# Managed by proxdomain: temporary HTTP vhost used to answer the ACME challenge.",
"# Replaced by the TLS vhost as soon as the certificate exists.",
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
"",
]
body = [
"server {",
" listen 80;",
" listen [::]:80;",
f" server_name {spec.fqdn};",
"",
" location /.well-known/acme-challenge/ {",
f" root {spec.webroot};",
" }",
"",
_nginx_proxy(spec, indent=" "),
"}",
]
return "\n".join(header + body) + "\n"
def _nginx_proxy(spec: SiteSpec, *, indent: str) -> str:
inner = indent + " "
lines = [
f"{indent}location / {{",
f"{inner}proxy_pass {spec.target};",
f"{inner}proxy_http_version 1.1;",
f"{inner}proxy_set_header Host $host;",
f"{inner}proxy_set_header X-Real-IP $remote_addr;",
f"{inner}proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
f"{inner}proxy_set_header X-Forwarded-Proto $scheme;",
# $http_connection forwards "Upgrade" for WebSocket and "keep-alive" otherwise,
# so no shared map{} entry is required in the http{} block.
f"{inner}proxy_set_header Upgrade $http_upgrade;",
f"{inner}proxy_set_header Connection $http_connection;",
f"{inner}proxy_read_timeout 3600s;",
f"{indent}}}",
]
return "\n".join(lines)
def render_caddy(spec: SiteSpec) -> str:
lines = [
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
"",
f"{spec.fqdn} {{",
"\tencode gzip",
]
if spec.tls_mode == "files":
lines.append(f"\ttls {spec.certificate} {spec.private_key}")
lines.append(f"\treverse_proxy {spec.target}")
lines.append("}")
return "\n".join(lines) + "\n"
def render_traefik(spec: SiteSpec) -> str:
key = "proxdomain-" + re.sub(r"[^a-z0-9]+", "-", spec.fqdn).strip("-")
lines = [
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
"http:",
" routers:",
f" {key}:",
" entryPoints:",
" - websecure",
f" rule: \"Host(`{spec.fqdn}`)\"",
f" service: {key}",
]
if spec.cert_resolver:
lines += [" tls:", f" certResolver: {spec.cert_resolver}"]
else:
lines += [" tls: {}"]
lines += [
" services:",
f" {key}:",
" loadBalancer:",
" servers:",
f" - url: \"{spec.target}\"",
]
return "\n".join(lines) + "\n"
def _directory_has_include(runner: Runner, directory: str, include_line: str) -> bool:
"""Check whether any *.conf directly in `directory` already contains the include."""
if not runner.exists(directory):
return False
try:
result = runner.run(
[
"grep",
"-RFl",
"--include=*.conf",
include_line,
directory,
]
)
except ProxdomainError:
return False
return result.ok