You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
220 lines
8.4 KiB
Python
220 lines
8.4 KiB
Python
"""Bounded observation of a VM's private network role.
|
|
|
|
This module deliberately only reads the domain definition. It does not run
|
|
``ip``, ``wg`` or ``nft`` commands and it never treats the host Fabric status
|
|
as proof that a tenant NIC is connected. The PHP control plane supplies the
|
|
VPC/member revision when it evaluates this observation at an operation
|
|
commit boundary.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import re
|
|
import time
|
|
import xml.etree.ElementTree as ET
|
|
from typing import Any
|
|
|
|
from virsh_panel.network_roles import (
|
|
PRIVATE_INTERFACE_ROLE,
|
|
interface_role,
|
|
private_interface_has_public_filter,
|
|
select_private_interface,
|
|
select_public_interface,
|
|
)
|
|
|
|
|
|
PRIVATE_STATE_VERSION = 1
|
|
PANEL_NS = "urn:virsh-panel:1"
|
|
_MAC_RE = re.compile(r"[0-9a-f]{2}(?::[0-9a-f]{2}){5}\Z")
|
|
_DIGEST_RE = re.compile(r"[0-9a-f]{64}\Z")
|
|
|
|
|
|
def _source(interface: ET.Element) -> tuple[str | None, str | None]:
|
|
source = interface.find("source")
|
|
if source is None:
|
|
return None, None
|
|
for kind in ("bridge", "network", "dev", "name", "path"):
|
|
value = source.get(kind)
|
|
if isinstance(value, str) and value.strip():
|
|
return kind, value.strip()
|
|
return None, None
|
|
|
|
|
|
def _managed_metadata(root: ET.Element) -> ET.Element | None:
|
|
# Only the panel-owned namespace is trusted for the optional identity
|
|
# metadata. Guest/user XML must never become a host-state assertion.
|
|
for node in root.findall("./metadata"):
|
|
for child in list(node):
|
|
if child.tag == f"{{{PANEL_NS}}}managed":
|
|
return child
|
|
return None
|
|
|
|
|
|
def _private_ip(root: ET.Element, managed: ET.Element | None) -> str | None:
|
|
values: list[str | None] = []
|
|
if managed is not None:
|
|
values.extend((managed.get("private-ip-cidr"), managed.get("private_ip_cidr")))
|
|
for node in root.findall("./metadata/*"):
|
|
if node.tag.rsplit("}", 1)[-1] in {"private-network", "private_state"}:
|
|
values.extend((node.get("ip-cidr"), node.get("private-ip-cidr"), node.get("cidr")))
|
|
for value in values:
|
|
if not isinstance(value, str) or not value:
|
|
continue
|
|
try:
|
|
address = ipaddress.ip_interface(value)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(address, ipaddress.IPv4Interface) and address.network.prefixlen == 32:
|
|
return str(address)
|
|
return None
|
|
|
|
|
|
def _revision(managed: ET.Element | None) -> int:
|
|
if managed is None:
|
|
return 0
|
|
raw = managed.get("private-network-revision") or managed.get("private_revision")
|
|
try:
|
|
value = int(raw or 0)
|
|
except (TypeError, ValueError):
|
|
return 0
|
|
return value if 0 <= value <= (1 << 63) - 1 else 0
|
|
|
|
|
|
def _digest(managed: ET.Element | None) -> str | None:
|
|
if managed is None:
|
|
return None
|
|
value = managed.get("private-network-digest") or managed.get("private_digest")
|
|
return value.lower() if isinstance(value, str) and _DIGEST_RE.fullmatch(value.lower()) else None
|
|
|
|
|
|
def _managed_id(managed: ET.Element | None, *keys: str) -> str | None:
|
|
"""Read one bounded panel-owned identity field from domain metadata."""
|
|
if managed is None:
|
|
return None
|
|
for key in keys:
|
|
value = managed.get(key)
|
|
if isinstance(value, str) and 1 <= len(value) <= 128:
|
|
# IDs are compared by the control plane; reject control characters
|
|
# here so an edited XML document cannot inject a log/header value.
|
|
if all(ord(char) >= 32 and ord(char) != 127 for char in value):
|
|
return value
|
|
return None
|
|
|
|
|
|
def observe_private_state(
|
|
root: ET.Element,
|
|
*,
|
|
vm_uuid: str | None = None,
|
|
host_verified: bool = False,
|
|
observed_at: int | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Return a stable, credential-free private NIC observation.
|
|
|
|
``disabled/confirmed`` means that the domain has no private role and no
|
|
VPC expectation was supplied to this read. A caller that has a VPC
|
|
expectation must independently change that result to ``degraded`` or
|
|
``uncertain`` until the expected member/revision/digest is verified.
|
|
"""
|
|
now = int(time.time()) if observed_at is None else int(observed_at)
|
|
base: dict[str, Any] = {
|
|
"version": PRIVATE_STATE_VERSION,
|
|
"required": False,
|
|
"vm_uuid": vm_uuid,
|
|
"vpc_id": None,
|
|
"member_id": None,
|
|
"interface": None,
|
|
"state": "disabled",
|
|
"desired_revision": 0,
|
|
"observed_revision": 0,
|
|
"desired_digest": None,
|
|
"observed_digest": None,
|
|
"readback": "confirmed",
|
|
"link_state": "absent",
|
|
"private_ip_cidr": None,
|
|
"private_mac": None,
|
|
"reason_code": None,
|
|
"observed_at": now,
|
|
}
|
|
interfaces = list(root.findall("./devices/interface"))
|
|
# Validate the complete role map even when no private NIC is present. A
|
|
# second unlabelled/ambiguous NIC must not disappear behind a successful
|
|
# public-only observation and later become an accidental data-plane path.
|
|
try:
|
|
public = select_public_interface(interfaces)
|
|
private = select_private_interface(interfaces)
|
|
except (TypeError, ValueError):
|
|
base.update(state="degraded", readback="mismatch",
|
|
reason_code="private_interface_role_invalid")
|
|
return base
|
|
if private is None:
|
|
return base
|
|
|
|
base["interface"] = PRIVATE_INTERFACE_ROLE
|
|
managed = _managed_metadata(root)
|
|
base["vpc_id"] = _managed_id(managed, "private-vpc-id", "private_vpc_id")
|
|
base["member_id"] = _managed_id(
|
|
managed, "private-member-id", "private_member_id")
|
|
base["private_ip_cidr"] = _private_ip(root, managed)
|
|
base["observed_revision"] = _revision(managed)
|
|
base["observed_digest"] = _digest(managed)
|
|
mac_node = private.find("mac")
|
|
mac = mac_node.get("address", "").lower() if mac_node is not None else ""
|
|
base["private_mac"] = mac or None
|
|
link = private.find("link")
|
|
link_state = link.get("state", "up").lower() if link is not None else "up"
|
|
base["link_state"] = link_state if link_state in {"up", "down"} else "absent"
|
|
|
|
private_kind, private_source = _source(private)
|
|
public_kind, public_source = _source(public) if public is not None else (None, None)
|
|
# The tenant data plane is an independent host bridge. A libvirt
|
|
# ``network``/``direct`` source does not let this layer prove which host
|
|
# bridge it resolves to, so accepting it would make a public bridge reuse
|
|
# indistinguishable from a private network. The future data-plane apply
|
|
# path may add an explicit verification marker to the managed metadata.
|
|
if (private_kind != "bridge" or private_source is None
|
|
or private_kind == public_kind and private_source == public_source):
|
|
base.update(state="degraded", readback="mismatch",
|
|
reason_code="private_source_invalid")
|
|
return base
|
|
if private_interface_has_public_filter(private):
|
|
base.update(state="degraded", readback="mismatch",
|
|
reason_code="private_filter_present")
|
|
return base
|
|
if not _MAC_RE.fullmatch(mac):
|
|
base.update(state="degraded", readback="mismatch",
|
|
reason_code="private_mac_missing")
|
|
return base
|
|
if base["private_ip_cidr"] is None:
|
|
base.update(state="degraded", readback="missing",
|
|
reason_code="private_ip_missing")
|
|
return base
|
|
# XML metadata is tenant/domain data and can be edited independently of
|
|
# the host. Only a future host adapter probe may set ``host_verified``;
|
|
# never use a managed-XML marker as proof of bridge/WireGuard/nft state.
|
|
if not host_verified:
|
|
base.update(state="degraded", readback="missing",
|
|
reason_code="private_source_unverified")
|
|
return base
|
|
if link_state not in {"up", "down"}:
|
|
base.update(state="degraded", readback="mismatch",
|
|
reason_code="private_link_state_invalid")
|
|
return base
|
|
base["state"] = "suspended" if link_state == "down" else "active"
|
|
return base
|
|
|
|
|
|
def observe_private_state_from_xml(
|
|
xml: str | bytes,
|
|
*,
|
|
vm_uuid: str | None = None,
|
|
host_verified: bool = False,
|
|
observed_at: int | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Parse a libvirt XML document and return :func:`observe_private_state`."""
|
|
root = ET.fromstring(xml)
|
|
return observe_private_state(
|
|
root, vm_uuid=vm_uuid, host_verified=host_verified,
|
|
observed_at=observed_at,
|
|
)
|