2026-11-20 15:16:41 +02:00
|
|
|
"""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 = ""
|
2026-11-22 22:44:47 +02:00
|
|
|
dns_ip: str = ""
|
2026-11-20 15:16:41 +02:00
|
|
|
port: int = 80
|
2026-11-22 22:44:47 +02:00
|
|
|
tls: str = "none"
|
2026-11-20 15:16:41 +02:00
|
|
|
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 ""),
|
2026-11-22 22:44:47 +02:00
|
|
|
dns_ip=str(payload.get("dns_ip") or ""),
|
2026-11-20 15:16:41 +02:00
|
|
|
port=int(payload.get("port") or 80),
|
2026-11-22 22:44:47 +02:00
|
|
|
tls=str(payload.get("tls") or "none"),
|
2026-11-20 15:16:41 +02:00
|
|
|
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
|