feat: implement VPC private dataplane

venix
admin 2 months ago
parent aabd8b8acb
commit d8cf44b2ad

@ -0,0 +1,49 @@
# Fabric 宿主机验收矩阵
这份矩阵用于真实宿主机验收。当前代码已经完成脚本语法、能力解析、回读和事务
契约测试;本仓库环境没有 AlmaLinux 10 或 Debian 13 宿主机,因此下列命令不能在
本地模拟为通过。
## AlmaLinux 10
确认 NetworkManager 是唯一网络管理器,`nmcli connection show` 能看到
`virt-cloud-wg-fabric0`,native `nftables.service` 为 active/enabled,firewalld
为 inactive/disabled。应用两台同地区宿主机后,记录 `wg show wg-fabric0`、
`ip -4 route show table all`、`nft list table inet virt_cloud_wg_fabric`、默认路由
和管理地址;这些证据中不得出现 `br0` 或管理接口被修改。
依次执行:
1. `systemctl reload nftables`,确认 include 重新加载 table,Fabric observe 在
repair timer 一个周期内仍为 active。
2. `systemctl restart NetworkManager`,确认 keyfile、peer、精确 `/32` 路由和
underlay endpoint 路由恢复,默认路由不漂移。
3. 重启宿主机,确认 `nftables.service`、NetworkManager、Fabric helper 和 timer
的 enabled/active 状态以及跨宿主机握手。
## Debian 13
确认 `/etc/network/interfaces` 或 `interfaces.d` 由经典 ifupdown 管理,探测到的
`ifup`、`ifdown`、`ifquery` 路径与面板记录一致,systemd-networkd 和 NetworkManager
没有 active/enabled/configured 接管证据。验证 `ifup --force wg-fabric0` 只操作
`wg-fabric0`,不会触碰 `br0`、默认路由或管理地址。
依次执行:
1. `systemctl reload nftables`,确认 persistent include 和 table 回读;不要用
`ifup` 代替 nftables reload。
2. `systemctl restart networking`,确认 ifupdown fragment、peer、地址和路由回读。
3. 重启宿主机,确认 `ifupdown`、nftables、Fabric repair timer 和跨宿主机握手。
## 失败回滚和安全边界
在隔离环境中分别让 `nft`、`wg`、`ip route`、`nmcli/ifup`、`systemctl enable`
和 `systemctl start timer` 返回失败。每次都应看到 apply 失败并保持
`uncertain/degraded`,且原 panel-owned peer、地址、路由、keyfile/fragment、nft
table/include 和 systemd 状态恢复;无法恢复时不得报告 active。预先放置一个
非 panel-owned 的同名 nft table、宽前缀路由(例如 `/16`、`/24`)、策略表路由或
同名接口时,apply 必须拒绝并保留原状态。
最后从另一台宿主机核验 WireGuard underlay UDP 监听端口、NAT、MTU、SELinux 和
公网防火墙。Fabric 的 native nft table 不负责放行 underlay UDP;如果公网防火墙
没有独立的持久规则,不能把本地 `wg-fabric0` active 视为跨宿主机可用。

@ -100,10 +100,26 @@ ICMP,其余来自或发往 `wg-fabric0` 的主机服务流量丢弃;systemd
重新核对宿主机能力快照和 revision。
当前阶段没有 Fabric 删除/撤销 API;成员变更必须由后续迁移流程以新 revision
显式处理。underlay 端点的公网防火墙、NAT、MTU、SELinux/firewalld、管理器重载
后的持久性,以及 AlmaLinux 的 NetworkManager、Debian 的 ifupdown 在真实重启后
的恢复,仍属于真实宿主机验收项。Fabric 只使用独立的 `wg-fabric0`;管理器适配
不得修改 `br0`、默认路由或宿主机管理接口。
显式处理。Fabric 下发现在会在每台宿主机操作前重新执行固定能力探测,并在远端
`/run/virt-cloud/wg-fabric0.lock` 内串行化 identity、apply、observe 和管理器 hook。
apply 会先保存 panel-owned 配置、WireGuard peer/地址/路由、systemd 单元和 nft
状态;任一后续步骤失败会恢复该宿主机原状态,回滚自身失败时只保留
`uncertain/degraded`,不会返回 active。跨宿主机仍不自动回退已经健康的节点。
目标 peer 的 `/32` 会与所有路由表的宽前缀、blackhole、unreachable 和其他设备逐一
检查,默认路由不被当作 Fabric overlay 路由;重叠或无法核验时 fail-closed。
nftables 规则现在保存为 root-only 的
`/etc/nftables.d/virt-cloud-wg-fabric.nft`,并要求 Debian 的
`/etc/nftables.conf` 或 AlmaLinux 的 `/etc/sysconfig/nftables.conf` 存在受管 include。
规则带 plan digest,启动 helper 会校验归属、结构、revision 和 include;规则被防火墙
重载清掉后,nftables 的持久配置负责重建,repair timer 负责短暂故障后的回读和修复。
启用或可能在重启时接管的 firewalld 与 native nftables 会被能力探测判为冲突;当前
Fabric 不把 raw nft 规则混入 firewalld direct/permanent 后端,也不会覆盖未知规则。
underlay UDP 端口的公网防火墙、NAT、MTU、SELinux/firewalld、管理器重载后的实际
连通性,以及 AlmaLinux 10 NetworkManager、Debian 13 ifupdown 在真实重启后的恢复,
仍属于真实宿主机验收项。Fabric 只使用独立的 `wg-fabric0`;管理器适配不得修改
`br0`、默认路由或宿主机管理接口。
真实验收步骤见 [Fabric 宿主机验收矩阵](FABRIC_HOST_ACCEPTANCE.md)。
### VPC 控制面(当前实现阶段)
@ -145,14 +161,29 @@ PHP 只有在所有参与宿主机的观测 revision/digest 完全匹配时才
`waiting_observed`、根同步状态为 `waiting`,专用 worker 不会每 30 秒重复请求;后续
数据面上线后必须由显式 reconcile 重新推进,不能把 waiting 当成 active。
本阶段故意不创建租户 `private0` 网卡、tap/bridge、guest route、WireGuard
AllowedIPs 或 VPC nft ACL;VPC API 返回 `applying/degraded/uncertain/waiting` 时页面和
调度器必须把 `usable` 视为 false。删除成员、子网、route 或 ACL 会保留版本和
tombstone,直到未来数据面回读确认后再清理。单台 VM 首版只允许加入一个 VPC,
与当前单一私网角色和防止跨租户混网的边界一致。Fabric 当前的 host-only nft
隔离优先于任何后续 VPC table,因此不能把“新建独立 nft table”误认为已经绕过
Fabric 的默认 drop;租户数据面必须在后续阶段由带 owner/revision 的更早优先级
规则显式放行,并同时具备回读和回滚。
VPC 私网数据面现在由引擎的独立 reconciler 执行。每台参与宿主机使用带 owner
标记的独立私网 bridge/tap,VM XML 使用不绑定 nwfilter 的 `private0` 和私网
`/32` 参数;公网 `br0`、公网默认路由和公网 nwfilter 不会被复用。宿主机策略表
只安装成员/服务精确 `/32` 路由(自机走私网 bridge,跨机走 `wg-fabric0`),并
为每个 WireGuard peer 合并精确 tenant `AllowedIPs`。每个 VPC 还有独立的 inet、
bridge 和 ARP nft 表:ACL 按 priority 处理,bridge 入口校验 MAC/IP/ARP,IPv6、
广播、多播和未知目的地址默认隔离;代理 ARP 仅允许面板登记的精确 `/32`。
云初始化 seed 同步写入 `public0`/`private0` 多网卡配置和 link-scope `/32` 路由。
宿主机 apply 在 Fabric 锁和 VPC 锁内执行,持久文件、NetworkManager/ifupdown
配置、路由、策略规则、WireGuard、nft、代理 ARP 和 sysctl 都有实际回读;apply、
实例接入和停机 libvirt 路径中途失败会按 ownership marker 恢复,响应不确定时保持
`uncertain`,不猜测性反向操作。删除/撤销路径另外保留阶段 journal 并 fail-closed:
未提交事务只进入 `uncertain/manual_reconcile`,不会重复执行破坏性删除,只有已提交
且完成资源不存在性证明后才清理 journal。PHP
只在每台宿主机的 XML、路由、ACL、反欺骗、代理 ARP、rp_filter 和完整 peer
AllowedIPs 证据都匹配当前 revision/digest 后才把 VPC 标为 `active`。
当前已完成脚本/解析器和引擎集成的静态验证;真实 AlmaLinux 10 NetworkManager、
Debian 13 ifupdown、nft 语法、重启、防火墙重载、跨宿主机握手和故障回滚仍需按
[VPC 私网数据面宿主机验收矩阵](VPC_DATAPLANE_ACCEPTANCE.md) 执行。删除成员仍
保留 PHP tombstone,直到对应 VM `private0` 移除和宿主机资源回读完成。单台 VM
首版只允许加入一个 VPC,与当前单一私网角色和防止跨租户混网的边界一致。
本阶段没有 VPC 根删除接口。CIDR reservation 在租户私网数据面、引擎删除
tombstone 和宿主机回读闭环之前不会释放;这会保留地址以避免未知状态下复用,
@ -168,9 +199,9 @@ VM 删除与 VPC 成员是两个独立状态机:仍有成员(包括 `deletin
引擎已返回成功后把 tombstone 伪造为 `deleted`。账户删除同样拒绝遗留 VPC 或私网
CIDR reservation,避免独立 VPC worker 继续消费孤儿租户计划。
AlmaLinux 10 与 Debian 13 的 WireGuard/NetworkManager/ifupdown 能力、
真实宿主机路由、SELinux/firewalld、MTU 和跨机房连通性尚未在本阶段宣称通过;
需要独立的宿主机验收矩阵后,才可实现 VPC 数据面。
AlmaLinux 10 与 Debian 13 的 WireGuard/NetworkManager/ifupdown 能力、真实宿主机
路由、SELinux/firewalld、MTU 和跨机房连通性尚未在本地环境宣称通过;必须完成
上述 Fabric 与 VPC 宿主机验收矩阵后,才能把环境状态推进为可上线。
PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志库可同实例或分别配置地址/端口。敏感业务数据加密;部署数据库连接配置仍是权限受限配置文件,不代表配置文件本身加密。

@ -0,0 +1,70 @@
# VPC 私网数据面宿主机验收矩阵
代码侧已经验证计划解析、稳定私网 MAC、cloud-init 多网卡、生成脚本的 POSIX
语法和 typed readback contract。当前开发环境没有 `ip`、`wg`、`nft`、`nmcli`、
`ifquery` 或 libvirt daemon,因此下面的宿主机步骤不能在本机冒充通过。
## 应用前证据
在每台同地区宿主机保存 Fabric `active` 的新鲜回读,并确认:
- `wg-fabric0` 由 Fabric owner marker 所有,Fabric 锁可用,IPv4 forwarding 和
`rp_filter` 处于兼容值;
- AlmaLinux 10 只有 NetworkManager/nmcli 处于 active/enabled,Debian 13 只有
ifupdown 的 `ifup`、`ifdown`、`ifquery` 和 `/etc/network/interfaces`(含已加载
的 `interfaces.d`)作为网络管理来源;
- native nftables 是唯一防火墙所有者,持久主配置只存在一个受管 include 入口,
`/etc/virt-cloud`、`/run/virt-cloud`、`/etc/nftables.d` 和 `sysctl.d` 不是符号链;
- `br0`、管理接口、默认路由和未知 nft 规则的快照已经保存。
## 成员接入和回读
对一个跨两台宿主机的 VPC,至少放置两个成员和一个 ACL,逐台检查:
1. 生成的 bridge 名称、owner/state/proxy 文件均为 root-only,bridge/tap 没有
地址、网关或 DNS;`private0` XML 的 bridge、稳定 MAC、`/32` 和持久/实时 XML
都一致,私网接口不绑定公网 `clean-traffic` nwfilter。
2. 每个成员 `/32` 和每条自定义 `/32` route 都带 panel route protocol、正确
device/table、`via` 和 metric;不存在 VPC CIDR、默认路由或宽前缀的替代项。
3. `wg show wg-fabric0 allowed-ips` 的每个 peer 与完整期望集合一致:overlay `/32`
加精确 tenant/service `/32`,没有 `0.0.0.0/0`、宽前缀或其他 VPC 的未授权地址。
4. nft inet/bridge/arp 三张表的 owner marker、chain priority、ACL comments、
anti-spoof、IPv6/广播/未知目的 drop 和精确 proxy-ARP set 均能被 observe 回读。
bridge 上通用 `proxy_arp=0`、同桥下一跳所需的 `proxy_arp_pvlan=1`、
`rp_filter=2`,代理项集合与 route destination 集合
完全相同;其他地址的 ARP reply 必须被过滤。
5. 从同机和跨机成员分别验证允许的 TCP/UDP/ICMP 流量、ACL deny、伪造源 MAC/IP、
IPv6、广播/多播和访问宿主机自身地址。验证结果同时记录 guest route、宿主机
route、WireGuard handshake 和 nft counter,不能只看页面的 `active`。
## 管理器和重启矩阵
AlmaLinux 10:执行 `nmcli connection reload`、`systemctl reload nftables`、
`systemctl restart NetworkManager` 和宿主机重启。每一步都要确认 private bridge、
route/rule、proxy ARP、nft include、WireGuard peer、private0 XML 和默认公网路径
恢复,且 NetworkManager 没有接管 `br0` 或管理接口。
Debian 13:执行 `ifquery <private-bridge>`、`ifup --force <private-bridge>`、
`systemctl reload nftables`、`systemctl restart networking` 和宿主机重启。确认
`interfaces.d` fragment、route/rule、proxy ARP、nft include、WireGuard peer 和
private0 XML 恢复;严禁用 ifdown 操作 `br0` 或管理接口。
## 故障回滚
在隔离环境中分别让 `ip link`、`ip route`、`ip rule`、`ip neigh`、`wg set`、
`nft -c`、`nft -f`、NetworkManager/ifup、sysctl 或 libvirt define/seed 上传在
每个阶段失败。预期结果是:
- apply、实例接入和停机 libvirt 变更失败时,原 panel-owned bridge、route/rule、
peer AllowedIPs、nft 表/include、proxy 项、sysctl、XML 和 seed 按快照恢复;
- 删除/撤销路径使用阶段 journal 和 fail-closed 收敛:未提交的 journal 在回读前
返回 `uncertain/manual_reconcile` 并保留现场,不重复执行破坏性删除;只有已经
提交且能证明面板资源全部不存在的 journal 才会被清理。因此删除路径的“回滚”
是可审计的停机与人工核对边界,不是假设资源可以自动恢复;
- 外部 bridge/profile、未知 route、未知 ARP proxy 项和未知 nft 规则不被删除;
- 恢复本身失败或响应丢失时返回 `uncertain/degraded`,保留事务目录供下一次
readback,绝不返回成功;
- 重试只依据新的完整宿主机回读,不对不确定的 libvirt 或网络变更盲目反向执行。
跨宿主机最后还要单独验证 underlay 公网防火墙、NAT、MTU、SELinux 和 UDP 监听。
Fabric/VPC 的本地 nft 表不等于 underlay 已放行。

@ -14,7 +14,8 @@ from virsh_panel.cloud_init import (
_build_seed_iso, _enable_network_updates, build_seed_iso,
generate_root_password,
hash_root_password,
read_seed_network, replace_seed_network, replace_seed_settings,
read_seed_network, replace_seed_network, replace_seed_private_network,
replace_seed_settings,
validate_cloud_network, validate_guest_hostname, validate_private_network,
_parse_network_config,
)
@ -268,10 +269,54 @@ def test_seed_iso_can_add_private_role_without_public_route_or_dns():
"mac": "52:54:00:12:34:56",
"private_ip_cidr": "10.24.3.7/32",
"private_mac": "52:54:00:12:34:57",
"private_routes": [],
"roles": ["public0", "private0"],
}
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_private_seed_routes_are_exact_and_can_be_reconciled_or_removed():
validated = validate_cloud_network(
"8.8.8.18/28", "8.8.8.17", ["1.1.1.1"], PUBLIC_KEY,
)
seed = build_seed_iso(
str(uuid.uuid4()), "private-route-vm", "52:54:00:12:34:56", validated,
private_mac="52:54:00:12:34:57",
private_network={
"private_ip_cidr": "10.24.3.7/32",
"routes": ["10.24.3.8/32"],
},
)
assert read_seed_network(seed)["private_routes"] == ["10.24.3.8/32"]
changed = replace_seed_private_network(
seed,
private_mac="52:54:00:12:34:58",
private_ip_cidr="10.24.3.9/32",
private_routes=["10.24.3.10/32", "10.24.3.11/32"],
)
changed_network = read_seed_network(changed)
assert changed_network["private_ip_cidr"] == "10.24.3.9/32"
assert changed_network["private_mac"] == "52:54:00:12:34:58"
assert changed_network["private_routes"] == ["10.24.3.10/32", "10.24.3.11/32"]
removed = replace_seed_private_network(
changed, private_mac=None, private_ip_cidr=None,
)
removed_network = read_seed_network(removed)
assert "private_ip_cidr" not in removed_network
assert "private_routes" not in removed_network
with pytest.raises(ValueError):
replace_seed_private_network(
seed,
private_mac="52:54:00:12:34:58",
private_ip_cidr="10.24.3.9/32",
private_routes=["10.24.3.0/24"],
)
@pytest.mark.skipif(importlib.util.find_spec("pycdlib") is None,
reason="pycdlib is not installed")
def test_seed_iso_has_nocloud_files_and_mac_specific_static_network():

@ -118,12 +118,27 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys():
assert result.returncode == 0, result.stderr
assert "br0" not in script
assert "PRIVATE KEY" not in script
observe = scripts[2]
assert "__VC_FABRIC_ADMIN_STATE__" in observe
assert "__VC_FABRIC_SYSCTL__ip_forward" in observe
assert "__VC_FABRIC_SYSCTL__rp_filter_default" in observe
assert "__VC_FABRIC_RPF__wg-fabric0" in observe
assert "__VC_FABRIC_VPC_STATE__" in observe
assert "list set inet virt_cloud_wg_fabric vpc_tenant_ips" in observe
assert 'table!="main" && table!="local"' in observe
apply = scripts[-1]
assert KEY2 in apply and KEY1 not in apply
assert 'KEY="$BASE/wg-fabric0.key"' in apply
assert "wg-fabric0" in apply
assert "address_conflict" in apply
assert "existing_route" in apply
assert "route_overlaps_target" in apply
assert "supernet" not in apply # shell check is numeric and bounded
assert "virt-cloud-wg-fabric.nft" in apply
assert "include \"/etc/nftables.d/virt-cloud-wg-fabric.nft\"" in apply
assert "trap rollback EXIT HUP INT TERM" in apply
assert '"$WG" showconf' in apply
assert "route save table all" in apply
assert 'chmod 700 "$BASE" /usr/local/libexec' not in apply
assert "virt-cloud-wg-fabric-v1" in apply
assert "virt_cloud_wg_fabric" in apply
@ -137,6 +152,14 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys():
assert "NetworkManager/system-connections" in apply
assert "nmcli" in apply
assert "flock" in apply
assert "vpc_state_load" in apply
assert "vpc_state_allowed_for_peer" in apply
assert "vpc_state_refresh_nft" in apply
assert "vpc_state_refresh_nft" in _BOOT_HELPER
assert 'vpc_state != "invalid"' in observe
assert 'vpc[prefix "|" device "|" table "|" via "|" metric]' in observe
assert "key|wg.conf|address.save|route.save|nft.table" in _BOOT_HELPER
assert 'journal_file_mode" = 600' in _BOOT_HELPER
ifup = _apply_script(current, current.nodes[0], {
"host-a": KEY1, "host-b": KEY2,
}, "ifupdown", "/usr/bin/ifup")
@ -147,10 +170,12 @@ def test_generated_helpers_are_posix_safe_and_do_not_embed_private_keys():
assert result.returncode == 0, result.stderr
assert "/etc/network/interfaces.d/virt-cloud-wg-fabric0" in ifup
assert "ifup" in ifup and "ifdown" in ifup
assert "ExecStart=/usr/bin/ifup --force wg-fabric0" in ifup
assert "ExecStart=/usr/local/libexec/virt-cloud-wg-fabric --ifupdown-service" in ifup
# The Debian 13 contract must also work with classic ifupdown; its
# ifquery implementation does not provide ifupdown2's --check flag.
assert "ifquery\" --check" not in ifup
assert "VC_FABRIC_LOCK_HELD=1" in ifup
assert "VC_FABRIC_ALLOW_TRANSITION=1" in ifup
assert "br0" not in ifup
with pytest.raises(FabricError):
_apply_script(current, current.nodes[0], {
@ -170,6 +195,12 @@ class FakeManager:
self.ping_ok = ping_ok
self.endpoint_device = endpoint_device
self.scripts = []
self.reprobe_calls = 0
self.admin_state = "up"
self.ip_forward = "1"
self.rp_filter = "2"
self.rp_filter_default = "2"
self.rp_filter_iface = "2"
self.profile = {
"ssh_config_file": "/tmp/fake-ssh-config",
"ssh_target": "vp-managed",
@ -192,6 +223,10 @@ class FakeManager:
def current(self):
return self.profile
def reprobe_current(self):
self.reprobe_calls += 1
return self.profile["capabilities"]
def _exec(self, argv, *, timeout, input_text=None):
assert argv[-1] == "/bin/sh -s"
assert timeout == 35
@ -234,14 +269,22 @@ class FakeManager:
f"__VC_FABRIC_PATH__={target}|{FABRIC_INTERFACE}\n"
f"__VC_FABRIC_ENDPOINT_PATH__={endpoint.split(':', 1)[0]}|{self.endpoint_device}\n"
f"__VC_FABRIC_PING__={target}|{'ok' if self.ping_ok else 'failed'}\n"
f"__VC_FABRIC_ROUTE_OVERLAP__={target}|clean\n"
"__VC_FABRIC_MANAGER_MODE__=networkmanager_nmcli\n"
"__VC_FABRIC_MANAGER_OWNER__=owned\n"
"__VC_FABRIC_MANAGER_ACTIVE__=active\n"
f"__VC_FABRIC_ADMIN_STATE__={self.admin_state}\n"
f"__VC_FABRIC_SYSCTL__ip_forward={self.ip_forward}\n"
f"__VC_FABRIC_SYSCTL__rp_filter={self.rp_filter}\n"
f"__VC_FABRIC_SYSCTL__rp_filter_default={self.rp_filter_default}\n"
f"__VC_FABRIC_RPF__wg-fabric0={self.rp_filter_iface}\n"
"__VC_FABRIC_ENABLED__=enabled\n"
"__VC_FABRIC_ACTIVE__=active\n"
"__VC_FABRIC_TIMER_ENABLED__=enabled\n"
"__VC_FABRIC_TIMER_ACTIVE__=active\n"
"__VC_FABRIC_NFT_GUARD__=owned\n"
"__VC_FABRIC_NFT_PERSISTENCE__=owned\n"
"__VC_FABRIC_VPC_NFT_STATE__=owned\n"
"__VC_FABRIC_KEY_SECURE__=yes\n"
"__VC_FABRIC_CONFIG_SECURE__=yes\n"
"__VC_FABRIC_HELPER__=owned\n"
@ -281,6 +324,24 @@ def test_adapter_ignores_the_kernel_connected_route_for_its_own_address():
assert observed["config_ok"] is True
def test_adapter_requires_admin_up_and_fabric_sysctl_readback():
current = plan()
manager = FakeManager(KEY1)
manager.admin_state = "down"
assert FabricHostAdapter(manager).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)["config_ok"] is False
manager.admin_state = "up"
manager.rp_filter_iface = "1"
observed = FabricHostAdapter(manager).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)
assert observed["config_ok"] is False
assert observed["observed"]["admin_state"] == "up"
assert observed["observed"]["rp_filters"][FABRIC_INTERFACE] == "1"
def test_adapter_rejects_stale_config_digest_and_failed_probe():
current = plan()
stale = FakeManager(KEY1, config_digest="0" * 64)
@ -389,6 +450,8 @@ def test_coordinator_keeps_successful_hosts_and_blocks_next_stage(monkeypatch):
assert result["next_stage_allowed"] is False
states = {node["host_id"]: node["state"] for node in result["nodes"]}
assert states == {"host-a": "active", "host-b": "uncertain"}
assert managers["host-a"].reprobe_calls == 1
assert managers["host-b"].reprobe_calls == 1
serialized = "\n".join(store.values.values())
assert "PRIVATE KEY" not in serialized
assert KEY1 in serialized and KEY2 in serialized
@ -488,3 +551,113 @@ def test_new_fabric_cannot_reuse_a_host_or_overlay_catalog_entry():
with pytest.raises(FabricError) as error:
asyncio.run(coordinator.apply(value))
assert error.value.error_code == "fabric_host_interface_conflict"
class TenantReadbackManager(FakeManager):
"""Synthetic readback with panel-owned VPC tenant state."""
def __init__(self, *args, tenant_ip="10.10.0.2/32", **kwargs):
super().__init__(*args, **kwargs)
self.tenant_ip = tenant_ip
def _exec(self, argv, *, timeout, input_text=None):
result = super()._exec(argv, timeout=timeout, input_text=input_text)
if input_text.startswith("#!/bin/sh\nset -eu"):
return result
peer = KEY2 if self.public_key == KEY1 else KEY1
target = "100.64.1.2" if self.public_key == KEY1 else "100.64.1.1"
endpoint = "203.0.113.2:51820" if self.public_key == KEY1 else "203.0.113.1:51820"
marker = f"__VC_FABRIC_PEER__={peer}|{endpoint}|{target}/32"
output = result.stdout.replace(marker, f"{marker},{self.tenant_ip}")
output += (
"__VC_FABRIC_VPC_STATE__=owned\n"
f"__VC_FABRIC_VPC_TENANT__={peer}|{self.tenant_ip}\n"
"__VC_FABRIC_VPC_NFT_STATE__=owned\n"
f"__VC_FABRIC_VPC_NFT_IP__={self.tenant_ip}\n"
)
return result.__class__(result.args, result.returncode, output, result.stderr)
def test_fabric_merges_and_reads_panel_owned_vpc_allowed_ips():
current = plan()
observed = FabricHostAdapter(TenantReadbackManager(KEY1)).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)
assert observed["config_ok"] is True
assert observed["observed"]["peer_allowed_exact"] is True
assert f"{KEY2}|10.10.0.2/32" in observed["observed"]["vpc_tenants"]
assert all("10001" not in route for route in observed["observed"]["routes"])
def test_fabric_rejects_unbacked_vpc_allowed_ip():
current = plan()
manager = FakeManager(KEY1)
original_exec = manager._exec
def unbacked(argv, *, timeout, input_text=None):
result = original_exec(argv, timeout=timeout, input_text=input_text)
if input_text.startswith("#!/bin/sh\nset -eu"):
return result
peer = KEY2
marker = f"__VC_FABRIC_PEER__={peer}|203.0.113.2:51820|100.64.1.2/32"
output = result.stdout.replace(marker, f"{marker},10.10.0.2/32")
return result.__class__(result.args, result.returncode, output, result.stderr)
manager._exec = unbacked
observed = FabricHostAdapter(manager).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)
assert observed["config_ok"] is False
assert observed["observed"]["peer_allowed_exact"] is False
def test_fabric_rejects_non_rfc1918_vpc_tenant_prefix():
current = plan()
observed = FabricHostAdapter(
TenantReadbackManager(KEY1, tenant_ip="169.254.1.2/32")
).observe(current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2})
assert observed["config_ok"] is False
assert observed["observed"]["peer_allowed_exact"] is False
def test_fabric_rejects_stale_vpc_nft_tenant_set():
current = plan()
manager = TenantReadbackManager(KEY1)
original_exec = manager._exec
def stale_nft(argv, *, timeout, input_text=None):
result = original_exec(argv, timeout=timeout, input_text=input_text)
if input_text.startswith("#!/bin/sh\nset -eu"):
return result
output = result.stdout.replace(
"__VC_FABRIC_VPC_NFT_IP__=10.10.0.2/32\n", "")
return result.__class__(result.args, result.returncode, output, result.stderr)
manager._exec = stale_nft
observed = FabricHostAdapter(manager).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)
assert observed["config_ok"] is False
assert observed["observed"]["vpc_nft_exact"] is False
def test_fabric_does_not_hide_foreign_custom_route():
current = plan()
manager = FakeManager(KEY1)
original_exec = manager._exec
def foreign_route(argv, *, timeout, input_text=None):
result = original_exec(argv, timeout=timeout, input_text=input_text)
if input_text.startswith("#!/bin/sh\nset -eu"):
return result
output = result.stdout + (
f"__VC_FABRIC_ROUTE__=10.10.0.2/32|10001|{FABRIC_INTERFACE}\n"
)
return result.__class__(result.args, result.returncode, output, result.stderr)
manager._exec = foreign_route
observed = FabricHostAdapter(manager).observe(
current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}
)
assert observed["config_ok"] is False
assert "10.10.0.2/32|10001|wg-fabric0" in observed["observed"]["routes"]

@ -85,6 +85,8 @@ __VCAP_SERVICE__nftables=active
__VCAP_SERVICE_ENABLED__network_manager=enabled
__VCAP_SERVICE_ENABLED__networkd=disabled
__VCAP_SERVICE_ENABLED__networking=disabled
__VCAP_SERVICE_ENABLED__firewall=disabled
__VCAP_SERVICE_ENABLED__nftables=enabled
__VCAP_FILE__interfaces=absent
__VCAP_FILE__interfaces_d=absent
__VCAP_FILE__networkmanager_profiles=absent
@ -119,6 +121,8 @@ class Runner:
self.ssh_exit = 0
self.encrypted = False
self.public_key_type = "ssh-ed25519"
self.capability_exit = 0
self.capability_output = CAPABILITY_OUTPUT
self.commands: list[list[str]] = []
def __call__(self, argv, **kwargs):
@ -134,7 +138,10 @@ class Runner:
return subprocess.CompletedProcess(argv, 0, f"{self.public_key_type} fake-public-key\n", "")
if argv[0] == "ssh":
if _CAPABILITY_MARKER in argv[-1]:
return subprocess.CompletedProcess(argv, 0, CAPABILITY_OUTPUT, "")
return subprocess.CompletedProcess(
argv, self.capability_exit, self.capability_output,
"private remote diagnostic",
)
return subprocess.CompletedProcess(argv, self.ssh_exit, "", "permission denied")
raise AssertionError(argv)
@ -474,6 +481,14 @@ def test_stage_test_commit_writes_private_pinned_ssh_config(tmp_path):
assert tested["capabilities"]["os"]["package_tool"] == "dnf"
assert tested["capabilities"]["os"]["package_tool_available"] is True
assert tested["capabilities"]["wireguard"]["deployment_mode"] == "networkmanager_nmcli"
assert tested["capabilities"]["nftables"]["service_active"] is True
assert tested["capabilities"]["nftables"]["service_persistent"] is True
assert tested["capabilities"]["network"]["firewall_manager_evidence"] == {
"firewalld_active": False,
"firewalld_enabled": False,
"nftables_active": True,
"nftables_enabled": True,
}
assert tested["capabilities"]["network"]["rp_filter_default"] == 2
assert tested["capabilities"]["network"]["rp_filter_interfaces"]["br0"] == 2
assert tested["capabilities"]["network_roles"]["private"]["host_interface"] == WG_FABRIC_INTERFACE
@ -511,6 +526,80 @@ def test_capability_snapshot_is_persisted_only_after_commit(tmp_path):
assert profile_after["capabilities"]["wireguard"]["interface"] == WG_FABRIC_INTERFACE
def test_current_capabilities_are_reprobed_through_pinned_generation(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(
make_profile(scanned, default_network="bridge:br0"),
scanned["fingerprint"],
)
manager.test(staged)
current = manager.commit(staged)
profile_path = staged.path / "profile.json"
persisted_before = profile_path.read_bytes()
runner.capability_output = CAPABILITY_OUTPUT.replace(
"__VCAP_SERVICE_ENABLED__nftables=enabled",
"__VCAP_SERVICE_ENABLED__nftables=disabled",
)
capabilities = manager.reprobe_current_capabilities()
assert capabilities["probe_valid"] is True
assert capabilities["network_roles"]["public"]["selector"] == "bridge:br0"
assert capabilities["nftables"]["service_active"] is True
assert capabilities["nftables"]["service_persistent"] is False
assert capabilities["vpc_ready"] is False
assert "nftables_service_not_enabled" in capabilities["reasons"]
assert profile_path.read_bytes() == persisted_before
assert current["capabilities"]["vpc_ready"] is True
assert runner.commands[-1][0:4] == [
"ssh", "-F", str(staged.path / "config"), "-T",
]
assert runner.commands[-1][-1] == _CAPABILITY_PROBE_COMMAND
def test_current_capability_reprobe_requires_configured_host(tmp_path):
manager = make_manager(tmp_path, Runner())
with pytest.raises(RemoteHostError) as error:
manager.reprobe_current_capabilities()
assert error.value.status == 409
assert error.value.error_code == "host_not_configured"
def test_current_capability_reprobe_hides_remote_failure_output(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
manager.test(staged)
manager.commit(staged)
runner.capability_exit = 255
with pytest.raises(RemoteHostError) as error:
manager.reprobe_current_capabilities()
assert error.value.status == 502
assert error.value.error_code == "host_capability_probe_failed"
assert "private remote diagnostic" not in str(error.value)
def test_current_capability_reprobe_rejects_invalid_protocol(tmp_path):
runner = Runner()
manager = make_manager(tmp_path, runner)
scanned = manager.scan("host.example", 2222)
staged = manager.stage(make_profile(scanned), scanned["fingerprint"])
manager.test(staged)
manager.commit(staged)
runner.capability_output = CAPABILITY_OUTPUT.replace("__VCAP_END__", "")
with pytest.raises(RemoteHostError) as error:
manager.reprobe_current_capabilities()
assert error.value.status == 502
assert error.value.error_code == "host_capability_probe_invalid"
def test_capability_probe_rejects_missing_private_plane_evidence():
output = CAPABILITY_OUTPUT.replace(
"__VCAP_TOOL__wg=/usr/bin/wg", "__VCAP_TOOL__wg=",
@ -524,11 +613,23 @@ def test_capability_probe_rejects_missing_private_plane_evidence():
assert capabilities["private_ready"] is False
assert capabilities["vpc_ready"] is False
assert "wireguard_tool_missing" in capabilities["reasons"]
assert "firewall_owner_not_nftables" in capabilities["reasons"]
assert "nftables_service_not_active" in capabilities["reasons"]
assert "ipv4_forwarding_disabled_or_unknown" in capabilities["reasons"]
assert capabilities["network_roles"]["private"]["separate_from_public"] is True
def test_capability_probe_rejects_firewalld_enabled_for_next_boot():
output = CAPABILITY_OUTPUT.replace(
"__VCAP_SERVICE_ENABLED__firewall=disabled",
"__VCAP_SERVICE_ENABLED__firewall=enabled",
)
capabilities = parse_host_capabilities(output, public_network="bridge:br0")
assert capabilities["network"]["firewall_manager"] == "conflict"
assert capabilities["nftables"]["ready"] is False
assert capabilities["vpc_ready"] is False
assert "firewall_owner_not_nftables" in capabilities["reasons"]
def test_capability_probe_rejects_preexisting_fabric_interface():
output = CAPABILITY_OUTPUT.replace(
'[{"ifname":"br0"}]',

@ -170,7 +170,7 @@ def test_plan_validates_routes_acl_ports_and_member_scope():
"private_ip_cidr": "10.20.0.11/32", "subnet_id": "subnet-a"},
]},
],
routes=[{"route_id": "route-a", "destination_cidr": "10.20.0.128/25",
routes=[{"route_id": "route-a", "destination_cidr": "10.20.0.128/32",
"next_hop_member_id": "member-a", "metric": 20}],
acls=[{"acl_id": "acl-a", "direction": "ingress", "action": "allow",
"protocol": "tcp", "source_cidr": "10.20.0.0/24",
@ -195,6 +195,12 @@ def test_plan_validates_routes_acl_ports_and_member_scope():
"route_id": "bad", "destination_cidr": "0.0.0.0/0",
"next_hop_host_id": "host-a",
}]))
with pytest.raises(VpcError) as broad_route:
parse_vpc_plan(payload(routes=[{
"route_id": "broad", "destination_cidr": "10.20.0.128/25",
"next_hop_member_id": "member-a",
}]))
assert broad_route.value.error_code == "vpc_route_not_exact"
with pytest.raises(VpcError):
parse_vpc_plan(payload(acls=[{
"acl_id": "bad", "direction": "egress", "action": "allow",

@ -0,0 +1,251 @@
"""Pure VPC private data-plane contract tests.
These tests render the host transaction only; real nft/ip/wg and libvirt
acceptance remains a host-matrix test because this checkout has no network
namespace or libvirt daemon.
"""
from __future__ import annotations
import subprocess
from dataclasses import replace
from virsh_panel.vpc import VPC_SCHEMA_VERSION
from virsh_panel.vpc_dataplane import (
_markers,
parse_vpc_dataplane_plan,
patch_private_interface_xml,
render_apply_script,
render_observe_script,
render_remove_script,
render_vpc_nft_rules,
)
WG_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE="
WG_KEY_2 = "AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI="
def _plan():
return parse_vpc_dataplane_plan({
"schema_version": VPC_SCHEMA_VERSION,
"vpc_id": "vpc-hk-dp",
"region": "hk",
"fabric_id": "fabric-hk",
"fabric_revision": 3,
"cidr": "10.42.0.0/24",
"desired_revision": 1,
"operation_id": "vpc-op-dp-0001",
"subnets": [{"subnet_id": "subnet-a", "cidr": "10.42.0.0/25"}],
"hosts": [
{"host_id": "host-a", "members": [{
"member_id": "member-a",
"instance_uuid": "11111111-1111-4111-8111-111111111111",
"private_ip_cidr": "10.42.0.10/32",
"subnet_id": "subnet-a",
}]},
{"host_id": "host-b", "members": [{
"member_id": "member-b",
"instance_uuid": "22222222-2222-4222-8222-222222222222",
"private_ip_cidr": "10.42.0.11/32",
"subnet_id": "subnet-a",
}]},
],
"routes": [{
"route_id": "service-a", "destination_cidr": "10.42.0.100/32",
"next_hop_member_id": "member-b", "metric": 20,
}],
"acls": [{
"acl_id": "allow-https", "direction": "ingress", "action": "allow",
"protocol": "tcp", "source_cidr": "10.42.0.0/24",
"destination_cidr": "10.42.0.10/32", "port_from": 443,
"port_to": 443, "priority": 10,
}],
"fabric_peers": [{
"host_id": "host-b", "public_key": WG_KEY,
"overlay_ip": "100.64.0.2/32",
"tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"],
}],
}, "host-a")
def test_rendered_data_plane_has_exact_routes_proxy_arp_and_atomic_nft_batch():
plan = _plan()
apply = render_apply_script(plan)
nft = render_vpc_nft_rules(plan)
assert "10.42.0.11/32|wg-fabric0" in apply
assert "10.42.0.100/32|wg-fabric0" in apply
assert 'route replace "$destination" table "$table" via "$via" dev "$device" onlink' in apply
assert 'neigh replace proxy "$proxy_ip"' in apply
assert "table arp" in nft
assert "arp-proxy-output" in nft
assert 'proxy_arp = 0' in apply
assert 'proxy_arp_pvlan = 1' in apply
assert 'NFT_BATCH="$TXN/apply.nft"' in apply
assert '"$NFT" -f "$NFT_BATCH"' in apply
assert '"$NFT" delete table inet "$TABLE"' not in apply
assert "anti-spoof-public-to-bridge" in nft
assert "anti-spoof-public-to-fabric" in nft
assert "anti-spoof-bridge-to-foreign" in nft
assert "anti-spoof-fabric-to-foreign" in nft
assert 'oifname "wg-fabric0" ip daddr @vpc_dest_ips drop' in nft
def test_rendered_scripts_are_posix_shell():
plan = _plan()
for script in (render_apply_script(plan), render_observe_script(plan)):
result = subprocess.run(
["/bin/sh", "-n"], input=script, text=True,
capture_output=True, check=False,
)
assert result.returncode == 0, result.stderr
def test_remove_script_checks_ownership_before_destructive_cleanup():
plan = _plan()
empty_host = replace(
plan,
members=tuple(member for member in plan.members
if member.host_id != plan.host_id),
)
for mode in ("networkmanager_nmcli", "ifupdown"):
script = render_remove_script(empty_host, deployment_mode=mode)
result = subprocess.run(
["/bin/sh", "-n"], input=script, text=True,
capture_output=True, check=False,
)
assert result.returncode == 0, result.stderr
assert 'connection.stable-id' in script
assert 'nm_empty ipv4.routes' in script
assert "virt-cloud-vpc-dataplane-v1 vpc=" in script
assert 'nft_table_count' in script
assert '[ "$name" = "$TABLE" ]' in script
assert 'BRIDGE_PRESENT=no' in script
assert 'if "$IP" link show dev "$BRIDGE"' in script
assert 'bridge_routes6' in script
assert 'proxy_left' in script
for phase in (
"routes_removed", "manager_removed", "bridge_removed",
"nft_removed", "files_removed", "wg_merged", "committed",
):
assert f"set_phase {phase}" in script
assert '[ "$RESUME" = yes ]' in script
assert 'committed)' in script
assert 'files_removed|wg_merged)' in script
def test_proxy_markers_are_bounded_and_typed():
parsed = _markers(
"__VC_VPC_PROXY_ARP__=0\n"
"__VC_VPC_PROXY_ARP_PVLAN__=1\n"
"__VC_VPC_PROXY_STATE__=owned\n"
"__VC_VPC_PROXY_IP__=10.42.0.11\n"
)
assert parsed["proxy_arp"] == "0"
assert parsed["proxy_arp_pvlan"] == "1"
assert parsed["proxy_state"] == "owned"
assert parsed["proxy_ips"] == ["10.42.0.11"]
def test_peer_allowed_ips_are_closed_over_vpc_or_trusted_fabric_set():
plan = _plan()
payload = plan.vpc.canonical()
payload["fabric_peers"] = [{
"host_id": "host-b", "public_key": WG_KEY,
"overlay_ip": "100.64.0.2/32",
"tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32",
"10.42.0.200/32"],
}]
try:
parse_vpc_dataplane_plan(payload, "host-a")
except Exception as exc:
assert getattr(exc, "error_code", None) == "vpc_tenant_allowed_ip_unowned"
else:
raise AssertionError("unowned peer AllowedIP was accepted")
parsed = parse_vpc_dataplane_plan(
payload, "host-a",
trusted_tenant_allowed_ips={
"host-b": ["10.42.0.11/32", "10.42.0.100/32",
"10.42.0.200/32"],
})
assert parsed.peers[0].tenant_allowed_ips[-1] == "10.42.0.200/32"
def test_observe_can_require_the_complete_authoritative_fabric_peer_set():
plan = _plan()
strict = parse_vpc_dataplane_plan(
plan.vpc.canonical(), "host-a",
fabric_peers=[{
"host_id": "host-b", "public_key": WG_KEY,
"overlay_ip": "100.64.0.2/32",
"tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"],
}],
trusted_tenant_allowed_ips={
"host-b": ["10.42.0.11/32", "10.42.0.100/32"],
},
fabric_peer_keys=[WG_KEY, WG_KEY_2],
)
assert strict.fabric_peer_keys == frozenset({WG_KEY, WG_KEY_2})
observe = render_observe_script(strict)
assert "__VC_VPC_WG_PEER_SET__" in observe
assert "live_fabric_peer_keys" in observe
try:
parse_vpc_dataplane_plan(
plan.vpc.canonical(), "host-a",
fabric_peers=[{
"host_id": "host-b", "public_key": WG_KEY,
"overlay_ip": "100.64.0.2/32",
"tenant_allowed_ips": ["10.42.0.11/32", "10.42.0.100/32"],
}],
trusted_tenant_allowed_ips={
"host-b": ["10.42.0.11/32", "10.42.0.100/32"],
},
fabric_peer_keys=[WG_KEY_2],
)
except Exception as exc:
assert getattr(exc, "error_code", None) == "vpc_fabric_peer_set_invalid"
else:
raise AssertionError("VPC peer outside authoritative Fabric set was accepted")
def test_private_xml_patch_keeps_public_role_and_leaves_private_filter_free():
plan = _plan()
member = plan.members[0]
xml = """<domain><metadata/><devices>
<interface type='bridge'><mac address='52:54:00:00:00:01'/>
<alias name='public0'/><source bridge='br0'/></interface>
</devices></domain>"""
patched = patch_private_interface_xml(
xml, member=member, resources=plan.resources,
vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision,
desired_digest=plan.desired_digest,
)
assert "alias name=\"public0\"" in patched
assert 'alias name="private0"' in patched
assert f'bridge="{plan.resources.bridge}"' in patched
assert 'filter="clean-traffic"' not in patched
assert f'private-network-digest="{plan.desired_digest}"' in patched
def test_private_xml_patch_promotes_legacy_single_nic_to_public_role():
plan = _plan()
member = plan.members[0]
legacy = """<domain><devices>
<interface type='bridge'><mac address='52:54:00:00:00:01'/>
<source bridge='br0'/></interface>
</devices></domain>"""
patched = patch_private_interface_xml(
legacy, member=member, resources=plan.resources,
vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision,
desired_digest=plan.desired_digest,
)
assert 'alias name="public0"' in patched
assert 'alias name="private0"' in patched
# A second reconciliation must still identify the original NIC as public.
reparsed = patch_private_interface_xml(
patched, member=member, resources=plan.resources,
vpc_id=plan.vpc.vpc_id, desired_revision=plan.desired_revision,
desired_digest=plan.desired_digest,
)
assert reparsed.count('alias name="public0"') == 1
assert reparsed.count('alias name="private0"') == 1

@ -321,6 +321,47 @@ def validate_private_network(private_ip_cidr: Any) -> dict[str, str]:
return {"private_ip_cidr": str(interface)}
def _validate_private_routes(value: Any) -> list[str]:
"""Validate the guest's exact on-link VPC routes.
The host owns inter-host forwarding, while the guest still needs a route
for each remote /32. Keep this list deliberately narrow: no gateways,
default routes, or broad prefixes are accepted on ``private0``.
"""
if value is None:
return []
if not isinstance(value, (list, tuple)) or len(value) > 4096:
raise ValueError("私网路由列表无效")
result: set[str] = set()
for item in value:
if isinstance(item, str):
destination = item
elif isinstance(item, dict):
if item.get("to") in {"default", "0.0.0.0/0", "::/0"}:
# Keep the legacy diagnostic used by seed validation callers:
# private0 is never allowed to acquire a default route.
raise ValueError("私网网卡必须是无默认路由的静态 /32")
if set(item) != {"to", "scope"} or item.get("scope") != "link":
raise ValueError("私网路由必须是 link scope 的 /32")
destination = item.get("to")
else:
raise ValueError("私网路由格式无效")
if destination in {"default", "0.0.0.0/0", "::/0"}:
raise ValueError("私网网卡必须是无默认路由的静态 /32")
try:
network = ipaddress.ip_network(destination, strict=True)
except (TypeError, ValueError) as exc:
raise ValueError("私网路由必须是 IPv4 /32") from exc
if (not isinstance(network, ipaddress.IPv4Network)
or network.prefixlen != 32
or not any(network.subnet_of(ipaddress.IPv4Network(block))
for block in ("10.0.0.0/8", "172.16.0.0/12",
"192.168.0.0/16"))):
raise ValueError("私网路由必须是 RFC1918 IPv4 /32")
result.add(str(network))
return sorted(result)
def _validate_network_mac(value: Any, label: str) -> str:
if not isinstance(value, str) or not _MAC.fullmatch(value):
raise ValueError(f"{label} MAC 地址无效")
@ -403,7 +444,6 @@ def _parse_network_config(config: Any) -> dict[str, Any]:
or private.get("accept-ra") is not False
or not isinstance(private.get("addresses"), list)
or len(private["addresses"]) != 1
or "routes" in private
or not isinstance(private_match, dict)
or set(private_match) != {"macaddress"}):
raise ValueError("原 cloud-init 私网网卡必须是无默认路由的静态 /32")
@ -414,6 +454,7 @@ def _parse_network_config(config: Any) -> dict[str, Any]:
result.update({
**private_network,
"private_mac": private_mac,
"private_routes": _validate_private_routes(private.get("routes")),
"roles": [PUBLIC_INTERFACE_ALIAS, PRIVATE_INTERFACE_ALIAS],
})
return result
@ -552,6 +593,9 @@ def build_seed_iso(
private_network.get("private_ip_cidr")
if isinstance(private_network, dict) else None
)
private_routes = _validate_private_routes(
private_network.get("routes", [])
if isinstance(private_network, dict) else [])
if normalized_private_mac == normalized_mac:
raise ValueError("公网和私网网卡不能使用同一个 MAC")
network_config["ethernets"][PRIVATE_INTERFACE_ALIAS] = {
@ -560,6 +604,10 @@ def build_seed_iso(
"dhcp6": False,
"accept-ra": False,
"addresses": [private["private_ip_cidr"]],
**({"routes": [
{"to": destination, "scope": "link"}
for destination in private_routes
]} if private_routes else {}),
}
if debian12_network_fix:
# dhcp6=false does not disable DHCPv6 started in response to a router
@ -776,6 +824,72 @@ def replace_seed_network(
raise ValueError("原 cloud-init 网络配置格式无效") from exc
def replace_seed_private_network(
seed: bytes,
*,
private_mac: str | None,
private_ip_cidr: str | None,
private_routes: list[str] | tuple[str, ...] | None = None,
) -> bytes:
"""Add, replace, or remove the panel-managed ``private0`` network.
The public NIC, credentials, hostname and DNS settings are copied from
the existing panel seed. A private NIC never receives DHCP, IPv6 RA, or a
default route; its only address is the validated RFC1918 /32. Passing
``None`` for both values removes the private role and is used when a VPC
member is detached.
"""
if (private_mac is None) != (private_ip_cidr is None):
raise ValueError("私网网卡必须同时提供 MAC 和地址")
if private_mac is None and private_routes:
raise ValueError("移除私网网卡时不能保留路由")
files = _read_seed_files(seed)
try:
config = json.loads(files["network-config"])
parsed = _parse_network_config(config)
# Validate the complete existing role before editing it. This keeps a
# hand-edited or foreign seed from becoming a partially managed
# multi-NIC configuration.
_parse_network_config(config)
user_data = _enable_network_updates(files["user-data"])
metadata = _decode_seed_metadata(files["meta-data"])
ethernets = config.get("ethernets")
if not isinstance(ethernets, dict):
raise ValueError("原 cloud-init 网卡配置无效")
if private_mac is None:
ethernets.pop(PRIVATE_INTERFACE_ALIAS, None)
else:
normalized_mac = _validate_network_mac(private_mac, "私网")
private = validate_private_network(private_ip_cidr)
routes = _validate_private_routes(private_routes)
if normalized_mac == parsed["mac"]:
raise ValueError("公网和私网网卡不能使用同一个 MAC")
ethernets[PRIVATE_INTERFACE_ALIAS] = {
"match": {"macaddress": normalized_mac},
"dhcp4": False,
"dhcp6": False,
"accept-ra": False,
"addresses": [private["private_ip_cidr"]],
**({"routes": [
{"to": destination, "scope": "link"}
for destination in routes
]} if routes else {}),
}
# Rotate the datasource identity so both add and remove operations are
# consumed on the next boot. Credentials remain opaque bytes.
metadata["instance-id"] = f"virt-cloud-private-{uuid.uuid4().hex}"
metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE
network_data = json.dumps(config, ensure_ascii=True).encode("ascii") + b"\n"
return _build_seed_iso((
("/USERDATA.;1", "user-data", "/user-data", user_data),
("/METADATA.;1", "meta-data", "/meta-data",
_encode_seed_metadata(metadata)),
("/NETWORK.;1", "network-config", "/network-config", network_data),
))
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
raise ValueError("原 cloud-init 网络配置格式无效") from exc
def _read_seed_files(seed: bytes) -> dict[str, bytes]:
"""Read the three bounded files from a panel-generated NoCloud seed."""
if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024:
@ -1101,6 +1215,7 @@ def read_seed_network(seed: bytes) -> dict[str, Any]:
result.update({
"private_ip_cidr": parsed["private_ip_cidr"],
"private_mac": parsed["private_mac"],
"private_routes": list(parsed.get("private_routes", [])),
"roles": list(parsed["roles"]),
})
return result

File diff suppressed because it is too large Load Diff

@ -362,7 +362,7 @@ class EngineApplication:
# VPC desired state has an independent model and per-VPC locks. It is
# deliberately separate from FabricCoordinator and the public
# VM/network_change operation state machine.
self.vpc = VpcCoordinator(store, self.fabric)
self.vpc = VpcCoordinator(store, self.fabric, self.registry)
self.introspection = introspection
project_dir = Path(config.get("project_dir", Path(__file__).resolve().parents[2]))
self.updater = updater or Updater(
@ -3342,9 +3342,9 @@ class EngineApplication:
await asyncio.to_thread(self.fabric.recover)
self.fabric_reconcile_task = asyncio.create_task(
self.fabric.reconcile_loop())
# At this phase VPC reconciliation only refreshes the
# Fabric gate and durable observed state. It has no
# private NIC, route or nftables side effects.
# VPC reconciliation applies the private data plane only
# after the Fabric gate is active, and records durable
# observed state for the all-host lifecycle gate.
await asyncio.to_thread(self.vpc.recover)
self.vpc_reconcile_task = asyncio.create_task(
self.vpc.reconcile_loop())

@ -22,14 +22,15 @@ import xml.etree.ElementTree as ET
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Iterator
from typing import Any, Callable, Iterator, Sequence
import libvirt
from virsh_panel.cloud_init import (
_validate_guest_auth, _validate_ssh_public_key,
build_seed_iso, default_guest_hostname, read_seed_network,
replace_seed_network, replace_seed_settings, validate_cloud_network,
replace_seed_network, replace_seed_private_network, replace_seed_settings,
validate_cloud_network,
validate_private_network,
validate_guest_hostname,
)
@ -1485,6 +1486,379 @@ class VMService:
root = self._vm_xml(domain)
return observe_private_state(root, vm_uuid=domain.UUIDString())
def read_private_domain_xml(self, uuid: str) -> str:
"""Return the persistent domain XML used by the VPC readback lane.
The VPC coordinator must compare the definition that will be used on
the next boot, rather than trusting a live QEMU XML response that can
lag a config-only update. A persistent domain is required; callers
that need the live definition can use ``read_private_domain_pair``.
"""
vm_uuid = self._uuid(uuid)
with self._connect() as conn:
domain = self._domain(conn, vm_uuid)
if not domain.isPersistent():
raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409,
error_code="vpc_vm_not_persistent")
return domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
def read_private_domain_pair(self, uuid: str) -> dict[str, str | None]:
"""Read persistent and live XML for an exact private NIC proof."""
vm_uuid = self._uuid(uuid)
with self._connect() as conn:
domain = self._domain(conn, vm_uuid)
if not domain.isPersistent():
raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409,
error_code="vpc_vm_not_persistent")
inactive = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
live = domain.XMLDesc(0) if domain.isActive() else None
return {"inactive": inactive, "live": live}
@staticmethod
def _private_interface_from_root(root: ET.Element) -> ET.Element | None:
try:
return select_private_interface(root.findall("./devices/interface"))
except ValueError as exc:
raise VMError("虚拟机网卡角色不明确,已停止私网接入", 409,
error_code="vpc_private_xml_role_invalid") from exc
def ensure_private_interface(
self,
vm_id: str,
*,
member: Any,
resources: Any,
vpc_id: str,
desired_revision: int,
desired_digest: str,
private_routes: Sequence[str] | None = None,
) -> dict[str, Any]:
"""Attach one panel-owned ``private0`` NIC and refresh its seed.
The operation is intentionally a single libvirt/seed transaction. A
running domain uses ``attach/updateDeviceFlags`` for live and config
state; a stopped domain is updated through ``defineXML``. On any
confirmed failure the original XML and seed are restored. If a live
libvirt response is lost, the method raises an ``uncertain`` error and
leaves reconciliation to the VPC readback lane instead of guessing.
"""
from .vpc_dataplane import VpcDataplaneError, patch_private_interface_xml
vm_uuid = self._uuid(vm_id)
if not isinstance(vpc_id, str) or not vpc_id:
raise VMError("VPC 标识无效", 422, error_code="vpc_invalid")
if (isinstance(desired_revision, bool)
or not isinstance(desired_revision, int)
or desired_revision < 1):
raise VMError("VPC revision 无效", 422, error_code="vpc_invalid")
if (not isinstance(desired_digest, str)
or not re.fullmatch(r"[0-9a-f]{64}", desired_digest)):
raise VMError("VPC 摘要无效", 422, error_code="vpc_invalid")
with _CREATE_LOCK, self._connect() as conn:
domain = self._domain(conn, vm_uuid)
if not domain.isPersistent():
raise VMError("VPC 私网网卡只能接入持久化虚拟机", 409,
error_code="vpc_vm_not_persistent")
if getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0):
raise VMError("虚拟机存在托管保存状态,请先处理后再接入私网", 409,
error_code="vpc_vm_managed_save_present")
try:
if int(getattr(domain, "snapshotNum", lambda _flags: 0)(0)) > 0:
raise VMError("虚拟机存在原生快照,请先处理后再接入私网", 409,
error_code="vpc_vm_native_snapshot_present")
except (TypeError, ValueError) as exc:
raise VMError("无法确认虚拟机原生快照状态", 502,
error_code="vpc_vm_native_snapshot_state_unknown") from exc
old_inactive_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
old_root = ET.fromstring(old_inactive_xml)
private_before = self._private_interface_from_root(old_root)
# A NIC owned by another VPC is never replaced implicitly. This
# also prevents a stale desired revision from hijacking a tenant
# interface after a VPC membership move.
if private_before is not None:
metadata = old_root.find(f"./metadata/{{{PANEL_NS}}}managed")
owner_vpc = metadata.get("private-vpc-id") if metadata is not None else None
if owner_vpc not in (None, vpc_id):
raise VMError("虚拟机 private0 已属于另一 VPC", 409,
error_code="vpc_private_interface_conflict")
try:
new_xml = patch_private_interface_xml(
old_inactive_xml, member=member, resources=resources,
vpc_id=vpc_id, desired_revision=desired_revision,
desired_digest=desired_digest)
except VpcDataplaneError as exc:
raise VMError(str(exc), exc.status, exc.error_code) from exc
new_root = ET.fromstring(new_xml)
target_private = self._private_interface_from_root(new_root)
if target_private is None:
raise VMError("无法生成 private0 网卡", 502,
error_code="vpc_private_xml_invalid")
was_running = bool(domain.isActive())
live_mutator = None
if was_running:
live_mutator = (getattr(domain, "attachDeviceFlags", None)
if private_before is None
else getattr(domain, "updateDeviceFlags", None))
if not callable(live_mutator):
raise VMError(
"运行中的虚拟机不支持安全添加或更新 private0", 409,
error_code="vpc_private_live_unsupported")
seed = self._owned_seed_volume(conn, domain)
if seed is None:
raise VMError("找不到 cloud-init 配置盘,无法接入私网", 409,
error_code="vpc_seed_missing")
old_seed = self._download_seed_volume(conn, seed)
try:
seed_network = read_seed_network(old_seed)
except (ImportError, ValueError) as exc:
raise VMError("原 cloud-init 配置盘格式无效,无法接入私网", 409,
error_code="vpc_seed_invalid") from exc
public = select_public_interface(old_root.findall("./devices/interface"))
public_mac = public.find("mac") if public is not None else None
managed = old_root.find(f"./metadata/{{{PANEL_NS}}}managed")
public_ip = managed.get("public-ip-cidr") if managed is not None else None
if (public_mac is None or not public_mac.get("address")
or seed_network.get("mac") != public_mac.get("address", "").lower()
or (public_ip and seed_network.get("public_ip_cidr") != public_ip)):
raise VMError("虚拟机公网 XML 与 cloud-init 配置盘不一致", 409,
error_code="vpc_seed_network_mismatch")
private_mac = target_private.find("mac")
private_ip_node = new_root.find(f"./metadata/{{{PANEL_NS}}}managed")
private_ip = (private_ip_node.get("private-ip-cidr")
if private_ip_node is not None else None)
if private_mac is None or not private_ip:
raise VMError("私网网卡身份不完整", 502,
error_code="vpc_private_xml_invalid")
try:
replacement_seed = replace_seed_private_network(
old_seed, private_mac=private_mac.get("address"),
private_ip_cidr=private_ip,
private_routes=list(private_routes or ()))
seed_check = read_seed_network(replacement_seed)
expected_seed_routes = sorted(set(private_routes or ()))
if sorted(seed_check.get("private_routes", [])) != expected_seed_routes:
raise VMError("私网 cloud-init 路由回读不一致", 502,
error_code="vpc_seed_route_readback_mismatch")
except (ImportError, ValueError) as exc:
raise VMError("无法生成私网 cloud-init 配置", 409,
error_code="vpc_seed_update_failed") from exc
switched_config = False
switched_live = False
seed_touched = False
config_attempted = False
live_attempted = False
result_uncertain = False
committed = False
try:
current_capacity = int(seed.info()[1])
if len(replacement_seed) > current_capacity:
seed.resize(len(replacement_seed), 0)
# Mark the seed dirty before the stream starts. A transport
# error can occur after a partial write, so setting this only
# after _upload_volume returns would skip the rollback.
seed_touched = True
self._upload_volume(conn, seed, iter((replacement_seed,)),
len(replacement_seed))
# Device APIs cannot update domain-level ownership metadata.
# Always persist the complete XML first, then alter only the
# live device when QEMU is running.
config_attempted = True
defined = conn.defineXML(new_xml)
if defined is None:
raise VMError("宿主机未能保存 private0 配置", 502,
error_code="vpc_private_define_failed")
switched_config = True
if was_running:
target_xml = ET.tostring(target_private, encoding="unicode")
live_attempted = True
live_mutator(target_xml, libvirt.VIR_DOMAIN_AFFECT_LIVE)
switched_live = True
pair = self.read_private_domain_pair(vm_uuid)
inactive_after = ET.fromstring(pair["inactive"] or "")
observed_private = self._private_interface_from_root(inactive_after)
observed_meta = inactive_after.find(f"./metadata/{{{PANEL_NS}}}managed")
observed_mac = observed_private.find("mac") if observed_private is not None else None
if (observed_private is None or observed_mac is None
or observed_mac.get("address", "").lower() != private_mac.get("address", "").lower()
or observed_meta is None
or observed_meta.get("private-vpc-id") != vpc_id
or observed_meta.get("private-network-revision") != str(desired_revision)
or observed_meta.get("private-network-digest") != desired_digest):
raise VMError("private0 配置回读不一致", 502,
error_code="vpc_private_xml_readback_mismatch")
if was_running:
live_after = ET.fromstring(pair["live"] or "")
live_private = self._private_interface_from_root(live_after)
live_source = (live_private.find("source")
if live_private is not None else None)
live_mac = (live_private.find("mac")
if live_private is not None else None)
if (live_private is None or live_source is None
or live_source.get("bridge") != resources.bridge
or live_mac is None
or live_mac.get("address", "").lower()
!= private_mac.get("address", "").lower()
or live_private.findall("filterref")):
raise VMError("private0 实时配置回读不一致", 502,
error_code="vpc_private_live_readback_mismatch")
committed = True
return {"xml": pair["inactive"], "live": pair["live"],
"seed_updated": True, "readback": "confirmed"}
except VMError as exc:
# Once a persistent definition or live device mutation has
# been attempted on a running domain, even a typed readback
# error cannot prove that the old state is still present.
# Keep the operation uncertain so the VPC reconciler performs
# a fresh pair read instead of reporting a plain apply error
# or issuing a speculative inverse live mutation.
if (was_running and (config_attempted or live_attempted)
and not result_uncertain):
result_uncertain = True
raise VMError(
"私网网卡应用结果不确定,请等待宿主机回读", 502,
error_code="vpc_private_result_uncertain") from exc
raise
except Exception as exc:
# A live libvirt response can be lost after the device was
# committed. Do not issue a speculative inverse operation in
# that case; the host adapter will mark the VPC uncertain.
if config_attempted or live_attempted:
result_uncertain = True
raise VMError("私网网卡应用结果不确定,请等待宿主机回读", 502,
error_code="vpc_private_result_uncertain") from exc
raise VMError("私网网卡应用失败", 502,
error_code="vpc_private_apply_failed") from exc
finally:
# For stopped domains, restore both XML and seed on a
# confirmed failure. Never overwrite a running domain after
# an uncertain live mutation.
# A seed upload performed before a failed define can still be
# restored safely while the old running domain is untouched.
# After a running XML/live mutation, leave the complete scene
# for readback and never guess an inverse operation.
rollback_xml_confirmed = not result_uncertain and not was_running
rollback_seed_confirmed = (
not result_uncertain
and (not was_running or not config_attempted and not live_attempted)
)
if seed_touched and not committed and (rollback_xml_confirmed or rollback_seed_confirmed):
try:
# If defineXML committed, restore the original
# persistent definition before restoring the seed.
if switched_config and rollback_xml_confirmed:
conn.defineXML(old_inactive_xml)
if rollback_seed_confirmed:
if len(old_seed) > int(seed.info()[1]):
seed.resize(len(old_seed), 0)
self._upload_volume(conn, seed, iter((old_seed,)), len(old_seed))
except Exception:
LOG.exception("Could not restore VPC seed for %s", vm_uuid)
def remove_private_interface(
self, vm_id: str, *, vpc_id: str, resources: Any,
desired_revision: int, desired_digest: str,
) -> dict[str, Any]:
"""Detach a private0 NIC only when its panel VPC ownership matches."""
vm_uuid = self._uuid(vm_id)
with _CREATE_LOCK, self._connect() as conn:
domain = self._domain(conn, vm_uuid)
if not domain.isPersistent() or getattr(domain, "hasManagedSaveImage", lambda _flags: 0)(0):
raise VMError("虚拟机状态不允许移除 private0", 409,
error_code="vpc_private_remove_unsafe")
if int(getattr(domain, "snapshotNum", lambda _flags: 0)(0)) > 0:
raise VMError("虚拟机存在原生快照,无法移除 private0", 409,
error_code="vpc_private_remove_unsafe")
if domain.isActive():
raise VMError("运行中的虚拟机需先停机再移除 private0", 409,
error_code="vpc_private_remove_requires_stopped")
old_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
root = ET.fromstring(old_xml)
private = self._private_interface_from_root(root)
managed = root.find(f"./metadata/{{{PANEL_NS}}}managed")
if private is None:
return {"removed": True, "already_absent": True,
"xml": old_xml, "readback": "confirmed"}
if managed is None or managed.get("private-vpc-id") != vpc_id:
raise VMError("private0 不属于目标 VPC", 409,
error_code="vpc_private_interface_conflict")
devices = root.find("./devices")
if devices is None:
raise VMError("虚拟机 XML 缺少 devices", 409,
error_code="vpc_private_xml_invalid")
devices.remove(private)
# Clear only private ownership fields; public metadata remains.
for key in ("private-vpc-id", "private-member-id", "private-ip-cidr",
"private-network-bridge", "private-network-verified",
"private-dataplane-owner", "private-network-revision",
"private-network-digest"):
managed.attrib.pop(key, None)
seed = self._owned_seed_volume(conn, domain)
if seed is None:
raise VMError("找不到 cloud-init 配置盘,无法移除私网", 409,
error_code="vpc_seed_missing")
old_seed = self._download_seed_volume(conn, seed)
replacement = replace_seed_private_network(
old_seed, private_mac=None, private_ip_cidr=None)
define_attempted = False
defined = False
seed_touched = False
committed = False
try:
define_attempted = True
defined_domain = conn.defineXML(ET.tostring(root, encoding="unicode"))
if defined_domain is None:
raise VMError("宿主机未能移除 private0", 502,
error_code="vpc_private_remove_failed")
defined = True
if len(replacement) > int(seed.info()[1]):
seed.resize(len(replacement), 0)
seed_touched = True
self._upload_volume(conn, seed, iter((replacement,)), len(replacement))
observed_xml = defined_domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
observed_root = ET.fromstring(observed_xml)
if self._private_interface_from_root(observed_root) is not None:
raise VMError("private0 移除回读不一致", 502,
error_code="vpc_private_remove_readback_mismatch")
observed_seed = read_seed_network(self._download_seed_volume(conn, seed))
if "private_ip_cidr" in observed_seed or "private_mac" in observed_seed:
raise VMError("私网配置盘移除回读不一致", 502,
error_code="vpc_seed_remove_readback_mismatch")
committed = True
return {"removed": True, "already_absent": False,
"xml": observed_xml, "readback": "confirmed"}
except VMError:
raise
except Exception as exc:
# A lost define/upload response must be reconciled from the
# host. Do not blindly re-attach a live or unknown device.
if define_attempted:
raise VMError("私网移除结果不确定,请等待宿主机回读", 502,
error_code="vpc_private_remove_uncertain") from exc
raise VMError("宿主机未能移除 private0", 502,
error_code="vpc_private_remove_failed") from exc
finally:
if not committed and defined:
try:
# The domain is stopped, so restoring the persistent
# XML and seed is a confirmed, safe inverse operation.
conn.defineXML(old_xml)
if seed_touched:
if len(old_seed) > int(seed.info()[1]):
seed.resize(len(old_seed), 0)
self._upload_volume(conn, seed, iter((old_seed,)), len(old_seed))
except Exception as rollback_exc:
LOG.exception("Could not roll back VPC private removal for %s", vm_uuid)
raise VMError(
"私网移除回滚失败,请等待宿主机核对", 502,
error_code="vpc_private_remove_rollback_failed") from rollback_exc
def get_vm_state(self, uuid: str) -> dict[str, Any]:
"""Fetch one domain's power state without loading its XML metadata."""
with self._connect() as conn:

@ -41,7 +41,7 @@ _IFACE_NAME = re.compile(r"[A-Za-z0-9_.:-]{1,15}\Z")
PUBLIC_POOL_KEY = re.compile(r"[0-9a-f]{32}\Z")
PUBLIC_POOL_STATES = frozenset({"active", "draining", "disabled"})
MAX_PUBLIC_NETWORK_POOLS = 32
HOST_CAPABILITY_SCHEMA_VERSION = 1
HOST_CAPABILITY_SCHEMA_VERSION = 2
WG_FABRIC_INTERFACE = "wg-fabric0"
WG_FABRIC_OWNERSHIP_MARKER = "virt-cloud-wg-fabric-v1"
_MAX_CAPABILITY_OUTPUT = 262144
@ -185,6 +185,8 @@ probe_service_enabled() {
probe_service_enabled network_manager NetworkManager
probe_service_enabled networkd systemd-networkd
probe_service_enabled networking networking
probe_service_enabled firewall firewalld
probe_service_enabled nftables nftables
# ifupdown ownership is represented by bounded facts only. The contents of
# interfaces files can include addresses, credentials, and arbitrary hooks;
@ -204,6 +206,15 @@ if test -d /etc/network/interfaces.d; then
done
fi
printf "%s\n" "__VCAP_FILE__interfaces_d=$interfaces_d_configured"
interfaces_d_loaded=absent
if test -f /etc/network/interfaces &&
/usr/bin/grep -Eq "^[[:space:]]*(source|source-directory)[[:space:]]+/etc/network/interfaces[.]d" /etc/network/interfaces 2>/dev/null; then
interfaces_d_loaded=present
elif test -f /etc/network/interfaces &&
/bin/grep -Eq "^[[:space:]]*(source|source-directory)[[:space:]]+/etc/network/interfaces[.]d" /etc/network/interfaces 2>/dev/null; then
interfaces_d_loaded=present
fi
printf "%s\n" "__VCAP_FILE__interfaces_d_loaded=$interfaces_d_loaded"
# A disabled manager can still take over on the next restart when it has
# persistent profiles. Return presence markers only; profile contents may
@ -999,7 +1010,10 @@ def parse_host_capabilities(
)
ifupdown_configured = (
files.get("interfaces") == "present"
or files.get("interfaces_d") == "present"
and (
files.get("interfaces_d") != "present"
or files.get("interfaces_d_loaded") == "present"
)
)
ifupdown_service_ready = networking_active or networking_enabled
# A configured interfaces file is ownership evidence even when the
@ -1064,9 +1078,16 @@ def parse_host_capabilities(
else:
network_deployment_mode = "unsupported"
firewalld_active = services.get("firewall") == "active"
nftables_active = services.get("nftables") == "active"
firewalld_enabled = service_enabled.get("firewall") in manager_enabled_states
nftables_enabled = service_enabled.get("nftables") in manager_enabled_states
firewall_managers = {
"firewalld": services.get("firewall") == "active",
"nftables": services.get("nftables") == "active",
# An enabled-but-currently-inactive service can take ownership after
# a reboot. Treat it as ownership evidence so Fabric never installs
# nft rules beside a firewalld instance that will start later.
"firewalld": firewalld_active or firewalld_enabled,
"nftables": nftables_active or nftables_enabled,
}
active_firewall_managers = [name for name, active in firewall_managers.items() if active]
if len(active_firewall_managers) == 1:
@ -1110,8 +1131,13 @@ def parse_host_capabilities(
# and own a dedicated private ACL table, then read it back before marking
# a VPC revision active. An unknown or unmanaged firewall is rejected so
# that the private policy cannot silently drift into a different owner.
nft_ready = bool(tool_state["nft"]["available"] and nft_readable
and firewall_manager == "nftables")
nft_ready = bool(
tool_state["nft"]["available"]
and nft_readable
and firewall_manager == "nftables"
and nftables_active
and nftables_enabled
)
forwarding_ready = ip_forward == 1
selector = public_network if isinstance(public_network, str) else ""
if selector.startswith("bridge:"):
@ -1177,6 +1203,10 @@ def parse_host_capabilities(
reasons.append("nftables_probe_failed")
if firewall_manager != "nftables":
reasons.append("firewall_owner_not_nftables")
elif not nftables_active:
reasons.append("nftables_service_not_active")
elif not nftables_enabled:
reasons.append("nftables_service_not_enabled")
if not forwarding_ready:
reasons.append("ipv4_forwarding_disabled_or_unknown")
if not rp_filter_ready:
@ -1206,6 +1236,9 @@ def parse_host_capabilities(
reasons.append("ifupdown_tools_missing")
if not ifupdown_configured:
reasons.append("ifupdown_configuration_missing")
elif (files.get("interfaces_d") == "present"
and files.get("interfaces_d_loaded") != "present"):
reasons.append("ifupdown_interfaces_d_not_included")
if not ifupdown_service_ready:
reasons.append("ifupdown_service_not_active_or_enabled")
elif network_manager not in {"ifupdown", "conflict", "unknown"}:
@ -1234,13 +1267,15 @@ def parse_host_capabilities(
"capability_probe_invalid", "unsupported_host_os", "wireguard_tool_missing",
"wireguard_kernel_unavailable", "iproute2_missing", "nftables_tool_missing",
"nftables_probe_failed", "firewall_owner_not_nftables",
"nftables_service_not_active", "nftables_service_not_enabled",
"iproute2_probe_failed", "flock_missing",
"ipv4_forwarding_disabled_or_unknown", "rp_filter_not_compatible",
"network_manager_conflict", "wireguard_fabric_interface_conflict",
"network_manager_unknown", "network_manager_policy_mismatch",
"systemd_networkd_not_supported", "networkmanager_nmcli_missing",
"networkmanager_service_not_active", "networkmanager_service_not_enabled",
"ifupdown_tools_missing", "ifupdown_configuration_missing",
"ifupdown_tools_missing", "ifupdown_configuration_missing",
"ifupdown_interfaces_d_not_included",
"ifupdown_service_not_active_or_enabled",
))
vpc_ready = private_ready and public_verified
@ -1281,6 +1316,7 @@ def parse_host_capabilities(
"ifupdown": {
"interfaces_file": files.get("interfaces") == "present",
"interfaces_d": files.get("interfaces_d") == "present",
"interfaces_d_loaded": files.get("interfaces_d_loaded") == "present",
"configured": ifupdown_configured,
"tools_available": ifupdown_tools_available,
"service_active": networking_active,
@ -1292,6 +1328,12 @@ def parse_host_capabilities(
},
"deployment_mode": network_deployment_mode,
"firewall_manager": firewall_manager,
"firewall_manager_evidence": {
"firewalld_active": firewalld_active,
"firewalld_enabled": firewalld_enabled,
"nftables_active": nftables_active,
"nftables_enabled": nftables_enabled,
},
"ip_probe_valid": ip_probe_valid,
"bridges": bridge_names,
"interfaces": all_interfaces,
@ -1322,6 +1364,10 @@ def parse_host_capabilities(
"tool_available": bool(tool_state["nft"]["available"]),
"ruleset_readable": nft_readable,
"owner": firewall_manager,
"service": services.get("nftables", "unknown"),
"service_enabled": service_enabled.get("nftables", "unknown"),
"service_active": nftables_active,
"service_persistent": nftables_enabled,
"ready": nft_ready,
},
"network_roles": {
@ -1882,6 +1928,86 @@ class RemoteHostManager:
for agent in agents:
agent.close()
def reprobe_current_snapshot(self) -> tuple[dict[str, Any], dict[str, Any]]:
"""Return a fresh capability snapshot bound to one SSH generation.
The profile and capability result are returned together while the
manager lock is held. Fabric can therefore not combine capabilities
from a newly committed generation with the SSH path of an older one.
The probe remains read-only and does not update the durable profile.
"""
with self._lock:
generation = self._current_generation()
if generation is None:
raise RemoteHostError(
"请先配置宿主机",
status=409,
error_code="host_not_configured",
)
profile = self.current()
if profile is None:
raise RemoteHostError(
"请先配置宿主机",
status=409,
error_code="host_not_configured",
)
if profile.get("key_locked"):
raise RemoteHostError(
"当前 SSH 私钥已锁定,请先解锁",
status=409,
error_code="host_private_key_locked",
)
ssh_config = generation / "config"
try:
config_info = ssh_config.lstat()
except OSError as exc:
raise RemoteHostError(
"已保存的 SSH 配置损坏", status=500,
) from exc
if (not stat.S_ISREG(config_info.st_mode)
or config_info.st_mode & 0o077):
raise RemoteHostError("已保存的 SSH 配置权限无效", status=500)
probe = self._exec(
[
self.ssh_binary,
"-F",
str(ssh_config),
"-T",
"-o",
"ConnectTimeout=10",
SSH_ALIAS,
_CAPABILITY_PROBE_COMMAND,
],
timeout=22,
)
if probe.returncode != 0:
raise RemoteHostError(
"宿主机能力重新探测失败;请检查 SSH 连接和宿主机状态",
status=502,
error_code="host_capability_probe_failed",
)
capabilities = parse_host_capabilities(
probe.stdout,
public_network=profile.get("default_network", ""),
)
if not capabilities["probe_valid"]:
raise RemoteHostError(
"宿主机能力探针返回无效结果",
status=502,
error_code="host_capability_probe_invalid",
)
return dict(profile), capabilities
def reprobe_current_capabilities(self) -> dict[str, Any]:
"""Read a fresh capability snapshot through the pinned generation."""
_profile, capabilities = self.reprobe_current_snapshot()
return capabilities
# Keep the shorter name available to Fabric callers while retaining the
# explicit name for other host-capability consumers.
def reprobe_current(self) -> dict[str, Any]:
return self.reprobe_current_capabilities()
def current(self) -> dict[str, Any] | None:
generation = self._current_generation()
if generation is None:

@ -9,13 +9,14 @@ to the later data-plane phase.
"""
from __future__ import annotations
import asyncio
import hashlib
import ipaddress
import json
import re
import time
from dataclasses import dataclass
from typing import Any, Mapping
from dataclasses import dataclass, replace
from typing import Any, Mapping, Sequence
from .fabric import FabricError
@ -548,10 +549,19 @@ def parse_vpc_plan(value: Mapping[str, Any]) -> VpcPlan:
_alias(raw, "destination_cidr", "destination",
"VPC route destination"),
"VPC route destination", min_prefix=network.prefixlen, max_prefix=32)
# A route may be an exact member /32; the future data-plane uses the
# same precision for WireGuard AllowedIPs and guest routes.
# The private data plane is an L3 /32 fabric. A wider route would
# become a cryptokey-routing and nftables bypass (and could overlap a
# different tenant), so reject it at the control-plane boundary rather
# than relying on the host adapter to catch it later.
if destination.prefixlen != 32:
raise VpcError("VPC route destination 必须是精确 /32", 409,
"vpc_route_not_exact")
if not destination.subnet_of(network):
raise VpcError("VPC route destination 必须是 VPC 内的网段")
if destination.network_address in {
network.network_address, network.broadcast_address}:
raise VpcError("VPC route destination 不能使用 VPC 保留地址", 409,
"vpc_route_reserved_address")
member_target = raw.get("next_hop_member_id")
host_target = raw.get("next_hop_host_id")
if (member_target is None) == (host_target is None):
@ -674,7 +684,9 @@ def _plan_from_record(value: Mapping[str, Any]) -> VpcPlan:
host_ids: list[str] = []
if isinstance(raw_host_rows, list):
for host in raw_host_rows:
if isinstance(host, Mapping) and isinstance(host.get("host_id"), str):
if (isinstance(host, Mapping)
and host.get("retiring") is not True
and isinstance(host.get("host_id"), str)):
host_ids.append(host["host_id"])
for host_id in members_by_host:
if host_id not in host_ids:
@ -709,9 +721,13 @@ def _plan_from_record(value: Mapping[str, Any]) -> VpcPlan:
class VpcCoordinator:
"""Durable desired/observed VPC state with an independent lock set."""
def __init__(self, store: Any, fabric: Any):
def __init__(self, store: Any, fabric: Any, registry: Any | None = None):
self.store = store
self.fabric = fabric
# The registry is optional for pure control-plane/unit callers. The
# production EngineApplication supplies it so a VPC revision can only
# become active after host bridge/WireGuard/nft and libvirt readback.
self.registry = registry
# Intentionally independent from FabricCoordinator._locks and from
# the VM/public network mutation locks.
self._locks: dict[str, Any] = {}
@ -814,11 +830,392 @@ class VpcCoordinator:
"error_code": error_code,
}
def _fabric_record(self, plan: VpcPlan) -> dict[str, Any]:
"""Load and validate the durable Fabric identity used by the data plane."""
loader = getattr(self.fabric, "_load", None)
raw = loader("fabric_desired", plan.fabric_id) if callable(loader) else None
if not isinstance(raw, Mapping):
raise VpcError("VPC Fabric 记录不可用", 409,
"vpc_fabric_record_unavailable")
try:
fabric_plan = self.fabric._plan_from_record(raw)
except Exception as exc:
raise VpcError("VPC Fabric 记录无效", 500,
"vpc_fabric_record_corrupt") from exc
if (fabric_plan.fabric_id != plan.fabric_id
or fabric_plan.region != plan.region
or fabric_plan.revision != plan.fabric_revision):
raise VpcError("VPC Fabric revision 或地区不匹配", 409,
"vpc_fabric_revision_mismatch")
return dict(raw)
def _validate_dataplane_resources(self, plan: VpcPlan) -> None:
"""Reject deterministic resource collisions before touching a host."""
from .vpc_dataplane import resource_names
current = resource_names(plan.vpc_id)
seen: dict[str, str] = {}
for field in ("bridge", "nft_table", "route_table"):
seen[str(getattr(current, field))] = plan.vpc_id
for priority in (current.rule_priority, current.rule_priority + 1):
seen[f"rule:{priority}"] = plan.vpc_id
for key, raw in self.store.list("vpc_desired").items():
if key == plan.vpc_id:
continue
try:
other = _plan_from_record(json.loads(raw))
except (TypeError, ValueError, VpcError) as exc:
raise VpcError("VPC 资源目录损坏", 500,
"vpc_record_corrupt") from exc
resources = resource_names(other.vpc_id)
for field in ("bridge", "nft_table", "route_table"):
marker = str(getattr(resources, field))
owner = seen.get(marker)
if owner is not None and owner != other.vpc_id:
raise VpcError("VPC 数据面资源发生冲突", 409,
"vpc_dataplane_resource_conflict")
seen[marker] = other.vpc_id
for priority in (resources.rule_priority, resources.rule_priority + 1):
marker = f"rule:{priority}"
owner = seen.get(marker)
if owner is not None and owner != other.vpc_id:
raise VpcError("VPC 数据面资源发生冲突", 409,
"vpc_dataplane_resource_conflict")
seen[marker] = other.vpc_id
def _fabric_peers_for_plan(
self, plan: VpcPlan, fabric_record: Mapping[str, Any],
) -> list[dict[str, Any]]:
"""Build per-peer overlay plus tenant /32 AllowedIPs.
WireGuard has one AllowedIPs list per peer. Every VPC sharing a
Fabric therefore contributes only its exact member /32s to the peer
on the member's host. Duplicate addresses are rejected across VPCs
before a host command is rendered.
"""
from .vpc_dataplane import _key
plans: list[VpcPlan] = [plan]
for key, raw in self.store.list("vpc_desired").items():
if key == plan.vpc_id:
continue
try:
candidate = _plan_from_record(json.loads(raw))
except (TypeError, ValueError, VpcError) as exc:
raise VpcError("VPC 资源目录损坏", 500,
"vpc_record_corrupt") from exc
if (candidate.fabric_id == plan.fabric_id
and candidate.region == plan.region):
plans.append(candidate)
address_owner: dict[str, str] = {}
tenant_by_host: dict[str, set[str]] = {}
for candidate in plans:
for member in candidate.members:
cidr = f"{member.private_ip}/32"
owner = address_owner.get(cidr)
if owner is not None and owner != candidate.vpc_id:
raise VpcError("VPC 私网地址跨 VPC 重复", 409,
"vpc_private_ip_conflict")
address_owner[cidr] = candidate.vpc_id
tenant_by_host.setdefault(member.host_id, set()).add(cidr)
# A custom service route is cryptokey-routed to the host that
# owns its next hop. It must be part of that peer's exact
# AllowedIPs set just like a VM /32; otherwise WireGuard sends it
# to no peer and the Fabric quarantine drops it.
members_by_id = {item.member_id: item for item in candidate.members}
for route in candidate.routes:
target = (members_by_id.get(route.next_hop_member_id)
if route.next_hop_member_id is not None else None)
target_host = target.host_id if target is not None else route.next_hop_host_id
if target_host is None:
raise VpcError("VPC route next hop 缺失", 409,
"vpc_route_next_hop_missing")
cidr = route.destination_cidr
owner = address_owner.get(cidr)
if owner is not None and owner != candidate.vpc_id:
raise VpcError("VPC 路由地址跨 VPC 重复", 409,
"vpc_route_address_conflict")
address_owner[cidr] = candidate.vpc_id
tenant_by_host.setdefault(target_host, set()).add(cidr)
raw_nodes = fabric_record.get("nodes")
raw_keys = fabric_record.get("public_keys")
if not isinstance(raw_nodes, list) or not isinstance(raw_keys, Mapping):
raise VpcError("Fabric peer 记录不完整", 500,
"vpc_fabric_record_corrupt")
peers: list[dict[str, Any]] = []
wanted_hosts = set(plan.host_ids)
for raw in raw_nodes:
if not isinstance(raw, Mapping):
continue
host_id = raw.get("host_id")
if not isinstance(host_id, str) or host_id not in wanted_hosts:
continue
# The caller supplies the local host separately when parsing each
# host plan; keep every other participating host in this list.
public_key = raw_keys.get(host_id)
overlay_ip = raw.get("overlay_ip")
if not isinstance(public_key, str) or not isinstance(overlay_ip, str):
raise VpcError("Fabric peer 记录无效", 500,
"vpc_fabric_record_corrupt")
_key(public_key)
peers.append({
"host_id": host_id,
"public_key": public_key,
"overlay_ip": overlay_ip,
"tenant_allowed_ips": sorted(tenant_by_host.get(host_id, set())),
})
return peers
@staticmethod
def _private_routes(plan: VpcPlan, member: VpcMember) -> list[str]:
destinations = {
f"{other.private_ip}/32" for other in plan.members
if other.private_ip != member.private_ip
}
destinations.update(route.destination_cidr for route in plan.routes)
destinations.discard(f"{member.private_ip}/32")
return sorted(destinations)
@staticmethod
def _observation_error(exc: Exception) -> str:
code = getattr(exc, "error_code", None)
if isinstance(code, str) and re.fullmatch(r"[a-z0-9_]{1,64}", code):
return code
return "vpc_private_dataplane_apply_failed"
def _run_host_dataplane(
self, plan: VpcPlan, host_id: str, component: Any,
profile: Mapping[str, Any], fabric_peers: list[dict[str, Any]],
previous_plan: VpcPlan | None,
retiring_members: Sequence[Mapping[str, Any]] | None = None,
fabric_public_keys: Mapping[str, str] | None = None,
) -> dict[str, Any]:
"""Apply and read back one host synchronously behind the VPC lock."""
from .libvirt_service import VMService
from .vpc_dataplane import (
VpcDataplanePlan, VpcPrivateHostAdapter,
parse_vpc_dataplane_plan, resource_names,
)
if host_id in plan.host_ids:
payload = plan.canonical()
payload["fabric_peers"] = [
peer for peer in fabric_peers
if peer.get("host_id") != host_id
]
trusted_peer_tenant_ips = {
str(peer["host_id"]): tuple(peer.get("tenant_allowed_ips", ()))
for peer in payload["fabric_peers"]
if isinstance(peer, Mapping) and isinstance(peer.get("host_id"), str)
}
authoritative_peer_keys = None
if fabric_public_keys is not None:
authoritative_peer_keys = [
key for peer_host, key in fabric_public_keys.items()
if peer_host != host_id
]
dataplane = parse_vpc_dataplane_plan(
payload, host_id,
trusted_tenant_allowed_ips=trusted_peer_tenant_ips,
fabric_peer_keys=authoritative_peer_keys)
else:
# A retiring host is intentionally absent from the new desired
# plan. Construct a typed empty-local plan directly so the
# removal transaction can validate the deterministic VPC
# resources without reintroducing the old host into Fabric.
dataplane = VpcDataplanePlan(
plan.vpc, host_id, tuple(plan.members), tuple(),
resource_names(plan.vpc_id))
adapter = VpcPrivateHostAdapter(component.manager, profile)
service = VMService(
profile["libvirt_uri"], profile["storage_pool"],
profile["iso_pool"], profile["default_network"],
rescue_iso_pool=profile.get("rescue_iso_pool", ""),
)
old_members: list[VpcMember] = []
if previous_plan is not None:
old_members.extend(
member for member in previous_plan.members
if member.host_id == host_id)
if retiring_members is not None:
for raw in retiring_members:
if not isinstance(raw, Mapping):
continue
try:
private_ip = str(raw.get("private_ip_cidr", "")).removesuffix("/32")
old_members.append(VpcMember(
str(raw["member_id"]), str(raw["instance_uuid"]),
str(raw.get("host_id", host_id)), private_ip,
str(raw.get("subnet_id", "retiring")),
str(raw.get("private_mac", ""))))
except (KeyError, TypeError, ValueError):
raise VpcError("VPC 宿主机清理成员证据无效", 500,
"vpc_retiring_member_invalid")
current_ids = {member.member_id for member in plan.members}
cleanup_plan = previous_plan or plan
seen_old: set[str] = set()
for old_member in old_members:
if old_member.member_id in seen_old:
continue
seen_old.add(old_member.member_id)
if old_member.host_id != host_id:
continue
if old_member.member_id in current_ids:
continue
service.remove_private_interface(
old_member.instance_uuid,
vpc_id=cleanup_plan.vpc_id,
resources=resource_names(cleanup_plan.vpc_id),
desired_revision=cleanup_plan.desired_revision,
desired_digest=cleanup_plan.desired_digest,
)
# A host with no local members is a removal target. Run the
# manager-aware teardown and require its positive absence marker;
# returning a normal empty observation would leave stale bridge,
# route, nft, and peer state behind.
if not dataplane.local_members:
removed = adapter.remove(dataplane)
removed.update({
"vpc_id": plan.vpc_id,
"host_id": host_id,
"desired_revision": plan.desired_revision,
"desired_digest": plan.desired_digest,
"transport_verified": True,
"private_dataplane_verified": True,
"rollback": removed.get("rollback", "none"),
})
return removed
adapter.apply(dataplane)
for member in dataplane.local_members:
service.ensure_private_interface(
member.instance_uuid, member=member,
resources=dataplane.resources, vpc_id=plan.vpc_id,
desired_revision=plan.desired_revision,
desired_digest=plan.desired_digest,
private_routes=self._private_routes(plan, member),
)
xml_by_instance: dict[str, Mapping[str, str | None]] = {}
for member in dataplane.local_members:
pair = service.read_private_domain_pair(member.instance_uuid)
inactive = pair.get("inactive")
if not isinstance(inactive, str):
raise VpcError("私网网卡持久配置回读缺失", 502,
"vpc_private_xml_readback_missing")
live = pair.get("live")
if live is not None and not isinstance(live, str):
raise VpcError("私网网卡实时配置回读无效", 502,
"vpc_private_live_readback_missing")
xml_by_instance[member.instance_uuid] = {
"inactive": inactive, "live": live,
}
observed = adapter.observe(dataplane, xml_by_instance=xml_by_instance)
observed.update({
"vpc_id": plan.vpc_id,
"host_id": host_id,
"desired_revision": plan.desired_revision,
"desired_digest": plan.desired_digest,
"transport_verified": True,
"private_dataplane_verified": observed.get("state") == "active",
"rollback": observed.get("rollback", "none"),
})
return observed
async def _reconcile_dataplane(
self, plan: VpcPlan, record: dict[str, Any], gate: Mapping[str, Any],
previous_plan: VpcPlan | None = None,
) -> None:
"""Apply/read back every participating host; stay closed on failure."""
retiring_ids = {
item.get("host_id") for item in record.get("hosts", [])
if isinstance(item, Mapping)
and item.get("retiring") is True
and isinstance(item.get("host_id"), str)
}
# A Fabric gate is required for normal applies. Retiring hosts still
# need one final SSH pass even when the new VPC has no members and the
# Fabric coordinator has already marked the tenant gate inactive.
if self.registry is None or (
gate.get("active") is not True and not retiring_ids):
self._finish(record, gate)
return
try:
self._validate_dataplane_resources(plan)
fabric_record = self._fabric_record(plan)
full_fabric_plan = self.fabric._plan_from_record(fabric_record)
raw_fabric_keys = fabric_record.get("public_keys")
if not isinstance(raw_fabric_keys, Mapping):
raise VpcError("Fabric 公钥记录不完整", 500,
"vpc_fabric_record_corrupt")
fabric_public_keys = {
node.host_id: raw_fabric_keys.get(node.host_id)
for node in full_fabric_plan.nodes
}
if any(not isinstance(key, str) for key in fabric_public_keys.values()):
raise VpcError("Fabric 公钥记录不完整", 500,
"vpc_fabric_record_corrupt")
fabric_plan = full_fabric_plan
wanted = set(plan.host_ids) | retiring_ids
fabric_plan = replace(
fabric_plan,
nodes=tuple(node for node in fabric_plan.nodes
if node.host_id in wanted),
)
components = await self.fabric._components(fabric_plan)
all_peers = self._fabric_peers_for_plan(plan, fabric_record)
except Exception as exc:
code = self._observation_error(exc)
for host in record.get("hosts", []):
if isinstance(host, dict):
host.update({"state": "uncertain",
"transport_verified": False,
"private_dataplane_verified": False,
"last_error_code": code})
self._finish(record, gate)
return
for host in record.get("hosts", []):
if not isinstance(host, dict):
continue
host_id = host.get("host_id")
if not isinstance(host_id, str) or host_id not in components:
host.update({"state": "uncertain",
"transport_verified": False,
"private_dataplane_verified": False,
"last_error_code": "vpc_host_unavailable"})
continue
component, profile = components[host_id]
try:
observed = await asyncio.to_thread(
self._run_host_dataplane, plan, host_id, component,
profile, all_peers, previous_plan,
host.get("retiring_members", []), fabric_public_keys)
host.update(observed)
host["observed_revision"] = (
plan.desired_revision
if observed.get("state") == "active" else 0)
host["observed_digest"] = (
plan.desired_digest
if observed.get("state") == "active" else None)
host["state"] = observed.get("state", "degraded")
host["last_error_code"] = observed.get("reason_code")
if host.get("retiring") is True:
host["removed"] = observed.get("removed") is True
except Exception as exc:
host.update({"state": "uncertain",
"transport_verified": False,
"private_dataplane_verified": False,
"observed_revision": 0,
"observed_digest": None,
"last_error_code": self._observation_error(exc)})
self._finish(record, gate)
@staticmethod
def _desired_record(plan: VpcPlan, gate: Mapping[str, Any], *, state: str,
observed_revision: int = 0,
observed_digest: str | None = None,
previous_hosts: Mapping[str, Mapping[str, Any]] | None = None,
previous_plan: VpcPlan | None = None,
updated_at: int | None = None) -> dict[str, Any]:
now = int(time.time()) if updated_at is None else updated_at
previous_hosts = previous_hosts or {}
@ -837,16 +1234,21 @@ class VpcCoordinator:
old_digest = _digest(old_digest, "observed_digest")
except VpcError:
old_digest = None
if not isinstance(old_readback, Mapping):
old_readback = {}
safe_readback = {
str(key): value for key, value in old_readback.items()
if isinstance(key, str) and len(key) <= 64
and _safe_scalar(value)
}
if isinstance(old_readback, str) and len(old_readback) <= 128:
safe_readback: Any = old_readback
elif isinstance(old_readback, Mapping):
safe_readback = {
str(key): value for key, value in old_readback.items()
if isinstance(key, str) and len(key) <= 64
and _safe_scalar(value)
}
else:
safe_readback = {}
host_records.append({
"host_id": host.host_id, "member_ids": list(host.member_ids),
"desired_revision": plan.desired_revision,
"vpc_id": plan.vpc_id,
"desired_digest": plan.desired_digest,
"observed_revision": old_revision,
"observed_digest": old_digest,
"state": "applying" if gate.get("active") else "uncertain",
@ -855,8 +1257,61 @@ class VpcCoordinator:
# tenant VPC. Only the future host adapter may set this
# after private0/route/nft/member readback.
"private_dataplane_verified": False,
"removed": bool(old.get("removed", False)) if isinstance(old, Mapping) else False,
"bridge": old.get("bridge") if isinstance(old, Mapping) else None,
"bridge_owner": old.get("bridge_owner") if isinstance(old, Mapping) else None,
"nft_table": old.get("nft_table") if isinstance(old, Mapping) else None,
"anti_spoof": bool(old.get("anti_spoof")) if isinstance(old, Mapping) else False,
"rp_filter": old.get("rp_filter") if isinstance(old, Mapping) else None,
"proxy_arp": old.get("proxy_arp") if isinstance(old, Mapping) else None,
"proxy_arp_pvlan": old.get("proxy_arp_pvlan") if isinstance(old, Mapping) else None,
"proxy_ips": old.get("proxy_ips", []) if isinstance(old, Mapping) else [],
"acl_revision": old.get("acl_revision") if isinstance(old, Mapping) else None,
"rollback": old.get("rollback", "none") if isinstance(old, Mapping) else "none",
"member_nics": old.get("member_nics", []) if isinstance(old, Mapping) else [],
"routes": old.get("routes", []) if isinstance(old, Mapping) else [],
"wg_allowed_ips": old.get("wg_allowed_ips", []) if isinstance(old, Mapping) else [],
"readback": safe_readback,
})
# Keep host tombstones in the durable engine record until the host-side
# removal script returns its typed absence proof. They are excluded
# from the new VPC plan by _plan_from_record(retiring=true), but retain
# the old instance identity so a restart can still remove private0.
current_host_ids = {host.host_id for host in plan.hosts}
if previous_plan is not None:
for old_host in previous_plan.hosts:
if old_host.host_id in current_host_ids:
continue
old_members = [
{"member_id": member.member_id,
"instance_uuid": member.instance_uuid,
"host_id": member.host_id,
"private_ip_cidr": f"{member.private_ip}/32",
"subnet_id": member.subnet_id,
"private_mac": member.private_mac}
for member in previous_plan.members
if member.host_id == old_host.host_id
]
host_records.append({
"host_id": old_host.host_id,
"member_ids": [item["member_id"] for item in old_members],
"vpc_id": plan.vpc_id,
"desired_revision": plan.desired_revision,
"desired_digest": plan.desired_digest,
"observed_revision": 0,
"observed_digest": None,
"state": "deleting",
"transport_verified": bool(gate.get("active")),
"private_dataplane_verified": False,
"retiring": True,
"retiring_members": old_members,
"bridge": None, "bridge_owner": None, "nft_table": None,
"anti_spoof": False, "rp_filter": None,
"proxy_arp": None, "proxy_arp_pvlan": None,
"proxy_ips": [], "acl_revision": None,
"rollback": "none", "member_nics": [], "routes": [],
"wg_allowed_ips": [], "readback": {},
})
return {
"schema_version": VPC_SCHEMA_VERSION,
"vpc_id": plan.vpc_id, "region": plan.region,
@ -930,10 +1385,12 @@ class VpcCoordinator:
if not isinstance(raw, Mapping):
continue
item = {key: raw[key] for key in (
"host_id", "member_ids", "desired_revision",
"host_id", "member_ids", "vpc_id", "desired_revision",
"desired_digest", "bridge", "bridge_owner", "nft_table",
"observed_revision", "observed_digest", "state",
"transport_verified", "private_dataplane_verified",
"last_error_code") if key in raw}
"last_error_code", "removed", "retiring", "anti_spoof", "rp_filter", "acl_revision", "rollback",
"proxy_arp", "proxy_arp_pvlan", "proxy_ips", "member_nics", "routes", "wg_allowed_ips") if key in raw}
readback = raw.get("readback")
if isinstance(readback, Mapping):
item["readback"] = {
@ -941,6 +1398,8 @@ class VpcCoordinator:
if isinstance(key, str) and len(key) <= 64
and _safe_scalar(val)
}
elif isinstance(readback, str) and len(readback) <= 128:
item["readback"] = readback
result["hosts"].append(item)
# PHP's typed VPC service consumes an explicit observed projection and
# keys host evidence by stable host ID. Keep this projection bounded
@ -955,9 +1414,29 @@ class VpcCoordinator:
item: dict[str, Any] = {}
for key in ("state", "observed_revision", "observed_digest",
"transport_verified", "private_dataplane_verified",
"last_error_code"):
"last_error_code", "vpc_id", "host_id",
"desired_revision", "desired_digest", "bridge",
"bridge_owner", "nft_table", "anti_spoof",
"rp_filter", "proxy_arp", "proxy_arp_pvlan", "proxy_ips", "acl_revision", "rollback", "removed", "retiring", "member_nics",
"routes", "wg_allowed_ips", "readback"):
if key in raw:
item[key] = raw[key]
value_item = raw[key]
if key in {"member_nics", "routes", "wg_allowed_ips", "proxy_ips"}:
if isinstance(value_item, (list, tuple)):
if key == "proxy_ips":
item[key] = [str(ip)[:64] for ip in value_item[:4096]
if isinstance(ip, str)]
else:
item[key] = [dict(row) for row in value_item[:4096]
if isinstance(row, Mapping)]
elif key == "readback":
if isinstance(value_item, str) and len(value_item) <= 128:
item[key] = value_item
elif isinstance(value_item, Mapping):
item[key] = {str(k): v for k, v in value_item.items()
if isinstance(k, str) and _safe_scalar(v)}
elif _safe_scalar(value_item):
item[key] = value_item
item["next_stage_allowed"] = (
raw.get("state") == "active"
and raw.get("transport_verified") is True
@ -1107,8 +1586,33 @@ class VpcCoordinator:
and item.get("transport_verified") is True
and item.get("private_dataplane_verified") is True
for item in hosts)
retiring_hosts = [
item for item in hosts if isinstance(item, Mapping)
and item.get("retiring") is True
] if isinstance(hosts, list) else []
live_hosts = [
item for item in hosts if not (isinstance(item, Mapping)
and item.get("retiring") is True)
] if isinstance(hosts, list) else []
all_removed = bool(retiring_hosts) and all(
item.get("state") == "active"
and item.get("removed") is True
and item.get("observed_revision") == desired_revision
and item.get("observed_digest") == desired_digest
and item.get("transport_verified") is True
and item.get("private_dataplane_verified") is True
for item in retiring_hosts)
fabric_active = gate.get("active") is True
if fabric_active and all_observed:
if all_removed and not live_hosts:
# A VPC with no remaining members is a terminal removal proof;
# the Fabric gate may correctly be inactive because there is no
# tenant transport left to activate.
record["state"] = "active"
record["next_stage_allowed"] = True
record["private_dataplane_verified"] = True
record["observed_revision"] = desired_revision
record["observed_digest"] = desired_digest
elif fabric_active and all_observed:
record["state"] = "active"
record["next_stage_allowed"] = True
record["private_dataplane_verified"] = True
@ -1136,6 +1640,7 @@ class VpcCoordinator:
plan = parse_vpc_plan(value)
async with self._lock(plan.vpc_id):
previous = self._load("vpc_desired", plan.vpc_id)
previous_plan: VpcPlan | None = None
old_revision = plan.desired_revision
if previous is not None:
# Validate the durable prior target before accepting a newer
@ -1162,6 +1667,8 @@ class VpcCoordinator:
gate = self._fabric_gate(plan)
record = dict(previous)
self._finish(record, gate)
await self._reconcile_dataplane(
plan, record, gate, previous_plan)
self._save("vpc_desired", plan.vpc_id, record)
self._save_children(record)
return self._public(record)
@ -1209,8 +1716,11 @@ class VpcCoordinator:
observed_revision=previous_observed_revision,
observed_digest=previous_observed_digest,
previous_hosts=previous_hosts,
previous_plan=previous_plan,
)
self._finish(record, gate)
await self._reconcile_dataplane(
plan, record, gate, previous_plan)
self._save("vpc_desired", plan.vpc_id, record)
self._save_children(record)
return self._public(record)
@ -1283,13 +1793,39 @@ class VpcCoordinator:
state = "applying"
observation_error = "vpc_private_dataplane_unverified"
readback = raw.get("readback", {})
if not isinstance(readback, Mapping) or len(readback) > 64:
if isinstance(readback, str) and len(readback) <= 128:
safe_readback: Any = readback
elif isinstance(readback, Mapping) and len(readback) <= 64:
safe_readback = {
str(key): value for key, value in readback.items()
if isinstance(key, str) and len(key) <= 64
and _safe_scalar(value)
}
else:
raise VpcError("VPC readback 无效")
safe_readback = {
str(key): value for key, value in readback.items()
if isinstance(key, str) and len(key) <= 64
and _safe_scalar(value)
}
typed_fields = (
"vpc_id", "host_id", "desired_revision", "desired_digest",
"bridge", "bridge_owner", "nft_table", "anti_spoof",
"rp_filter", "proxy_arp", "proxy_arp_pvlan", "proxy_ips", "acl_revision", "rollback", "removed", "member_nics", "routes",
"wg_allowed_ips",
)
typed = {}
for field in typed_fields:
if field not in raw:
continue
item_value = raw[field]
if field in {"member_nics", "routes", "wg_allowed_ips", "proxy_ips"}:
if isinstance(item_value, (list, tuple)) and len(item_value) <= VPC_MAX_READBACK:
if field == "proxy_ips":
typed[field] = [str(ip)[:64] for ip in item_value
if isinstance(ip, str)]
else:
typed[field] = [dict(row) for row in item_value
if isinstance(row, Mapping)]
elif field == "readback":
continue
elif _safe_scalar(item_value):
typed[field] = item_value
host.update({"state": state,
"observed_revision": observed_revision,
"observed_digest": observed_digest,
@ -1299,8 +1835,9 @@ class VpcCoordinator:
"last_error_code": observation_error
if isinstance(observation_error, str)
and len(observation_error) <= 64 else None})
host.update(typed)
gate = self._fabric_gate(plan)
self._finish(record, gate)
await self._reconcile_dataplane(plan, record, gate, plan)
self._save("vpc_desired", vpc_id, record)
self._save_children(record)
return self._public(record)
@ -1316,7 +1853,10 @@ class VpcCoordinator:
raise VpcError("VPC 计划摘要与持久化记录不一致", 500,
"vpc_record_corrupt")
gate = self._fabric_gate(plan)
self._finish(record, gate)
# Reconcile is the durable retry path after a host response was
# lost or the engine restarted. Refreshing only the Fabric gate
# would leave private0/routes/nft in an unknown state forever.
await self._reconcile_dataplane(plan, record, gate, plan)
self._save("vpc_desired", vpc_id, record)
self._save_children(record)
return self._public(record)

File diff suppressed because it is too large Load Diff

@ -238,6 +238,14 @@ final class CloudEngineClient
'vpc_record_corrupt' => 'VPC 控制面记录损坏,请联系管理员',
'vpc_observation_incomplete' => 'VPC 宿主机回读未完成,正在核对',
'vpc_data_plane_deferred' => 'VPC 私网数据面尚未启用',
'vpc_private_dataplane_unverified' => 'VPC 私网数据面回读未通过,正在核对',
'vpc_private_readback_missing' => 'VPC 私网宿主机回读缺失,正在核对',
'vpc_private_readback_mismatch' => 'VPC 私网宿主机回读不一致,正在核对',
'vpc_private_nic_readback_mismatch' => 'VPC 私网网卡回读不一致,正在核对',
'vpc_private_route_readback_mismatch' => 'VPC 私网路由回读不一致,正在核对',
'vpc_private_wireguard_readback_missing' => 'VPC WireGuard 私网回读缺失,正在核对',
'vpc_private_wireguard_readback_mismatch' => 'VPC WireGuard 私网路由回读不一致,正在核对',
'vpc_private_dataplane_readback_mismatch' => 'VPC 私网数据面回读不一致,正在核对',
'vpc_operation_mismatch' => 'VPC 引擎结果身份不一致,正在核对',
][$value] ?? null;
}

@ -23,8 +23,9 @@ use App\Models\User;
* the public network mutation lane. It stores only typed tenant intent,
* serialises each VPC with its own row lock, and advances observed state only after the engine
* reports an exact desired revision/digest for every participating host.
* Tenant NICs, routes and nftables are data-plane work owned by the engine's
* later VPC phase; a VPC remains unusable while that phase is pending.
* Tenant NICs, routes and nftables are applied by the engine's independent
* VPC dataplane lane; a VPC remains unusable until typed host readback proves
* the requested revision on every participating host.
*/
final class CloudVpcService
{
@ -41,6 +42,10 @@ final class CloudVpcService
private const DIRECTIONS = ['ingress', 'egress'];
private const ACTIONS = ['allow', 'deny'];
private const PROTOCOLS = ['all', 'tcp', 'udp', 'icmp'];
/** Stable private NIC/dataplane contract shared with the engine. */
private const PRIVATE_INTERFACE = 'private0';
private const FABRIC_INTERFACE = 'wg-fabric0';
private const PRIVATE_DATAPLANE_OWNER = 'virt-cloud-vpc-dataplane-v1';
/** Return VPCs visible to an actor without contacting a host. */
public static function listing(array $actor): array
@ -750,8 +755,9 @@ final class CloudVpcService
/**
* Send the latest desired document to the private engine VPC lane. The
* engine rejects it unless the referenced Fabric is active on every host.
* No general VM-job or public-network mutation row is created here.
* engine rejects it unless the referenced Fabric is active on every host,
* then applies/readbacks the private dataplane. No general VM-job or
* public-network mutation row is created here.
*/
public static function reconcile(string $vpcKey, array $actor, bool $allowDeferredRetry = false): array
{
@ -839,6 +845,25 @@ final class CloudVpcService
throw new CloudError('引擎 VPC 结果与操作编号不一致,正在核对', 502);
}
$observed = is_array($result['observed'] ?? null) ? $result['observed'] : $result;
// Some engine versions expose a compact `observed` projection and
// the full typed host readback beside it. Merge the latter into
// the bounded projection before validating; never discard
// member_nics/routes/WireGuard evidence merely because the
// transport envelope used a compact view.
if (is_array($result['hosts'] ?? null)) {
if (!is_array($observed['hosts'] ?? null)) {
$observed['hosts'] = [];
}
foreach ($result['hosts'] as $hostKey => $hostItem) {
if (!is_array($hostItem)) {
continue;
}
$hostKey = (string) ($hostItem['host_id'] ?? $hostKey);
$compact = is_array($observed['hosts'][$hostKey] ?? null)
? $observed['hosts'][$hostKey] : [];
$observed['hosts'][$hostKey] = array_replace($compact, $hostItem);
}
}
if (isset($observed['operation_id'])
&& (string) $observed['operation_id'] !== (string) $operation->operation_id) {
throw new CloudError('引擎 VPC 观测与操作编号不一致,正在核对', 502);
@ -941,6 +966,86 @@ final class CloudVpcService
$hostKey = (string) ($item['host_id'] ?? $key);
$hosts[$hostKey] = $item;
}
// Validate typed tenant dataplane evidence before evaluating the
// all-host gate. Fabric transport alone can only leave this
// independent VPC lane waiting/uncertain.
$expectedMembersByHost = [];
$allExpectedMembers = [];
$expectedDestinations = [];
$desiredRoutes = [];
$desiredContractValid = true;
try {
$desired = self::desiredDocument($vpc);
// The host adapter installs only member /32 routes and the
// explicitly configured VPC routes. The VPC/subnet CIDRs
// themselves are control-plane address ranges, not an
// allowance for a broad host route in the data plane.
foreach (is_array($desired['routes'] ?? null) ? $desired['routes'] : [] as $route) {
if (is_array($route) && isset($route['destination_cidr'])) {
$desiredRoutes[] = $route;
$expectedDestinations[] = (string) $route['destination_cidr'];
}
}
foreach (is_array($desired['members'] ?? null) ? $desired['members'] : [] as $member) {
if (!is_array($member) || !isset($member['member_id'])) {
continue;
}
$memberId = (string) $member['member_id'];
$memberHost = (string) ($member['host_id'] ?? '');
$member['private_mac'] = strtolower((string) ($member['private_mac'] ?? ''));
$expectedMembersByHost[$memberHost][$memberId] = $member;
$allExpectedMembers[$memberId] = $member;
if (isset($member['private_ip_cidr'])) {
$expectedDestinations[] = (string) $member['private_ip_cidr'];
}
}
} catch (\Throwable) {
// A malformed desired ledger is itself a closed gate.
$desiredContractValid = false;
$expectedMembersByHost = [];
$allExpectedMembers = [];
$expectedDestinations = [];
$desiredRoutes = [];
}
$expectedDestinations = array_values(array_unique(array_filter(
$expectedDestinations,
static fn ($value): bool => is_string($value) && $value !== ''
)));
foreach ($hosts as $hostKey => $item) {
if (($item['private_dataplane_verified'] ?? false) !== true) {
continue;
}
$errorCode = $desiredContractValid
? self::validateHostDataplaneEvidence(
$item,
(string) $hostKey,
$expectedMembersByHost[(string) $hostKey] ?? [],
array_values($allExpectedMembers),
$expectedDestinations,
$desiredRoutes,
$vpcKey,
$revision,
$digest
)
: 'vpc_private_readback_mismatch';
if ($errorCode !== null) {
$item['private_dataplane_verified'] = false;
$item['last_error_code'] = $errorCode;
$hosts[$hostKey] = $item;
$observedHosts = is_array($observed['hosts'] ?? null)
? $observed['hosts'] : [];
$observedHosts[$hostKey] = $item;
$observed['hosts'] = $observedHosts;
$observed['private_dataplane_verified'] = false;
} elseif (($item['removed'] ?? false) === true) {
$item['removal_verified'] = true;
$hosts[$hostKey] = $item;
$observedHosts = is_array($observed['hosts'] ?? null)
? $observed['hosts'] : [];
$observedHosts[$hostKey] = $item;
$observed['hosts'] = $observedHosts;
}
}
$required = CloudVpcHostDeployment::where('vpc_id', $vpc->id)
->whereNotIn('state', ['deleted'])
->lockForUpdate()->get()->keyBy(static fn ($row): int => (int) $row->host_id);
@ -992,10 +1097,10 @@ final class CloudVpcService
}
$liveRequired = $required->filter(static fn ($row): bool =>
(string) $row->state !== 'deleting');
// This phase has no private-NIC/route/nft readback. A Fabric or
// host control-plane digest therefore cannot prove that a
// A Fabric or host control-plane digest cannot prove that a
// deleting child/host is gone from the data plane. Keep every
// tombstone closed until that later evidence is introduced.
// tombstone closed until the typed private-NIC/route/nft evidence
// is introduced by the engine.
$pendingChildTombstone = false;
foreach ([
CloudVpcSubnet::class,
@ -1014,6 +1119,8 @@ final class CloudVpcService
(string) $row->state === 'deleting');
$allActive = $globalActive && $liveRequired->count() > 0
&& !$pendingChildTombstone && !$pendingHostTombstone;
$allRemovalProof = true;
$hasRemovalTarget = false;
foreach ($hosts as $hostKey => $_item) {
if (!$required->has((int) $hostKey)) {
$allActive = false;
@ -1044,17 +1151,36 @@ final class CloudVpcService
&& $itemRevision <= $revision
&& $itemRevision === $revision && hash_equals($digest, $itemDigest);
$deleting = (string) $deployment->state === 'deleting';
$removalActive = $deleting
&& ($item['removed'] ?? false) === true
&& ($item['removal_verified'] ?? false) === true
&& ($item['state'] ?? null) === 'active'
&& ($item['transport_verified'] ?? false) === true
&& ($item['private_dataplane_verified'] ?? false) === true
&& $itemRevision === $revision
&& hash_equals($digest, $itemDigest);
if ($deleting) {
$hasRemovalTarget = true;
if (!$removalActive) {
$allRemovalProof = false;
}
}
$deployment->observed_revision = $itemRevision;
$deployment->observed_digest = $itemDigest !== '' ? $itemDigest : null;
// An empty-host target is only a desired control-plane
// document. Without a data-plane removal readback, preserve
// the deleting state even when the Fabric digest is exact.
if (!$deleting) {
if ($removalActive) {
$deployment->state = 'deleted';
$deployment->last_error_code = null;
} elseif (!$deleting) {
$deployment->state = $active ? 'active' : 'degraded';
$deployment->last_error_code = $active ? null : 'vpc_host_observation_mismatch';
} else {
$deployment->last_error_code = 'vpc_host_removal_unverified';
}
$deployment->last_error_code = $active ? null : 'vpc_host_observation_mismatch';
$deployment->updated_at = time();
if ($active) {
if ($active || $removalActive) {
$deployment->last_success_at = time();
} else {
$deployment->last_failure_at = time();
@ -1062,12 +1188,36 @@ final class CloudVpcService
}
$deployment->save();
}
$removalOnlyComplete = $hasRemovalTarget && $allRemovalProof
&& $liveRequired->count() === 0 && !$pendingChildTombstone;
if ($hasRemovalTarget && $allRemovalProof && $liveRequired->count() === 0) {
$observedAt = time();
foreach ([
CloudVpcSubnet::class,
CloudVpcPrivateIp::class,
CloudVpcMember::class,
CloudVpcRoute::class,
CloudVpcAclRule::class,
] as $childModel) {
$childModel::where('vpc_id', $vpc->id)
->where('state', 'deleting')
->update([
'observed_revision' => $revision,
'observed_digest' => $digest,
'state' => 'deleted',
'last_error_code' => null,
'updated_at' => $observedAt,
]);
}
$removalOnlyComplete = true;
}
$operationSucceeded = $allActive || $removalOnlyComplete;
// The engine's current observed contract is host-scoped: an
// active exact digest means the complete typed document for this
// revision was accepted by every participating host. Mirror that
// gate onto live child rows. Deletion tombstones intentionally
// remain untouched until the later data-plane readback phase.
// remain untouched until a typed removal readback proves absence.
if ($allActive) {
$observedAt = time();
// Persist a proof marker on each member only after the full
@ -1101,27 +1251,27 @@ final class CloudVpcService
}
$operation->observed_json = json_encode(self::boundedObserved($observed),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$operation->status = $allActive ? 'succeeded'
$operation->status = $operationSucceeded ? 'succeeded'
: ($dataPlaneDeferred ? 'waiting_observed'
: ($terminalGate ? 'failed' : 'uncertain'));
$operation->error_code = $allActive ? null
$operation->error_code = $operationSucceeded ? null
: ($dataPlaneDeferred ? 'vpc_data_plane_deferred'
: ($terminalGate ? $gateError : 'vpc_observation_incomplete'));
$operation->updated_at = time();
$operation->finished_at = ($allActive || $dataPlaneDeferred || $terminalGate)
$operation->finished_at = ($operationSucceeded || $dataPlaneDeferred || $terminalGate)
? time() : null;
$operation->lease_until = 0;
$operation->save();
$vpc->observed_revision = $allActive ? $revision : (int) $vpc->observed_revision;
$vpc->observed_digest = $allActive ? $digest : $vpc->observed_digest;
$vpc->state = $allActive ? 'active' : 'degraded';
$vpc->sync_state = $allActive ? 'applied'
$vpc->observed_revision = $operationSucceeded ? $revision : (int) $vpc->observed_revision;
$vpc->observed_digest = $operationSucceeded ? $digest : $vpc->observed_digest;
$vpc->state = $operationSucceeded ? 'active' : 'degraded';
$vpc->sync_state = $operationSucceeded ? 'applied'
: ($dataPlaneDeferred ? 'waiting' : ($terminalGate ? 'failed' : 'uncertain'));
$vpc->last_error_code = $allActive ? null
$vpc->last_error_code = $operationSucceeded ? null
: ($dataPlaneDeferred ? 'vpc_data_plane_deferred'
: ($terminalGate ? $gateError : 'vpc_observation_incomplete'));
$vpc->last_success_at = $allActive ? time() : (int) $vpc->last_success_at;
$vpc->last_failure_at = $allActive ? (int) $vpc->last_failure_at : time();
$vpc->last_success_at = $operationSucceeded ? time() : (int) $vpc->last_success_at;
$vpc->last_failure_at = $operationSucceeded ? (int) $vpc->last_failure_at : time();
$vpc->updated_at = time();
$vpc->save();
}, 3);
@ -1156,6 +1306,7 @@ final class CloudVpcService
->whereIn('member_id', $members->pluck('id')->map(static fn ($id): int => (int) $id)->all())
->get()->keyBy('member_id');
$memberKeys = [];
$privateMacs = [];
$memberRows = [];
foreach ($members as $row) {
$instance = $instances[(int) $row->instance_id] ?? null;
@ -1174,12 +1325,22 @@ final class CloudVpcService
}
$memberKey = (string) $row->member_key;
$memberKeys[(int) $row->id] = $memberKey;
// The MAC is derived from the immutable VPC/member identities so
// retries, host migration and engine restarts keep the same NIC
// identity. It is locally administered and unicast; no schema
// column is needed and the value remains part of the signed DTO.
$privateMac = self::privateMacForMember((string) $vpc->vpc_key, $memberKey);
if ($privateMac === null || isset($privateMacs[$privateMac])) {
throw new CloudError('VPC 成员私网 MAC 无效,无法生成引擎目标', 409);
}
$privateMacs[$privateMac] = $memberKey;
$memberRows[] = [
'member_id' => $memberKey,
'instance_uuid' => strtolower((string) $instance->uuid),
'host_id' => (string) $row->host_id,
'private_ip_cidr' => (string) $privateIp->private_ip . '/32',
'subnet_id' => $subnetKey,
'private_mac' => $privateMac,
];
}
$hostMembers = [];
@ -1399,13 +1560,28 @@ final class CloudVpcService
'reason_code' => 'vpc_private_expectation_invalid',
];
}
$privateMac = self::privateMacForMember(
(string) $vpc->vpc_key, (string) $member->member_key
);
if ($privateMac === null) {
return [
'required' => true, 'state' => 'uncertain',
'desired_state' => $desiredState,
'vpc_id' => (string) $vpc->vpc_key,
'member_id' => (string) $member->member_key,
'private_ip_cidr' => $validIp ? $member->private_ip . '/32' : null,
'private_mac' => null, 'desired_revision' => max(0, $revision),
'desired_digest' => $validDigest ? $digest : null,
'reason_code' => 'vpc_private_expectation_invalid',
];
}
return [
'required' => true, 'state' => $state,
'desired_state' => $desiredState,
'vpc_id' => (string) $vpc->vpc_key,
'member_id' => (string) $member->member_key,
'private_ip_cidr' => $member->private_ip . '/32',
'private_mac' => null,
'private_mac' => $privateMac,
'desired_revision' => $revision,
'desired_digest' => $digest,
'reason_code' => null,
@ -1436,7 +1612,7 @@ final class CloudVpcService
// target is bound by desired_state, identity, IP, revision and digest;
// removal remains strict because it changes desired_state to removed.
foreach (['required', 'desired_state', 'vpc_id', 'member_id',
'private_ip_cidr', 'desired_revision', 'desired_digest'] as $key) {
'private_ip_cidr', 'private_mac', 'desired_revision', 'desired_digest'] as $key) {
if ((string) ($captured[$key] ?? null) !== (string) ($current[$key] ?? null)) {
return false;
}
@ -1461,7 +1637,7 @@ final class CloudVpcService
'observed_digest' => null, 'readback' => $expectation['required'] ? 'missing' : 'confirmed',
'link_state' => $expectation['required'] ? 'absent' : 'absent',
'private_ip_cidr' => $expectation['private_ip_cidr'] ?? null,
'private_mac' => null,
'private_mac' => $expectation['private_mac'] ?? null,
'reason_code' => $expectation['reason_code']
?? ($expectation['required'] ? 'vpc_private_observation_missing' : null),
'observed_at' => 0,
@ -1580,6 +1756,10 @@ final class CloudVpcService
&& $memberExact && $privateExact;
$base['observed_revision'] = $observedRevision;
$base['observed_digest'] = $observedDigest;
// Keep the stable desired identity in the projection even before
// a host readback is confirmed. The observation validator below
// still requires the engine to echo the exact same MAC.
$base['private_mac'] = $expectation['private_mac'] ?? null;
$base['state'] = $confirmed ? 'active'
: ((string) $member->state === 'degraded'
|| (string) $privateIp->state === 'degraded'
@ -1627,9 +1807,8 @@ final class CloudVpcService
* Validate one engine private_state at a mutation commit boundary.
*
* The engine's XML observation is necessary but not sufficient for an
* attached VPC: the member identity, desired revision and digest must
* also be echoed by a future data-plane reconciler. Until then this
* method intentionally returns an uncertain gate for VPC members.
* attached VPC: the member identity, stable MAC, desired revision and
* digest must be echoed by the VPC data-plane readback.
*/
public static function validatePrivateObservation(
array $expectation, ?array $observation, string $kind
@ -1645,7 +1824,7 @@ final class CloudVpcService
'desired_digest' => $expectation['desired_digest'] ?? null,
'observed_digest' => null, 'readback' => 'missing',
'link_state' => 'absent', 'private_ip_cidr' => null,
'private_mac' => null,
'private_mac' => $expectation['private_mac'] ?? null,
'reason_code' => 'vpc_private_observation_missing',
'observed_at' => time(),
];
@ -1745,11 +1924,17 @@ final class CloudVpcService
$ip = $expectedState === 'removed'
|| (is_string($expectation['private_ip_cidr'])
&& hash_equals((string) $expectation['private_ip_cidr'], (string) $state['private_ip_cidr']));
$mac = $expectedState === 'removed'
|| (is_string($expectation['private_mac'] ?? null)
&& is_string($observation['private_mac'] ?? null)
&& is_string($state['private_mac'] ?? null)
&& hash_equals(strtolower((string) $expectation['private_mac']),
strtolower((string) $state['private_mac'])));
$desired = $expectedState === 'removed'
? in_array($state['state'], ['disabled', 'removed'], true)
: in_array($state['state'], ['active', 'suspended'], true);
$link = $linkExpected === null || $state['link_state'] === $linkExpected;
$ok = $shape && $identity && $revision && $digest && $ip && $desired && $link
$ok = $shape && $identity && $revision && $digest && $ip && $mac && $desired && $link
&& $state['readback'] === 'confirmed';
if (!$ok) {
$state['state'] = $state['state'] === 'degraded' ? 'degraded' : 'uncertain';
@ -2450,7 +2635,12 @@ final class CloudVpcService
}
CloudInput::only($item, ['route_key', 'destination_cidr', 'next_hop_ip', 'metric']);
$key = self::assertKey($item['route_key'] ?? null, '路由');
$destination = self::cidr($item['destination_cidr'] ?? null, 8, 32, '路由目标');
// The host data plane is intentionally routed as exact /32s.
// Accepting a wider prefix here would let a tenant's route
// replace the per-member cryptokey and nft boundary, even though
// the engine later rejects it. Reject it at the PHP boundary so
// the API and engine cannot disagree about a usable target.
$destination = self::cidr($item['destination_cidr'] ?? null, 32, 32, '路由目标');
$next = self::ipv4($item['next_hop_ip'] ?? null, '路由下一跳');
$metric = self::positiveInt($item['metric'] ?? 100, 1, 65535, '路由 metric 无效');
$result[] = ['route_key' => $key, 'destination' => $destination,
@ -2519,6 +2709,401 @@ final class CloudVpcService
&& hash_equals($left, $right);
}
/**
* Derive the stable locally-administered MAC used by one VPC member.
*
* Member keys are scoped to a VPC, so binding both identities prevents a
* key reused in another tenant from receiving the same NIC identity. The
* first octet is forced to unicast/local-administered (02/06/0a/0e
* families) and the remaining bytes are cryptographic hash material.
*/
private static function privateMacForMember(string $vpcKey, string $memberKey): ?string
{
if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1
|| preg_match(self::KEY_PATTERN, $memberKey) !== 1) {
return null;
}
$digest = hash('sha256', 'virt-cloud:vpc-private0:' . $vpcKey . ':' . $memberKey);
$octets = [];
for ($index = 0; $index < 6; $index++) {
$octets[] = hexdec(substr($digest, $index * 2, 2));
}
$octets[0] = ($octets[0] & 0xfc) | 0x02;
return implode(':', array_map(
static fn (int $octet): string => sprintf('%02x', $octet), $octets
));
}
private static function privateBridgeForVpc(string $vpcKey): ?string
{
return preg_match(self::KEY_PATTERN, $vpcKey) === 1
? 'vcv-' . substr(hash('sha256', $vpcKey), 0, 11) : null;
}
private static function privateNftTableForVpc(string $vpcKey): ?string
{
return preg_match(self::KEY_PATTERN, $vpcKey) === 1
? 'virt_cloud_vpc_' . substr(hash('sha256', $vpcKey), 0, 12) : null;
}
private static function privateRouteTableForVpc(string $vpcKey): ?int
{
if (preg_match(self::KEY_PATTERN, $vpcKey) !== 1) {
return null;
}
$digest = hash('sha256', $vpcKey);
return 10000 + (hexdec(substr($digest, 12, 8)) % 10000);
}
/**
* Validate typed host-side private dataplane evidence. Raw command output
* is deliberately ignored: only bounded identity, route, ACL and XML
* readback fields can open the PHP VPC gate.
*
* A null return means the evidence is exact; otherwise the returned code
* is safe to persist as a diagnostic and keeps the host degraded.
*/
private static function validateHostDataplaneEvidence(
array $item,
string $hostId,
array $expectedMembers,
array $allMembers,
array $expectedDestinations,
array $desiredRoutes,
string $vpcKey,
int $revision,
string $digest
): ?string {
// These fields are identity evidence, not optional status hints. A
// compact/legacy host projection must therefore stay closed until a
// full typed readback is supplied by the engine.
if (!array_key_exists('vpc_id', $item)
|| !array_key_exists('host_id', $item)
|| !array_key_exists('desired_revision', $item)
|| !array_key_exists('desired_digest', $item)
|| !array_key_exists('observed_revision', $item)
|| !array_key_exists('observed_digest', $item)
|| (string) $item['vpc_id'] !== $vpcKey
|| !self::digestMatches($digest, (string) $item['desired_digest'])
|| (string) $item['host_id'] !== $hostId
|| (string) ($item['state'] ?? '') !== 'active'
|| (int) $item['desired_revision'] !== $revision
|| (int) $item['observed_revision'] !== $revision
|| !self::digestMatches($digest, (string) $item['observed_digest'])) {
return 'vpc_private_readback_mismatch';
}
// A host removal is a distinct typed proof. It must not be treated
// as an empty successful apply: all panel-owned resources and
// tenant-facing evidence must be absent before a deleting deployment
// can be finalized.
if (($item['removed'] ?? false) === true) {
$readback = $item['readback'] ?? null;
$readbackState = is_string($readback) ? strtolower($readback)
: (is_array($readback)
? strtolower((string) ($readback['state'] ?? $readback['status'] ?? ''))
: '');
foreach (['member_nics', 'routes', 'wg_allowed_ips', 'proxy_ips'] as $field) {
if (!is_array($item[$field] ?? null) || $item[$field] !== []) {
return 'vpc_private_removal_readback_mismatch';
}
}
if ($expectedMembers !== []
|| $readbackState !== 'confirmed'
|| ($item['bridge'] ?? null) !== null
|| ($item['bridge_owner'] ?? null) !== null
|| ($item['nft_table'] ?? null) !== null
|| !in_array((string) ($item['rollback'] ?? ''), ['none', 'ok'], true)) {
return 'vpc_private_removal_readback_mismatch';
}
return null;
}
$bridge = self::privateBridgeForVpc($vpcKey);
$nftTable = self::privateNftTableForVpc($vpcKey);
$routeTable = self::privateRouteTableForVpc($vpcKey);
if ($bridge === null || $nftTable === null
|| $routeTable === null
|| (string) ($item['bridge'] ?? '') !== $bridge
|| (string) ($item['bridge_owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER
|| (string) ($item['nft_table'] ?? '') !== $nftTable
|| ($item['anti_spoof'] ?? false) !== true
|| (int) ($item['rp_filter'] ?? -1) !== 2
|| (int) ($item['proxy_arp'] ?? -1) !== 0
|| (int) ($item['proxy_arp_pvlan'] ?? -1) !== 1
|| (int) ($item['acl_revision'] ?? 0) !== $revision
|| !array_key_exists('rollback', $item)
|| !in_array((string) $item['rollback'], ['none', 'ok'], true)) {
return 'vpc_private_dataplane_unverified';
}
$readback = $item['readback'] ?? null;
$readbackState = is_string($readback) ? strtolower($readback)
: (is_array($readback)
? strtolower((string) ($readback['state'] ?? $readback['status'] ?? ''))
: '');
if ($readbackState !== 'confirmed') {
return 'vpc_private_readback_missing';
}
// The bridge uses routed guest /32s. Generic proxy ARP stays off;
// only exact panel-owned proxy-neighbour entries (with pvlan enabled
// for same-bridge next hops) may answer. A missing or broadened
// proxy set keeps the host degraded.
$proxyIps = $item['proxy_ips'] ?? null;
if (!is_array($proxyIps)) {
return 'vpc_private_proxy_arp_readback_missing';
}
$expectedProxyIps = [];
foreach ($expectedDestinations as $destination) {
if (!is_string($destination)
|| !preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\/32$/D', $destination, $match)
|| filter_var($match[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$expectedProxyIps[] = $match[1];
}
$expectedProxyIps = array_values(array_unique($expectedProxyIps));
sort($expectedProxyIps, SORT_STRING);
$observedProxyIps = [];
foreach ($proxyIps as $proxyIp) {
if (!is_string($proxyIp)
|| filter_var($proxyIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$observedProxyIps[] = $proxyIp;
}
$observedProxyIps = array_values(array_unique($observedProxyIps));
sort($observedProxyIps, SORT_STRING);
if ($observedProxyIps !== $expectedProxyIps) {
return 'vpc_private_proxy_arp_readback_mismatch';
}
$nics = $item['member_nics'] ?? null;
if (!is_array($nics) || count($nics) !== count($expectedMembers)) {
return 'vpc_private_nic_readback_mismatch';
}
$seen = [];
foreach ($nics as $nic) {
if (!is_array($nic)) {
return 'vpc_private_nic_readback_mismatch';
}
$memberId = (string) ($nic['member_id'] ?? '');
if ($memberId === '' || isset($seen[$memberId])
|| !isset($expectedMembers[$memberId])) {
return 'vpc_private_nic_readback_mismatch';
}
$expected = $expectedMembers[$memberId];
$observedMac = strtolower((string) ($nic['private_mac'] ?? ''));
if ((string) ($nic['interface'] ?? '') !== self::PRIVATE_INTERFACE
|| strtolower((string) ($nic['instance_uuid'] ?? ''))
!== strtolower((string) $expected['instance_uuid'])
|| (string) ($nic['private_ip_cidr'] ?? '')
!== (string) $expected['private_ip_cidr']
|| $observedMac !== strtolower((string) $expected['private_mac'])
|| ($nic['xml_verified'] ?? false) !== true) {
return 'vpc_private_nic_readback_mismatch';
}
$seen[$memberId] = true;
}
if (count($seen) !== count($expectedMembers)) {
return 'vpc_private_nic_readback_mismatch';
}
// Routes are checked against the exact host-specific next hop and
// metric. A dataplane readback must never install a default or
// otherwise broad route owned by a different subsystem.
$routes = $item['routes'] ?? null;
if (!is_array($routes)) {
return 'vpc_private_route_readback_missing';
}
$memberById = [];
foreach ($allMembers as $member) {
if (is_array($member) && isset($member['member_id'])) {
$memberById[(string) $member['member_id']] = $member;
}
}
$expectedRouteRows = [];
foreach ($allMembers as $member) {
if (!is_array($member) || !isset($member['private_ip_cidr'])) {
continue;
}
$expectedRouteRows[] = [
'destination_cidr' => (string) $member['private_ip_cidr'],
'device' => (string) (($member['host_id'] ?? '') === $hostId
? $bridge : self::FABRIC_INTERFACE),
'via' => null,
'metric' => 100,
];
}
foreach ($desiredRoutes as $desiredRoute) {
if (!is_array($desiredRoute)
|| !isset($desiredRoute['destination_cidr'])) {
return 'vpc_private_route_readback_mismatch';
}
$nextMemberId = isset($desiredRoute['next_hop_member_id'])
? (string) $desiredRoute['next_hop_member_id'] : '';
$nextMember = $nextMemberId !== ''
? ($memberById[$nextMemberId] ?? null) : null;
$nextHost = is_array($nextMember)
? (string) ($nextMember['host_id'] ?? '')
: (string) ($desiredRoute['next_hop_host_id'] ?? '');
if ($nextHost === '') {
return 'vpc_private_route_readback_mismatch';
}
$expectedRouteRows[] = [
'destination_cidr' => (string) $desiredRoute['destination_cidr'],
'device' => $nextHost === $hostId ? $bridge : self::FABRIC_INTERFACE,
'via' => $nextHost === $hostId && is_array($nextMember)
? (string) preg_replace(
'/\/32$/D', '',
(string) ($nextMember['private_ip']
?? $nextMember['private_ip_cidr'] ?? '')
)
: null,
'metric' => (int) ($desiredRoute['metric'] ?? 100),
];
}
$expectedRouteMap = [];
foreach ($expectedRouteRows as $expectedRoute) {
$via = (string) ($expectedRoute['via'] ?? '');
$key = $expectedRoute['destination_cidr'] . '|'
. $expectedRoute['device'] . '|' . $via . '|'
. (string) $expectedRoute['metric'];
if (isset($expectedRouteMap[$key])) {
return 'vpc_private_route_readback_mismatch';
}
$expectedRouteMap[$key] = true;
}
$seenRoutes = [];
foreach ($routes as $route) {
if (!is_array($route)
|| !is_string($route['destination_cidr'] ?? null)
|| !isset($route['device'])
|| !is_string($route['device'])
|| $route['device'] === ''
|| !array_key_exists('table', $route)
|| !in_array($route['device'], [$bridge, self::FABRIC_INTERFACE], true)
|| (string) ($route['owner'] ?? '') !== self::PRIVATE_DATAPLANE_OWNER) {
return 'vpc_private_route_readback_mismatch';
}
$destination = (string) $route['destination_cidr'];
if (in_array($destination, ['0.0.0.0/0', '::/0'], true)
|| !in_array($destination, $expectedDestinations, true)) {
return 'vpc_private_route_readback_mismatch';
}
$via = $route['via'] ?? null;
if ($via !== null && !is_string($via)) {
return 'vpc_private_route_readback_mismatch';
}
$metric = $route['metric'] ?? null;
if ((is_string($metric) && !ctype_digit($metric))
|| (!is_int($metric) && !is_string($metric))) {
return 'vpc_private_route_readback_mismatch';
}
$metric = (int) $metric;
$key = $destination . '|' . (string) $route['device'] . '|'
. (string) ($via ?? '') . '|' . (string) $metric;
if (isset($seenRoutes[$key])) {
return 'vpc_private_route_readback_mismatch';
}
if (!isset($expectedRouteMap[$key])) {
return 'vpc_private_route_readback_mismatch';
}
$seenRoutes[$key] = true;
if ((!is_int($route['table'])
&& !(is_string($route['table']) && is_numeric($route['table'])))
|| (int) $route['table'] !== $routeTable) {
return 'vpc_private_route_readback_mismatch';
}
}
$expectedRouteSet = array_keys($expectedRouteMap);
$observedRouteSet = array_keys($seenRoutes);
sort($expectedRouteSet, SORT_STRING);
sort($observedRouteSet, SORT_STRING);
if ($observedRouteSet !== $expectedRouteSet) {
return 'vpc_private_route_readback_mismatch';
}
// The engine reports tenant AllowedIPs separately from Fabric overlay
// addresses. Require an exact remote-member /32 set, preventing a
// broad prefix from crossing a host or VPC boundary.
$expectedPeers = [];
foreach ($allMembers as $member) {
if ((string) ($member['host_id'] ?? '') === $hostId) {
continue;
}
$peerHost = (string) ($member['host_id'] ?? '');
$expectedPeers[$peerHost][] = (string) $member['private_ip_cidr'];
}
foreach ($desiredRoutes as $route) {
if (!is_array($route)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$target = null;
if (isset($route['next_hop_member_id'])) {
$target = $memberById[(string) $route['next_hop_member_id']] ?? null;
}
$peerHost = is_array($target)
? (string) ($target['host_id'] ?? '')
: (string) ($route['next_hop_host_id'] ?? '');
if ($peerHost !== '' && $peerHost !== $hostId
&& isset($route['destination_cidr'])) {
$expectedPeers[$peerHost][] = (string) $route['destination_cidr'];
}
}
foreach ($expectedPeers as &$ips) {
$ips = array_values(array_unique($ips));
sort($ips, SORT_STRING);
}
unset($ips);
$wg = $item['wg_allowed_ips'] ?? null;
if (!is_array($wg)) {
return 'vpc_private_wireguard_readback_missing';
}
$seenPeers = [];
foreach ($wg as $peer) {
if (!is_array($peer)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$peerHost = (string) ($peer['peer_host_id'] ?? '');
$tenantIps = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? null;
$publicKey = $peer['public_key'] ?? null;
if ($peerHost === '' || isset($seenPeers[$peerHost])
|| !array_key_exists($peerHost, $expectedPeers)
|| !is_array($tenantIps)
|| !is_string($publicKey)
|| preg_match('/^[A-Za-z0-9+\/]{42}[A-Za-z0-9+\/]==$|^[A-Za-z0-9+\/]{43}=$/D',
$publicKey) !== 1) {
return 'vpc_private_wireguard_readback_mismatch';
}
$decodedKey = base64_decode($publicKey, true);
if ($decodedKey === false || strlen($decodedKey) !== 32
|| trim($decodedKey, "\0") === '') {
return 'vpc_private_wireguard_readback_mismatch';
}
$normalizedIps = [];
foreach ($tenantIps as $ip) {
if (!is_string($ip)) {
return 'vpc_private_wireguard_readback_mismatch';
}
$normalizedIps[] = $ip;
}
$normalizedIps = array_values(array_unique($normalizedIps));
sort($normalizedIps, SORT_STRING);
foreach ($normalizedIps as $ip) {
if (!preg_match('/^[0-9.]+\/32$/D', $ip)) {
return 'vpc_private_wireguard_readback_mismatch';
}
}
if ($normalizedIps !== $expectedPeers[$peerHost]) {
return 'vpc_private_wireguard_readback_mismatch';
}
$seenPeers[$peerHost] = true;
}
if (count($seenPeers) !== count($expectedPeers)) {
return 'vpc_private_wireguard_readback_mismatch';
}
return null;
}
private static function boundedObserved(array $value): array
{
$hosts = [];
@ -2526,7 +3111,14 @@ final class CloudVpcService
if (!is_array($host) || count($hosts) >= 256) {
continue;
}
$hosts[(string) $key] = [
$bounded = [
'host_id' => is_string($host['host_id'] ?? null)
? substr($host['host_id'], 0, 64) : (string) $key,
'vpc_id' => is_string($host['vpc_id'] ?? null)
? substr($host['vpc_id'], 0, 64) : null,
'desired_revision' => max(0, (int) ($host['desired_revision'] ?? 0)),
'desired_digest' => is_string($host['desired_digest'] ?? null)
? substr($host['desired_digest'], 0, 64) : null,
'state' => is_string($host['state'] ?? null) ? substr($host['state'], 0, 16) : 'unknown',
'observed_revision' => max(0, (int) ($host['observed_revision'] ?? $host['revision'] ?? 0)),
'observed_digest' => is_string($host['observed_digest'] ?? $host['digest'] ?? null)
@ -2535,8 +3127,102 @@ final class CloudVpcService
'private_dataplane_verified' => (
($host['private_dataplane_verified'] ?? false) === true
),
'removed' => ($host['removed'] ?? false) === true,
'retiring' => ($host['retiring'] ?? false) === true,
'next_stage_allowed' => ($host['next_stage_allowed'] ?? false) === true,
];
if (is_string($host['last_error_code'] ?? null)) {
$bounded['last_error_code'] = substr($host['last_error_code'], 0, 64);
}
foreach (['bridge', 'bridge_owner', 'nft_table', 'readback', 'rollback'] as $field) {
if (is_string($host[$field] ?? null)) {
$bounded[$field] = substr($host[$field], 0, 128);
}
}
if (isset($host['anti_spoof'])) {
$bounded['anti_spoof'] = $host['anti_spoof'] === true;
}
if (isset($host['acl_revision'])) {
$bounded['acl_revision'] = max(0, (int) $host['acl_revision']);
}
if (isset($host['rp_filter'])) {
$bounded['rp_filter'] = max(0, (int) $host['rp_filter']);
}
if (isset($host['proxy_arp'])) {
$bounded['proxy_arp'] = max(0, (int) $host['proxy_arp']);
}
if (isset($host['proxy_arp_pvlan'])) {
$bounded['proxy_arp_pvlan'] = max(0, (int) $host['proxy_arp_pvlan']);
}
if (is_array($host['proxy_ips'] ?? null)) {
$bounded['proxy_ips'] = array_values(array_slice(array_map(
static fn ($ip): string => substr((string) $ip, 0, 64),
$host['proxy_ips']
), 0, 4096));
}
if (is_array($host['member_nics'] ?? null)) {
$bounded['member_nics'] = [];
foreach (array_slice($host['member_nics'], 0, 4096) as $nic) {
if (!is_array($nic)) {
continue;
}
$bounded['member_nics'][] = [
'member_id' => is_string($nic['member_id'] ?? null)
? substr($nic['member_id'], 0, 64) : null,
'instance_uuid' => is_string($nic['instance_uuid'] ?? null)
? substr($nic['instance_uuid'], 0, 64) : null,
'interface' => is_string($nic['interface'] ?? null)
? substr($nic['interface'], 0, 32) : null,
'private_ip_cidr' => is_string($nic['private_ip_cidr'] ?? null)
? substr($nic['private_ip_cidr'], 0, 64) : null,
'private_mac' => is_string($nic['private_mac'] ?? null)
? substr(strtolower($nic['private_mac']), 0, 32) : null,
'xml_verified' => ($nic['xml_verified'] ?? false) === true,
];
}
}
if (is_array($host['routes'] ?? null)) {
$bounded['routes'] = [];
foreach (array_slice($host['routes'], 0, 256) as $route) {
if (!is_array($route)) {
continue;
}
$bounded['routes'][] = [
'destination_cidr' => is_string($route['destination_cidr'] ?? null)
? substr($route['destination_cidr'], 0, 64) : null,
'device' => is_string($route['device'] ?? null)
? substr($route['device'], 0, 64) : null,
'table' => is_scalar($route['table'] ?? null)
? substr((string) $route['table'], 0, 32) : null,
'owner' => is_string($route['owner'] ?? null)
? substr($route['owner'], 0, 64) : null,
'via' => is_string($route['via'] ?? null)
? substr($route['via'], 0, 64) : null,
'metric' => is_scalar($route['metric'] ?? null)
? substr((string) $route['metric'], 0, 16) : null,
];
}
}
if (is_array($host['wg_allowed_ips'] ?? null)) {
$bounded['wg_allowed_ips'] = [];
foreach (array_slice($host['wg_allowed_ips'], 0, 256) as $peer) {
if (!is_array($peer)) {
continue;
}
$ips = $peer['tenant_allowed_ips'] ?? $peer['allowed_ips'] ?? [];
$bounded['wg_allowed_ips'][] = [
'peer_host_id' => is_string($peer['peer_host_id'] ?? null)
? substr($peer['peer_host_id'], 0, 64) : null,
'public_key' => is_string($peer['public_key'] ?? null)
? substr($peer['public_key'], 0, 64) : null,
'tenant_allowed_ips' => is_array($ips)
? array_values(array_slice(array_map(
static fn ($ip): string => substr((string) $ip, 0, 64), $ips
), 0, 4096)) : [],
];
}
}
$hosts[(string) $key] = $bounded;
}
return ['hosts' => $hosts];
}

@ -19,17 +19,22 @@ final class CloudVpcWorkerService
$candidate = (new CloudVpcOperation())->getConnection()->transaction(
static function (): ?array {
$now = time();
$allowDeferredRetry = false;
$operation = CloudVpcOperation::where(function ($query) use ($now): void {
$query->where(function ($queued) use ($now): void {
$queued->where('status', 'queued')
->where('updated_at', '<=', $now - 2);
})->orWhere(function ($uncertain) use ($now): void {
// Transport ambiguity is retryable. A deliberate
// waiting_observed result is excluded: phase 3
// has no private-NIC/readback lane, so only the
// explicit reconcile API may resume it later.
// Transport ambiguity is retryable.
$uncertain->where('status', 'uncertain')
->where('updated_at', '<=', $now - 30);
})->orWhere(function ($waiting) use ($now): void {
// The Fabric gate may complete before the host
// private0/route/nft readback. Retry this same
// VPC operation on its own lane after a quiet
// period; it never enters network_change.
$waiting->where('status', 'waiting_observed')
->where('updated_at', '<=', $now - 30);
})->orWhere(function ($running) use ($now): void {
$running->where('status', 'running')
->where('lease_until', '<=', $now);
@ -39,6 +44,7 @@ final class CloudVpcWorkerService
if ($operation === null) {
return null;
}
$allowDeferredRetry = (string) $operation->status === 'waiting_observed';
$vpc = CloudVpc::where('id', (int) $operation->vpc_id)->first();
if ($vpc === null) {
$operation->status = 'failed';
@ -48,24 +54,24 @@ final class CloudVpcWorkerService
$operation->save();
return null;
}
return [(string) $vpc->vpc_key, (int) $operation->user_id];
return [(string) $vpc->vpc_key, (int) $operation->user_id,
$allowDeferredRetry];
}, 3
);
if ($candidate === null) {
return false;
}
[$vpcKey, $userId] = $candidate;
[$vpcKey, $userId, $allowDeferredRetry] = $candidate;
$actor = [
'user_id' => $userId, 'is_admin' => false,
'is_super_admin' => false, 'can_manage' => true,
'session_id' => '',
];
try {
CloudVpcService::reconcile($vpcKey, $actor);
CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry);
} catch (CloudError) {
// The service records failed/uncertain status under the operation
// lease. waiting_observed is intentionally not selected again;
// no destructive replay is performed by this worker.
// lease. No public network job is replayed by this worker.
}
return true;
}

@ -1147,7 +1147,7 @@ final class CloudWorkerService
// immutable target. Removal is represented by desired_state and
// therefore remains strict.
foreach (['required', 'desired_state', 'vpc_id', 'member_id',
'private_ip_cidr', 'desired_revision', 'desired_digest'] as $key) {
'private_ip_cidr', 'private_mac', 'desired_revision', 'desired_digest'] as $key) {
$left = $capturedExpectation[$key] ?? null;
$right = $currentExpectation[$key] ?? null;
if ((string) $left !== (string) $right) {

@ -24,6 +24,7 @@ $accountDeletion = $read('app/Services/UserDataDeletionService.php');
$jobService = $read('app/Services/Cloud/CloudJobService.php');
$orderService = $read('app/Services/Cloud/CloudOrderService.php');
$workerService = $read('app/Services/Cloud/CloudWorkerService.php');
$vpcWorkerService = $read('app/Services/Cloud/CloudVpcWorkerService.php');
foreach ([
'cloud_region_fabrics',
@ -105,9 +106,27 @@ $assert(str_contains($service, '$orphanLease')
$assert(str_contains($service, '当前 VPC 控制面不支持子网网关')
&& str_contains($service, "'private_ip_cidr'")
&& str_contains($service, "'next_hop_member_id'")
&& str_contains($service, "self::cidr(\$item['destination_cidr'] ?? null, 32, 32, '路由目标')")
&& str_contains($service, 'VPC 私网地址账本与成员不一致')
&& str_contains($service, 'firstFreeIp($subnet, $privateIps)'),
'VPC service lost no-gateway, /32 member or typed route boundaries.');
$assert(str_contains($service, 'privateMacForMember')
&& str_contains($service, "'private_mac' => \$privateMac")
&& str_contains($service, 'validateHostDataplaneEvidence')
&& str_contains($service, 'member_nics')
&& str_contains($service, 'wg_allowed_ips')
&& str_contains($service, 'privateRouteTableForVpc')
&& str_contains($service, 'expectedRouteSet')
&& str_contains($service, 'desiredContractValid')
&& str_contains($service, "array_key_exists('observed_digest', \$item)")
&& str_contains($service, "base64_decode(\$publicKey, true)")
&& str_contains($service, 'FABRIC_INTERFACE')
&& str_contains($service, 'PRIVATE_DATAPLANE_OWNER'),
'VPC desired DTO or host dataplane readback contract lost stable NIC identity/ACL gates.');
$assert(str_contains($vpcWorkerService, "'waiting_observed'")
&& str_contains($vpcWorkerService, 'allowDeferredRetry')
&& str_contains($vpcWorkerService, 'CloudVpcService::reconcile($vpcKey, $actor, $allowDeferredRetry)'),
'VPC worker must retry waiting_observed through its independent apply lane.');
$assert(str_contains($routes, "'/vpcs'")
&& str_contains($routes, "'/vpcs/{vpc_key:[0-9a-f]{32}}/reconcile'")
@ -136,5 +155,8 @@ $assert(str_contains($workerService, '$hasPrivateState')
&& $privateReadback !== false
&& $legacyPrivateGate < $privateReadback,
'Legacy public-only jobs without private_state must remain compatible while structured observations stay gated.');
$assert(str_contains($workerService, "'private_mac', 'desired_revision'")
&& str_contains($service, "'private_mac', 'desired_revision'"),
'Private MAC must remain part of the immutable lifecycle/VPC target tuple.');
echo "VPC control-plane schema, API, typed DTO and independent operation contracts passed.\n";

Loading…
Cancel
Save