add --port flag

This commit is contained in:
leo committed 2026-11-23 00:05:50 +02:00
1 parent 2d564a1546
commit 9a818fce9f
10 files changed
+294 -14

No files matched your search

+1 -1
View File
@@ -7,5 +7,5 @@ reverse-proxy config for nginx, Caddy or Traefik.
from __future__ import annotations
__version__ = "0.3.0"
__version__ = "0.4.0"
__all__ = ["__version__"]
+6 -1
View File
@@ -64,7 +64,12 @@ def build_parser() -> argparse.ArgumentParser:
"--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(
"--port",
type=int,
help="backend port on the guest (default: port declared by the guest, else "
"general.default_port)",
)
assign.add_argument("--ip", help="override the guest IP used as the proxy target")
assign.add_argument(
"--address",
+41 -2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import ipaddress
import re
from dataclasses import dataclass, field
from typing import Iterable
@@ -10,6 +11,11 @@ from .config import ProxmoxConfig
from .errors import ApiError, ProxdomainError
from .http import JsonClient, Transport, UrllibTransport
# `proxdomain-port=8080` on its own or inside a sentence, in the guest Notes field.
PORT_NOTE_RE = re.compile(r"proxdomain-port\s*[:=]\s*(\d{1,5})", re.IGNORECASE)
# Equivalent shorthand as a Proxmox tag: `proxdomain-port-8080`.
PORT_TAG_RE = re.compile(r"^proxdomain-port-(\d{1,5})$", re.IGNORECASE)
@dataclass(frozen=True)
class Guest:
@@ -110,6 +116,25 @@ class ProxmoxClient:
result.append(guest)
return result
# -- per-guest settings ---------------------------------------------
def guest_port(self, guest: Guest) -> tuple[int | None, str]:
"""Port the guest declares for itself, plus where it was found.
Checked in this order: the Notes field (`proxdomain-port=8080`), then a
tag (`proxdomain-port-8080`). Returns (None, "") when the guest says
nothing, so the caller can fall back to its own default.
"""
notes = self._config_document(guest).get("description")
if isinstance(notes, str):
match = PORT_NOTE_RE.search(notes)
if match:
return _checked_port(match.group(1), guest, "its Notes field"), "guest notes"
for tag in guest.tags:
match = PORT_TAG_RE.match(tag.strip())
if match:
return _checked_port(match.group(1), guest, f"the tag {tag!r}"), "guest tag"
return None, ""
# -- addressing -----------------------------------------------------
def guest_ip(self, guest: Guest) -> str | None:
want = self.config.ip_preference
@@ -188,17 +213,21 @@ class ProxmoxClient:
found.append(value)
return found
def _config_ips(self, guest: Guest) -> list[str]:
def _config_document(self, guest: Guest) -> dict:
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 []
return {}
config = data if isinstance(data, dict) else {}
if "data" in config and isinstance(config["data"], dict):
config = config["data"]
return config
def _config_ips(self, guest: Guest) -> list[str]:
config = self._config_document(guest)
found: list[str] = []
for key, value in sorted(config.items()):
if not (key.startswith("net") or key.startswith("ipconfig")):
@@ -251,6 +280,16 @@ def _split_tags(value: object) -> tuple[str, ...]:
return tuple(tag.strip() for tag in normalized.split(";") if tag.strip())
def _checked_port(raw: str, guest: Guest, where: str) -> int:
port = int(raw)
if not 1 <= port <= 65535:
raise ProxdomainError(
f"{guest.label} declares the port {port} in {where}, which is not a "
"valid TCP port (1-65535)"
)
return port
def _version(address: str) -> int:
try:
return ipaddress.ip_address(address).version
+47 -5
View File
@@ -162,10 +162,6 @@ class DomainService:
report.add("dns-address", "ok", f"{published.address} ({published.source})")
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(
@@ -174,6 +170,12 @@ class DomainService:
"pass --force to take it over",
)
try:
target_port, port_source = self._resolve_port(guest, port, existing)
except ProxdomainError as exc:
return report.fail("port", str(exc))
report.add("port", "ok", f"{target_port} ({port_source})")
zone = self._find_zone(report, fqdn, dry_run=dry_run)
if zone is None and not dry_run:
return report
@@ -455,7 +457,19 @@ class DomainService:
f"{assignment.fqdn}: {assignment.dns_ip or '-'} -> "
f"{published.address} ({published.source})",
)
spec = self._site_spec(guest, assignment.fqdn, guest_address, assignment.port)
try:
declared_port, port_source = self.proxmox.guest_port(guest)
except ProxdomainError as exc:
report.fail("port", f"{assignment.fqdn}: {exc}")
continue
target_port = declared_port or assignment.port
if target_port != assignment.port:
report.add(
"port",
"planned" if dry_run else "changed",
f"{assignment.fqdn}: {assignment.port} -> {target_port} ({port_source})",
)
spec = self._site_spec(guest, assignment.fqdn, guest_address, target_port)
try:
result = self.webserver.apply(spec, dry_run=dry_run)
except ProxdomainError as exc:
@@ -463,6 +477,7 @@ class DomainService:
continue
if result.changed:
changed += 1
assignment.port = target_port
report.add(
"web-config",
"planned" if dry_run else ("changed" if result.changed else "ok"),
@@ -730,6 +745,25 @@ class DomainService:
raise ProxdomainError(f"{fqdn!r} is not a valid DNS name")
return fqdn
def _resolve_port(
self,
guest: Guest,
port: int | None,
existing: Assignment | None,
) -> tuple[int, str]:
"""Pick the backend port: explicit flag, guest declaration, stored, default."""
if port is not None:
return _valid_port(int(port), "--port"), "command line"
declared, source = self.proxmox.guest_port(guest)
if declared is not None:
return declared, source
if existing is not None and existing.port:
# Re-running assign must not silently reset a custom port.
return _valid_port(existing.port, "the stored assignment"), "previous assignment"
return _valid_port(self.config.general.default_port, "general.default_port"), (
"general.default_port"
)
def _dns_before_config(self, spec: SiteSpec) -> bool:
"""True when ACME needs the public record in place before the vhost."""
webserver = self.config.webserver
@@ -848,6 +882,14 @@ class DomainService:
self.state.flush()
def _valid_port(port: int, source: str) -> int:
if not 1 <= port <= 65535:
raise ProxdomainError(
f"{port} is not a valid TCP port (1-65535); it came from {source}"
)
return port
def sanitize_hostname(name: str, vmid: int) -> str:
value = _HOSTNAME_STRIP.sub("-", (name or "").strip().lower()).strip("-")
value = _DASHES.sub("-", value)