add --port flag
This commit is contained in:
1 parent
2d564a1546
commit
9a818fce9f
10 files changed
+294
-14
No files matched your search
@@ -183,7 +183,6 @@ proxdomain assign --vmid 101
|
||||
|
||||
# pick the name and backend port explicitly
|
||||
proxdomain assign --name "web01" --subdomain app --port 8080
|
||||
|
||||
# a full name under another zone the token can read
|
||||
proxdomain assign --vmid 101 --subdomain app.example.net
|
||||
|
||||
@@ -211,6 +210,28 @@ scripting around exit codes:
|
||||
* `1` — the action failed (DNS, web server, or lookup)
|
||||
* `2` — usage or configuration error
|
||||
|
||||
### Backend port
|
||||
|
||||
A guest is proxied to `http://<guest IP>:<port>`. The port is resolved in this
|
||||
order, and `assign` prints which source won:
|
||||
|
||||
1. `--port` on the command line
|
||||
2. `proxdomain-port=8080` in the guest's **Notes** field (Options → Notes), or a
|
||||
`proxdomain-port-8080` tag — so a VM/CT carries its own port and automatic
|
||||
assignment picks it up
|
||||
3. the port already stored for that domain — re-running `assign` never resets a
|
||||
custom port back to the default
|
||||
4. `general.default_port`
|
||||
|
||||
```bash
|
||||
proxdomain assign --vmid 101 --port 8080 # one-off, stored in state.json
|
||||
proxdomain sync # re-reads Notes/tags, rewrites vhosts
|
||||
```
|
||||
|
||||
Changing the port later is the same command, or edit the Notes field and run
|
||||
`sync`; the vhost and the Cloudflare record do not need to be recreated. Ports
|
||||
outside 1–65535 are refused before any file or DNS change.
|
||||
|
||||
## Automatic assignment for new guests
|
||||
|
||||
Tag a guest `proxdomain` in the Proxmox UI (or set `watch.tag`), then:
|
||||
@@ -337,6 +358,7 @@ records every config/DNS/remove action with a UTC timestamp.
|
||||
| Symptom | Cause / fix |
|
||||
| --- | --- |
|
||||
| `no usable IP address found` | Install and start `qemu-guest-agent` in the VM, set a static `ip=` in the guest/cloud-init config, or pass `--ip`. |
|
||||
| Wrong port in the vhost | Check the `port` line of `assign`: `--port`, then the guest Notes/tag declaration, then the stored value, then `general.default_port`. |
|
||||
| `401/403` from Proxmox | Token ACL or `--privsep`. Grant `VM.Audit VM.Monitor` on `/` (or at least `/vms`). |
|
||||
| `token_secret_env ... must be the name of an environment variable` | The secret was pasted into the setting that should hold the variable name. Set `token_secret_env = "PROXDOMAIN_PVE_TOKEN"` and export the secret, or use `token_secret_file` / `token_secret`. |
|
||||
| Secret reported as empty although it was set inline | `VAR=value && proxdomain ...` sets a variable and then runs an unrelated command. Use `export VAR=value` first, or `VAR=value proxdomain ...`. |
|
||||
|
||||
+3
-1
@@ -9,7 +9,9 @@ base_domain = "example.com"
|
||||
# Placeholders: {hostname} {vmid} {node} {kind} {base_domain}
|
||||
# Keep {hostname} or {vmid} so every guest gets a unique name.
|
||||
domain_template = "{hostname}.{base_domain}"
|
||||
# Backend port used when `assign` is called without --port.
|
||||
# Backend port used when neither --port nor a guest declaration (Notes field
|
||||
# `proxdomain-port=8080`, or tag `proxdomain-port-8080`) nor a stored
|
||||
# assignment provides one.
|
||||
default_port = 80
|
||||
|
||||
[dns]
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "proxdomain"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
description = "Assign public domains to Proxmox VMs/containers via Cloudflare DNS and a reverse proxy on the PVE host"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
+2
-1
@@ -203,6 +203,7 @@ def add_proxmox_routes(
|
||||
guests: list[dict] | None = None,
|
||||
agent_ips: list[str] | None = None,
|
||||
node: str = "pve",
|
||||
guest_config: dict | None = None,
|
||||
) -> None:
|
||||
transport.add(
|
||||
"GET",
|
||||
@@ -230,7 +231,7 @@ def add_proxmox_routes(
|
||||
transport.add(
|
||||
"GET",
|
||||
f"/api2/json/nodes/{node}/qemu/101/config",
|
||||
pve({}),
|
||||
pve(dict(guest_config or {})),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -77,6 +77,75 @@ class GuestParsingTests(unittest.TestCase):
|
||||
self.assertEqual(_split_tags(None), ())
|
||||
|
||||
|
||||
class PortDeclarationTests(unittest.TestCase):
|
||||
"""A VM/CT can declare its own backend port."""
|
||||
|
||||
def _guest(self, tags: tuple = ()) -> Guest:
|
||||
return Guest(
|
||||
vmid=101, node="pve", name="web01", kind="qemu", status="running", tags=tags
|
||||
)
|
||||
|
||||
def _client(self, *, description: str = "", tags: tuple = ()) -> ProxmoxClient:
|
||||
transport = FakeTransport()
|
||||
add_proxmox_routes(
|
||||
transport,
|
||||
guests=[
|
||||
{
|
||||
"vmid": 101,
|
||||
"node": "pve",
|
||||
"type": "qemu",
|
||||
"name": "web01",
|
||||
"status": "running",
|
||||
"tags": ",".join(tags),
|
||||
}
|
||||
],
|
||||
guest_config={"description": description},
|
||||
)
|
||||
return client(transport)
|
||||
|
||||
def test_port_from_notes(self) -> None:
|
||||
proxmox = self._client(description="proxdomain-port=8080\n")
|
||||
self.assertEqual(proxmox.guest_port(self._guest()), (8080, "guest notes"))
|
||||
|
||||
def test_port_in_a_sentence(self) -> None:
|
||||
proxmox = self._client(description="App server. proxdomain-port: 3000 for the UI")
|
||||
self.assertEqual(proxmox.guest_port(self._guest())[0], 3000)
|
||||
|
||||
def test_port_from_tag(self) -> None:
|
||||
proxmox = self._client(tags=("proxdomain", "proxdomain-port-8096"))
|
||||
self.assertEqual(proxmox.guest_port(self._guest(tags=("proxdomain", "proxdomain-port-8096"))), (8096, "guest tag"))
|
||||
|
||||
def test_notes_win_over_tag(self) -> None:
|
||||
proxmox = self._client(description="proxdomain-port=8080", tags=("proxdomain-port-9000",))
|
||||
self.assertEqual(
|
||||
proxmox.guest_port(self._guest(tags=("proxdomain-port-9000",)))[0], 8080
|
||||
)
|
||||
|
||||
def test_no_declaration(self) -> None:
|
||||
proxmox = self._client(description="just a web server")
|
||||
self.assertEqual(proxmox.guest_port(self._guest()), (None, ""))
|
||||
|
||||
def test_unrelated_tag_is_ignored(self) -> None:
|
||||
proxmox = self._client(tags=("proxdomain", "prod"))
|
||||
self.assertEqual(proxmox.guest_port(self._guest(tags=("proxdomain", "prod"))), (None, ""))
|
||||
|
||||
def test_out_of_range_port_is_rejected(self) -> None:
|
||||
proxmox = self._client(description="proxdomain-port=70000")
|
||||
with self.assertRaises(ProxdomainError) as ctx:
|
||||
proxmox.guest_port(self._guest())
|
||||
self.assertIn("not a valid TCP port", str(ctx.exception))
|
||||
|
||||
def test_config_read_failure_means_no_declaration(self) -> None:
|
||||
transport = FakeTransport()
|
||||
transport.add(
|
||||
"GET",
|
||||
"/api2/json/nodes/pve/qemu/101/config",
|
||||
{"errors": [{"message": "unavailable"}]},
|
||||
status=500,
|
||||
)
|
||||
self.assertEqual(client(transport).guest_port(self._guest()), (None, ""))
|
||||
|
||||
|
||||
class AddressTests(unittest.TestCase):
|
||||
def _guest(self, kind: str = "qemu", vmid: int = 101) -> Guest:
|
||||
return Guest(vmid=vmid, node="pve", name="web01", kind=kind, status="running")
|
||||
|
||||
+101
-1
@@ -25,6 +25,7 @@ def build(
|
||||
dns: dict | None = None,
|
||||
resolver_factory=None,
|
||||
files: dict[str, str] | None = None,
|
||||
guest_config: dict | None = None,
|
||||
**webserver,
|
||||
):
|
||||
guests = guests if guests is not None else [
|
||||
@@ -39,7 +40,9 @@ def build(
|
||||
]
|
||||
agent_ips = agent_ips if agent_ips is not None else ["127.0.0.1", "10.0.0.5"]
|
||||
transport = FakeTransport()
|
||||
add_proxmox_routes(transport, guests=guests, agent_ips=agent_ips)
|
||||
add_proxmox_routes(
|
||||
transport, guests=guests, agent_ips=agent_ips, guest_config=guest_config
|
||||
)
|
||||
stored = list(records or [])
|
||||
|
||||
transport.add("GET", "/client/v4/zones", cf([{"id": ZONE, "name": "example.com"}]))
|
||||
@@ -388,6 +391,103 @@ class DiscoveryTests(unittest.TestCase):
|
||||
self.assertEqual(runner.files, {})
|
||||
|
||||
|
||||
class PortTests(unittest.TestCase):
|
||||
"""Backend port: flag, guest declaration, stored value, default."""
|
||||
|
||||
SITE = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf"
|
||||
|
||||
def test_default_port(self) -> None:
|
||||
service, _, runner, _ = build()
|
||||
report = service.assign(vmid=101)
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:80;", runner.files[self.SITE])
|
||||
step = next(s for s in report.steps if s.name == "port")
|
||||
self.assertIn("general.default_port", step.detail)
|
||||
|
||||
def test_command_line_port(self) -> None:
|
||||
service, _, runner, _ = build()
|
||||
report = service.assign(vmid=101, port=8443)
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:8443;", runner.files[self.SITE])
|
||||
self.assertEqual(report.assignment.port, 8443)
|
||||
step = next(s for s in report.steps if s.name == "port")
|
||||
self.assertIn("command line", step.detail)
|
||||
|
||||
def test_guest_notes_port_is_used(self) -> None:
|
||||
service, _, runner, _ = build(guest_config={"description": "proxdomain-port=8080"})
|
||||
report = service.assign(vmid=101)
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:8080;", runner.files[self.SITE])
|
||||
self.assertIn("guest notes", next(s for s in report.steps if s.name == "port").detail)
|
||||
|
||||
def test_flag_beats_guest_notes(self) -> None:
|
||||
service, _, runner, _ = build(guest_config={"description": "proxdomain-port=8080"})
|
||||
report = service.assign(vmid=101, port=9000)
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:9000;", runner.files[self.SITE])
|
||||
|
||||
def test_guest_tag_port_is_used(self) -> None:
|
||||
service, _, runner, _ = build(
|
||||
guests=[
|
||||
{
|
||||
"vmid": 101,
|
||||
"node": "pve",
|
||||
"type": "qemu",
|
||||
"name": "web01",
|
||||
"status": "running",
|
||||
"tags": "proxdomain,proxdomain-port-8096",
|
||||
}
|
||||
]
|
||||
)
|
||||
report = service.assign(vmid=101)
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:8096;", runner.files[self.SITE])
|
||||
|
||||
def test_rerun_keeps_the_custom_port(self) -> None:
|
||||
"""Regression: a second assign without --port used to reset to 80."""
|
||||
service, _, runner, _ = build()
|
||||
self.assertTrue(service.assign(vmid=101, port=8080).ok)
|
||||
again = service.assign(vmid=101)
|
||||
self.assertTrue(again.ok, again.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:8080;", runner.files[self.SITE])
|
||||
self.assertEqual(service.state.get("web01.example.com").port, 8080)
|
||||
self.assertIn("previous assignment", next(s for s in again.steps if s.name == "port").detail)
|
||||
|
||||
def test_sync_adopts_a_new_port_from_the_guest(self) -> None:
|
||||
service, _, runner, _ = build()
|
||||
self.assertTrue(service.assign(vmid=101).ok)
|
||||
# The guest now declares a port in its Notes field.
|
||||
routes = service.proxmox.http.transport.routes
|
||||
config_route = next(r for r in routes if r.path.endswith("/101/config"))
|
||||
config_route.handler = {"data": {"description": "proxdomain-port=3000"}}
|
||||
report = service.sync()
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:3000;", runner.files[self.SITE])
|
||||
self.assertEqual(service.state.get("web01.example.com").port, 3000)
|
||||
|
||||
def test_sync_keeps_the_stored_port_without_declaration(self) -> None:
|
||||
service, _, runner, _ = build()
|
||||
self.assertTrue(service.assign(vmid=101, port=8080).ok)
|
||||
report = service.sync()
|
||||
self.assertTrue(report.ok, report.to_dict())
|
||||
self.assertIn("proxy_pass http://10.0.0.5:8080;", runner.files[self.SITE])
|
||||
|
||||
def test_invalid_flag_is_rejected_before_writing(self) -> None:
|
||||
service, _, runner, _ = build()
|
||||
report = service.assign(vmid=101, port=70000)
|
||||
self.assertFalse(report.ok)
|
||||
self.assertEqual(report.steps[-1].name, "port")
|
||||
self.assertIn("not a valid TCP port", report.steps[-1].detail)
|
||||
self.assertEqual(runner.files, {})
|
||||
|
||||
def test_invalid_guest_port_is_rejected_before_writing(self) -> None:
|
||||
service, _, runner, _ = build(guest_config={"description": "proxdomain-port=0"})
|
||||
report = service.assign(vmid=101)
|
||||
self.assertFalse(report.ok)
|
||||
self.assertIn("Notes field", " ".join(s.detail for s in report.steps))
|
||||
self.assertEqual(runner.files, {})
|
||||
|
||||
|
||||
class TlsTests(unittest.TestCase):
|
||||
"""Automatic Let's Encrypt certificates."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user