From 5f69df48adc2c9e1ee9899d59778969333eeb64f Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 9 Oct 2026 08:32:12 +0800 Subject: [PATCH] Run Fabric apply as host systemd operations --- docs/FABRIC_HOST_ACCEPTANCE.md | 25 + docs/INTEGRATION_PLAN.md | 34 +- docs/VALIDATION.md | 29 + engine/tests/test_engine_boundary.py | 42 +- engine/tests/test_fabric.py | 1548 ++++++++++++ engine/virsh_panel/fabric.py | 2194 ++++++++++++++++- engine/virsh_panel/internal.py | 13 +- .../CloudAdminFabricController.php | 26 +- .../Cloud/CloudAdminFabricService.php | 218 +- web/app/Services/Cloud/CloudEngineClient.php | 9 + web/public/cloud/admin-fabric.js | 286 ++- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminFabricContractTest.php | 42 +- .../AdminFabricOperationProjectionTest.php | 96 + .../AdminFabricReadinessWorkflowTest.php | 37 +- web/tests/AdminFabricWizardBehaviorTest.mjs | 109 + web/tests/CloudFirewallUiContractTest.php | 2 +- .../CloudHostFabricEndpointContractTest.php | 2 +- 18 files changed, 4619 insertions(+), 95 deletions(-) create mode 100644 web/tests/AdminFabricOperationProjectionTest.php diff --git a/docs/FABRIC_HOST_ACCEPTANCE.md b/docs/FABRIC_HOST_ACCEPTANCE.md index 8413ebed..e26f29dd 100644 --- a/docs/FABRIC_HOST_ACCEPTANCE.md +++ b/docs/FABRIC_HOST_ACCEPTANCE.md @@ -126,6 +126,31 @@ ACL-first helper。后一分支不得 restart 主 Fabric unit 或任何 libvirt 人为让主 helper 持有 Fabric flock,确认 dispatcher 等待期间 apply 不会持锁死锁;让同步 启动失败时,确认 committed journal 仍保留且旧进程不会删除并发新事务的 ready journal。 +## 异步 operation 与安全日志 + +1. 点击“自动配置地区私网”或“重新核对”时,HTTP 应在宿主 apply 完成前返回 + `202`,回执中的 operation ID 必须是 32 位小写十六进制,根记录和全部宿主行必须 + 显示同一 ID。轮询过程不得再出现第二个 POST。 +2. 在宿主机上用回执 ID 查看 + `systemctl status virt-cloud-fabric-apply-.service`(任务仍被 systemd + 保留时)和 `journalctl -u virt-cloud-fabric-apply-.service --no-pager`。 + transient unit 使用 `--collect`,因此终态后 `systemctl status` 可以变成 not-found, + 但 journal 仍必须可按完整 unit 名回查。journal 只得出现 + operation ID、固定 state/checkpoint/reason 与 systemd 生命周期;不得出现私钥、完整脚本、 + peer 全量配置、SSH 路径或原始 stderr。 +3. `/run/virt-cloud/fabric-operations/` 必须为 root:root `0700`,manifest/status + 必须为 `0600`,apply/update/runner 必须为 `0700`;任一符号链接、多余文件、owner/mode/hash + 漂移都必须 fail-closed。达到上限时只能精确删除最旧的已验证终态目录,不得删除 + queued/running/当前 ID 或未知对象。 +4. 分别在“dispatch 已接纳但 SSH 回包丢失”、“operation 目录发布后、systemd-run 前中断”、 + “第一台宿主已接纳、第二台尚未下发”、“Engine 重启”和“页面/CDN 超时”复现。页面 GET + 与周期核对必须只读;显式“重新核对”只能在完整 ID/hash/unit/逐节点 dispatch fence 证据下 + 启动原 queued runner,或在已接纳节点精确收敛后对确定未接纳节点继续同 ID 下发。宿主只能 + 出现一个同 ID 任务,已接纳节点不得重派,也不得生成新 ID;在终态未证明前,新 apply 必须 + 被拒绝、Fabric gate 必须关闭。 +5. 人为卡住宿主 helper 超过 operation 运行上限,systemd 必须终止该 cgroup,状态只记录 + 固定的 interrupted/uncertain 原因,保留 journal/emergency guard 并禁止自动重放。 + ## 失败回滚和安全边界 在隔离环境中分别让 `nft -c/-f`、`firewall-cmd`、`wg`、`ip route`、 diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md index c25a421f..492d1299 100644 --- a/docs/INTEGRATION_PLAN.md +++ b/docs/INTEGRATION_PLAN.md @@ -140,7 +140,30 @@ CAS 激活;VPC pin 漂移或映射缺失会直接进入显式迁移阶段。 再次复读平台拓扑,并在事务中锁定地区和映射;完整的多表 topology generation/CAS 仍是 后续并发强化边界。 -浏览器对结果未知的保护按地区保存在当前页面内;Engine 端以确定性 Fabric ID、revision +浏览器内的“结果未知”只用于当前页面的交互防护,不作为执行账本、不会触发写操作重放。Engine 在接纳 apply/reconcile 时先持久化 +32 位小写十六进制 `operation_id`,以 `202 Accepted` 立即返回;根记录只投影 +`apply|reconcile` 与 `queued|running|succeeded|failed|uncertain|interrupted`,节点只投影 +`identity|observe|apply`、固定 checkpoint 和固定 reason。同一轮所有宿主机共用同一 +operation ID,页面仅轮询 Fabric GET 回读,不会因超时、刷新或第二管理员而重放 POST。 + +Engine 将每台宿主机的精确 apply 脚本、manifest 和状态以 root-only 文件写入 +`/run/virt-cloud/fabric-operations//`,然后通过 +`virt-cloud-fabric-apply-.service` transient systemd oneshot 异步执行。 +SSH 只负责精确 ID 的 dispatch/status 协议;任务 stdout/stderr 不返回面板,journal 只记录 +operation ID、固定 state、checkpoint 和 reason。运行时间有上限,中断保留事务日志与 +emergency guard;远端 operation 目录有严格 owner/mode/hash 校验和有界终态清理,不删除 +queued/running 或无法证明归属的对象。 + +Engine 重启或 dispatch 回包丢失时,页面 GET 与周期 reconcile 只使用原 operation ID +读取宿主状态并做精确 observe,绝不发起宿主写。只有管理员显式“重新核对”可以在严格证据下 +继续同一个 ID:若不可变 operation 目录已发布、status 仍为 queued 且 systemd unit 的 +`LoadState` 被证明为 `not-found`(任何 loaded unit 都不重启),可启动该目录中原 runner; +若部分宿主已经接纳任务,则必须先证明这些宿主 +精确收敛,再对具有持久化“从未 dispatch”证据的其余宿主继续一次同 ID 下发。已接纳宿主绝不 +重派,恢复过程绝不生成新 ID。旧 ID 仍无法终结时,新 apply 必须拒绝。只有所有宿主的计划 +digest/revision/owner 精确回读且传输核验通过,才可设置 `next_stage_allowed=true`。 + +Engine 端仍以确定性 Fabric ID、revision 与 plan digest 拒绝不同计划覆盖,并让 Fabric apply/reconcile 与 VPC apply/delete/reconcile/lifecycle reconcile/observe 共用一个进程内 catalog 准入锁。锁序固定为 “每资源锁 → catalog 锁 → 排序后的 VM 锁”;所有会读取 Fabric gate 后接触宿主私网数据面 @@ -151,12 +174,9 @@ apply/delete/reconcile/lifecycle reconcile/observe 共用一个进程内 catalog 不能把当前 asyncio 锁解释为数据库事务。VPC apply 会扫描全部持久化 `fabric_desired` endpoint(不仅是它固定的 Fabric),重建每份计划并校验已存 `plan_digest`;损坏或 stale 记录一律 fail-closed,防止跨 Fabric 的 endpoint/CIDR 冲突。 -调用方取消上述 mutation 时也不得提前释放锁:引擎会在持锁状态下 drain 已进入 -`asyncio.to_thread` 的底层 mutation 及其 desired state 提交,然后才向上传播 -`CancelledError`。跨页面刷新或第二管理员的 -持久未知状态需要后续增加服务端 operation ID、lease 与 phase 账本,不能依据一次暂时的 -404 就证明原 apply 未在执行;因此当前页面会继续保持 reconcile-only,直到固定 desired -state 可被权威回读。 +面板侧协调协程被取消时只停止状态轮询;已被宿主 systemd 接纳的 mutation 继续由原 +operation ID 所有。下次 Engine 启动先持久化关闭 Fabric gate,再做只读状态/精确回读; +一次暂时 404 或 SSH 断线不能证明原 apply 未执行。 readiness 的平台宿主机闭集由 active/draining 资源池成员、非删除实例宿主机、非删除 VPC deployment 宿主机与引擎 Fabric 漂移节点合并而成。断裂的成员关系、资源池/线路、 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 26b46fc4..02b344d1 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,34 @@ # 本版验证记录 +## 2026-10-09:Fabric 宿主 systemd 异步 operation 与安全回读 + +- Fabric apply/reconcile 不再让 HTTP/SSH 长连接等待完整宿主配置。Engine 先持久化同一轮 + 32 位小写十六进制 `operation_id`,HTTP 以 `202 Accepted` 返回;每台宿主把不可变脚本、 + manifest 和固定枚举 status 放入 root-only 的 + `/run/virt-cloud/fabric-operations/`,再由有运行上限的 transient systemd + oneshot 独立执行。原始 stdout/stderr、命令、路径、私钥和 peer 全量配置不会进入 API 或 + 安全阶段日志。 +- 页面只通过 Fabric GET 轮询原 ID,replacement、缺失地区、连续读取失败或 CDN 超时均停止 + 自动跟踪并进入结果未知,绝不 POST 重放。PHP 写边界强制 operation ID、kind 和 status; + 首次 apply 只返回回执且不发布地区映射,只有后续显式“重新核对”完成平台代次、宿主闭集、 + VPC pin、active 与 `next_stage_allowed` 权威回读后才能激活映射。 +- 周期 reconcile 与页面 GET 始终只读。只有显式 POST 能在严格 immutable hash、systemd unit + 和逐节点 dispatch fence 证据下继续原 ID:恢复 publish-before-systemd 的 queued runner, + 或在已接纳节点精确收敛后续派确定未接纳节点;不得重派已接纳节点或生成替代 ID。 +- 最终 Python 3.12 聚焦回归:`engine/tests/test_fabric.py` **375 passed**; + `test_engine_boundary.py + test_vpc.py + test_vpc_dataplane.py` **278 passed、23 warnings**。 + 后一组与 Fabric 全测并行时曾触发一个既有云模板后台 GC 计时断言,取消并行后完整重跑通过。 + `py_compile` 与 `git diff --check` 通过。 +- PHP 8.5/WASM 下 6 个修改/相关 PHP 文件语法、Fabric 静态合同、operation 严格投影、宿主 + 网络池/调度、资源调度、多公网池、资产和防火墙 UI 合同通过;Node JavaScript 语法及 Fabric + 向导行为测试通过。当前隔离 vendor 缺少 `Illuminate\\Database\\Capsule\\Manager` 实体文件, + 因而 `AdminFabricReadinessWorkflowTest.php` 仅完成语法检查,未执行数据库流程;该测试必须在 + 部署端完整 Composer dev 依赖与 PDO SQLite 环境复跑。 +- 尚未连接真实 Debian 13 / AlmaLinux 10 宿主机验证 SSH 断线、transient unit、journal、重启、 + NetworkManager/ifupdown 及 firewalld/native nftables。部署后必须用页面显示的同一 ID 查询 + `journalctl --utc -u virt-cloud-fabric-apply-.service --no-pager -o short-iso-precise`, + 并完成双宿主 WireGuard 握手、跨宿主 VPC 流量和重启恢复后,才能认定生产组网验收完成。 + ## 2026-10-09:真实宿主探针兼容修复 - AlmaLinux 10 现场证明配置的 endpoint 唯一属于 `br0`,firewalld 使用 diff --git a/engine/tests/test_engine_boundary.py b/engine/tests/test_engine_boundary.py index 7a1fc4d5..61ad05ad 100644 --- a/engine/tests/test_engine_boundary.py +++ b/engine/tests/test_engine_boundary.py @@ -362,7 +362,7 @@ def test_fabric_is_engine_global_and_super_admin_write_only(boundary): "fabric_remote_command_failed", "identity", ) - with patch.object(engine.fabric, "apply", failed_identity): + with patch.object(engine.fabric, "enqueue_apply", failed_identity): identity_failed = call( client, "POST", "/internal/v1/fabric/apply", SUPER, {}, ) @@ -372,6 +372,46 @@ def test_fabric_is_engine_global_and_super_admin_write_only(boundary): "error_code": "fabric_remote_command_failed", "failure_phase": "identity", } + + receipt = { + "fabric_id": "fabric-hk", + "operation": { + "id": "a" * 32, + "kind": "apply", + "status": "queued", + "started_at": None, + "updated_at": 1, + "finished_at": None, + }, + } + + async def accepted_apply(_value): + return receipt + + with patch.object(engine.fabric, "enqueue_apply", accepted_apply): + accepted = call( + client, "POST", "/internal/v1/fabric/apply", SUPER, {}, + ) + assert accepted.status_code == 202 + assert accepted.json() == receipt + + reconcile_receipt = { + **receipt, + "operation": {**receipt["operation"], "kind": "reconcile"}, + } + + async def accepted_reconcile(fabric_id): + assert fabric_id == "fabric-hk" + return reconcile_receipt + + with patch.object( + engine.fabric, "enqueue_reconcile", accepted_reconcile): + accepted = call( + client, "POST", + "/internal/v1/fabric/fabric-hk/reconcile", SUPER, {}, + ) + assert accepted.status_code == 202 + assert accepted.json() == reconcile_receipt assert call( client, "POST", "/internal/v1/fabric/probe", USER, {"host_ids": ["host-a"]}, diff --git a/engine/tests/test_fabric.py b/engine/tests/test_fabric.py index fb936f56..50603556 100644 --- a/engine/tests/test_fabric.py +++ b/engine/tests/test_fabric.py @@ -20,6 +20,11 @@ import pytest from virsh_panel.fabric import ( FABRIC_NFT_MANIFEST, + FABRIC_OPERATION_CHECKPOINTS, + FABRIC_OPERATION_ROOT, + FABRIC_OPERATION_REASONS, + FABRIC_OPERATION_STATUSES, + FABRIC_OPERATION_UNIT_PREFIX, FABRIC_PROBE_CONCURRENCY, FABRIC_INTERFACE, FABRIC_OWNER_MARKER, @@ -29,6 +34,7 @@ from virsh_panel.fabric import ( FIREWALL_MODE_FIREWALLD, FIREWALL_MODE_NATIVE, MAX_VPC_STATE_FILES, + MAX_FABRIC_OPERATION_DIRECTORIES, FabricError, FabricHostAdapter, FabricCoordinator, @@ -42,11 +48,16 @@ from virsh_panel.fabric import ( _UNIT, _apply_script, _fabric_endpoint_rp_filter_evidence, + _fabric_operation_dispatch_script, + _fabric_operation_runner_script, + _fabric_operation_status_script, _firewalld_endpoint_zone_evidence, _identity_script, + _new_operation_id, _nm_profile_template, _nft_rules_text, _observe_script, + _parse_operation_status, _profile_firewall_mode, _sysctl_text, parse_fabric_plan, @@ -3784,6 +3795,7 @@ esac "vpc_state_nft_set_matches() { return 0; }", "vc_fabric_sysctl_file_owned() { return 0; }", "read_sysctl() { cat \"$1\"; }", + "vc_fabric_operation_checkpoint() { :; }", *trap_setup, "exec 9>>\"$LOCK\"", tail, @@ -5790,6 +5802,333 @@ def test_firewalld_apply_retry_accepts_only_proven_quarantine(): assert '[ "$FIREWALL_RUNTIME_ZONE_BEFORE" = quarantined ]' in script +def _operation_status_output( + operation_id, *, status="queued", checkpoint="dispatch", + reason="none", created_at=100, started_at=0, updated_at=100, + finished_at=0): + return "\n".join(( + "__VC_FABRIC_OPERATION_SCHEMA__=1", + f"__VC_FABRIC_OPERATION_ID__={operation_id}", + f"__VC_FABRIC_OPERATION_STATUS__={status}", + "__VC_FABRIC_OPERATION_PHASE__=apply", + f"__VC_FABRIC_OPERATION_CHECKPOINT__={checkpoint}", + f"__VC_FABRIC_OPERATION_REASON__={reason}", + f"__VC_FABRIC_OPERATION_CREATED_AT__={created_at}", + f"__VC_FABRIC_OPERATION_STARTED_AT__={started_at}", + f"__VC_FABRIC_OPERATION_UPDATED_AT__={updated_at}", + f"__VC_FABRIC_OPERATION_FINISHED_AT__={finished_at}", + "", + )) + + +def test_fabric_operation_ids_are_opaque_fixed_lowercase_hex(): + operation_ids = {_new_operation_id() for _index in range(128)} + + assert len(operation_ids) == 128 + assert all(re.fullmatch(r"[0-9a-f]{32}", value) + for value in operation_ids) + + +@pytest.mark.parametrize("operation_id", [ + "", "a" * 31, "a" * 33, "A" * 32, "g" * 32, + "../" + "a" * 29, "a" * 31 + "/", "a" * 31 + "\n", + "$(id)".ljust(32, "a"), +]) +def test_fabric_operation_id_is_validated_before_rendering_remote_shell( + operation_id): + with pytest.raises(FabricError) as error: + _fabric_operation_status_script(operation_id) + + assert error.value.error_code == "fabric_operation_invalid" + + +@pytest.mark.parametrize(("kwargs", "expected"), [ + ({}, { + "status": "queued", "checkpoint": "dispatch", "reason": "none", + "started_at": None, "finished_at": None, + }), + ({ + "status": "running", "checkpoint": "journal_recovery", + "created_at": 100, "started_at": 101, "updated_at": 102, + }, { + "status": "running", "checkpoint": "journal_recovery", + "reason": "none", "started_at": 101, "finished_at": None, + }), + ({ + "status": "succeeded", "checkpoint": "complete", + "created_at": 100, "started_at": 101, "updated_at": 103, + "finished_at": 103, + }, { + "status": "succeeded", "checkpoint": "complete", + "reason": "none", "started_at": 101, "finished_at": 103, + }), + ({ + "status": "failed", "checkpoint": "nft_install", + "reason": "nft_failed", "created_at": 100, "started_at": 101, + "updated_at": 104, "finished_at": 104, + }, { + "status": "failed", "checkpoint": "nft_install", + "reason": "nft_failed", "started_at": 101, "finished_at": 104, + }), +]) +def test_fabric_operation_status_parser_accepts_only_complete_safe_projection( + kwargs, expected): + operation_id = "1" * 32 + result = _parse_operation_status( + _operation_status_output(operation_id, **kwargs), operation_id) + + assert result["operation_id"] == operation_id + assert result["phase"] == "apply" + for field, value in expected.items(): + assert result[field] == value + + +def _replace_status_line(output, prefix, replacement): + lines = output.splitlines() + return "\n".join( + replacement if line.startswith(prefix) else line + for line in lines + ) + "\n" + + +@pytest.mark.parametrize("mutation", [ + lambda value: value + "__VC_FABRIC_OPERATION_EXTRA__=value\n", + lambda value: value + "__VC_FABRIC_OPERATION_STATUS__=queued\n", + lambda value: value.replace( + "__VC_FABRIC_OPERATION_REASON__=none\n", ""), + lambda value: "attacker-controlled diagnostic\n" + value, + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_STATUS__=", + "__VC_FABRIC_OPERATION_STATUS__=unknown"), + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_PHASE__=", + "__VC_FABRIC_OPERATION_PHASE__=identity"), + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_CHECKPOINT__=", + "__VC_FABRIC_OPERATION_CHECKPOINT__=arbitrary"), + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_REASON__=", + "__VC_FABRIC_OPERATION_REASON__=/root/private-key"), + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_CREATED_AT__=", + "__VC_FABRIC_OPERATION_CREATED_AT__=-1"), + lambda value: _replace_status_line( + value, "__VC_FABRIC_OPERATION_UPDATED_AT__=", + "__VC_FABRIC_OPERATION_UPDATED_AT__=99"), +]) +def test_fabric_operation_status_parser_rejects_extra_duplicate_or_invalid_data( + mutation): + operation_id = "2" * 32 + output = mutation(_operation_status_output(operation_id)) + + with pytest.raises(FabricError) as error: + _parse_operation_status(output, operation_id) + + assert error.value.error_code == "fabric_operation_status_invalid" + safe_error = json.dumps({ + "message": str(error.value), + "code": error.value.error_code, + "phase": error.value.failure_phase, + }) + assert "attacker-controlled" not in safe_error + assert "/root/private-key" not in safe_error + + +def test_fabric_operation_status_parser_fences_different_attempts(): + first = "3" * 32 + second = "4" * 32 + + with pytest.raises(FabricError) as error: + _parse_operation_status(_operation_status_output(first), second) + + assert error.value.error_code == "fabric_operation_status_invalid" + + +@pytest.mark.parametrize(("status", "checkpoint", "reason", "started", "finished"), [ + ("queued", "dispatch", "none", 1, 0), + ("running", "preflight", "none", 0, 0), + ("running", "preflight", "nft_failed", 101, 0), + ("succeeded", "final_readback", "none", 101, 102), + ("succeeded", "complete", "command_failed", 101, 102), + ("failed", "nft_install", "none", 101, 102), +]) +def test_fabric_operation_status_parser_rejects_impossible_state_combinations( + status, checkpoint, reason, started, finished): + operation_id = "5" * 32 + output = _operation_status_output( + operation_id, status=status, checkpoint=checkpoint, reason=reason, + started_at=started, updated_at=102, finished_at=finished) + + with pytest.raises(FabricError) as error: + _parse_operation_status(output, operation_id) + + assert error.value.error_code == "fabric_operation_status_invalid" + + +def test_fabric_operation_protocol_has_fixed_bounded_vocabulary(): + assert FABRIC_OPERATION_STATUSES == { + "queued", "running", "succeeded", "failed", "uncertain", + "interrupted", + } + assert FABRIC_OPERATION_CHECKPOINTS == { + "dispatch", "host_lock", "identity", "journal_recovery", + "preflight", "transaction", "nft_install", "network_activate", + "persistence", "final_readback", "complete", + } + assert FABRIC_OPERATION_REASONS == { + "none", "tool_missing", "ownership_conflict", "journal_conflict", + "firewall_conflict", "underlay_conflict", "network_manager_failed", + "nft_failed", "systemd_failed", "readback_failed", + "command_failed", "transport_failed", "status_invalid", + } + + +def test_fabric_operation_status_reader_is_strictly_read_only(): + operation_id = "6" * 32 + script = _fabric_operation_status_script(operation_id) + + assert f"OPERATION_ID={operation_id}" in script + assert "__VC_FABRIC_OPERATION_STATUS__=$state" in script + assert '"$UPDATE" interrupted' not in script + assert "mv " not in script + assert "rm " not in script + assert "systemctl start" not in script + assert "systemctl restart" not in script + + +def test_fabric_operation_dispatch_uses_fixed_nonblocking_systemd_command(): + operation_id = "7" * 32 + secret = "private-key-material-must-not-be-logged" + rendered_apply = f"#!/bin/sh\nprintf '%s' {shlex.quote(secret)} >/dev/null\n" + script = _fabric_operation_dispatch_script( + operation_id, rendered_apply, "8" * 64) + systemd_start = script.index('"$SYSTEMD_RUN" --unit="$UNIT"') + + assert f"UNIT={FABRIC_OPERATION_UNIT_PREFIX}{operation_id}.service" in script + assert "--collect --no-block --quiet" in script[systemd_start:] + assert "--property=Type=oneshot" in script[systemd_start:] + assert "--property=StandardOutput=journal" in script[systemd_start:] + assert "--property=StandardError=null" in script[systemd_start:] + assert '"$OPERATION_DIR/runner"' in script[systemd_start:] + assert "/bin/sh -c" not in script[systemd_start:] + assert "exec >/dev/null 2>&1" in script + assert "operation=%s state=%s checkpoint=%s reason=%s" in script + assert secret not in script[systemd_start:] + + +def test_fabric_operation_runner_preserves_apply_exit_status_for_safe_reason(): + runner = _fabric_operation_runner_script("7" * 32, "8" * 64) + + run_apply = runner.index('if /bin/sh "$APPLY"; then') + success = runner.index('"$UPDATE" succeeded complete none', run_apply) + capture = runner.index("else\n apply_rc=$?\nfi", success) + tool_reason = runner.index("70) reason=tool_missing", capture) + journal_reason = runner.index("79) reason=journal_conflict", tool_reason) + failed = runner.index( + '"$UPDATE" failed "$checkpoint" "$reason"', journal_reason) + assert run_apply < success < capture < tool_reason < journal_reason < failed + + +def test_fabric_operation_spool_is_ephemeral_bounded_and_fail_closed(): + operation_id = "8" * 32 + script = _fabric_operation_dispatch_script( + operation_id, "#!/bin/sh\nexit 0\n", "9" * 64) + + assert FABRIC_OPERATION_ROOT == "/run/virt-cloud/fabric-operations" + assert f"ROOT={FABRIC_OPERATION_ROOT}" in script + assert ( + f'if [ "$operation_count" -ge {MAX_FABRIC_OPERATION_DIRECTORIES} ]; ' + "then" + ) in script + assert '"__VC_FABRIC_OPERATION_DISPATCHED__=limit"' in script + assert 'case "$operation_name" in' in script + assert "*[!0-9a-f]*) exit 71" in script + assert '[ "${#operation_name}" = 32 ] || exit 71' in script + assert 'validate_retained_operation "$operation_path" || exit 71' in script + assert '[ "$operation_hidden" = "$LOCK" ] || exit 71' in script + limit = script.index( + f'if [ "$operation_count" -ge {MAX_FABRIC_OPERATION_DIRECTORIES} ];') + validate = script.index( + 'validate_retained_operation "$oldest_terminal_path"', limit) + terminal = script.index( + 'succeeded|failed|uncertain|interrupted)', validate) + remove = script.index( + 'for retained_file in manifest status apply update runner; do', + terminal) + rmdir = script.index('rmdir -- "$oldest_terminal_path"', remove) + limit_result = script.index( + '"__VC_FABRIC_OPERATION_DISPATCHED__=limit"', rmdir) + assert limit < validate < terminal < remove < rmdir < limit_result + assert 'rm -rf -- "$oldest_terminal_path"' not in script + + +def test_fabric_operation_existing_attempt_recovers_only_orphaned_queue(): + operation_id = "9" * 32 + script = _fabric_operation_dispatch_script( + operation_id, "#!/bin/sh\nexit 0\n", "a" * 64) + queued = script.index('if [ "$retained_state" = queued ]; then') + unit_read = script.index( + '"$SYSTEMCTL" show "$UNIT" --property=LoadState --value', + queued) + missing = script.index("not-found)", unit_read) + recover = script.index("recover_operation_unit", missing) + loaded = script.index("loaded) : ;;", recover) + existing = script.index( + '"__VC_FABRIC_OPERATION_DISPATCHED__=existing"', loaded) + existing_exit = script.index(" exit 0", existing) + + assert queued < unit_read < missing < recover < loaded < existing + assert existing < existing_exit + assert script.count("recover_operation_unit") == 2 + recover_function = script[script.index("recover_operation_unit()"): + script.index("validate_retained_operation()")] + assert recover_function.count('"$SYSTEMD_RUN"') == 1 + assert '"$OPERATION_DIR/runner"' in recover_function + assert ( + '[ "$(sed -n \'2p\' "$OPERATION_DIR/manifest")" = ' + '"operation_id=$OPERATION_ID" ]' + ) in script + assert ( + '[ "$(sed -n \'3p\' "$OPERATION_DIR/manifest")" = ' + '"plan_digest=$PLAN_DIGEST" ]' + ) in script + assert ( + '[ "$(sed -n \'4p\' "$OPERATION_DIR/manifest")" = ' + '"script_digest=$SCRIPT_DIGEST" ]' + ) in script + assert ( + 'case "${operation_file##*/}" in ' + "manifest|status|apply|update|runner) : ;; *) exit 71 ;; esac" + ) in script + assert 'for operation_file in manifest status; do' in script + assert ' = 0:600 ] || exit 71' in script + assert 'for operation_file in apply update runner; do' in script + assert ' = 0:700 ] || exit 71' in script + assert ( + '$SHA256SUM "$OPERATION_DIR/apply"' in script + and '$SHA256SUM "$OPERATION_DIR/update"' in script + and '$SHA256SUM "$OPERATION_DIR/runner"' in script + ) + + +def test_fabric_async_apply_records_recovery_before_new_transaction(): + current = plan() + script = _apply_script( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}) + recovery_checkpoint = script.index( + "vc_fabric_operation_checkpoint journal_recovery") + recovery = script.index( + 'case "$journal_existing_state" in', recovery_checkpoint) + preflight = script.index( + "vc_fabric_operation_checkpoint preflight", recovery) + transaction = script.index( + "vc_fabric_operation_checkpoint transaction", preflight) + + assert recovery_checkpoint < recovery < preflight < transaction + for checkpoint in FABRIC_OPERATION_CHECKPOINTS - {"dispatch"}: + assert f"vc_fabric_operation_checkpoint {checkpoint}" in script + + class FakeManager: ssh_binary = "ssh" @@ -5970,6 +6309,174 @@ class FakeManager: return subprocess.CompletedProcess(argv, 0, output, "") +class AsyncOperationManager(FakeManager): + def __init__(self, *args, operation_id, status="queued", + checkpoint="dispatch", reason="none", **kwargs): + super().__init__(*args, **kwargs) + self.operation_id = operation_id + self.operation_status = status + self.operation_checkpoint = checkpoint + self.operation_reason = reason + self.dispatch_result = "yes" + self.disconnect_dispatch = False + + def _status_output(self): + started_at = 0 + finished_at = 0 + if self.operation_status != "queued": + started_at = 101 + if self.operation_status in { + "succeeded", "failed", "uncertain", "interrupted"}: + finished_at = 103 + return _operation_status_output( + self.operation_id, + status=self.operation_status, + checkpoint=self.operation_checkpoint, + reason=self.operation_reason, + started_at=started_at, + updated_at=103 if finished_at else 102, + finished_at=finished_at, + ) + + def _exec(self, argv, *, timeout, input_text=None): + assert argv[-1] == "/bin/sh -s" + self.timeouts.append(timeout) + self.scripts.append(input_text) + if 'SYSTEMD_RUN=$(find_tool ' in input_text: + if self.disconnect_dispatch: + raise RemoteHostError( + "ambiguous disconnect with /secret/path", 502, + "host_remote_command_failed") + output = ( + f"__VC_FABRIC_OPERATION_DISPATCHED__={self.dispatch_result}\n" + f"__VC_FABRIC_OPERATION_ID__={self.operation_id}\n" + ) + return subprocess.CompletedProcess(argv, 0, output, "") + if "__VC_FABRIC_OPERATION_SCHEMA__=$schema" in input_text: + return subprocess.CompletedProcess( + argv, 0, self._status_output(), "") + raise AssertionError("unexpected asynchronous Fabric command") + + +def test_adapter_dispatches_apply_and_reads_status_without_waiting_for_job(): + current = plan() + operation_id = "b" * 32 + manager = AsyncOperationManager(KEY1, operation_id=operation_id) + adapter = FabricHostAdapter(manager) + + result = adapter.dispatch_apply( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}, + operation_id) + + assert result == { + "operation_id": operation_id, + "status": "queued", + "phase": "apply", + "checkpoint": "dispatch", + "reason": "none", + "created_at": 100, + "started_at": None, + "updated_at": 102, + "finished_at": None, + } + serialized = json.dumps(result) + assert KEY1 not in serialized + assert KEY2 not in serialized + assert "/run/virt-cloud" not in serialized + assert manager.timeouts == [ + FABRIC_REMOTE_READ_TIMEOUT_SECONDS, + FABRIC_REMOTE_READ_TIMEOUT_SECONDS, + ] + assert len(manager.scripts) == 2 + assert "--no-block" in manager.scripts[0] + assert "__VC_FABRIC_APPLIED__" in manager.scripts[0] + assert "__VC_FABRIC_OPERATION_STATUS__=$state" in manager.scripts[1] + + +@pytest.mark.parametrize(("status", "checkpoint", "reason"), [ + ("running", "journal_recovery", "none"), + ("succeeded", "complete", "none"), + ("failed", "nft_install", "nft_failed"), +]) +def test_adapter_can_read_exact_attempt_after_dispatch_connection_loss( + status, checkpoint, reason): + current = plan() + operation_id = "c" * 32 + manager = AsyncOperationManager( + KEY1, operation_id=operation_id, status=status, + checkpoint=checkpoint, reason=reason) + manager.disconnect_dispatch = True + adapter = FabricHostAdapter(manager) + + with pytest.raises(FabricError) as error: + adapter.dispatch_apply( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}, + operation_id) + + assert error.value.error_code == "fabric_host_connection_failed" + assert error.value.failure_phase == "apply" + assert len(manager.scripts) == 1 + + # A lost dispatch response is reconciled only by its exact operation id; + # the adapter does not submit the mutation a second time. + manager.disconnect_dispatch = False + observed = adapter.apply_status(operation_id) + assert observed["operation_id"] == operation_id + assert observed["status"] == status + assert observed["checkpoint"] == checkpoint + assert observed["reason"] == reason + assert len(manager.scripts) == 2 + assert 'SYSTEMD_RUN=$(find_tool ' not in manager.scripts[-1] + + +def test_adapter_rejects_cross_attempt_status_without_redispatch(): + operation_id = "d" * 32 + manager = AsyncOperationManager(KEY1, operation_id="e" * 32) + adapter = FabricHostAdapter(manager) + + with pytest.raises(FabricError) as error: + adapter.apply_status(operation_id) + + assert error.value.error_code == "fabric_operation_status_invalid" + assert len(manager.scripts) == 1 + assert 'SYSTEMD_RUN=$(find_tool ' not in manager.scripts[0] + + +def test_adapter_reports_exact_missing_operation_without_leaking_paths(): + operation_id = "a" * 32 + manager = AsyncOperationManager(KEY1, operation_id=operation_id) + manager._status_output = lambda: ( + "__VC_FABRIC_OPERATION_MISSING__=yes\n" + f"__VC_FABRIC_OPERATION_ID__={operation_id}\n" + ) + adapter = FabricHostAdapter(manager) + + with pytest.raises(FabricError) as error: + adapter.apply_status(operation_id) + + assert error.value.status == 409 + assert error.value.error_code == "fabric_operation_not_found" + assert error.value.failure_phase == "observe" + assert "/run/virt-cloud" not in str(error.value) + assert KEY1 not in str(error.value) + assert len(manager.scripts) == 1 + assert 'SYSTEMD_RUN=$(find_tool ' not in manager.scripts[0] + + +def test_adapter_validates_operation_id_before_remote_dispatch(): + current = plan() + manager = AsyncOperationManager(KEY1, operation_id="f" * 32) + adapter = FabricHostAdapter(manager) + + with pytest.raises(FabricError) as error: + adapter.dispatch_apply( + current, current.nodes[0], {"host-a": KEY1, "host-b": KEY2}, + "../not-an-operation") + + assert error.value.error_code == "fabric_operation_invalid" + assert manager.scripts == [] + + def test_adapter_readback_requires_exact_peer_route_and_persistence(): current = plan() manager = FakeManager(KEY1) @@ -6980,6 +7487,1047 @@ def _fabric_components(current): return components +def _remote_operation_status( + operation_id, status, *, checkpoint=None, reason=None): + checkpoint = checkpoint or ( + "complete" if status == "succeeded" else "preflight") + reason = reason or ( + "none" if status in {"queued", "running", "succeeded"} + else "command_failed") + started_at = None if status == "queued" else 101 + finished_at = ( + 103 if status in {"succeeded", "failed", "uncertain", "interrupted"} + else None) + return { + "operation_id": operation_id, + "status": status, + "phase": "apply", + "checkpoint": checkpoint, + "reason": reason, + "created_at": 100, + "started_at": started_at, + "updated_at": 103 if finished_at else 102, + "finished_at": finished_at, + } + + +class AsyncCoordinatorAdapter: + """Host stub that separates one dispatch from read-only status polling.""" + + def __init__(self, manager, _profile=None): + self.manager = manager + + def identity(self, *, create_key=True): + self.manager.async_identity_calls += 1 + return self.manager.public_key + + def dispatch_apply(self, _plan, _host, _keys, operation_id=None): + self.manager.async_dispatch_calls += 1 + self.manager.async_operation_id = operation_id + if self.manager.async_dispatch_entered is not None: + self.manager.async_dispatch_entered.set() + if self.manager.async_dispatch_release is not None: + assert self.manager.async_dispatch_release.wait(timeout=2) + if self.manager.async_dispatch_error is not None: + error = self.manager.async_dispatch_error + self.manager.async_dispatch_error = None + raise error + return _remote_operation_status(operation_id, "queued") + + def apply_status(self, operation_id): + self.manager.async_status_calls += 1 + assert operation_id == self.manager.async_operation_id + statuses = self.manager.async_statuses + if len(statuses) > 1: + status = statuses.pop(0) + else: + status = statuses[0] + if isinstance(status, Exception): + raise status + if isinstance(status, dict): + return dict(status) + return _remote_operation_status( + operation_id, status, + checkpoint=("nft_install" if status == "failed" else None), + reason=("nft_failed" if status == "failed" else None), + ) + + def observe(self, current, host, _keys): + self.manager.async_observe_calls += 1 + return _reconcile_observation(current, host) + + +class PublishedQueuedGapAdapter(AsyncCoordinatorAdapter): + """First dispatch publishes the directory but dies before systemd-run.""" + + def dispatch_apply(self, _plan, _host, _keys, operation_id=None): + self.manager.async_dispatch_calls += 1 + self.manager.async_operation_id = operation_id + if self.manager.async_dispatch_calls == 1: + raise FabricError( + "ambiguous transport /root/private", 502, + "fabric_host_connection_failed", "apply") + self.manager.async_runner_starts += 1 + self.manager.async_statuses = ["succeeded"] + return _remote_operation_status(operation_id, "queued") + + +class RecoveredQueuedGapAdapter(AsyncCoordinatorAdapter): + """Restart joins a published queue and starts its original runner once.""" + + def dispatch_apply(self, _plan, _host, _keys, operation_id=None): + self.manager.async_dispatch_calls += 1 + assert operation_id == self.manager.async_operation_id + self.manager.async_runner_starts += 1 + self.manager.async_statuses = ["succeeded"] + return _remote_operation_status(operation_id, "queued") + + +class PartialHostCrashAdapter(AsyncCoordinatorAdapter): + """Host A was admitted; host B still needs same-id continuation.""" + + def identity(self, *, create_key=True): + self.manager.async_identity_calls += 1 + self.manager.partial_identity_create_flags.append(create_key) + return self.manager.public_key + + def dispatch_apply(self, _plan, _host, _keys, operation_id=None): + assert self.manager.partial_configured is False + self.manager.async_dispatch_calls += 1 + self.manager.async_operation_id = operation_id + self.manager.partial_configured = True + return _remote_operation_status(operation_id, "succeeded") + + def observe(self, current, host, _keys): + self.manager.async_observe_calls += 1 + if self.manager.partial_configured: + return _reconcile_observation(current, host) + return { + "state": "degraded", + "config_ok": False, + "transport_verified": False, + "public_key": self.manager.public_key, + "observed": { + "interface": None, + "config_revision": None, + "config_digest": None, + }, + } + + +def _async_components(current): + components = _fabric_components(current) + for component in components.values(): + manager = component.manager + manager.async_identity_calls = 0 + manager.async_dispatch_calls = 0 + manager.async_status_calls = 0 + manager.async_observe_calls = 0 + manager.async_operation_id = None + manager.async_dispatch_entered = None + manager.async_dispatch_release = None + manager.async_dispatch_error = None + manager.async_runner_starts = 0 + manager.partial_configured = False + manager.partial_identity_create_flags = [] + manager.async_statuses = ["succeeded"] + return components + + +async def _await_fabric_operation(coordinator, fabric_id): + for _attempt in range(500): + task = coordinator._operation_tasks_by_fabric.get(fabric_id) + if task is None: + return + await asyncio.sleep(0.002) + raise AssertionError("Fabric background operation did not finish") + + +def test_enqueue_apply_returns_before_host_systemd_job_finishes(monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + entered = threading.Event() + release = threading.Event() + components["host-a"].manager.async_dispatch_entered = entered + components["host-a"].manager.async_dispatch_release = release + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + assert admitted["operation"]["status"] == "queued" + assert re.fullmatch(r"[0-9a-f]{32}", admitted["operation"]["id"]) + assert not entered.is_set() + + for _attempt in range(100): + if entered.is_set(): + break + await asyncio.sleep(0.002) + assert entered.is_set() + live = coordinator.get_status(current.fabric_id) + assert live["operation"]["status"] == "running" + release.set() + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, coordinator.get_status(current.fabric_id) + + admitted, final = asyncio.run(exercise()) + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert final["operation"]["status"] == "succeeded" + assert all(node["operation"]["status"] == "succeeded" + for node in final["nodes"]) + assert all(component.manager.async_dispatch_calls == 1 + for component in components.values()) + + +def test_cancelled_async_dispatch_drains_then_recovers_without_redispatch( + monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + entered = threading.Event() + release = threading.Event() + first = components["host-a"].manager + first.async_dispatch_entered = entered + first.async_dispatch_release = release + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + for _attempt in range(100): + if entered.is_set(): + break + await asyncio.sleep(0.002) + assert entered.is_set() + operation_task = coordinator._operation_tasks_by_fabric[ + current.fabric_id] + + lock_entered = asyncio.Event() + + async def wait_for_fabric_lock(): + async with coordinator._locks[current.fabric_id]: + lock_entered.set() + + waiter = asyncio.create_task(wait_for_fabric_lock()) + operation_task.cancel() + await asyncio.sleep(0) + assert operation_task.done() is False + assert lock_entered.is_set() is False + release.set() + with pytest.raises(asyncio.CancelledError): + await operation_task + await asyncio.wait_for(waiter, timeout=1) + assert lock_entered.is_set() is True + + coordinator.recover() + first.async_operation_id = admitted["operation"]["id"] + first.async_statuses = ["succeeded"] + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == admitted["operation"]["id"] + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, coordinator.get_status(current.fabric_id) + + try: + admitted, final = asyncio.run(exercise()) + finally: + release.set() + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert first.async_dispatch_calls == 1 + assert components["host-b"].manager.async_dispatch_calls == 0 + + +@pytest.mark.parametrize(("terminal", "expected_root"), [ + ("succeeded", "succeeded"), + ("failed", "failed"), +]) +def test_dispatch_disconnect_is_reconciled_by_status_without_replay( + monkeypatch, terminal, expected_root): + current = plan() + store = MemoryStore() + components = _async_components(current) + disconnected = components["host-a"].manager + disconnected.async_dispatch_error = FabricError( + "safe disconnect", 502, "fabric_host_connection_failed", "apply") + disconnected.async_statuses = ["running", terminal] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, coordinator.get_status(current.fabric_id) + + admitted, final = asyncio.run(exercise()) + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert final["operation"]["status"] == expected_root + failed_or_recovered = next( + node for node in final["nodes"] if node["host_id"] == "host-a") + assert failed_or_recovered["operation"]["status"] == terminal + assert disconnected.async_dispatch_calls == 1 + assert disconnected.async_status_calls >= 2 + if terminal == "succeeded": + assert disconnected.async_observe_calls == 1 + else: + assert disconnected.async_observe_calls == 0 + + +def test_async_apply_timeout_is_uncertain_and_never_redispatched(monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + stalled = components["host-a"].manager + stalled.async_statuses = ["running"] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0.002) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_TIMEOUT_SECONDS", 0.01) + + async def exercise(): + await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + stalled_node = next( + node for node in final["nodes"] if node["host_id"] == "host-a") + assert final["operation"]["status"] == "uncertain" + assert stalled_node["operation"]["status"] == "uncertain" + assert stalled_node["operation"]["reason"] == "transport_failed" + assert stalled.async_dispatch_calls == 1 + assert stalled.async_status_calls >= 1 + + +@pytest.mark.parametrize("error_code", [ + "fabric_operation_status_invalid", + "fabric_operation_not_found", + "fabric_remote_command_failed", +]) +def test_confirmed_dispatch_status_error_stays_uncertain_and_resumes_same_id( + monkeypatch, error_code): + current = plan() + store = MemoryStore() + components = _async_components(current) + for component in components.values(): + component.manager.async_statuses = [ + FabricError("unsafe /root/private", 502, error_code, "observe"), + "succeeded", + ] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + uncertain = coordinator.get_status(current.fabric_id) + assert uncertain["operation"]["status"] == "uncertain" + assert uncertain["next_stage_allowed"] is False + + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == admitted["operation"]["id"] + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, coordinator.get_status(current.fabric_id) + + admitted, final = asyncio.run(exercise()) + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert final["operation"]["status"] == "succeeded" + assert all(component.manager.async_dispatch_calls == 1 + for component in components.values()) + assert all(component.manager.async_status_calls >= 2 + for component in components.values()) + assert "/root/private" not in json.dumps(final) + + +def test_published_queue_gap_recovers_original_runner_once_with_same_id( + monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + for component in components.values(): + component.manager.async_statuses = ["queued"] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", PublishedQueuedGapAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0.001) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_TIMEOUT_SECONDS", 0.004) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + stalled = coordinator.get_status(current.fabric_id) + assert stalled["operation"]["status"] == "uncertain" + assert stalled["next_stage_allowed"] is False + + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == admitted["operation"]["id"] + await _await_fabric_operation(coordinator, current.fabric_id) + restarted = coordinator.get_status(current.fabric_id) + assert restarted["operation"]["status"] == "running" + assert restarted["next_stage_allowed"] is False + await coordinator.reconcile_all() + return admitted, coordinator.get_status(current.fabric_id) + + admitted, final = asyncio.run(exercise()) + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert final["operation"]["status"] == "succeeded" + assert final["next_stage_allowed"] is True + assert all(component.manager.async_dispatch_calls == 2 + for component in components.values()) + assert all(component.manager.async_runner_starts == 1 + for component in components.values()) + assert all(component.manager.async_operation_id + == admitted["operation"]["id"] + for component in components.values()) + + +def test_restart_periodic_queued_status_still_allows_same_id_runner_recovery( + monkeypatch): + current = plan() + operation_id = "a" * 32 + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + admitted = coordinator._admit_apply_record(current, operation_id) + admitted["operation"].update( + status="running", started_at=101, updated_at=101) + admitted["public_keys"] = {"host-a": KEY1, "host-b": KEY2} + for node, key in zip(admitted["nodes"], (KEY1, KEY2)): + node["public_key"] = key + node["operation"].update( + status="running", phase="apply", checkpoint="dispatch", + started_at=101, updated_at=101) + store.set( + "fabric_desired", current.fabric_id, + json.dumps(admitted)) + coordinator.recover() + for component in components.values(): + manager = component.manager + manager.async_operation_id = operation_id + manager.async_statuses = ["queued"] + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", RecoveredQueuedGapAdapter) + + async def exercise(): + await coordinator.reconcile_all() + observed = coordinator.get_status(current.fabric_id) + assert observed["operation"]["id"] == operation_id + assert observed["operation"]["status"] == "running" + assert observed["next_stage_allowed"] is False + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + restarted = coordinator.get_status(current.fabric_id) + assert restarted["operation"]["status"] == "running" + assert restarted["next_stage_allowed"] is False + await coordinator.reconcile_all() + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert final["next_stage_allowed"] is True + assert all(component.manager.async_dispatch_calls == 1 + for component in components.values()) + assert all(component.manager.async_runner_starts == 1 + for component in components.values()) + assert all(component.manager.async_operation_id == operation_id + for component in components.values()) + + +def _interrupted_async_record(current, operation_id): + record = _active_fabric_record(current) + record.update(state="uncertain", next_stage_allowed=False) + record["operation"] = { + "id": operation_id, + "kind": "apply", + "status": "interrupted", + "created_at": 100, + "started_at": 101, + "updated_at": 102, + "finished_at": 102, + } + for node in record["nodes"]: + node.update( + state="uncertain", transport_verified=False, + observed_revision=None, observed_plan_digest=None, + operation={ + "id": operation_id, + "status": "uncertain", + "phase": "apply", + "checkpoint": "preflight", + "reason": "transport_failed", + "created_at": 100, + "started_at": 101, + "updated_at": 102, + "finished_at": 102, + }, + ) + return record + + +@pytest.mark.parametrize("crash_stage", [ + "before_identity", + "mid_identity", + "identity_fenced", +]) +def test_pre_dispatch_crash_resumes_same_operation_id_without_replay( + monkeypatch, crash_stage): + current = plan() + operation_id = "5" * 32 + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + admitted = coordinator._admit_apply_record(current, operation_id) + if crash_stage in {"mid_identity", "identity_fenced"}: + admitted["operation"].update( + status="running", started_at=101, updated_at=101) + admitted["nodes"][0]["operation"].update( + status="running", phase="identity", checkpoint="identity", + started_at=101, updated_at=101) + if crash_stage == "identity_fenced": + admitted["public_keys"] = {"host-a": KEY1, "host-b": KEY2} + for node, key in zip(admitted["nodes"], (KEY1, KEY2)): + node["public_key"] = key + node["operation"].update( + status="running", phase="identity", + checkpoint="identity", started_at=101, updated_at=101) + store.set( + "fabric_desired", current.fabric_id, + json.dumps(admitted)) + coordinator.recover() + for component in components.values(): + component.manager.async_operation_id = operation_id + component.manager.async_statuses = ["succeeded"] + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert all(component.manager.async_dispatch_calls == 1 + for component in components.values()) + + +def _partial_host_crash_record(coordinator, current, operation_id): + admitted = coordinator._admit_apply_record(current, operation_id) + admitted["operation"].update( + status="running", started_at=101, updated_at=101) + admitted["public_keys"] = {"host-a": KEY1, "host-b": KEY2} + for node, key in zip(admitted["nodes"], (KEY1, KEY2)): + node["public_key"] = key + node["operation"].update( + status="running", phase="identity", + checkpoint="identity", started_at=101, updated_at=101) + admitted["nodes"][0]["operation"].update( + phase="apply", checkpoint="dispatch") + return admitted + + +def test_crash_between_hosts_continues_only_undispatched_host_with_same_id( + monkeypatch): + current = plan() + operation_id = "6" * 32 + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + admitted = _partial_host_crash_record( + coordinator, current, operation_id) + store.set( + "fabric_desired", current.fabric_id, + json.dumps(admitted)) + coordinator.recover() + + first = components["host-a"].manager + second = components["host-b"].manager + first.async_operation_id = operation_id + first.async_statuses = ["succeeded"] + first.partial_configured = True + second.async_statuses = ["succeeded"] + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", PartialHostCrashAdapter) + + async def exercise(): + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + continuing = coordinator.get_status(current.fabric_id) + assert continuing["operation"]["status"] == "running" + assert continuing["next_stage_allowed"] is False + await coordinator.reconcile_all() + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert final["next_stage_allowed"] is True + assert first.async_dispatch_calls == 0 + assert second.async_dispatch_calls == 1 + assert first.async_identity_calls == 0 + assert second.async_identity_calls == 1 + assert second.partial_identity_create_flags == [False] + assert second.async_operation_id == operation_id + + +def test_partial_remote_failed_but_exact_continues_only_undispatched_host( + monkeypatch): + current = plan() + operation_id = "7" * 32 + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_partial_host_crash_record( + coordinator, current, operation_id))) + coordinator.recover() + + first = components["host-a"].manager + second = components["host-b"].manager + first.async_operation_id = operation_id + first.async_statuses = ["failed"] + first.partial_configured = True + second.async_statuses = ["succeeded"] + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", PartialHostCrashAdapter) + + async def exercise(): + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + continuing = coordinator.get_status(current.fabric_id) + assert continuing["operation"]["status"] == "running" + assert continuing["next_stage_allowed"] is False + await coordinator.reconcile_all() + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert final["next_stage_allowed"] is True + assert first.async_dispatch_calls == 0 + assert second.async_dispatch_calls == 1 + assert first.async_identity_calls == 0 + assert second.async_identity_calls == 1 + assert second.partial_identity_create_flags == [False] + assert second.async_operation_id == operation_id + + +def test_partial_remote_failed_and_nonexact_blocks_all_continuation( + monkeypatch): + current = plan() + operation_id = "8" * 32 + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_partial_host_crash_record( + coordinator, current, operation_id))) + coordinator.recover() + + first = components["host-a"].manager + second = components["host-b"].manager + first.async_operation_id = operation_id + first.async_statuses = ["failed"] + first.partial_configured = False + second.partial_configured = False + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", PartialHostCrashAdapter) + + async def exercise(): + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "uncertain" + assert final["state"] == "uncertain" + assert final["next_stage_allowed"] is False + assert first.async_dispatch_calls == 0 + assert second.async_dispatch_calls == 0 + assert first.async_identity_calls == 0 + assert second.async_identity_calls == 0 + + +class NonExactAsyncCoordinatorAdapter(AsyncCoordinatorAdapter): + def observe(self, current, host, keys): + result = super().observe(current, host, keys) + result.update( + state="degraded", config_ok=False, + transport_verified=False) + result["observed"]["config_digest"] = "0" * 64 + return result + + +def test_remote_success_with_non_exact_readback_is_terminal_uncertain( + monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", + NonExactAsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + degraded = coordinator.get_status(current.fabric_id) + assert degraded["operation"]["status"] == "uncertain" + assert degraded["next_stage_allowed"] is False + durable = json.loads(store.get( + "fabric_desired", current.fabric_id)) + assert all( + node["operation"]["phase"] == "observe" + and node["operation"]["checkpoint"] == "final_readback" + for node in durable["nodes"]) + assert coordinator._operation_may_have_dispatched( + durable, admitted["operation"]["id"]) is True + + resumed = await coordinator.enqueue_reconcile(current.fabric_id) + assert resumed["operation"]["id"] == admitted["operation"]["id"] + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, coordinator.get_status(current.fabric_id) + + admitted, final = asyncio.run(exercise()) + + assert final["operation"]["id"] == admitted["operation"]["id"] + assert final["operation"]["status"] == "uncertain" + assert final["state"] == "uncertain" + assert final["next_stage_allowed"] is False + assert all(node["operation"]["status"] == "uncertain" + for node in final["nodes"]) + assert all(component.manager.async_dispatch_calls == 1 + for component in components.values()) + + +def test_restart_resume_reads_exact_operation_without_redispatch(monkeypatch): + current = plan() + operation_id = "1" * 32 + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_interrupted_async_record(current, operation_id))) + components = _async_components(current) + for component in components.values(): + component.manager.async_operation_id = operation_id + component.manager.async_statuses = ["succeeded"] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + async def exercise(): + admitted = await coordinator.enqueue_reconcile(current.fabric_id) + assert admitted["operation"]["id"] == operation_id + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert final["next_stage_allowed"] is True + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + assert all(component.manager.async_status_calls == 1 + for component in components.values()) + assert all(component.manager.async_observe_calls == 1 + for component in components.values()) + + +def test_restart_resume_does_not_publish_running_job_as_succeeded(monkeypatch): + current = plan() + operation_id = "2" * 32 + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_interrupted_async_record(current, operation_id))) + components = _async_components(current) + for component in components.values(): + component.manager.async_operation_id = operation_id + component.manager.async_statuses = ["running"] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + async def exercise(): + await coordinator.enqueue_reconcile(current.fabric_id) + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "running" + assert final["next_stage_allowed"] is False + assert all(node["operation"]["status"] == "running" + for node in final["nodes"]) + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + assert all(component.manager.async_observe_calls == 0 + for component in components.values()) + + +def test_restart_missing_runtime_operation_can_converge_by_exact_observation( + monkeypatch): + current = plan() + operation_id = "3" * 32 + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_interrupted_async_record(current, operation_id))) + components = _async_components(current) + for component in components.values(): + component.manager.async_operation_id = operation_id + component.manager.async_statuses = [FabricError( + "safe missing", 409, "fabric_operation_not_found", "observe")] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + asyncio.run(coordinator.reconcile_all()) + final = coordinator.get_status(current.fabric_id) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "succeeded" + assert final["state"] == "active" + assert final["next_stage_allowed"] is True + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + assert all(component.manager.async_observe_calls == 1 + for component in components.values()) + + +@pytest.mark.parametrize("error_code", [ + "fabric_host_connection_failed", + "fabric_operation_status_invalid", + "fabric_remote_command_failed", +]) +def test_restart_status_failure_cannot_use_old_exact_observation( + monkeypatch, error_code): + current = plan() + operation_id = "4" * 32 + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_interrupted_async_record(current, operation_id))) + components = _async_components(current) + for component in components.values(): + component.manager.async_operation_id = operation_id + component.manager.async_statuses = [FabricError( + "unsafe transport output /root/private", 502, + error_code, "observe")] + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + asyncio.run(coordinator.reconcile_all()) + final = coordinator.get_status(current.fabric_id) + durable = json.loads(store.get("fabric_desired", current.fabric_id)) + + assert final["operation"]["id"] == operation_id + assert final["operation"]["status"] == "uncertain" + assert final["state"] == "uncertain" + assert final["next_stage_allowed"] is False + assert all(node["operation"]["status"] == "uncertain" + for node in final["nodes"]) + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + assert "/root/private" not in json.dumps(durable) + + +def test_async_identity_is_durably_fenced_before_first_host_dispatch( + monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + entered = threading.Event() + release = threading.Event() + components["host-a"].manager.async_dispatch_entered = entered + components["host-a"].manager.async_dispatch_release = release + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + monkeypatch.setattr( + "virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0) + + async def exercise(): + admitted = await coordinator.enqueue_apply(plan_payload(current)) + for _attempt in range(100): + if entered.is_set(): + break + await asyncio.sleep(0.002) + assert entered.is_set() + durable = json.loads(store.get( + "fabric_desired", current.fabric_id)) + release.set() + await _await_fabric_operation(coordinator, current.fabric_id) + return admitted, durable + + try: + admitted, durable = asyncio.run(exercise()) + finally: + release.set() + + assert durable["operation"]["id"] == admitted["operation"]["id"] + assert durable["public_keys"] == {"host-a": KEY1, "host-b": KEY2} + assert { + node["host_id"]: node.get("public_key") + for node in durable["nodes"] + } == {"host-a": KEY1, "host-b": KEY2} + + +def test_observe_only_probe_failure_closes_durable_active_gate(monkeypatch): + current = plan() + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_active_fabric_record(current))) + components = _fabric_components(current) + + def probe_failed(): + raise RemoteHostError( + "unsafe remote detail /root/private", 502, + "host_capability_probe_failed") + + components["host-a"].manager.reprobe_current = probe_failed + coordinator = FabricCoordinator(store, Registry(components)) + + asyncio.run(coordinator.reconcile_all()) + + durable = json.loads(store.get("fabric_desired", current.fabric_id)) + assert durable["state"] == "uncertain" + assert durable["next_stage_allowed"] is False + assert all(node["transport_verified"] is False + for node in durable["nodes"]) + assert "/root/private" not in json.dumps(durable) + + +def test_enqueue_reconcile_admission_uses_shared_catalog_lock(monkeypatch): + current = plan() + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_active_fabric_record(current))) + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + async def exercise(): + shared = coordinator.catalog_mutation_lock() + async with shared: + admission = asyncio.create_task( + coordinator.enqueue_reconcile(current.fabric_id)) + await asyncio.sleep(0.02) + assert admission.done() is False + durable = json.loads(store.get( + "fabric_desired", current.fabric_id)) + assert "operation" not in durable + receipt = await asyncio.wait_for(admission, timeout=1) + await coordinator.shutdown_operations() + return receipt + + receipt = asyncio.run(exercise()) + assert receipt["operation"]["kind"] == "reconcile" + assert receipt["operation"]["status"] == "queued" + + +def test_background_internal_error_cannot_leave_operation_running(monkeypatch): + current = plan() + store = MemoryStore() + components = _async_components(current) + + class UnexpectedFailureAdapter(AsyncCoordinatorAdapter): + def dispatch_apply(self, *_args, **_kwargs): + self.manager.async_dispatch_calls += 1 + raise RuntimeError("unsafe implementation detail /root/private") + + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", UnexpectedFailureAdapter) + + async def exercise(): + await coordinator.enqueue_apply(plan_payload(current)) + await _await_fabric_operation(coordinator, current.fabric_id) + return coordinator.get_status(current.fabric_id) + + final = asyncio.run(exercise()) + + assert final["operation"]["status"] in { + "failed", "uncertain", "interrupted", + } + assert final["operation"]["finished_at"] is not None + assert all(node["operation"]["status"] not in {"pending", "running"} + for node in final["nodes"]) + assert "/root/private" not in json.dumps(final) + + +def test_periodic_reconcile_is_read_only_and_never_dispatches(monkeypatch): + current = plan() + store = MemoryStore() + store.set( + "fabric_desired", current.fabric_id, + json.dumps(_active_fabric_record(current))) + components = _async_components(current) + coordinator = FabricCoordinator(store, Registry(components)) + monkeypatch.setattr( + "virsh_panel.fabric.FabricHostAdapter", AsyncCoordinatorAdapter) + + asyncio.run(coordinator.reconcile_all()) + + final = coordinator.get_status(current.fabric_id) + assert final["state"] == "active" + assert final["next_stage_allowed"] is True + assert all(component.manager.async_dispatch_calls == 0 + for component in components.values()) + assert all(component.manager.async_status_calls == 0 + for component in components.values()) + assert all(component.manager.async_observe_calls == 1 + for component in components.values()) + + def _reconcile_observation(current, host): public_key = KEY1 if host.host_id == "host-a" else KEY2 return { diff --git a/engine/virsh_panel/fabric.py b/engine/virsh_panel/fabric.py index 3e7c436d..9e8343ce 100644 --- a/engine/virsh_panel/fabric.py +++ b/engine/virsh_panel/fabric.py @@ -13,6 +13,7 @@ import base64 import hashlib import ipaddress import json +import logging import re import shlex import time @@ -25,6 +26,9 @@ from .remote_host import RemoteHostError from .shell_contracts import IP_RULE_CONVERGENCE_SH, VPC_SYSCTL_VALIDATION_SH +LOG = logging.getLogger(__name__) + + FABRIC_SCHEMA_VERSION = 1 FABRIC_INTERFACE = "wg-fabric0" FABRIC_OWNER_MARKER = "virt-cloud-wg-fabric-v1" @@ -65,6 +69,34 @@ FABRIC_FIREWALL_MODES = frozenset(( FABRIC_FAILURE_PHASES = frozenset(("identity", "observe", "apply")) FABRIC_REMOTE_READ_TIMEOUT_SECONDS = 35 FABRIC_REMOTE_APPLY_TIMEOUT_SECONDS = 300 +FABRIC_OPERATION_ROOT = "/run/virt-cloud/fabric-operations" +MAX_FABRIC_OPERATION_DIRECTORIES = 32 +FABRIC_OPERATION_UNIT_PREFIX = "virt-cloud-fabric-apply-" +FABRIC_OPERATION_STATUSES = frozenset(( + "queued", "running", "succeeded", "failed", "uncertain", + "interrupted", +)) +FABRIC_OPERATION_KINDS = frozenset(("apply", "reconcile")) +FABRIC_NODE_OPERATION_STATUSES = frozenset(( + "pending", "running", "succeeded", "failed", "uncertain", "skipped", +)) +FABRIC_OPERATION_CHECKPOINTS = frozenset(( + "dispatch", "host_lock", "identity", "journal_recovery", "preflight", + "transaction", "nft_install", "network_activate", "persistence", + "final_readback", "complete", +)) +FABRIC_OPERATION_REASONS = frozenset(( + "none", "tool_missing", "ownership_conflict", "journal_conflict", + "firewall_conflict", "underlay_conflict", "network_manager_failed", + "nft_failed", "systemd_failed", "readback_failed", "command_failed", + "transport_failed", "status_invalid", +)) +FABRIC_OPERATION_POLL_INTERVAL_SECONDS = 1 +FABRIC_OPERATION_POLL_TIMEOUT_SECONDS = 900 +# Keep the host-owned job bounded independently of the panel-side poller. The +# smaller host limit leaves time for one final exact-id status read before the +# coordinator's own deadline expires. +FABRIC_OPERATION_RUNTIME_MAX_SECONDS = 840 IFUP_PATHS = frozenset(("/usr/sbin/ifup", "/usr/bin/ifup", "/sbin/ifup", "/bin/ifup")) IFDOWN_PATHS = frozenset(("/usr/sbin/ifdown", "/usr/bin/ifdown", "/sbin/ifdown", "/bin/ifdown")) IFQUERY_PATHS = frozenset(("/usr/sbin/ifquery", "/usr/bin/ifquery", "/sbin/ifquery", "/bin/ifquery")) @@ -90,6 +122,7 @@ _FABRIC_KEY = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z") _READINESS_REASON = re.compile(r"[a-z][a-z0-9_]{0,63}\Z") _SAFE_INTERFACE = re.compile(r"[A-Za-z0-9_.:-]{1,15}\Z") _SAFE_FIREWALL_ZONE = re.compile(r"[A-Za-z0-9_-]{1,64}\Z") +_OPERATION_ID = re.compile(r"[0-9a-f]{32}\Z") _RFC1918_NETWORKS = ( ipaddress.IPv4Network("10.0.0.0/8"), ipaddress.IPv4Network("172.16.0.0/12"), @@ -1217,6 +1250,584 @@ def _here_doc(path: str, content: str) -> str: return f"cat > {target} <<'{marker}'\n{content}{end}{marker}\n" +def _new_operation_id() -> str: + """Return one opaque, non-reusable Fabric operation identifier.""" + return uuid.uuid4().hex + + +def _validate_operation_id(value: Any) -> str: + if not isinstance(value, str) or _OPERATION_ID.fullmatch(value) is None: + raise FabricError( + "Fabric 操作标识无效", 422, "fabric_operation_invalid") + return value + + +def _parse_operation_status( + output: str, expected_operation_id: str) -> dict[str, Any]: + """Parse the complete safe projection emitted by the remote host. + + No remote command output is passed through. The status reader emits one + fixed marker per field, and this parser rejects missing, duplicate or + unknown lines so a compromised command cannot smuggle diagnostics into an + administrator response. + """ + operation_id = _validate_operation_id(expected_operation_id) + if not isinstance(output, str) or len(output) > 4096: + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + prefix = "__VC_FABRIC_OPERATION_" + fields = { + "SCHEMA": "schema", + "ID": "operation_id", + "STATUS": "status", + "PHASE": "phase", + "CHECKPOINT": "checkpoint", + "REASON": "reason", + "CREATED_AT": "created_at", + "STARTED_AT": "started_at", + "UPDATED_AT": "updated_at", + "FINISHED_AT": "finished_at", + } + parsed: dict[str, str] = {} + for line in output.splitlines(): + if not line: + continue + if not line.startswith(prefix) or "__=" not in line: + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + marker, value = line[len(prefix):].split("__=", 1) + key = fields.get(marker) + if key is None or key in parsed or len(value) > 64: + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + parsed[key] = value + if set(parsed) != set(fields.values()): + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + if (parsed["schema"] != "1" + or parsed["operation_id"] != operation_id + or parsed["status"] not in FABRIC_OPERATION_STATUSES + or parsed["phase"] != "apply" + or parsed["checkpoint"] not in FABRIC_OPERATION_CHECKPOINTS + or parsed["reason"] not in FABRIC_OPERATION_REASONS): + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + times: dict[str, int] = {} + for key in ("created_at", "started_at", "updated_at", "finished_at"): + raw = parsed[key] + if not raw.isascii() or not raw.isdigit() or len(raw) > 12: + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + times[key] = int(raw) + state = parsed["status"] + if (times["created_at"] <= 0 + or times["updated_at"] < times["created_at"] + or times["started_at"] < 0 + or times["finished_at"] < 0 + or (times["started_at"] > 0 + and times["updated_at"] < times["started_at"])): + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + if state == "queued": + valid_state = ( + parsed["checkpoint"] == "dispatch" + and parsed["reason"] == "none" + and times["started_at"] == 0 + and times["finished_at"] == 0) + elif state == "running": + valid_state = ( + parsed["reason"] == "none" + and times["started_at"] > 0 + and times["finished_at"] == 0) + elif state == "succeeded": + valid_state = ( + parsed["checkpoint"] == "complete" + and parsed["reason"] == "none" + and times["started_at"] > 0 + and times["finished_at"] >= times["started_at"]) + else: + valid_state = ( + parsed["reason"] != "none" + and times["finished_at"] >= times["created_at"]) + if not valid_state: + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + return { + "operation_id": operation_id, + "status": state, + "phase": "apply", + "checkpoint": parsed["checkpoint"], + "reason": parsed["reason"], + "created_at": times["created_at"], + "started_at": times["started_at"] or None, + "updated_at": times["updated_at"], + "finished_at": times["finished_at"] or None, + } + + +def _fabric_operation_update_script( + operation_id: str, plan_digest: str) -> str: + operation_id = _validate_operation_id(operation_id) + if not re.fullmatch(r"[0-9a-f]{64}", plan_digest): + raise FabricError( + "Fabric 计划摘要无效", 500, "fabric_plan_corrupt") + operation_dir = f"{FABRIC_OPERATION_ROOT}/{operation_id}" + return f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +OPERATION_ID={_q(operation_id)} +PLAN_DIGEST={_q(plan_digest)} +OPERATION_DIR={_q(operation_dir)} +STATUS="$OPERATION_DIR/status" +MANIFEST="$OPERATION_DIR/manifest" +new_state=${{1:-}} +new_checkpoint=${{2:-}} +new_reason=${{3:-}} +case "$new_state" in queued|running|succeeded|failed|uncertain|interrupted) : ;; *) exit 64 ;; esac +case "$new_checkpoint" in dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; *) exit 64 ;; esac +case "$new_reason" in none|tool_missing|ownership_conflict|journal_conflict|firewall_conflict|underlay_conflict|network_manager_failed|nft_failed|systemd_failed|readback_failed|command_failed|transport_failed|status_invalid) : ;; *) exit 64 ;; esac +[ -d "$OPERATION_DIR" ] && [ ! -L "$OPERATION_DIR" ] || exit 65 +[ "$(stat -c '%u:%a' "$OPERATION_DIR" 2>/dev/null)" = 0:700 ] || exit 65 +for operation_file in "$MANIFEST" "$STATUS"; do + [ -f "$operation_file" ] && [ ! -L "$operation_file" ] || exit 65 + [ "$(stat -c '%u:%a' "$operation_file" 2>/dev/null)" = 0:600 ] || exit 65 +done +[ "$(sed -n '1p' "$MANIFEST")" = schema=1 ] || exit 65 +[ "$(sed -n '2p' "$MANIFEST")" = operation_id="$OPERATION_ID" ] || exit 65 +[ "$(sed -n '3p' "$MANIFEST")" = plan_digest="$PLAN_DIGEST" ] || exit 65 +[ "$(wc -l < "$STATUS" | tr -d ' ')" = 10 ] || exit 65 +[ "$(sed -n '1p' "$STATUS")" = schema=1 ] || exit 65 +[ "$(sed -n '2p' "$STATUS")" = operation_id="$OPERATION_ID" ] || exit 65 +old_state=$(sed -n '3s/^status=//p' "$STATUS") +old_phase=$(sed -n '4s/^phase=//p' "$STATUS") +old_checkpoint=$(sed -n '5s/^checkpoint=//p' "$STATUS") +old_reason=$(sed -n '6s/^reason=//p' "$STATUS") +created_at=$(sed -n '7s/^created_at=//p' "$STATUS") +started_at=$(sed -n '8s/^started_at=//p' "$STATUS") +old_updated_at=$(sed -n '9s/^updated_at=//p' "$STATUS") +old_finished_at=$(sed -n '10s/^finished_at=//p' "$STATUS") +case "$old_state" in queued|running|succeeded|failed|uncertain|interrupted) : ;; *) exit 65 ;; esac +[ "$old_phase" = apply ] || exit 65 +case "$old_checkpoint" in dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; *) exit 65 ;; esac +case "$old_reason" in none|tool_missing|ownership_conflict|journal_conflict|firewall_conflict|underlay_conflict|network_manager_failed|nft_failed|systemd_failed|readback_failed|command_failed|transport_failed|status_invalid) : ;; *) exit 65 ;; esac +for operation_time in "$created_at" "$started_at" "$old_updated_at" "$old_finished_at"; do + case "$operation_time" in ''|*[!0-9]*) exit 65 ;; esac +done +case "$old_state:$new_state" in + queued:queued|queued:running|queued:failed|queued:uncertain|queued:interrupted|running:running|running:succeeded|running:failed|running:uncertain|running:interrupted) : ;; + succeeded:*|failed:*|uncertain:*|interrupted:*) exit 0 ;; + *) exit 65 ;; +esac +case "$new_state" in + queued|running|succeeded) [ "$new_reason" = none ] || exit 64 ;; + failed|uncertain|interrupted) [ "$new_reason" != none ] || exit 64 ;; +esac +now=$(date +%s) +case "$now" in ''|*[!0-9]*) exit 65 ;; esac +[ "$now" -ge "$created_at" ] || exit 65 +if [ "$new_state" = running ] && [ "$started_at" = 0 ]; then started_at=$now; fi +finished_at=0 +case "$new_state" in succeeded|failed|uncertain|interrupted) finished_at=$now ;; esac +status_tmp=$(mktemp "$OPERATION_DIR/.status.XXXXXX") +{{ + printf '%s\n' schema=1 "operation_id=$OPERATION_ID" \ + "status=$new_state" phase=apply \ + "checkpoint=$new_checkpoint" "reason=$new_reason" \ + "created_at=$created_at" "started_at=$started_at" \ + "updated_at=$now" "finished_at=$finished_at" +}} > "$status_tmp" +chmod 600 "$status_tmp" +mv -f "$status_tmp" "$STATUS" +sync +printf 'virt-cloud-fabric operation=%s state=%s checkpoint=%s reason=%s\n' \ + "$OPERATION_ID" "$new_state" "$new_checkpoint" "$new_reason" >&3 2>/dev/null || true +''' + + +def _fabric_operation_runner_script( + operation_id: str, plan_digest: str) -> str: + operation_id = _validate_operation_id(operation_id) + operation_dir = f"{FABRIC_OPERATION_ROOT}/{operation_id}" + return f'''#!/bin/sh +set -u +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +OPERATION_ID={_q(operation_id)} +OPERATION_DIR={_q(operation_dir)} +UPDATE="$OPERATION_DIR/update" +APPLY="$OPERATION_DIR/apply" +exec 3>&1 +exec >/dev/null 2>&1 +operation_interrupted() {{ + trap - HUP INT TERM + checkpoint=$(sed -n '5s/^checkpoint=//p' "$OPERATION_DIR/status" 2>/dev/null || true) + case "$checkpoint" in + dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; + *) checkpoint=dispatch ;; + esac + "$UPDATE" interrupted "$checkpoint" systemd_failed || true + exit 1 +}} +trap operation_interrupted HUP INT TERM +"$UPDATE" running dispatch none || exit 1 +export VC_FABRIC_OPERATION_ID="$OPERATION_ID" +if /bin/sh "$APPLY"; then + "$UPDATE" succeeded complete none || exit 1 + exit 0 +else + apply_rc=$? +fi +checkpoint=$(sed -n '5s/^checkpoint=//p' "$OPERATION_DIR/status" 2>/dev/null || true) +case "$checkpoint" in + dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; + *) checkpoint=dispatch ;; +esac +case "$apply_rc" in + 70) reason=tool_missing ;; + 79) reason=journal_conflict ;; + *) + case "$checkpoint" in + host_lock|identity|preflight) reason=ownership_conflict ;; + journal_recovery|transaction) reason=journal_conflict ;; + nft_install) reason=nft_failed ;; + network_activate) reason=network_manager_failed ;; + persistence) reason=systemd_failed ;; + final_readback|complete) reason=readback_failed ;; + *) reason=command_failed ;; + esac + ;; +esac +"$UPDATE" failed "$checkpoint" "$reason" || exit 1 +exit 1 +''' + + +def _fabric_operation_status_script(operation_id: str) -> str: + operation_id = _validate_operation_id(operation_id) + operation_dir = f"{FABRIC_OPERATION_ROOT}/{operation_id}" + return f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +OPERATION_ID={_q(operation_id)} +OPERATION_DIR={_q(operation_dir)} +STATUS="$OPERATION_DIR/status" +[ ! -L "$OPERATION_DIR" ] || exit 71 +if [ ! -e "$OPERATION_DIR" ]; then + printf '%s\n' '__VC_FABRIC_OPERATION_MISSING__=yes' \ + "__VC_FABRIC_OPERATION_ID__=$OPERATION_ID" + exit 0 +fi +[ -d "$OPERATION_DIR" ] && [ ! -L "$OPERATION_DIR" ] || exit 71 +[ "$(stat -c '%u:%a' "$OPERATION_DIR" 2>/dev/null)" = 0:700 ] || exit 71 +[ -f "$STATUS" ] && [ ! -L "$STATUS" ] || exit 71 +[ "$(stat -c '%u:%a' "$STATUS" 2>/dev/null)" = 0:600 ] || exit 71 +[ "$(wc -l < "$STATUS" | tr -d ' ')" = 10 ] || exit 71 +schema=$(sed -n '1s/^schema=//p' "$STATUS") +status_id=$(sed -n '2s/^operation_id=//p' "$STATUS") +state=$(sed -n '3s/^status=//p' "$STATUS") +phase=$(sed -n '4s/^phase=//p' "$STATUS") +checkpoint=$(sed -n '5s/^checkpoint=//p' "$STATUS") +reason=$(sed -n '6s/^reason=//p' "$STATUS") +created_at=$(sed -n '7s/^created_at=//p' "$STATUS") +started_at=$(sed -n '8s/^started_at=//p' "$STATUS") +updated_at=$(sed -n '9s/^updated_at=//p' "$STATUS") +finished_at=$(sed -n '10s/^finished_at=//p' "$STATUS") +[ "$schema" = 1 ] && [ "$status_id" = "$OPERATION_ID" ] && [ "$phase" = apply ] || exit 71 +case "$state" in queued|running|succeeded|failed|uncertain|interrupted) : ;; *) exit 71 ;; esac +case "$checkpoint" in dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; *) exit 71 ;; esac +case "$reason" in none|tool_missing|ownership_conflict|journal_conflict|firewall_conflict|underlay_conflict|network_manager_failed|nft_failed|systemd_failed|readback_failed|command_failed|transport_failed|status_invalid) : ;; *) exit 71 ;; esac +for operation_time in "$created_at" "$started_at" "$updated_at" "$finished_at"; do + case "$operation_time" in ''|*[!0-9]*) exit 71 ;; esac +done +printf '%s\n' \ + "__VC_FABRIC_OPERATION_SCHEMA__=$schema" \ + "__VC_FABRIC_OPERATION_ID__=$status_id" \ + "__VC_FABRIC_OPERATION_STATUS__=$state" \ + "__VC_FABRIC_OPERATION_PHASE__=$phase" \ + "__VC_FABRIC_OPERATION_CHECKPOINT__=$checkpoint" \ + "__VC_FABRIC_OPERATION_REASON__=$reason" \ + "__VC_FABRIC_OPERATION_CREATED_AT__=$created_at" \ + "__VC_FABRIC_OPERATION_STARTED_AT__=$started_at" \ + "__VC_FABRIC_OPERATION_UPDATED_AT__=$updated_at" \ + "__VC_FABRIC_OPERATION_FINISHED_AT__=$finished_at" +''' + + +def _fabric_operation_dispatch_script( + operation_id: str, rendered_apply: str, plan_digest: str) -> str: + operation_id = _validate_operation_id(operation_id) + if not isinstance(rendered_apply, str) or not rendered_apply.startswith("#!/bin/sh\n"): + raise FabricError( + "Fabric 应用脚本无效", 500, "fabric_plan_corrupt") + if not re.fullmatch(r"[0-9a-f]{64}", plan_digest): + raise FabricError( + "Fabric 计划摘要无效", 500, "fabric_plan_corrupt") + script_digest = hashlib.sha256(rendered_apply.encode()).hexdigest() + update_script = _fabric_operation_update_script( + operation_id, plan_digest) + runner_script = _fabric_operation_runner_script( + operation_id, plan_digest) + update_digest = hashlib.sha256(update_script.encode()).hexdigest() + runner_digest = hashlib.sha256(runner_script.encode()).hexdigest() + operation_dir = f"{FABRIC_OPERATION_ROOT}/{operation_id}" + unit = f"{FABRIC_OPERATION_UNIT_PREFIX}{operation_id}.service" + return f'''#!/bin/sh +set -eu +umask 077 +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +OPERATION_ID={_q(operation_id)} +PLAN_DIGEST={_q(plan_digest)} +SCRIPT_DIGEST={_q(script_digest)} +UPDATE_DIGEST={_q(update_digest)} +RUNNER_DIGEST={_q(runner_digest)} +ROOT={_q(FABRIC_OPERATION_ROOT)} +OPERATION_DIR={_q(operation_dir)} +UNIT={_q(unit)} +find_tool() {{ for p in "$@"; do [ -x "$p" ] && {{ printf '%s' "$p"; return 0; }}; done; return 1; }} +STAT=$(find_tool /usr/bin/stat /bin/stat /usr/sbin/stat /sbin/stat) || exit 70 +FLOCK=$(find_tool /usr/bin/flock /usr/sbin/flock /bin/flock /sbin/flock) || exit 70 +SHA256SUM=$(find_tool /usr/bin/sha256sum /bin/sha256sum /usr/sbin/sha256sum /sbin/sha256sum) || exit 70 +SYSTEMD_RUN=$(find_tool /usr/bin/systemd-run /bin/systemd-run /usr/sbin/systemd-run /sbin/systemd-run) || exit 70 +SYSTEMCTL=$(find_tool /usr/bin/systemctl /bin/systemctl /usr/sbin/systemctl /sbin/systemctl) || exit 70 +recover_operation_unit() {{ + "$SYSTEMD_RUN" \ + --unit="$UNIT" --collect --no-block --quiet \ + --property=Type=oneshot --property=StandardOutput=journal \ + --property=StandardError=null \ + --property=RuntimeMaxSec={FABRIC_OPERATION_RUNTIME_MAX_SECONDS}s \ + "$OPERATION_DIR/runner" >/dev/null 2>&1 +}} +validate_retained_operation() {{ + retained_path=$1 + retained_id=${{retained_path##*/}} + case "$retained_id" in *[!0-9a-f]*) return 1 ;; esac + [ "${{#retained_id}}" = 32 ] || return 1 + [ -d "$retained_path" ] && [ ! -L "$retained_path" ] || return 1 + [ "$($STAT -c '%u:%a' "$retained_path" 2>/dev/null)" = 0:700 ] || return 1 + retained_file_count=0 + for retained_file in "$retained_path"/*; do + [ "$retained_file" != "$retained_path/*" ] || continue + case "${{retained_file##*/}}" in manifest|status|apply|update|runner) : ;; *) return 1 ;; esac + retained_file_count=$((retained_file_count + 1)) + done + [ "$retained_file_count" = 5 ] || return 1 + for retained_hidden in "$retained_path"/.[!.]* "$retained_path"/..?*; do + [ "$retained_hidden" != "$retained_path/.[!.]*" ] || continue + [ "$retained_hidden" != "$retained_path/..?*" ] || continue + return 1 + done + for retained_file in manifest status; do + [ -f "$retained_path/$retained_file" ] && [ ! -L "$retained_path/$retained_file" ] || return 1 + [ "$($STAT -c '%u:%a' "$retained_path/$retained_file" 2>/dev/null)" = 0:600 ] || return 1 + done + for retained_file in apply update runner; do + [ -f "$retained_path/$retained_file" ] && [ ! -L "$retained_path/$retained_file" ] || return 1 + [ "$($STAT -c '%u:%a' "$retained_path/$retained_file" 2>/dev/null)" = 0:700 ] || return 1 + done + [ "$(wc -l < "$retained_path/manifest" | tr -d ' ')" = 7 ] || return 1 + [ "$(sed -n '1p' "$retained_path/manifest")" = schema=1 ] || return 1 + [ "$(sed -n '2p' "$retained_path/manifest")" = "operation_id=$retained_id" ] || return 1 + retained_plan=$(sed -n '3s/^plan_digest=//p' "$retained_path/manifest") + retained_apply=$(sed -n '4s/^script_digest=//p' "$retained_path/manifest") + retained_update=$(sed -n '5s/^update_digest=//p' "$retained_path/manifest") + retained_runner=$(sed -n '6s/^runner_digest=//p' "$retained_path/manifest") + retained_created=$(sed -n '7s/^created_at=//p' "$retained_path/manifest") + for retained_digest in "$retained_plan" "$retained_apply" "$retained_update" "$retained_runner"; do + case "$retained_digest" in *[!0-9a-f]*) return 1 ;; esac + [ "${{#retained_digest}}" = 64 ] || return 1 + done + case "$retained_created" in ''|*[!0-9]*) return 1 ;; esac + [ "$($SHA256SUM "$retained_path/apply" | awk '{{print $1}}')" = "$retained_apply" ] || return 1 + [ "$($SHA256SUM "$retained_path/update" | awk '{{print $1}}')" = "$retained_update" ] || return 1 + [ "$($SHA256SUM "$retained_path/runner" | awk '{{print $1}}')" = "$retained_runner" ] || return 1 + [ "$(wc -l < "$retained_path/status" | tr -d ' ')" = 10 ] || return 1 + [ "$(sed -n '1p' "$retained_path/status")" = schema=1 ] || return 1 + [ "$(sed -n '2p' "$retained_path/status")" = "operation_id=$retained_id" ] || return 1 + retained_state=$(sed -n '3s/^status=//p' "$retained_path/status") + retained_phase=$(sed -n '4s/^phase=//p' "$retained_path/status") + retained_checkpoint=$(sed -n '5s/^checkpoint=//p' "$retained_path/status") + retained_reason=$(sed -n '6s/^reason=//p' "$retained_path/status") + retained_status_created=$(sed -n '7s/^created_at=//p' "$retained_path/status") + retained_started=$(sed -n '8s/^started_at=//p' "$retained_path/status") + retained_updated=$(sed -n '9s/^updated_at=//p' "$retained_path/status") + retained_finished=$(sed -n '10s/^finished_at=//p' "$retained_path/status") + case "$retained_state" in queued|running|succeeded|failed|uncertain|interrupted) : ;; *) return 1 ;; esac + [ "$retained_phase" = apply ] || return 1 + case "$retained_checkpoint" in dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; *) return 1 ;; esac + case "$retained_reason" in none|tool_missing|ownership_conflict|journal_conflict|firewall_conflict|underlay_conflict|network_manager_failed|nft_failed|systemd_failed|readback_failed|command_failed|transport_failed|status_invalid) : ;; *) return 1 ;; esac + [ "$retained_status_created" = "$retained_created" ] || return 1 + for retained_time in "$retained_started" "$retained_updated" "$retained_finished"; do + case "$retained_time" in ''|*[!0-9]*) return 1 ;; esac + done + return 0 +}} +for parent in /run/virt-cloud "$ROOT"; do + if [ -L "$parent" ] || {{ [ -e "$parent" ] && [ ! -d "$parent" ]; }}; then exit 71; fi + if [ ! -e "$parent" ]; then mkdir "$parent"; chmod 700 "$parent"; fi + [ "$($STAT -c '%u:%a' "$parent" 2>/dev/null)" = 0:700 ] || exit 71 +done +LOCK="$ROOT/.dispatch.lock" +[ ! -L "$LOCK" ] || exit 71 +if [ ! -e "$LOCK" ]; then : > "$LOCK"; chmod 600 "$LOCK"; fi +[ -f "$LOCK" ] && [ "$($STAT -c '%u:%a' "$LOCK" 2>/dev/null)" = 0:600 ] || exit 71 +exec 9>>"$LOCK" +"$FLOCK" -x 9 || exit 71 +if [ -e "$OPERATION_DIR" ] || [ -L "$OPERATION_DIR" ]; then + validate_retained_operation "$OPERATION_DIR" || exit 71 + [ -d "$OPERATION_DIR" ] && [ ! -L "$OPERATION_DIR" ] || exit 71 + [ "$($STAT -c '%u:%a' "$OPERATION_DIR" 2>/dev/null)" = 0:700 ] || exit 71 + operation_file_count=0 + for operation_file in "$OPERATION_DIR"/*; do + [ "$operation_file" != "$OPERATION_DIR/*" ] || continue + case "${{operation_file##*/}}" in manifest|status|apply|update|runner) : ;; *) exit 71 ;; esac + operation_file_count=$((operation_file_count + 1)) + done + [ "$operation_file_count" = 5 ] || exit 71 + for operation_file in manifest status; do + [ -f "$OPERATION_DIR/$operation_file" ] && [ ! -L "$OPERATION_DIR/$operation_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$OPERATION_DIR/$operation_file" 2>/dev/null)" = 0:600 ] || exit 71 + done + for operation_file in apply update runner; do + [ -f "$OPERATION_DIR/$operation_file" ] && [ ! -L "$OPERATION_DIR/$operation_file" ] || exit 71 + [ "$($STAT -c '%u:%a' "$OPERATION_DIR/$operation_file" 2>/dev/null)" = 0:700 ] || exit 71 + done + [ "$(wc -l < "$OPERATION_DIR/manifest" | tr -d ' ')" = 7 ] || exit 71 + [ "$(sed -n '1p' "$OPERATION_DIR/manifest")" = schema=1 ] || exit 71 + [ "$(sed -n '2p' "$OPERATION_DIR/manifest")" = "operation_id=$OPERATION_ID" ] || exit 71 + [ "$(sed -n '3p' "$OPERATION_DIR/manifest")" = "plan_digest=$PLAN_DIGEST" ] || exit 71 + [ "$(sed -n '4p' "$OPERATION_DIR/manifest")" = "script_digest=$SCRIPT_DIGEST" ] || exit 71 + [ "$(sed -n '5p' "$OPERATION_DIR/manifest")" = "update_digest=$UPDATE_DIGEST" ] || exit 71 + [ "$(sed -n '6p' "$OPERATION_DIR/manifest")" = "runner_digest=$RUNNER_DIGEST" ] || exit 71 + manifest_created_at=$(sed -n '7s/^created_at=//p' "$OPERATION_DIR/manifest") + case "$manifest_created_at" in ''|*[!0-9]*) exit 71 ;; esac + [ "$($SHA256SUM "$OPERATION_DIR/apply" | awk '{{print $1}}')" = "$SCRIPT_DIGEST" ] || exit 71 + [ "$($SHA256SUM "$OPERATION_DIR/update" | awk '{{print $1}}')" = "$UPDATE_DIGEST" ] || exit 71 + [ "$($SHA256SUM "$OPERATION_DIR/runner" | awk '{{print $1}}')" = "$RUNNER_DIGEST" ] || exit 71 + if [ "$retained_state" = queued ]; then + # The operation directory is atomically published before systemd-run. + # If the dispatch shell died in that narrow gap, recover only this + # exact immutable id. A loaded unit is never started a second time. + unit_load=$("$SYSTEMCTL" show "$UNIT" --property=LoadState --value 2>/dev/null) || exit 71 + unit_active=$("$SYSTEMCTL" show "$UNIT" --property=ActiveState --value 2>/dev/null) || exit 71 + case "$unit_active" in + inactive|activating|active|deactivating|failed) : ;; + *) exit 71 ;; + esac + case "$unit_load" in + not-found) + [ "$unit_active" = inactive ] || exit 71 + if ! recover_operation_unit; then + exec 3>/dev/null + "$OPERATION_DIR/update" failed dispatch systemd_failed || exit 71 + fi + ;; + loaded) : ;; + *) exit 71 ;; + esac + fi + printf '%s\n' "__VC_FABRIC_OPERATION_DISPATCHED__=existing" \ + "__VC_FABRIC_OPERATION_ID__=$OPERATION_ID" + exit 0 +fi +for operation_hidden in "$ROOT"/.[!.]* "$ROOT"/..?*; do + [ "$operation_hidden" != "$ROOT/.[!.]*" ] || continue + [ "$operation_hidden" != "$ROOT/..?*" ] || continue + [ "$operation_hidden" = "$LOCK" ] || exit 71 +done +operation_count=0 +oldest_terminal_path= +oldest_terminal_created= +for operation_path in "$ROOT"/*; do + [ "$operation_path" != "$ROOT/*" ] || continue + operation_name=${{operation_path##*/}} + case "$operation_name" in + *[!0-9a-f]*) exit 71 ;; + esac + [ "${{#operation_name}}" = 32 ] || exit 71 + validate_retained_operation "$operation_path" || exit 71 + operation_count=$((operation_count + 1)) + case "$retained_state" in + succeeded|failed|uncertain|interrupted) + if [ -z "$oldest_terminal_created" ] || + [ "$retained_created" -lt "$oldest_terminal_created" ]; then + oldest_terminal_created=$retained_created + oldest_terminal_path=$operation_path + fi + ;; + esac +done +if [ "$operation_count" -ge {MAX_FABRIC_OPERATION_DIRECTORIES} ]; then + if [ -n "$oldest_terminal_path" ]; then + validate_retained_operation "$oldest_terminal_path" || exit 71 + case "$retained_state" in succeeded|failed|uncertain|interrupted) : ;; *) exit 71 ;; esac + for retained_file in manifest status apply update runner; do + rm -f -- "$oldest_terminal_path/$retained_file" || exit 71 + done + rmdir -- "$oldest_terminal_path" || exit 71 + operation_count=$((operation_count - 1)) + fi + if [ "$operation_count" -ge {MAX_FABRIC_OPERATION_DIRECTORIES} ]; then + printf '%s\n' "__VC_FABRIC_OPERATION_DISPATCHED__=limit" \ + "__VC_FABRIC_OPERATION_ID__=$OPERATION_ID" + exit 0 + fi +fi +tmp_dir=$(mktemp -d "$ROOT/.${{OPERATION_ID}}.XXXXXX") +cleanup_dispatch() {{ [ -z "${{tmp_dir:-}}" ] || rm -rf -- "$tmp_dir" || true; }} +trap cleanup_dispatch EXIT HUP INT TERM +chmod 700 "$tmp_dir" +{_here_doc('$tmp_dir/apply', rendered_apply).rstrip()} +{_here_doc('$tmp_dir/update', update_script).rstrip()} +{_here_doc('$tmp_dir/runner', runner_script).rstrip()} +chmod 700 "$tmp_dir/apply" "$tmp_dir/update" "$tmp_dir/runner" +[ "$($SHA256SUM "$tmp_dir/apply" | awk '{{print $1}}')" = "$SCRIPT_DIGEST" ] || exit 71 +created_at=$(date +%s) +case "$created_at" in ''|*[!0-9]*) exit 71 ;; esac +{{ + printf '%s\n' schema=1 "operation_id=$OPERATION_ID" \ + "plan_digest=$PLAN_DIGEST" "script_digest=$SCRIPT_DIGEST" \ + "update_digest=$UPDATE_DIGEST" "runner_digest=$RUNNER_DIGEST" \ + "created_at=$created_at" +}} > "$tmp_dir/manifest" +{{ + printf '%s\n' schema=1 "operation_id=$OPERATION_ID" status=queued \ + phase=apply checkpoint=dispatch reason=none \ + "created_at=$created_at" started_at=0 \ + "updated_at=$created_at" finished_at=0 +}} > "$tmp_dir/status" +chmod 600 "$tmp_dir/manifest" "$tmp_dir/status" +[ "$($STAT -c '%u:%a' "$tmp_dir" 2>/dev/null)" = 0:700 ] || exit 71 +sync +mv "$tmp_dir" "$OPERATION_DIR" +tmp_dir= +sync +if ! "$SYSTEMD_RUN" --unit="$UNIT" --collect --no-block --quiet \ + --property=Type=oneshot --property=StandardOutput=journal \ + --property=StandardError=null \ + --property=RuntimeMaxSec={FABRIC_OPERATION_RUNTIME_MAX_SECONDS}s \ + "$OPERATION_DIR/runner" >/dev/null 2>&1; then + exec 3>/dev/null + "$OPERATION_DIR/update" failed dispatch systemd_failed || exit 71 +fi +printf '%s\n' "__VC_FABRIC_OPERATION_DISPATCHED__=yes" \ + "__VC_FABRIC_OPERATION_ID__=$OPERATION_ID" +''' + + def _nft_rules_text(digest: str) -> str: """Return the persistent, revision-bound host quarantine ruleset.""" marker = f"{FABRIC_OWNER_MARKER}:{digest}" @@ -7190,6 +7801,14 @@ def _apply_script(plan: FabricPlan, host: FabricNode, sysctl_content = _sysctl_text(plan) nft_rules = _nft_rules_text(plan.digest) nft_rules_sha256 = hashlib.sha256(nft_rules.encode()).hexdigest() + transaction_boundary = ( + "# A fixed-path sysctl file may be reused only when the authoritative owner\n") + if _TRANSACTION_SCRIPT.count(transaction_boundary) != 1: + raise FabricError( + "Fabric 事务脚本边界无效", 500, "fabric_plan_corrupt") + transaction_recovery, transaction_begin = _TRANSACTION_SCRIPT.split( + transaction_boundary, 1) + transaction_begin = transaction_boundary + transaction_begin helper_content = _BOOT_HELPER.replace( "__VC_FABRIC_DIGEST__", plan.digest).replace( "__VC_FABRIC_NFT_RULES_SHA256__", nft_rules_sha256).replace( @@ -7524,6 +8143,20 @@ set -eu umask 077 PATH=/usr/sbin:/usr/bin:/sbin:/bin export PATH +vc_fabric_operation_checkpoint() {{ + vc_operation_checkpoint=$1 + [ -n "${{VC_FABRIC_OPERATION_ID:-}}" ] || return 0 + case "$VC_FABRIC_OPERATION_ID" in *[!0-9a-f]*) exit 79 ;; esac + [ "${{#VC_FABRIC_OPERATION_ID}}" = 32 ] || exit 79 + case "$vc_operation_checkpoint" in + dispatch|host_lock|identity|journal_recovery|preflight|transaction|nft_install|network_activate|persistence|final_readback|complete) : ;; + *) exit 79 ;; + esac + vc_operation_update={_q(FABRIC_OPERATION_ROOT)}/$VC_FABRIC_OPERATION_ID/update + [ -f "$vc_operation_update" ] && [ ! -L "$vc_operation_update" ] || exit 79 + [ "$(stat -c '%u:%a' "$vc_operation_update" 2>/dev/null)" = 0:700 ] || exit 79 + "$vc_operation_update" running "$vc_operation_checkpoint" none || exit 79 +}} _tmp_key= _tmp_owner= _tmp_conf= @@ -7605,6 +8238,7 @@ fi # Serialize before sampling the previous link state. Without this, two # concurrent applies can both quarantine before flock and the waiter can later # restore a stale DOWN observation over a healthy completed apply. +vc_fabric_operation_checkpoint host_lock if [ -L /run/virt-cloud ] || {{ [ -e /run/virt-cloud ] && [ ! -d /run/virt-cloud ]; }}; then exit 71; fi if [ -e /run/virt-cloud ]; then [ -d /run/virt-cloud ] && [ ! -L /run/virt-cloud ] || exit 71 @@ -7622,6 +8256,7 @@ exec 9>>"$LOCK" # Identity collection always precedes apply. Revalidate the fixed local # public key under the same host lock before quarantine or any persistent # mutation; apply must never manufacture a replacement identity. +vc_fabric_operation_checkpoint identity [ -f "$KEY" ] && [ ! -L "$KEY" ] || exit 71 [ "$($STAT -c '%u:%a' "$KEY" 2>/dev/null)" = 0:600 ] || exit 71 [ "$($WG pubkey < "$KEY")" = "$EXPECTED_PUBLIC_KEY" ] || exit 71 @@ -7664,6 +8299,19 @@ else fi fi vc_firewall_mode_ready || exit 71 +if [ -e "$BASE" ]; then + [ -d "$BASE" ] && [ ! -L "$BASE" ] || exit 71 + [ "$($STAT -c '%u:%a' "$BASE" 2>/dev/null)" = 0:700 ] || exit 71 +else + mkdir "$BASE" + chmod 700 "$BASE" +fi +_tmp_helper=$(mktemp "$BASE/.wg-fabric0.helper.XXXXXX") +{_here_doc('$_tmp_helper', helper_content).rstrip()} +chmod 700 "$_tmp_helper" +vc_fabric_operation_checkpoint journal_recovery +{transaction_recovery} +vc_fabric_operation_checkpoint preflight read_sysctl() {{ [ -r "$1" ] || return 1 sysctl_value= @@ -7797,10 +8445,8 @@ else mkdir /etc/nftables.d chmod 755 /etc/nftables.d fi -_tmp_helper=$(mktemp "$BASE/.wg-fabric0.helper.XXXXXX") -{_here_doc('$_tmp_helper', helper_content).rstrip()} -chmod 700 "$_tmp_helper" -{_TRANSACTION_SCRIPT} +vc_fabric_operation_checkpoint transaction +{transaction_begin} vc_fabric_quarantine || exit 71 if ! vc_fabric_owner_file_owned; then [ ! -e "$OWNER" ] && [ ! -L "$OWNER" ] || exit 71 @@ -7873,6 +8519,7 @@ fi # Only after every read-only ownership, endpoint, route, address, and # persistence preflight has passed may this helper create or validate the # host-only nftables guard. +vc_fabric_operation_checkpoint nft_install write_nft_phase installing || exit 76 {_NFT_GUARD} nft_installed=$($NFT -s list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 72 @@ -7962,6 +8609,7 @@ publish_desired_file "$_tmp_helper" "$HELPER" helper || exit 76 _tmp_helper= {nm_write} {ifupdown_write} +vc_fabric_operation_checkpoint network_activate if ! "$IP" link show dev "$IFACE" >/dev/null 2>&1; then "$IP" link add dev "$IFACE" type wireguard || exit 72 fi @@ -8032,6 +8680,7 @@ vc_fabric_rp_filter_set || exit 71 vc_fabric_rp_filter_set || exit 71 {route_commands} {path_checks} +vc_fabric_operation_checkpoint persistence _tmp_conf_template=$(mktemp "$BASE/.wg-fabric0.conf-template.XXXXXX") {_here_doc('$_tmp_conf_template', config).rstrip()} _tmp_conf=$(mktemp "$BASE/.wg-fabric0.conf.XXXXXX") @@ -8082,6 +8731,7 @@ done "$SYSTEMCTL" enable {FABRIC_SERVICE} >/dev/null "$SYSTEMCTL" enable {FABRIC_TIMER} >/dev/null "$SYSTEMCTL" start {FABRIC_TIMER} >/dev/null +vc_fabric_operation_checkpoint final_readback if [ "$FIREWALL_MODE" = firewalld_nft ] || [ -n "${{VC_FABRIC_EMERGENCY_SNAPSHOT:-}}" ]; then final_fabric_acl=$($NFT -s list table inet virt_cloud_wg_fabric 2>/dev/null) || exit 72 @@ -8238,6 +8888,7 @@ printf '%s\n' "$final_emergency_tables" | final_emergency_tables_verify=$($NFT list tables 2>/dev/null) || exit 79 [ "$final_emergency_tables_verify" = "$final_emergency_tables" ] || exit 79 [ ! -e "$final_emergency_owner" ] && [ ! -L "$final_emergency_owner" ] || exit 79 +vc_fabric_operation_checkpoint complete printf '%s\\n' '__VC_FABRIC_APPLIED__' ''' @@ -9159,13 +9810,17 @@ class FabricHostAdapter: # generation halfway through could configure a different host. self.profile = dict(profile) if isinstance(profile, Mapping) else None - def _run(self, script: str, *, failure_phase: str) -> str: + def _run(self, script: str, *, failure_phase: str, + timeout_seconds: int | None = None) -> str: safe_phase = _fabric_failure_phase(failure_phase) - timeout = ( + timeout = timeout_seconds if timeout_seconds is not None else ( FABRIC_REMOTE_APPLY_TIMEOUT_SECONDS - if safe_phase == "apply" - else FABRIC_REMOTE_READ_TIMEOUT_SECONDS - ) + if safe_phase == "apply" else FABRIC_REMOTE_READ_TIMEOUT_SECONDS) + if (not isinstance(timeout, int) or isinstance(timeout, bool) + or not 1 <= timeout <= FABRIC_REMOTE_APPLY_TIMEOUT_SECONDS): + raise FabricError( + "宿主机 Fabric 超时参数无效", 500, + "fabric_runner_unsupported", safe_phase) try: current = self.profile if self.profile is not None else self.manager.current() except RemoteHostError as exc: @@ -9248,6 +9903,87 @@ class FabricHostAdapter: "宿主机未确认 Fabric 应用", 502, "fabric_apply_unconfirmed", "apply") + def dispatch_apply( + self, plan: FabricPlan, host: FabricNode, + public_keys: Mapping[str, str], + operation_id: str | None = None) -> dict[str, Any]: + """Install and enqueue one exact apply without waiting for it. + + The operation id is a durable attempt identity, never permission to + render a replacement mutation. An absent per-host directory is + installed once (including partial multi-host continuation). An + existing directory must match every immutable file and digest; only + an exact queued operation whose unit is proven not-found may start its + retained runner to close the publish-before-systemd crash gap. A + loaded, running or terminal unit is never restarted. + """ + if set(public_keys) != {node.host_id for node in plan.nodes}: + raise FabricError( + "Fabric 公钥集合与节点不一致", 500, + "fabric_plan_corrupt") + for host_id, key in public_keys.items(): + validate_wireguard_key(key, f"Fabric 节点 {host_id} 公钥") + safe_operation_id = _validate_operation_id( + operation_id if operation_id is not None else _new_operation_id()) + profile = ( + self.profile if self.profile is not None else self.manager.current()) + rendered_apply = _apply_script( + plan, host, public_keys, + deployment_mode=self._deployment_mode(), + firewall_mode=self._firewall_mode(), + ifup_path=_profile_ifup_path(profile), + ifquery_path=_profile_ifquery_path(profile), + ifdown_path=_profile_ifdown_path(profile), + ) + output = self._run( + _fabric_operation_dispatch_script( + safe_operation_id, rendered_apply, plan.digest), + failure_phase="apply", + timeout_seconds=FABRIC_REMOTE_READ_TIMEOUT_SECONDS, + ) + dispatched: str | None = None + returned_id: str | None = None + for line in output.splitlines(): + if line.startswith("__VC_FABRIC_OPERATION_DISPATCHED__="): + if dispatched is not None: + dispatched = None + break + dispatched = line.split("=", 1)[1] + elif line.startswith("__VC_FABRIC_OPERATION_ID__="): + if returned_id is not None: + returned_id = None + break + returned_id = line.split("=", 1)[1] + elif line: + dispatched = None + break + if dispatched == "limit" and returned_id == safe_operation_id: + raise FabricError( + "宿主机 Fabric 操作目录已达安全上限", 409, + "fabric_operation_limit", "apply") + if (dispatched not in {"yes", "existing"} + or returned_id != safe_operation_id): + raise FabricError( + "宿主机未确认 Fabric 异步任务", 502, + "fabric_apply_unconfirmed", "apply") + return self.apply_status(safe_operation_id) + + def apply_status(self, operation_id: str) -> dict[str, Any]: + safe_operation_id = _validate_operation_id(operation_id) + output = self._run( + _fabric_operation_status_script(safe_operation_id), + failure_phase="observe", + timeout_seconds=FABRIC_REMOTE_READ_TIMEOUT_SECONDS, + ) + missing_lines = [line for line in output.splitlines() if line] + if missing_lines == [ + "__VC_FABRIC_OPERATION_MISSING__=yes", + f"__VC_FABRIC_OPERATION_ID__={safe_operation_id}"]: + raise FabricError( + "宿主机 Fabric 操作状态已不存在", 409, + "fabric_operation_not_found", "observe") + return _parse_operation_status(output, safe_operation_id) + def observe(self, plan: FabricPlan, host: FabricNode, public_keys: Mapping[str, str]) -> dict[str, Any]: targets = tuple( @@ -9645,6 +10381,8 @@ class FabricCoordinator: # second batch instead of allowing concurrent HTTP requests to build # an unbounded queue behind the dedicated workers. self._probe_running = False + self._operation_tasks: set[asyncio.Task[Any]] = set() + self._operation_tasks_by_fabric: dict[str, asyncio.Task[Any]] = {} # A single engine process must not apply two independent Fabric plans # to the reserved host interface, or admit a new VPC CIDR while a # Fabric endpoint change is between its catalog scan and durable @@ -9672,9 +10410,125 @@ class FabricCoordinator: return self._catalog_lock def close(self) -> None: - """Drain and release the readiness-only worker pool.""" + """Release synchronous resources without blocking on async work.""" self._probe_executor.shutdown(wait=True, cancel_futures=True) + async def shutdown_operations(self) -> None: + """Stop panel-side pollers; host systemd jobs remain authoritative.""" + tasks = tuple(self._operation_tasks) + for task in tasks: + task.cancel() + if tasks: + await asyncio.gather(*tasks, return_exceptions=True) + + def _track_operation_task( + self, fabric_id: str, awaitable: Any) -> None: + if fabric_id in self._operation_tasks_by_fabric: + raise FabricError( + "Fabric 操作正在执行", 409, "fabric_operation_busy") + task = asyncio.create_task( + self._guard_operation_task(fabric_id, awaitable)) + self._operation_tasks.add(task) + self._operation_tasks_by_fabric[fabric_id] = task + + def completed(done: asyncio.Task[Any]) -> None: + self._operation_tasks.discard(done) + if self._operation_tasks_by_fabric.get(fabric_id) is done: + self._operation_tasks_by_fabric.pop(fabric_id, None) + try: + done.exception() + except (asyncio.CancelledError, Exception): + pass + + task.add_done_callback(completed) + + async def _guard_operation_task( + self, fabric_id: str, awaitable: Any) -> None: + try: + await awaitable + except asyncio.CancelledError: + raise + except Exception: + # Do not attach the original exception: a transport/library + # exception may embed a remote command, path or stderr. The + # validated Fabric id is sufficient to correlate the durable + # operation projection and its fixed reason/checkpoint. + if _FABRIC_KEY.fullmatch(fabric_id) is not None: + LOG.exception( + "Unexpected Fabric operation failure: fabric_id=%s", + fabric_id, exc_info=False) + # Never leave a durable admission row indefinitely "running" + # merely because the panel-side poller hit an unexpected bug. + # The remote unit is not cancelled or replayed; its exact id can + # still be reconciled by the read-only startup loop. + lock = self._locks.setdefault(fabric_id, asyncio.Lock()) + async with lock: + desired = await asyncio.to_thread( + self._load, "fabric_desired", fabric_id) + if desired is None: + return + operation = desired.get("operation") + if (not isinstance(operation, dict) + or operation.get("status") not in { + "queued", "running"}): + return + operation_id = operation.get("id") + dispatch_possible = self._operation_may_have_dispatched( + desired, operation_id) + for node in desired.get("nodes", []): + if not isinstance(node, dict): + continue + node_operation = node.get("operation") + if (isinstance(node_operation, dict) + and node_operation.get("id") + == operation_id + and node_operation.get("status") in { + "pending", "running"}): + phase = _fabric_failure_phase( + node_operation.get("phase")) or "apply" + checkpoint = node_operation.get("checkpoint") + safe_checkpoint = ( + checkpoint + if checkpoint in FABRIC_OPERATION_CHECKPOINTS + else "dispatch") + if (dispatch_possible + and self._node_operation_may_have_dispatched( + node, operation_id)): + self._update_node_operation( + node, status="uncertain", phase=phase, + checkpoint=safe_checkpoint, + reason="status_invalid") + self._record_node_error( + node, "fabric_operation_status_invalid", + failure_phase=phase) + elif dispatch_possible: + self._update_node_operation( + node, status="uncertain", phase=phase, + checkpoint=safe_checkpoint, + reason="status_invalid") + self._record_node_error( + node, "fabric_operation_interrupted", + failure_phase=phase) + else: + # No node had a durable apply/dispatch intent, so + # this exact attempt can safely continue identity + # after an explicit reconcile. Preserve its id; + # automatic recovery still never dispatches it. + self._update_node_operation( + node, status="uncertain", phase=phase, + checkpoint=safe_checkpoint, + reason="status_invalid") + self._record_node_error( + node, "fabric_operation_status_invalid", + failure_phase=phase) + self._update_root_operation( + desired, + "uncertain" if dispatch_possible else "interrupted") + desired["state"] = "uncertain" + desired["next_stage_allowed"] = False + async with self.catalog_mutation_lock(): + await self._persist_operation(desired) + @staticmethod def _probe_host_ids(value: Mapping[str, Any]) -> tuple[str, ...]: """Validate the bounded, exact bulk readiness request.""" @@ -10085,6 +10939,167 @@ class FabricCoordinator: kind, key, json.dumps(value, ensure_ascii=True, separators=(",", ":"))) + @staticmethod + def _new_root_operation( + operation_id: str, kind: str, now: int) -> dict[str, Any]: + operation_id = _validate_operation_id(operation_id) + if kind not in FABRIC_OPERATION_KINDS: + raise FabricError( + "Fabric 操作类型无效", 500, "fabric_operation_invalid") + return { + "id": operation_id, + "kind": kind, + "status": "queued", + "created_at": now, + "started_at": None, + "updated_at": now, + "finished_at": None, + } + + @staticmethod + def _new_node_operation( + operation_id: str, phase: str, now: int) -> dict[str, Any]: + operation_id = _validate_operation_id(operation_id) + if phase not in FABRIC_FAILURE_PHASES: + raise FabricError( + "Fabric 操作阶段无效", 500, "fabric_operation_invalid") + return { + "id": operation_id, + "status": "pending", + "phase": phase, + "checkpoint": "dispatch", + "reason": "none", + "created_at": now, + "started_at": None, + "updated_at": now, + "finished_at": None, + } + + @staticmethod + def _safe_operation_projection( + raw: Any, *, node: bool = False) -> dict[str, Any] | None: + if not isinstance(raw, Mapping): + return None + operation_id = raw.get("id") + status = raw.get("status") + if (not isinstance(operation_id, str) + or _OPERATION_ID.fullmatch(operation_id) is None): + return None + allowed_statuses = ( + FABRIC_NODE_OPERATION_STATUSES if node + else FABRIC_OPERATION_STATUSES) + if status not in allowed_statuses: + return None + result: dict[str, Any] = { + "id": operation_id, + "status": status, + } + if node: + phase = _fabric_failure_phase(raw.get("phase")) + checkpoint = raw.get("checkpoint") + reason = raw.get("reason") + if (phase is None + or checkpoint not in FABRIC_OPERATION_CHECKPOINTS + or reason not in FABRIC_OPERATION_REASONS): + return None + result.update( + phase=phase, checkpoint=checkpoint, reason=reason) + else: + kind = raw.get("kind") + if kind not in FABRIC_OPERATION_KINDS: + return None + result["kind"] = kind + for key in ( + "created_at", "started_at", "updated_at", "finished_at"): + value = raw.get(key) + if value is None and key in {"started_at", "finished_at"}: + result[key] = None + elif (isinstance(value, int) and not isinstance(value, bool) + and value >= 0): + result[key] = value + else: + return None + return result + + @staticmethod + def _operation_reason_for_error(exc: FabricError) -> str: + code = exc.error_code + if code in { + "fabric_host_connection_failed", "fabric_host_unavailable", + "fabric_host_capability_probe_failed"}: + return "transport_failed" + if code in { + "fabric_host_network_manager_conflict", + "fabric_host_capability_missing"}: + return "network_manager_failed" + if code in { + "fabric_host_firewall_mode_conflict", + "firewalld_endpoint_zone_unverified"}: + return "firewall_conflict" + if code in { + "fabric_endpoint_mismatch", "fabric_endpoint_not_local", + "fabric_endpoint_missing", "fabric_endpoint_invalid"}: + return "underlay_conflict" + if code in { + "fabric_identity_conflict", "fabric_host_identity_mismatch"}: + return "ownership_conflict" + if code == "fabric_operation_status_invalid": + return "status_invalid" + if code == "fabric_operation_limit": + return "systemd_failed" + return "command_failed" + + @staticmethod + def _update_root_operation( + desired: dict[str, Any], status: str) -> None: + operation = desired.get("operation") + if (not isinstance(operation, dict) + or status not in FABRIC_OPERATION_STATUSES): + raise FabricError( + "Fabric 操作记录损坏", 500, "fabric_record_corrupt") + now = int(time.time()) + if status == "running" and operation.get("started_at") is None: + operation["started_at"] = now + operation["status"] = status + operation["updated_at"] = now + if status in {"queued", "running"}: + operation["finished_at"] = None + if status in {"succeeded", "failed", "uncertain", "interrupted"}: + operation["finished_at"] = now + desired["updated_at"] = now + + @staticmethod + def _update_node_operation( + node: dict[str, Any], *, status: str, phase: str, + checkpoint: str, reason: str = "none", + remote_times: Mapping[str, Any] | None = None) -> None: + operation = node.get("operation") + if (not isinstance(operation, dict) + or status not in FABRIC_NODE_OPERATION_STATUSES + or phase not in FABRIC_FAILURE_PHASES + or checkpoint not in FABRIC_OPERATION_CHECKPOINTS + or reason not in FABRIC_OPERATION_REASONS): + raise FabricError( + "Fabric 节点操作记录损坏", 500, + "fabric_record_corrupt") + now = int(time.time()) + if status == "running" and operation.get("started_at") is None: + operation["started_at"] = now + operation.update( + status=status, phase=phase, checkpoint=checkpoint, + reason=reason, updated_at=now) + if status in {"pending", "running"}: + operation["finished_at"] = None + if isinstance(remote_times, Mapping): + for key in ("created_at", "started_at", "updated_at", "finished_at"): + value = remote_times.get(key) + if ((isinstance(value, int) and not isinstance(value, bool) + and value >= 0) or value is None): + operation[key] = value + if status in {"succeeded", "failed", "uncertain", "skipped"}: + operation["finished_at"] = ( + operation.get("finished_at") or now) + @staticmethod def _public(value: Mapping[str, Any]) -> dict[str, Any]: """Return a bounded status projection, never a raw durable record. @@ -10105,6 +11120,10 @@ class FabricCoordinator: if (isinstance(listen_port, int) and not isinstance(listen_port, bool) and 1 <= listen_port <= 65535): result["listen_port"] = listen_port + operation = FabricCoordinator._safe_operation_projection( + value.get("operation")) + if operation is not None: + result["operation"] = operation raw_nodes = value.get("nodes") if isinstance(raw_nodes, list): @@ -10126,6 +11145,10 @@ class FabricCoordinator: and isinstance(raw.get("last_error_code"), str) and raw.get("last_error_code")): node["last_error_phase"] = failure_phase + operation = FabricCoordinator._safe_operation_projection( + raw.get("operation"), node=True) + if operation is not None: + node["operation"] = operation observed = raw.get("observed") if isinstance(observed, Mapping): safe_observed: dict[str, Any] = {} @@ -10243,6 +11266,45 @@ class FabricCoordinator: if not isinstance(value, dict): continue self._invalidate(value) + now = int(time.time()) + operation = value.get("operation") + if (isinstance(operation, dict) + and operation.get("status") in {"queued", "running"}): + operation_id = operation.get("id") + dispatch_possible = self._operation_may_have_dispatched( + value, operation_id) + # Preserve the exact attempt id across every crash boundary. + # With no durable apply-phase node, explicit reconcile may + # safely continue identity under this same id. Once any node + # reached apply, recovery is status/readback-only. + operation["status"] = "interrupted" + operation["updated_at"] = now + operation["finished_at"] = now + else: + operation_id = None + dispatch_possible = False + for node in value.get("nodes", []): + if not isinstance(node, dict): + continue + node_operation = node.get("operation") + if (isinstance(node_operation, dict) + and node_operation.get("id") == operation_id + and node_operation.get("status") in { + "pending", "running"}): + if (dispatch_possible + and self._node_operation_may_have_dispatched( + node, operation_id)): + node_operation.update( + status="uncertain", reason="transport_failed", + updated_at=now, finished_at=now) + elif dispatch_possible: + node_operation.update( + status="uncertain", reason="status_invalid", + updated_at=now, finished_at=now) + else: + node_operation.update( + status="uncertain", reason="status_invalid", + updated_at=now, finished_at=now) self._save("fabric_desired", key, value) self._save_nodes_sync(value) @@ -10411,6 +11473,743 @@ class FabricCoordinator: return await _await_mutation_completion( self._apply_locked(plan)) + def _admit_apply_record( + self, plan: FabricPlan, operation_id: str) -> dict[str, Any]: + previous = self._load("fabric_desired", plan.fabric_id) + if previous is not None: + old_operation = previous.get("operation") + if (isinstance(old_operation, Mapping) + and old_operation.get("status") in {"queued", "running"}): + raise FabricError( + "Fabric 操作正在执行", 409, "fabric_operation_busy") + if (isinstance(old_operation, Mapping) + and old_operation.get("status") in { + "interrupted", "uncertain"} + and isinstance(previous.get("nodes"), list) + and any( + isinstance(node, Mapping) + and isinstance(node.get("operation"), Mapping) + and node["operation"].get("id") + == old_operation.get("id") + and node["operation"].get("status") in { + "pending", "running", "uncertain"} + for node in previous.get("nodes", []))): + raise FabricError( + "上次 Fabric 操作结果仍需按原标识核对", 409, + "fabric_operation_reconcile_required") + old_revision = previous.get("revision") + if isinstance(old_revision, int) and plan.revision < old_revision: + raise FabricError( + "Fabric revision 不能回退", 409, + "fabric_revision_conflict") + if (plan.revision == old_revision + and previous.get("plan_digest") == plan.digest): + raise FabricError( + "相同 Fabric 计划已固定,请使用重新核对", + 409, "fabric_operation_reconcile_required") + if (plan.revision == old_revision + and previous.get("plan_digest") != plan.digest): + raise FabricError( + "相同 revision 的 Fabric 计划已存在", 409, + "fabric_revision_conflict") + if plan.region != previous.get("region"): + raise FabricError( + "Fabric 地区不可直接变更,请走迁移流程", 409, + "fabric_region_conflict") + old_nodes = previous.get("nodes") + if not isinstance(old_nodes, list): + raise FabricError( + "Fabric 持久化记录损坏", 500, + "fabric_record_corrupt") + old_hosts = { + item.get("host_id") for item in old_nodes + if isinstance(item, Mapping) + } + if len(old_hosts) != len(old_nodes): + raise FabricError( + "Fabric 持久化记录损坏", 500, + "fabric_record_corrupt") + if old_hosts != {node.host_id for node in plan.nodes}: + raise FabricError( + "Fabric 参与宿主机集合不可直接变更,请走迁移流程", + 409, "fabric_membership_conflict") + self._validate_resource_exclusivity(plan) + now = int(time.time()) + return { + "schema_version": FABRIC_SCHEMA_VERSION, + "fabric_id": plan.fabric_id, + "region": plan.region, + "overlay_cidr": plan.overlay_cidr, + "revision": plan.revision, + "listen_port": plan.listen_port, + "plan_digest": plan.digest, + "interface": FABRIC_INTERFACE, + "state": "applying", + "next_stage_allowed": False, + "public_keys": {}, + "operation": self._new_root_operation( + operation_id, "apply", now), + "nodes": [ + { + "host_id": node.host_id, + "overlay_ip": node.overlay_ip, + "endpoint": node.endpoint, + "listen_port": node.listen_port, + "state": "applying", + "transport_verified": False, + "observed_revision": None, + "observed_plan_digest": None, + "operation": self._new_node_operation( + operation_id, "identity", now), + } + for node in plan.nodes + ], + "updated_at": now, + } + + async def enqueue_apply( + self, value: Mapping[str, Any]) -> dict[str, Any]: + """Durably admit an apply and return before host mutation completes.""" + plan = parse_fabric_plan(value) + if plan.fabric_id in self._operation_tasks_by_fabric: + raise FabricError( + "Fabric 操作正在执行", 409, "fabric_operation_busy") + operation_id = _new_operation_id() + lock = self._locks.setdefault(plan.fabric_id, asyncio.Lock()) + async with lock: + async with self.catalog_mutation_lock(): + desired = await asyncio.to_thread( + self._admit_apply_record, plan, operation_id) + await asyncio.to_thread( + self._save, "fabric_desired", plan.fabric_id, desired) + await self._save_nodes(desired) + self._track_operation_task( + plan.fabric_id, + self._run_enqueued_operation( + plan.fabric_id, operation_id, "apply")) + return self._public(desired) + + async def enqueue_reconcile(self, fabric_id: str) -> dict[str, Any]: + """Queue an explicit fixed-plan reconciliation without HTTP waiting.""" + if not _FABRIC_KEY.fullmatch(fabric_id): + raise FabricError("Fabric 标识无效") + if fabric_id in self._operation_tasks_by_fabric: + raise FabricError( + "Fabric 操作正在执行", 409, "fabric_operation_busy") + operation_id = _new_operation_id() + resume_existing = False + resume_status_only = False + resume_kind = "reconcile" + identity_bootstrap = False + lock = self._locks.setdefault(fabric_id, asyncio.Lock()) + async with lock: + # Lock order is always per-Fabric -> shared catalog. Close the + # authoritative gate and admit the operation while holding the + # same lock used by VPC catalog consumers. + async with self.catalog_mutation_lock(): + desired, plan = await _await_mutation_completion( + self._begin_reconcile(fabric_id)) + old_operation = desired.get("operation") + if (isinstance(old_operation, Mapping) + and old_operation.get("status") in { + "queued", "running", "interrupted", "uncertain"} + and isinstance(old_operation.get("id"), str) + and _OPERATION_ID.fullmatch( + old_operation["id"]) is not None): + unsettled = any( + isinstance(node, Mapping) + and isinstance(node.get("operation"), Mapping) + and node["operation"].get("id") + == old_operation["id"] + and node["operation"].get("status") in { + "pending", "running", "uncertain"} + for node in desired.get("nodes", []) + ) + # A queued/running durable row without a task owned by + # this process is necessarily a restart join. Periodic + # readback may have changed the recovered root from + # interrupted back to running after observing the same + # remote queued job. Explicit reconcile must therefore + # retain the exact id and enter the guarded queued-gap + # recovery instead of returning busy forever. The task + # registry check above remains the authoritative in- + # process concurrency guard. + if (old_operation.get("status") in {"queued", "running"} + or unsettled): + operation_id = old_operation["id"] + resume_existing = True + resume_status_only = ( + self._operation_may_have_dispatched( + desired, operation_id)) + old_kind = old_operation.get("kind") + if old_kind not in FABRIC_OPERATION_KINDS: + raise FabricError( + "Fabric 操作记录损坏", 500, + "fabric_record_corrupt") + resume_kind = old_kind + elif (isinstance(old_operation, Mapping) + and old_operation.get("status") in { + "queued", "running"}): + # Never replace an apparently live attempt whose exact + # operation identity cannot be proven. + raise FabricError( + "Fabric 操作记录损坏", 500, + "fabric_record_corrupt") + + raw_nodes = desired.get("nodes") + if not isinstance(raw_nodes, list): + raise FabricError( + "Fabric 节点记录损坏", 500, + "fabric_record_corrupt") + public_keys = desired.get("public_keys") + validated_keys: dict[str, str] | None = None + if (isinstance(public_keys, dict) + and set(public_keys) == { + node.host_id for node in plan.nodes}): + try: + validated_keys = { + host_id: validate_wireguard_key(key) + for host_id, key in public_keys.items() + } + except FabricError: + validated_keys = None + if (validated_keys is not None + and len(set(validated_keys.values())) + != len(validated_keys)): + validated_keys = None + + # A failed attempt with no durable apply-phase node proves + # that no host unit could have been accepted. Explicit + # reconcile may safely resume identity collection for the + # fixed desired plan; all other incomplete key records remain + # fail-closed corruption. + identity_bootstrap = bool( + validated_keys is None + and isinstance(old_operation, Mapping) + and not self._operation_may_have_dispatched( + desired, old_operation.get("id")) + and (resume_existing + or old_operation.get("status") == "failed")) + if validated_keys is None and not identity_bootstrap: + raise FabricError( + "Fabric 公钥记录损坏", 500, + "fabric_record_corrupt") + + if resume_existing: + # Preserve the exact operation id. Before the durable + # apply fence it is safe to continue identity/coordinator + # work under that id; after the fence this admission is + # strictly status/readback-only. + self._update_root_operation(desired, "running") + else: + now = int(time.time()) + desired["operation"] = self._new_root_operation( + operation_id, "reconcile", now) + if identity_bootstrap: + desired["public_keys"] = {} + for node in raw_nodes: + if not isinstance(node, dict): + raise FabricError( + "Fabric 节点记录损坏", 500, + "fabric_record_corrupt") + node["operation"] = self._new_node_operation( + operation_id, + "identity" if identity_bootstrap else "observe", + now) + desired["state"] = "applying" + desired["next_stage_allowed"] = False + await _await_mutation_completion( + self._persist_operation(desired)) + self._track_operation_task( + fabric_id, + (self._observe_only( + fabric_id, allow_tracked=True, recover_queued=True) + if resume_status_only else + self._run_enqueued_operation( + fabric_id, operation_id, + resume_kind if resume_existing else "reconcile"))) + return self._public(desired) + + async def _persist_operation(self, desired: dict[str, Any]) -> None: + fabric_id = desired.get("fabric_id") + if not isinstance(fabric_id, str): + raise FabricError( + "Fabric 操作记录损坏", 500, "fabric_record_corrupt") + operation = desired.get("operation") + if (isinstance(operation, Mapping) + and operation.get("status") in {"queued", "running"}): + desired["state"] = "applying" + desired["next_stage_allowed"] = False + await asyncio.to_thread( + self._save, "fabric_desired", fabric_id, desired) + await self._save_nodes(desired) + + @staticmethod + def _operation_matches( + desired: Mapping[str, Any], operation_id: str, + kind: str) -> bool: + operation = desired.get("operation") + return bool( + isinstance(operation, Mapping) + and operation.get("id") == operation_id + and operation.get("kind") == kind + and operation.get("status") in { + "queued", "running", "interrupted", "uncertain"}) + + @staticmethod + def _node_operation_may_have_dispatched( + node: Mapping[str, Any], operation_id: Any) -> bool: + if (not isinstance(operation_id, str) + or _OPERATION_ID.fullmatch(operation_id) is None): + return False + operation = node.get("operation") + if (not isinstance(operation, Mapping) + or operation.get("id") != operation_id): + return False + return bool( + operation.get("phase") == "apply" + or (operation.get("phase") == "observe" + and operation.get("checkpoint") in { + "final_readback", "complete"})) + + @classmethod + def _operation_may_have_dispatched( + cls, desired: Mapping[str, Any], operation_id: Any) -> bool: + """Return whether a remote unit may own this exact operation id. + + The coordinator durably changes a node to phase ``apply`` immediately + before sending the dispatcher. Earlier phases therefore prove that + no remote mutation could have been accepted. Final readback is also a + dispatch fence because it is reached only after remote success. + """ + nodes = desired.get("nodes") + return bool( + isinstance(nodes, list) + and any( + isinstance(node, Mapping) + and cls._node_operation_may_have_dispatched( + node, operation_id) + for node in nodes)) + + async def _fail_operation_before_dispatch( + self, desired: dict[str, Any], exc: FabricError, + *, phase: str) -> None: + reason = self._operation_reason_for_error(exc) + for node in desired.get("nodes", []): + if not isinstance(node, dict): + continue + operation = node.get("operation") + if (isinstance(operation, Mapping) + and operation.get("status") in {"pending", "running"}): + self._update_node_operation( + node, status="failed", phase=phase, + checkpoint="dispatch", reason=reason) + self._record_node_error( + node, exc.error_code, failure_phase=phase) + self._update_root_operation(desired, "failed") + self._finish(desired) + await self._persist_operation(desired) + + async def _run_enqueued_operation( + self, fabric_id: str, operation_id: str, kind: str) -> None: + """Drive one admitted operation while the host owns each mutation.""" + lock = self._locks.setdefault(fabric_id, asyncio.Lock()) + async with lock: + desired = await asyncio.to_thread( + self._load, "fabric_desired", fabric_id) + if (desired is None + or not self._operation_matches( + desired, operation_id, kind)): + return + self._update_root_operation(desired, "running") + await self._persist_operation(desired) + try: + plan = self._plan_from_record(desired) + components = await self._components(plan) + except asyncio.CancelledError: + raise + except FabricError as exc: + await self._fail_operation_before_dispatch( + desired, exc, phase="identity") + return + except Exception: + await self._fail_operation_before_dispatch( + desired, + FabricError( + "Fabric 操作准备失败", 502, + "fabric_host_unavailable", "identity"), + phase="identity") + return + + node_records = { + node.get("host_id"): node + for node in desired.get("nodes", []) + if isinstance(node, dict) + and isinstance(node.get("host_id"), str) + } + adapters = { + host.host_id: FabricHostAdapter( + components[host.host_id][0].manager, + components[host.host_id][1]) + for host in plan.nodes + } + public_keys: dict[str, str] + raw_keys = desired.get("public_keys") + fixed_public_keys: dict[str, str] | None = None + if (isinstance(raw_keys, dict) + and set(raw_keys) == { + host.host_id for host in plan.nodes}): + fixed_public_keys = { + host_id: validate_wireguard_key(key) + for host_id, key in raw_keys.items() + } + identity_bootstrap = bool( + kind == "apply" + or ( + kind == "reconcile" + and (not isinstance(raw_keys, dict) + or set(raw_keys) != { + host.host_id for host in plan.nodes}) + and not self._operation_may_have_dispatched( + desired, operation_id) + and all( + isinstance(node.get("operation"), Mapping) + and node["operation"].get("id") == operation_id + and node["operation"].get("phase") == "identity" + for node in node_records.values()))) + if identity_bootstrap: + public_keys = {} + identity_failed = False + for host in plan.nodes: + node = node_records[host.host_id] + self._update_node_operation( + node, status="running", phase="identity", + checkpoint="identity") + await self._persist_operation(desired) + try: + public_keys[host.host_id] = ( + await _await_mutation_completion( + asyncio.to_thread( + adapters[host.host_id].identity))) + except FabricError as exc: + identity_failed = True + self._update_node_operation( + node, status="failed", phase="identity", + checkpoint="identity", + reason=self._operation_reason_for_error(exc)) + self._record_node_error( + node, exc.error_code, failure_phase="identity") + identity_changed = bool( + fixed_public_keys is not None + and public_keys != fixed_public_keys) + if (identity_failed or identity_changed + or len(set(public_keys.values())) != len(plan.nodes)): + if identity_changed: + conflict = FabricError( + "宿主机 WireGuard 身份与固定计划不一致", + 409, "fabric_identity_conflict", "identity") + for node in node_records.values(): + self._update_node_operation( + node, status="failed", phase="identity", + checkpoint="identity", + reason="ownership_conflict") + self._record_node_error( + node, conflict.error_code, + failure_phase="identity") + if (not identity_failed + and not identity_changed + and len(set(public_keys.values())) != len(plan.nodes)): + duplicate = FabricError( + "Fabric 宿主机公钥不能重复", 409, + "fabric_identity_conflict", "identity") + for node in node_records.values(): + self._update_node_operation( + node, status="failed", phase="identity", + checkpoint="identity", + reason="ownership_conflict") + self._record_node_error( + node, duplicate.error_code, + failure_phase="identity") + for node in node_records.values(): + operation = node.get("operation") + if (isinstance(operation, Mapping) + and operation.get("status") in { + "pending", "running"}): + self._update_node_operation( + node, status="skipped", phase="identity", + checkpoint="identity") + self._update_root_operation(desired, "failed") + self._finish(desired) + await self._persist_operation(desired) + return + desired["public_keys"] = dict(public_keys) + for node in desired.get("nodes", []): + if isinstance(node, dict): + node["public_key"] = public_keys[node["host_id"]] + # This identity fence must be durable before the first host + # can accept the shared operation id. A panel crash can then + # always reconstruct the exact fixed plan for status-only + # recovery without inventing replacement keys. + await self._persist_operation(desired) + else: + if (not isinstance(raw_keys, dict) + or set(raw_keys) != { + host.host_id for host in plan.nodes}): + await self._fail_operation_before_dispatch( + desired, + FabricError( + "Fabric 公钥记录损坏", 500, + "fabric_record_corrupt", "identity"), + phase="identity") + return + public_keys = { + host_id: validate_wireguard_key(key) + for host_id, key in raw_keys.items() + } + + targets: list[FabricNode] = list(plan.nodes) + if kind == "reconcile" and not identity_bootstrap: + targets = [] + for host in plan.nodes: + node = node_records[host.host_id] + self._update_node_operation( + node, status="running", phase="observe", + checkpoint="preflight") + try: + observed = await asyncio.to_thread( + adapters[host.host_id].observe, + plan, host, public_keys) + self._record_reconcile_observation(node, observed) + if self._reconcile_observation_is_exact( + observed, plan, host, public_keys): + self._update_node_operation( + node, status="skipped", phase="observe", + checkpoint="complete") + else: + targets.append(host) + except FabricError: + targets.append(host) + await self._persist_operation(desired) + + identities_valid = True + for host in targets: + node = node_records[host.host_id] + self._update_node_operation( + node, status="running", phase="identity", + checkpoint="identity") + try: + actual_key = await asyncio.to_thread( + adapters[host.host_id].identity, + create_key=False) + if actual_key != public_keys[host.host_id]: + raise FabricError( + "宿主机 WireGuard 身份与固定计划不一致", + 409, "fabric_identity_conflict", "identity") + except FabricError as exc: + identities_valid = False + self._update_node_operation( + node, status="failed", phase="identity", + checkpoint="identity", + reason=self._operation_reason_for_error(exc)) + self._record_node_error( + node, exc.error_code, + failure_phase="identity") + await self._persist_operation(desired) + if not identities_valid: + for host in targets: + node = node_records[host.host_id] + operation = node.get("operation") + if (isinstance(operation, Mapping) + and operation.get("status") == "running"): + self._update_node_operation( + node, status="skipped", phase="identity", + checkpoint="identity") + self._update_root_operation(desired, "failed") + self._finish(desired) + await self._persist_operation(desired) + return + + pending: dict[str, tuple[FabricNode, FabricHostAdapter]] = {} + for host in targets: + node = node_records[host.host_id] + self._update_node_operation( + node, status="running", phase="apply", + checkpoint="dispatch") + # Persist intent before the remote dispatcher can accept the + # unit. Recovery therefore treats this exact id as possibly + # admitted even when the SSH response is lost. + await self._persist_operation(desired) + try: + remote_status = await _await_mutation_completion( + asyncio.to_thread( + adapters[host.host_id].dispatch_apply, + plan, host, public_keys, operation_id)) + self._record_remote_operation_status( + node, remote_status) + pending[host.host_id] = ( + host, adapters[host.host_id]) + except FabricError as exc: + # Once the dispatcher call starts, every failure except + # its explicit pre-admission directory limit is + # ambiguous: the host may have accepted the exact id and + # only the follow-up status read may have failed. Keep + # polling that same id and never replay the dispatcher. + failure_reason = self._operation_reason_for_error(exc) + definitely_not_admitted = ( + exc.error_code == "fabric_operation_limit") + node_status = ( + "failed" if definitely_not_admitted else "uncertain") + if (not definitely_not_admitted + and exc.error_code in { + "fabric_operation_status_invalid", + "fabric_remote_command_failed", + "fabric_operation_not_found"}): + failure_reason = "status_invalid" + self._update_node_operation( + node, status=node_status, phase="apply", + checkpoint="dispatch", + reason=failure_reason) + self._record_node_error( + node, exc.error_code, failure_phase="apply") + if not definitely_not_admitted: + # The dispatcher may have accepted the exact id before + # the response/status loss. Poll only that id; never + # replay the dispatch to discover the outcome. + pending[host.host_id] = ( + host, adapters[host.host_id]) + await self._persist_operation(desired) + + deadline = time.monotonic() + FABRIC_OPERATION_POLL_TIMEOUT_SECONDS + while pending and time.monotonic() < deadline: + for host_id, (host, adapter) in tuple(pending.items()): + node = node_records[host_id] + try: + remote_status = await asyncio.to_thread( + adapter.apply_status, operation_id) + except FabricError as exc: + reason = self._operation_reason_for_error(exc) + if reason == "transport_failed": + # A temporary SSH failure says nothing about the + # host-owned unit. Keep polling only this exact id. + continue + checkpoint = node.get("operation", {}).get( + "checkpoint") + if exc.error_code in { + "fabric_operation_status_invalid", + "fabric_remote_command_failed", + "fabric_operation_not_found"}: + reason = "status_invalid" + self._update_node_operation( + node, status="uncertain", phase="apply", + checkpoint=( + checkpoint + if checkpoint in FABRIC_OPERATION_CHECKPOINTS + else "dispatch"), + reason=reason) + self._record_node_error( + node, exc.error_code, + failure_phase="apply") + pending.pop(host_id, None) + continue + self._record_remote_operation_status( + node, remote_status) + if remote_status["status"] == "succeeded": + try: + observed = await asyncio.to_thread( + adapter.observe, plan, host, public_keys) + self._record_reconcile_observation(node, observed) + if self._reconcile_observation_is_exact( + observed, plan, host, public_keys): + self._update_node_operation( + node, status="succeeded", + phase="observe", checkpoint="complete", + remote_times=remote_status) + else: + self._update_node_operation( + node, status="uncertain", + phase="observe", + checkpoint="final_readback", + reason="readback_failed", + remote_times=remote_status) + self._record_node_error( + node, "fabric_readback_mismatch", + failure_phase="observe") + except FabricError as exc: + self._update_node_operation( + node, status="uncertain", phase="observe", + checkpoint="final_readback", + reason=self._operation_reason_for_error(exc), + remote_times=remote_status) + self._record_node_error( + node, exc.error_code, + failure_phase="observe") + pending.pop(host_id, None) + elif remote_status["status"] in { + "failed", "uncertain", "interrupted"}: + self._record_node_error( + node, "fabric_remote_command_failed", + failure_phase="apply") + pending.pop(host_id, None) + await self._persist_operation(desired) + if pending: + await asyncio.sleep(FABRIC_OPERATION_POLL_INTERVAL_SECONDS) + for host_id in pending: + node = node_records[host_id] + operation = node.get("operation") + checkpoint = ( + operation.get("checkpoint") + if isinstance(operation, Mapping) else "dispatch") + self._update_node_operation( + node, status="uncertain", phase="apply", + checkpoint=(checkpoint + if checkpoint in FABRIC_OPERATION_CHECKPOINTS + else "dispatch"), + reason="transport_failed") + self._record_node_error( + node, "fabric_operation_status_timeout", + failure_phase="apply") + + operation_statuses = { + node.get("operation", {}).get("status") + for node in node_records.values() + if isinstance(node.get("operation"), Mapping) + } + if operation_statuses <= {"succeeded", "skipped"}: + root_status = "succeeded" + elif "uncertain" in operation_statuses: + root_status = "uncertain" + else: + root_status = "failed" + self._update_root_operation(desired, root_status) + async with self.catalog_mutation_lock(): + await _await_mutation_completion( + self._publish_reconcile( + desired, plan, respect_operation=True)) + + def _record_remote_operation_status( + self, node: dict[str, Any], remote: Mapping[str, Any]) -> None: + state = remote.get("status") + checkpoint = remote.get("checkpoint") + reason = remote.get("reason") + if (state not in FABRIC_OPERATION_STATUSES + or checkpoint not in FABRIC_OPERATION_CHECKPOINTS + or reason not in FABRIC_OPERATION_REASONS): + raise FabricError( + "宿主机 Fabric 操作状态无效", 502, + "fabric_operation_status_invalid", "observe") + node_status = { + "queued": "pending", + "running": "running", + "succeeded": "running", + "failed": "failed", + "uncertain": "uncertain", + "interrupted": "uncertain", + }[state] + self._update_node_operation( + node, status=node_status, phase="apply", + checkpoint=checkpoint, reason=reason, + remote_times=remote) + def _validate_resource_exclusivity(self, plan: FabricPlan) -> None: """Reserve host, overlay and underlay address space fail closed. @@ -10696,6 +12495,10 @@ class FabricCoordinator: and isinstance(node.get("last_error_code"), str) and node.get("last_error_code")): value["last_error_phase"] = failure_phase + operation = self._safe_operation_projection( + node.get("operation"), node=True) + if operation is not None: + value["operation"] = operation self._save( "fabric_node", self._node_key( @@ -10738,19 +12541,20 @@ class FabricCoordinator: if desired is None: raise FabricError( "Fabric 不存在", 404, "fabric_not_found") - plan = self._plan_from_record(desired) - if desired.get("plan_digest") != plan.digest: - raise FabricError( - "Fabric 计划摘要与持久化记录不一致", 500, - "fabric_record_corrupt") - # The root row is the VPC admission authority, so close it before - # updating diagnostic node projections. A failure between the two - # writes therefore remains fail closed. + # parsing keys, rebuilding components, or updating diagnostic node + # projections. Any corrupt record or offline host therefore leaves + # the authoritative gate durably closed rather than returning with a + # stale active decision. self._invalidate(desired) await asyncio.to_thread( self._save, "fabric_desired", fabric_id, desired) await self._save_nodes(desired) + plan = self._plan_from_record(desired) + if desired.get("plan_digest") != plan.digest: + raise FabricError( + "Fabric 计划摘要与持久化记录不一致", 500, + "fabric_record_corrupt") # Reject deterministic catalog conflicts before doing any SSH work. # The same check is repeated at publication because another catalog # writer may complete while the shared lock is released for readback. @@ -10758,7 +12562,8 @@ class FabricCoordinator: return desired, plan async def _publish_reconcile( - self, desired: dict[str, Any], plan: FabricPlan) -> None: + self, desired: dict[str, Any], plan: FabricPlan, *, + respect_operation: bool = False) -> None: """Revalidate the catalog and publish a completed readback. The caller holds the per-Fabric lock followed by the shared catalog @@ -10766,8 +12571,36 @@ class FabricCoordinator: gate, so readers can never observe an active root with stale node diagnostics from this reconcile pass. """ + current = await asyncio.to_thread( + self._load, "fabric_desired", plan.fabric_id) + if current is None: + raise FabricError( + "Fabric 操作记录已不存在", 409, + "fabric_operation_status_invalid") + desired_operation = desired.get("operation") + current_operation = current.get("operation") + desired_operation_id = ( + desired_operation.get("id") + if isinstance(desired_operation, Mapping) else None) + current_operation_id = ( + current_operation.get("id") + if isinstance(current_operation, Mapping) else None) + if (current.get("plan_digest") != plan.digest + or desired.get("plan_digest") != plan.digest + or current_operation_id != desired_operation_id): + raise FabricError( + "Fabric 操作已被新的持久化状态替代", 409, + "fabric_operation_status_invalid") await asyncio.to_thread(self._validate_resource_exclusivity, plan) self._finish(desired) + if respect_operation and isinstance(desired_operation, Mapping): + operation_status = desired_operation.get("status") + if operation_status != "succeeded": + desired["next_stage_allowed"] = False + desired["state"] = ( + "applying" if operation_status in {"queued", "running"} + else "uncertain") + desired["updated_at"] = int(time.time()) await self._save_nodes(desired) await asyncio.to_thread( self._save, "fabric_desired", plan.fabric_id, desired) @@ -10947,16 +12780,333 @@ class FabricCoordinator: self._publish_reconcile(desired, plan)) return self._public(desired) + async def _observe_only( + self, fabric_id: str, *, allow_tracked: bool = False, + recover_queued: bool = False) -> None: + """Refresh one plan; only explicit recovery may continue its exact id.""" + if (not allow_tracked + and fabric_id in self._operation_tasks_by_fabric): + return + lock = self._locks.setdefault(fabric_id, asyncio.Lock()) + async with lock: + # Close the VPC admission gate under the shared catalog lock + # before any key validation, component lookup or SSH read. An + # offline host or corrupt record can then never leave a stale + # active root visible to a concurrent VPC admission. + async with self.catalog_mutation_lock(): + desired, plan = await _await_mutation_completion( + self._begin_reconcile(fabric_id)) + raw_keys = desired.get("public_keys") + if (not isinstance(raw_keys, dict) + or set(raw_keys) != { + host.host_id for host in plan.nodes}): + raise FabricError( + "Fabric 公钥记录损坏", 500, + "fabric_record_corrupt") + public_keys = { + host_id: validate_wireguard_key(key) + for host_id, key in raw_keys.items() + } + if len(set(public_keys.values())) != len(public_keys): + raise FabricError( + "Fabric 公钥记录包含重复身份", 500, + "fabric_record_corrupt") + components = await self._components(plan) + nodes = { + node.get("host_id"): node + for node in desired.get("nodes", []) + if isinstance(node, dict) + and isinstance(node.get("host_id"), str) + } + operation = desired.get("operation") + operation_id = ( + operation.get("id") if isinstance(operation, Mapping) + else None) + operation_unsettled = bool( + isinstance(operation_id, str) + and _OPERATION_ID.fullmatch(operation_id) is not None + and isinstance(operation, Mapping) + and operation.get("status") in { + "queued", "running", "interrupted", "uncertain"}) + remote_operation_running = False + undispatched_targets: list[ + tuple[FabricNode, dict[str, Any], FabricHostAdapter] + ] = [] + for host in plan.nodes: + node = nodes.get(host.host_id) + if not isinstance(node, dict): + continue + adapter = FabricHostAdapter( + components[host.host_id][0].manager, + components[host.host_id][1]) + node_operation = node.get("operation") + node_dispatched = bool( + operation_unsettled + and self._node_operation_may_have_dispatched( + node, operation_id)) + terminal_remote = False + in_progress_remote = False + status_unavailable = False + if (node_dispatched + and isinstance(node_operation, dict) + and node_operation.get("id") == operation_id + and node_operation.get("status") not in { + "succeeded", "skipped", "failed"}): + try: + remote_status = await asyncio.to_thread( + adapter.apply_status, operation_id) + if (recover_queued + and remote_status.get("status") == "queued"): + # Explicit reconcile may close the narrow crash + # gap after the immutable operation directory was + # published but before systemd-run. The dispatcher + # validates the exact retained scripts/id and only + # starts the original runner when the unit is + # proven not-found; a loaded unit is never replayed. + remote_status = await _await_mutation_completion( + asyncio.to_thread( + adapter.dispatch_apply, + plan, host, public_keys, operation_id)) + self._record_remote_operation_status( + node, remote_status) + in_progress_remote = remote_status.get("status") in { + "queued", "running"} + remote_operation_running = ( + remote_operation_running or in_progress_remote) + terminal_remote = remote_status.get("status") in { + "failed", "uncertain", "interrupted"} + if terminal_remote: + self._record_node_error( + node, "fabric_remote_command_failed", + failure_phase="apply") + except FabricError as exc: + # The /run operation directory may disappear after a + # host reboot. Exact observation below can still + # prove that the journal/boot repair converged; absent + # proof, the same operation remains uncertain. + if exc.error_code != "fabric_operation_not_found": + checkpoint = node_operation.get("checkpoint") + reason = self._operation_reason_for_error(exc) + if exc.error_code in { + "fabric_operation_status_invalid", + "fabric_remote_command_failed"}: + reason = "status_invalid" + self._update_node_operation( + node, status="uncertain", phase="apply", + checkpoint=( + checkpoint + if checkpoint + in FABRIC_OPERATION_CHECKPOINTS + else "dispatch"), + reason=reason) + self._record_node_error( + node, exc.error_code, + failure_phase="apply") + terminal_remote = True + status_unavailable = True + # A real remote terminal state may still have converged + # exactly (for example the runner reported failure after the + # final host write). Prove that with read-only observation so + # a partial multi-host attempt can continue safely. In + # contrast, an unavailable/invalid status must never borrow an + # old exact observation while the host unit may still run. + if in_progress_remote or status_unavailable: + continue + try: + observed = await asyncio.to_thread( + adapter.observe, plan, host, public_keys) + self._record_reconcile_observation(node, observed) + if (operation_unsettled + and isinstance(node_operation, dict) + and node_operation.get("id") == operation_id): + if self._reconcile_observation_is_exact( + observed, plan, host, public_keys): + self._update_node_operation( + node, status="succeeded", phase="observe", + checkpoint="complete") + elif not node_dispatched: + # Preserve the per-node proof that no dispatcher + # was ever admitted. Explicit reconcile may finish + # this node later under the same operation id once + # every already-admitted node is exact. + self._update_node_operation( + node, status="uncertain", phase="identity", + checkpoint="identity", + reason="readback_failed") + self._record_node_error( + node, "fabric_readback_mismatch", + failure_phase="observe") + undispatched_targets.append( + (host, node, adapter)) + else: + self._update_node_operation( + node, status="uncertain", phase="observe", + checkpoint="final_readback", + reason="readback_failed") + self._record_node_error( + node, "fabric_readback_mismatch", + failure_phase="observe") + except FabricError as exc: + self._record_node_error( + node, exc.error_code, failure_phase="observe") + if (operation_unsettled + and isinstance(node_operation, dict) + and node_operation.get("id") == operation_id + and node_operation.get("status") not in { + "failed", "succeeded"}): + if node_dispatched: + checkpoint = node_operation.get("checkpoint") + self._update_node_operation( + node, status="uncertain", phase="observe", + checkpoint=( + checkpoint + if checkpoint + in FABRIC_OPERATION_CHECKPOINTS + else "final_readback"), + reason=self._operation_reason_for_error(exc)) + else: + self._update_node_operation( + node, status="uncertain", phase="identity", + checkpoint="identity", + reason=self._operation_reason_for_error(exc)) + undispatched_targets.append( + (host, node, adapter)) + + if recover_queued and undispatched_targets: + dispatched_nodes = [ + node for node in nodes.values() + if (isinstance(node, Mapping) + and self._node_operation_may_have_dispatched( + node, operation_id)) + ] + admitted_exact = bool(dispatched_nodes) and all( + isinstance(node.get("operation"), Mapping) + and node["operation"].get("status") == "succeeded" + and node.get("state") == "active" + and node.get("transport_verified") is True + and str(node.get("observed_revision", "")) + == str(plan.revision) + and node.get("observed_plan_digest") == plan.digest + for node in dispatched_nodes + ) + identities_valid = admitted_exact + if admitted_exact: + # Revalidate every definitely-unadmitted identity before + # the first continuation write, matching the original + # all-identities-before-dispatch safety gate. + for host, node, adapter in undispatched_targets: + try: + actual_key = await _await_mutation_completion( + asyncio.to_thread( + adapter.identity, create_key=False)) + if actual_key != public_keys[host.host_id]: + raise FabricError( + "宿主机 WireGuard 身份与固定计划不一致", + 409, "fabric_identity_conflict", + "identity") + except FabricError as exc: + identities_valid = False + self._update_node_operation( + node, status="failed", phase="identity", + checkpoint="identity", + reason=self._operation_reason_for_error(exc)) + self._record_node_error( + node, exc.error_code, + failure_phase="identity") + if identities_valid: + for host, node, adapter in undispatched_targets: + self._update_node_operation( + node, status="running", phase="apply", + checkpoint="dispatch") + # Per-node intent is durable before this host can + # accept the shared operation id. + await self._persist_operation(desired) + try: + remote_status = ( + await _await_mutation_completion( + asyncio.to_thread( + adapter.dispatch_apply, + plan, host, public_keys, + operation_id))) + self._record_remote_operation_status( + node, remote_status) + if remote_status.get("status") in { + "failed", "uncertain", "interrupted"}: + self._record_node_error( + node, "fabric_remote_command_failed", + failure_phase="apply") + if node.get("operation", {}).get("status") in { + "pending", "running"}: + remote_operation_running = True + except FabricError as exc: + definitely_not_admitted = ( + exc.error_code == "fabric_operation_limit") + reason = self._operation_reason_for_error(exc) + if (not definitely_not_admitted + and exc.error_code in { + "fabric_operation_status_invalid", + "fabric_remote_command_failed", + "fabric_operation_not_found"}): + reason = "status_invalid" + self._update_node_operation( + node, + status=("failed" if definitely_not_admitted + else "uncertain"), + phase="apply", checkpoint="dispatch", + reason=reason) + self._record_node_error( + node, exc.error_code, + failure_phase="apply") + await self._persist_operation(desired) + if remote_operation_running: + desired["state"] = "applying" + desired["next_stage_allowed"] = False + desired["updated_at"] = int(time.time()) + else: + self._finish(desired) + if operation_unsettled and isinstance(operation, dict): + statuses = { + node.get("operation", {}).get("status") + for node in nodes.values() + if (isinstance(node.get("operation"), Mapping) + and node["operation"].get("id") == operation_id) + } + if statuses and statuses <= {"succeeded", "skipped"}: + self._update_root_operation(desired, "succeeded") + elif statuses & {"pending", "running"}: + self._update_root_operation(desired, "running") + elif "uncertain" in statuses: + self._update_root_operation(desired, "uncertain") + elif "failed" in statuses: + self._update_root_operation(desired, "failed") + async with self.catalog_mutation_lock(): + await _await_mutation_completion( + self._publish_reconcile( + desired, plan, respect_operation=True)) + async def reconcile_all(self) -> None: - """Read back every durable fabric after an engine restart.""" + """Read back every durable Fabric; never create a host write.""" items = await asyncio.to_thread(self.list_status) for item in items: fabric_id = item.get("fabric_id") - if not isinstance(fabric_id, str): + if (not isinstance(fabric_id, str) + or _FABRIC_KEY.fullmatch(fabric_id) is None): continue try: - await self.reconcile(fabric_id) + await self._observe_only(fabric_id) + except asyncio.CancelledError: + raise + except FabricError: + # Expected host/configuration failures are already projected + # through fixed error codes and operation checkpoints. + continue except Exception: + # As above, omit the original exception because third-party + # exceptions may carry raw remote output. The validated id + # safely correlates this internal failure with durable state. + LOG.exception( + "Unexpected Fabric reconciliation failure: fabric_id=%s", + fabric_id, exc_info=False) # One offline host must not block engine startup or prevent # other fabrics from being observed. continue diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index 4530891e..f98dac62 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -1061,8 +1061,8 @@ class EngineApplication: raise FabricError("Fabric 计划 JSON 无效", 422) from exc if not isinstance(value, dict): raise FabricError("Fabric 计划必须是对象", 422) - result = await self.fabric.apply(value) - await json_response(send, 200, result) + result = await self.fabric.enqueue_apply(value) + await json_response(send, 202, result) return if resource == "fabric/probe": try: @@ -1085,8 +1085,8 @@ class EngineApplication: if match is not None: if body not in (b"", b"{}"): raise FabricError("Fabric reconcile 不接受请求体", 422) - result = await self.fabric.reconcile(match[1]) - await json_response(send, 200, result) + result = await self.fabric.enqueue_reconcile(match[1]) + await json_response(send, 202, result) return raise FabricError("内部资源不存在", 404) except FabricError as exc: @@ -3568,6 +3568,11 @@ class EngineApplication: await send({"type": "lifespan.startup.failed", "message": "引擎初始化失败"}) return elif message["type"] == "lifespan.shutdown": + # Stop only the panel-side operation pollers. A Fabric write + # already accepted by a host remains owned by its transient + # systemd unit and is recovered by operation-id readback after + # the engine restarts; it must never be replayed here. + await self.fabric.shutdown_operations() if self.vpc_reconcile_task is not None: self.vpc_reconcile_task.cancel() await asyncio.gather( diff --git a/web/app/Controllers/CloudAdminFabricController.php b/web/app/Controllers/CloudAdminFabricController.php index 53c8e9f9..d70262c5 100644 --- a/web/app/Controllers/CloudAdminFabricController.php +++ b/web/app/Controllers/CloudAdminFabricController.php @@ -38,6 +38,12 @@ final class CloudAdminFabricController } } + private function operationStatus(array $payload): int + { + $status = $payload['operation']['status'] ?? null; + return in_array($status, ['queued', 'running'], true) ? 202 : 200; + } + public function index($request, $response) { return $this->json($response, @@ -66,19 +72,23 @@ final class CloudAdminFabricController { $actor = $this->actor($request, true); $this->assertEmptyBody($request, '地区私网自动配置'); - return $this->json($response, - CloudAdminFabricService::applyRegion( - (string) ($args['region_id'] ?? ''), $actor - )); + $payload = CloudAdminFabricService::applyRegion( + (string) ($args['region_id'] ?? ''), $actor + ); + return $this->json( + $response, $payload, $this->operationStatus($payload) + ); } public function reconcileRegion($request, $response, $args) { $actor = $this->actor($request, true); $this->assertEmptyBody($request, '地区私网重新核对'); - return $this->json($response, - CloudAdminFabricService::reconcileRegion( - (string) ($args['region_id'] ?? ''), $actor - )); + $payload = CloudAdminFabricService::reconcileRegion( + (string) ($args['region_id'] ?? ''), $actor + ); + return $this->json( + $response, $payload, $this->operationStatus($payload) + ); } } diff --git a/web/app/Services/Cloud/CloudAdminFabricService.php b/web/app/Services/Cloud/CloudAdminFabricService.php index e1866316..6acd4e48 100644 --- a/web/app/Services/Cloud/CloudAdminFabricService.php +++ b/web/app/Services/Cloud/CloudAdminFabricService.php @@ -36,6 +36,24 @@ final class CloudAdminFabricService private const HOST_STATES = ['active', 'draining', 'disabled']; private const ENDPOINT_SOURCES = ['configured', 'ssh_host_ipv4']; private const ERROR_PHASES = ['identity', 'observe', 'apply']; + private const OPERATION_KINDS = ['apply', 'reconcile']; + private const OPERATION_STATES = [ + 'queued', 'running', 'succeeded', 'failed', 'uncertain', 'interrupted', + ]; + private const NODE_OPERATION_STATES = [ + 'pending', 'running', 'succeeded', 'failed', 'uncertain', 'skipped', + ]; + private const OPERATION_CHECKPOINTS = [ + 'dispatch', 'host_lock', 'identity', 'journal_recovery', 'preflight', + 'transaction', 'nft_install', 'network_activate', 'persistence', + 'final_readback', 'complete', + ]; + private const OPERATION_REASONS = [ + 'none', 'tool_missing', 'ownership_conflict', 'journal_conflict', + 'firewall_conflict', 'underlay_conflict', 'network_manager_failed', + 'nft_failed', 'systemd_failed', 'readback_failed', 'command_failed', + 'transport_failed', 'status_invalid', + ]; private const ERROR_CODES = [ 'fabric_apply_unconfirmed', 'fabric_host_capability_missing', 'fabric_host_capability_probe_failed', 'fabric_host_capability_probe_invalid', @@ -51,8 +69,13 @@ final class CloudAdminFabricService 'fabric_host_not_configured', 'fabric_host_unavailable', 'fabric_identity_conflict', 'fabric_identity_invalid', 'fabric_invalid', 'fabric_membership_conflict', 'fabric_not_found', 'fabric_overlay_conflict', + 'fabric_readback_mismatch', 'fabric_region_conflict', 'fabric_plan_corrupt', 'fabric_readback_invalid', 'fabric_record_corrupt', + 'fabric_operation_busy', 'fabric_operation_invalid', + 'fabric_operation_limit', 'fabric_operation_not_found', + 'fabric_operation_reconcile_required', 'fabric_operation_status_invalid', + 'fabric_operation_status_timeout', 'fabric_operation_interrupted', 'fabric_remote_command_failed', 'fabric_revision_conflict', 'fabric_runner_unsupported', ]; @@ -190,7 +213,6 @@ final class CloudAdminFabricService '地区 Fabric 已固定,请使用重新核对恢复或激活', 409 ); } - $mappingExpectation = self::mappingExpectation($mapping); $engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS); $expectedFabricRegion = (string) $region->code; $fabricId = self::automaticFabricId((string) $region->code); @@ -226,6 +248,11 @@ final class CloudAdminFabricService $current, (string) $region->code, $candidates, $probeByHost, $fabrics ); + if (is_array($current['operation'] ?? null) + && in_array($current['operation']['status'] ?? null, + ['queued', 'running'], true)) { + return self::operationReceipt($current['operation']); + } throw new CloudError( '检测到未映射的部分成功 Fabric,请使用重新核对恢复', 409 @@ -264,27 +291,14 @@ final class CloudAdminFabricService $fabric, (string) $region->code, $candidates, $probeByHost, $fabrics ); - self::assertPlatformContextUnchanged( - $region, $candidateIds + $operation = self::mutationOperation( + $fabric['operation'] ?? null, ['apply'] ); - // The mapping writer re-reads the exact active engine gate. If apply - // succeeded but this database write fails, the region remains visibly - // unready and "重新核对" can recover without creating another Fabric. - CloudAdminResourceService::saveRegionFabric((string) $region->id, [ - 'fabric_id' => $fabricId, - 'fabric_region' => $fabricRegion, - 'fabric_revision' => (int) $fabric['revision'], - 'state' => 'active', - ], $actor, false, $engine, $mappingExpectation, - static function () use ( - $region, $candidateIds - ): void { - self::assertPlatformContextUnchanged( - $region, $candidateIds - ); - } - ); - return self::listing($actor, $engine); + // Apply only admits the host-owned asynchronous operation. Even if a + // very fast engine reports it terminal in this response, the region + // mapping is committed only by the later explicit reconcile path, + // after a fresh platform/host readback under the same operation ID. + return self::operationReceipt($operation); } /** Reconcile only the fixed desired Fabric; never generate a new plan. */ @@ -336,6 +350,21 @@ final class CloudAdminFabricService $before, $expectedRegion, $requiredIds, $expectedRevision ); + $beforeOperation = is_array($before['operation'] ?? null) + ? $before['operation'] : null; + if ($beforeOperation !== null) { + $beforeOperation = self::mutationOperation( + $beforeOperation, self::OPERATION_KINDS + ); + } + if (is_array($beforeOperation) + && in_array($beforeOperation['status'] ?? null, + ['queued', 'running'], true)) { + // Join an already accepted operation before repeating the slower + // status/probe preflight. This is read-only and does not weaken + // the identity proof above. + return self::operationReceipt($beforeOperation); + } $statusFabrics = self::projectFabrics( $engine->fabricStatuses($actor) ); @@ -374,6 +403,27 @@ final class CloudAdminFabricService (int) $region->id, $mapping !== null, $fabricId, $expectedRegion, $expectedRevision ); + if (($mapping === null || (string) $mapping->state === 'disabled') + && is_array($beforeOperation) + && ($beforeOperation['status'] ?? null) === 'succeeded' + && ($before['state'] ?? null) === 'active' + && ($before['next_stage_allowed'] ?? false) === true) { + // Initial asynchronous apply has completed. This POST is the + // explicit control-plane confirmation: it commits the fixed + // mapping without replaying the already successful host write. + self::assertPlatformContextUnchanged($region, $requiredIds); + CloudAdminResourceService::saveRegionFabric((string) $region->id, [ + 'fabric_id' => $fabricId, + 'fabric_region' => $expectedRegion, + 'fabric_revision' => (int) $before['revision'], + 'state' => 'active', + ], $actor, false, $engine, $mappingExpectation, + static function () use ($region, $requiredIds): void { + self::assertPlatformContextUnchanged($region, $requiredIds); + } + ); + return self::operationReceipt($beforeOperation); + } // Close the inventory race opened by detail/list/probe network round // trips. A host or region changed meanwhile must not be reconciled. self::assertPlatformContextUnchanged( @@ -391,6 +441,15 @@ final class CloudAdminFabricService $fabric, $expectedRegion, $requiredIds, $expectedRevision ); + // A reconcile can either create a reconcile operation or resume the + // exact interrupted apply operation. Both are reviewed root kinds, + // but a missing/malformed receipt must never fall through to mapping. + $operation = self::mutationOperation( + $fabric['operation'] ?? null, self::OPERATION_KINDS + ); + if (($operation['status'] ?? null) !== 'succeeded') { + return self::operationReceipt($operation); + } if ($mapping === null) { // Recover only the deterministic identity left by an earlier // partial success. No plan, revision or membership is invented. @@ -423,6 +482,34 @@ final class CloudAdminFabricService return self::listing($actor, $engine); } + /** Return immediately without a second Engine round trip after accept. */ + private static function operationReceipt(array $operation): array + { + return [ + 'operation' => self::mutationOperation( + $operation, self::OPERATION_KINDS + ), + 'engine_available' => true, + ]; + } + + /** Require an auditable root receipt on every Fabric mutation path. */ + private static function mutationOperation($value, array $expectedKinds): array + { + if (!is_array($value) + || !is_string($value['id'] ?? null) + || preg_match('/^[0-9a-f]{32}$/D', $value['id']) !== 1 + || !is_string($value['kind'] ?? null) + || !in_array($value['kind'], $expectedKinds, true) + || !is_string($value['status'] ?? null) + || !in_array($value['status'], self::OPERATION_STATES, true)) { + throw new CloudError( + 'Fabric operation 回执无效,已阻止发布地区映射', 502 + ); + } + return $value; + } + private static function regionById(string $value): CloudRegion { if (preg_match('/^[1-9][0-9]*$/D', $value) !== 1) { @@ -1140,6 +1227,7 @@ final class CloudAdminFabricService 'observed_revision' => $observedNode['observed_revision'] ?? null, 'last_error_code' => $observedNode['last_error_code'] ?? null, 'last_error_phase' => $observedNode['last_error_phase'] ?? null, + 'operation' => $observedNode['operation'] ?? null, 'readiness_state' => $state, 'reasons' => $reasons, ]); @@ -1164,6 +1252,7 @@ final class CloudAdminFabricService 'fabric_revision' => $mapping['fabric_revision'] ?? ($fabric['revision'] ?? null), 'mapping_state' => $mapping['state'] ?? 'unconfigured', 'fabric_state' => $fabric['state'] ?? null, + 'operation' => $fabric['operation'] ?? null, 'next_stage_allowed' => $conflictFabrics === [] && ($fabric['next_stage_allowed'] ?? false) === true, 'fabric_conflicts' => array_map( @@ -1237,18 +1326,19 @@ final class CloudAdminFabricService }; $result = static function (string $stage, bool $canApply, bool $canReconcile) use (&$reasons, $canProbe): array { + $probeAllowed = $stage !== 'operation_running' && $canProbe; $action = 'none'; if ($stage === 'ready_to_apply' && $canApply) { $action = 'apply'; } elseif ($stage === 'needs_reconcile' && $canReconcile) { $action = 'reconcile'; } elseif (in_array($stage, ['needs_probe', 'blocked'], true) - && $canProbe) { + && $probeAllowed) { $action = 'probe'; } return [[ 'stage' => $stage, - 'can_probe' => $canProbe, + 'can_probe' => $probeAllowed, 'can_apply' => $canApply, 'can_reconcile' => $canReconcile, 'blocking_reasons' => array_values($reasons), @@ -1299,6 +1389,17 @@ final class CloudAdminFabricService $addReason($reasons, 'engine_unavailable'); return $result('engine_unavailable', false, false); } + $currentOperation = is_array($desiredFabric['operation'] ?? null) + ? $desiredFabric['operation'] : null; + if (is_array($currentOperation) + && in_array($currentOperation['status'] ?? null, + ['queued', 'running'], true)) { + $addReason($reasons, 'fabric_operation_running'); + return $withPreview( + $result('operation_running', false, false), + $existingPreview($desiredFabric) + ); + } if ($mappingConfigured && $desiredFabric === null) { // A database mapping pins one exact desired identity. A different // same-region Fabric is a second problem, not a replacement plan @@ -1986,6 +2087,7 @@ final class CloudAdminFabricService 'state' => $state, 'next_stage_allowed' => ($value['next_stage_allowed'] ?? false) === true, 'updated_at' => max(0, (int) ($value['updated_at'] ?? 0)), + 'operation' => self::operation($value['operation'] ?? null, false), 'nodes' => [], ]; $nodes = $value['nodes'] ?? []; @@ -2016,6 +2118,9 @@ final class CloudAdminFabricService 'observed_plan_digest' => self::nullableDigest($node['observed_plan_digest'] ?? null), 'last_error_code' => $lastErrorCode, 'last_error_phase' => $lastErrorPhase, + 'operation' => self::operation( + $node['operation'] ?? null, true + ), 'observed' => self::observed($node['observed'] ?? []), ]; $result['nodes'][] = $row; @@ -2365,4 +2470,71 @@ final class CloudAdminFabricService } return $value; } + + /** + * Project only the fixed, credential-free operation receipt contract. + * Unknown enum values become the literal "unknown" marker; arbitrary + * Engine strings never cross into the administrator response. + */ + private static function operation($value, bool $node): ?array + { + if ($value === null || $value === '') { + return null; + } + if (!is_array($value)) { + $result = [ + 'id' => null, + 'status' => 'unknown', + 'started_at' => null, 'updated_at' => null, + 'finished_at' => null, + ]; + if ($node) { + $result += [ + 'phase' => 'unknown', 'checkpoint' => 'unknown', + 'reason' => 'unknown', + ]; + } else { + $result['kind'] = 'unknown'; + } + return $result; + } + $id = $value['id'] ?? null; + if (!is_string($id) + || preg_match('/^[0-9a-f]{32}$/D', $id) !== 1) { + $id = null; + } + $statuses = $node + ? self::NODE_OPERATION_STATES : self::OPERATION_STATES; + $status = is_string($value['status'] ?? null) + && in_array($value['status'], $statuses, true) + ? $value['status'] : 'unknown'; + $result = [ + 'id' => $id, + 'status' => $status, + 'started_at' => self::operationTime($value['started_at'] ?? null), + 'updated_at' => self::operationTime($value['updated_at'] ?? null), + 'finished_at' => self::operationTime($value['finished_at'] ?? null), + ]; + if (!$node) { + $result['kind'] = is_string($value['kind'] ?? null) + && in_array($value['kind'], self::OPERATION_KINDS, true) + ? $value['kind'] : 'unknown'; + return $result; + } + $result['phase'] = is_string($value['phase'] ?? null) + && in_array($value['phase'], self::ERROR_PHASES, true) + ? $value['phase'] : 'unknown'; + $result['checkpoint'] = is_string($value['checkpoint'] ?? null) + && in_array($value['checkpoint'], self::OPERATION_CHECKPOINTS, true) + ? $value['checkpoint'] : 'unknown'; + $result['reason'] = is_string($value['reason'] ?? null) + && in_array($value['reason'], self::OPERATION_REASONS, true) + ? $value['reason'] : 'unknown'; + return $result; + } + + private static function operationTime($value): ?int + { + return is_int($value) && $value > 0 ? $value : null; + } } diff --git a/web/app/Services/Cloud/CloudEngineClient.php b/web/app/Services/Cloud/CloudEngineClient.php index aafbda12..93e95486 100644 --- a/web/app/Services/Cloud/CloudEngineClient.php +++ b/web/app/Services/Cloud/CloudEngineClient.php @@ -319,6 +319,15 @@ final class CloudEngineClient 'fabric_host_connection_failed' => 'Fabric 宿主机连接失败', 'fabric_host_key_locked' => 'Fabric 宿主机 SSH 私钥仍锁定', 'fabric_runner_unsupported' => '宿主机不支持 Fabric 执行器', + 'fabric_operation_busy' => '该 Fabric 已有宿主机任务正在执行,请等待状态回读', + 'fabric_operation_invalid' => 'Fabric operation 标识或类型无效', + 'fabric_operation_limit' => '宿主机 Fabric operation 记录已达安全上限,请先核对状态', + 'fabric_operation_not_found' => '宿主机已无法读取该 Fabric operation 状态', + 'fabric_operation_reconcile_required' => '上次 Fabric operation 结果仍需按原标识核对', + 'fabric_operation_status_invalid' => '宿主机 Fabric operation 状态记录无效', + 'fabric_operation_status_timeout' => 'Fabric operation 状态回读超时,请按原标识继续核对', + 'fabric_operation_interrupted' => 'Fabric operation 协调过程被中断,请按原标识重新核对', + 'fabric_readback_mismatch' => '宿主机 Fabric 最终回读与固定方案不一致', 'fabric_remote_command_failed' => '宿主机 Fabric 命令执行失败', 'fabric_plan_corrupt' => 'Fabric 计划损坏', ][$value] ?? null; diff --git a/web/public/cloud/admin-fabric.js b/web/public/cloud/admin-fabric.js index 873a6969..7e0edd0f 100644 --- a/web/public/cloud/admin-fabric.js +++ b/web/public/cloud/admin-fabric.js @@ -10,12 +10,15 @@ const state = { loading: false, pendingAction: '', outcomeUnknownRegionIds: new Set(), + operationsByRegion: new Map(), + operationPollTimer: 0, + operationPollFailures: 0, }; const workflowStages = new Set([ 'engine_unavailable', 'no_hosts', 'needs_probe', 'blocked', 'ready_to_apply', 'needs_reconcile', 'active', - 'migration_required', 'recovery_required', + 'migration_required', 'recovery_required', 'operation_running', ]); const workflowStageCopy = { engine_unavailable: { @@ -45,6 +48,9 @@ const workflowStageCopy = { recovery_required: { title: '需要恢复固定方案', help: '请按服务端恢复指引处理,向导不会重新生成 desired state。', step: 'reconcile', }, + operation_running: { + title: '宿主机任务执行中', help: '页面正在只读轮询 operation 状态;请勿重复提交。', step: 'apply', + }, }; const stateLabels = { @@ -85,6 +91,15 @@ const errorLabels = { fabric_membership_conflict: '参与宿主机集合冲突', fabric_readback_invalid: 'Fabric 回读无效', fabric_remote_command_failed: '宿主机远程配置命令失败', + fabric_operation_busy: '该 Fabric 已有宿主机任务正在执行', + fabric_operation_invalid: 'Fabric operation 标识或类型无效', + fabric_operation_limit: '宿主机 Fabric operation 记录已达安全上限', + fabric_operation_not_found: '宿主机已无法读取该 Fabric operation 状态', + fabric_operation_reconcile_required: '上次 Fabric operation 结果仍需按原标识核对', + fabric_operation_status_invalid: '宿主机 Fabric operation 状态记录无效', + fabric_operation_status_timeout: 'Fabric operation 状态回读超时,请按原标识继续核对', + fabric_operation_interrupted: 'Fabric operation 协调过程被中断,请按原标识重新核对', + fabric_readback_mismatch: '宿主机 Fabric 最终回读与固定方案不一致', fabric_revision_conflict: 'Fabric revision 冲突', }; const lastErrorPhaseLabels = { @@ -92,6 +107,32 @@ const lastErrorPhaseLabels = { observe: 'observe(回读)', apply: 'apply(应用)', }; +const operationKindLabels = { + apply: '自动配置', reconcile: '重新核对', unknown: '未知操作', +}; +const operationStatusLabels = { + queued: 'queued(等待执行)', pending: 'pending(等待执行)', + running: 'running(执行中)', succeeded: 'succeeded(成功)', + failed: 'failed(失败)', uncertain: 'uncertain(待核对)', + interrupted: 'interrupted(已中断)', skipped: 'skipped(已跳过)', + unknown: '未知状态', +}; +const operationCheckpointLabels = { + dispatch: '下发任务', host_lock: '宿主机互斥锁', identity: '身份核验', + journal_recovery: '事务恢复', preflight: '执行前检查', transaction: '事务准备', + nft_install: '安装 nft 规则', network_activate: '激活网络', + persistence: '安装持久化恢复', final_readback: '最终回读', complete: '完成', + unknown: '未知检查点', +}; +const operationReasonLabels = { + none: '无', tool_missing: '缺少必要工具', ownership_conflict: '资源归属冲突', + journal_conflict: '事务记录冲突', firewall_conflict: '防火墙配置冲突', + underlay_conflict: '传输网络冲突', network_manager_failed: '网络管理器操作失败', + nft_failed: 'nftables 操作失败', systemd_failed: 'systemd 任务失败', + readback_failed: '最终回读失败', command_failed: '宿主机命令失败', + transport_failed: '宿主机传输失败', status_invalid: '状态记录无效', + unknown: '未识别原因(已隐藏原始值)', +}; const reasonLabels = { host_disabled: '宿主机未启用', host_record_missing: '面板宿主机记录缺失', @@ -186,6 +227,7 @@ const reasonLabels = { platform_gate_failed: '地区或宿主机平台门禁未通过', fresh_probe_failed: 'fresh 宿主机检测未通过', fabric_reconcile_required: '固定 desired state 需要重新核对', + fabric_operation_running: 'Fabric 宿主机任务正在执行', }; function el(tag, className, value) { @@ -213,6 +255,48 @@ function lastErrorPhaseLabel(value) { return Object.prototype.hasOwnProperty.call(lastErrorPhaseLabels, value) ? lastErrorPhaseLabels[value] : null; } +function operationOf(value, node = false) { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const id = typeof value.id === 'string' && /^[0-9a-f]{32}$/.test(value.id) + ? value.id : null; + const rootStates = ['queued', 'running', 'succeeded', 'failed', 'uncertain', 'interrupted']; + const nodeStates = ['pending', 'running', 'succeeded', 'failed', 'uncertain', 'skipped']; + const states = node ? nodeStates : rootStates; + const operation = { + id, + status: states.includes(value.status) ? value.status : 'unknown', + started_at: Number.isInteger(value.started_at) && value.started_at > 0 + ? value.started_at : null, + updated_at: Number.isInteger(value.updated_at) && value.updated_at > 0 + ? value.updated_at : null, + finished_at: Number.isInteger(value.finished_at) && value.finished_at > 0 + ? value.finished_at : null, + }; + if (!node) { + operation.kind = ['apply', 'reconcile'].includes(value.kind) + ? value.kind : 'unknown'; + return operation; + } + operation.phase = Object.prototype.hasOwnProperty.call(lastErrorPhaseLabels, value.phase) + ? value.phase : 'unknown'; + operation.checkpoint = Object.prototype.hasOwnProperty.call( + operationCheckpointLabels, value.checkpoint) ? value.checkpoint : 'unknown'; + operation.reason = Object.prototype.hasOwnProperty.call( + operationReasonLabels, value.reason) ? value.reason : 'unknown'; + return operation; +} +function operationRunning(operation) { + return Boolean(operation && ['queued', 'running'].includes(operation.status)); +} +function operationStatusLabel(value) { + return operationStatusLabels[value] || operationStatusLabels.unknown; +} +function operationForHost(region, host) { + const rootOperation = operationOf(region && region.operation); + const hostOperation = operationOf(host && host.operation, true); + return rootOperation && rootOperation.id && hostOperation + && hostOperation.id === rootOperation.id ? hostOperation : null; +} function sysctl(value, enabledValue) { if (value === null || value === undefined || value === '' || typeof value === 'boolean') { return '未检测'; @@ -425,6 +509,8 @@ function syncControls() { const region = selectedRegion(); const hasRegion = region !== null; const workflow = workflowOf(region); + const currentOperation = operationOf(region && region.operation) + || state.operationsByRegion.get(regionIdOf(region)) || null; const permissions = { probe: workflow.can_probe, apply: workflow.can_apply, @@ -437,11 +523,14 @@ function syncControls() { const allowed = outcomeUnknown ? action === 'reconcile' : permissions[action] === true; button.disabled = !canManage || !hasRegion || !allowed - || state.loading || state.pendingAction !== ''; + || state.loading || state.pendingAction !== '' || operationRunning(currentOperation); button.setAttribute('aria-disabled', button.disabled ? 'true' : 'false'); if (!canManage) button.title = '仅超级管理员可以执行此操作'; else if (!hasRegion) button.title = '请先选择地区'; else if (state.pendingAction) button.title = '请等待当前操作返回'; + else if (operationRunning(currentOperation)) { + button.title = '宿主机任务正在执行,请等待只读状态回传'; + } else if (outcomeUnknown && action !== 'reconcile') { button.title = '上次写操作结果未知,请先重新核对,切勿重复配置'; } else if (!allowed) button.title = '服务端尚未允许执行此步骤'; @@ -471,12 +560,23 @@ function wizardProgress(stage) { } function renderWizardSteps(region) { const workflow = workflowOf(region); - const stage = region ? workflow.stage : ''; - const copy = workflowStageCopy[stage] || { + const trackedOperation = operationOf(region && region.operation) + || state.operationsByRegion.get(regionIdOf(region)) || null; + const stage = region + ? (operationRunning(trackedOperation) ? 'operation_running' : workflow.stage) : ''; + let copy = workflowStageCopy[stage] || { title: '请选择地区', help: '选择地区后,向导会显示服务端给出的下一步。', step: 'select', }; + if (stage === 'operation_running' && trackedOperation) { + copy = { + ...copy, + help: 'operation ' + text(trackedOperation.id, '标识未确认') + + ' 正在执行;页面会自动读取安全阶段状态。', + step: trackedOperation.kind === 'reconcile' ? 'reconcile' : 'apply', + }; + } const unknown = region && state.outcomeUnknownRegionIds.has(regionIdOf(region)); byId('fabric-wizard-stage').textContent = unknown ? '操作结果尚未确认' : copy.title; byId('fabric-wizard-stage-help').textContent = unknown @@ -484,7 +584,9 @@ function renderWizardSteps(region) { : copy.help; const order = ['select', 'probe', 'apply', 'reconcile']; - const currentIndex = region ? wizardProgress(stage) : 0; + const currentIndex = region ? (stage === 'operation_running' + ? (trackedOperation && trackedOperation.kind === 'reconcile' ? 3 : 2) + : wizardProgress(stage)) : 0; document.querySelectorAll('[data-fabric-wizard-step]').forEach(item => { const index = order.indexOf(String(item.dataset.fabricWizardStep || '')); item.classList.remove('is-complete', 'is-current', 'is-blocked'); @@ -509,15 +611,21 @@ function renderWizardSteps(region) { else if (['ready_to_apply', 'needs_reconcile', 'active'].includes(stage)) probeState = '检测已通过'; else if (stage === 'engine_unavailable') probeState = '引擎不可用'; else if (stage === 'no_hosts') probeState = '没有宿主机'; + else if (stage === 'operation_running') probeState = '检测已通过'; byId('fabric-step-probe-state').textContent = probeState; byId('fabric-step-apply-state').textContent = stage === 'ready_to_apply' - ? '等待执行' : ['needs_reconcile', 'active'].includes(stage) + ? '等待执行' : stage === 'operation_running' + ? (trackedOperation && trackedOperation.kind === 'reconcile' + ? '固定方案已存在' : '宿主机任务执行中') + : ['needs_reconcile', 'active'].includes(stage) ? '已提交固定方案' : stage === 'migration_required' ? '需要显式迁移' : stage === 'recovery_required' ? '不能重新生成' : '等待检测通过'; byId('fabric-step-reconcile-state').textContent = stage === 'active' ? '权威回读已通过' : ['needs_reconcile', 'recovery_required'].includes(stage) - ? '等待重新核对' : unknown ? '结果未知' : '等待配置'; + ? '等待重新核对' : stage === 'operation_running' + && trackedOperation && trackedOperation.kind === 'reconcile' + ? '宿主机任务执行中' : unknown ? '结果未知' : '等待配置'; } function renderWizardBlockers(region) { const box = byId('fabric-wizard-blockers'); @@ -655,11 +763,23 @@ function renderHosts(region) { const fabric = el('td'); const lastErrorPhase = host.last_error_code ? lastErrorPhaseLabel(host.last_error_phase) : null; + const currentHostOperation = operationForHost(region, host); + const operationLines = currentHostOperation ? [ + '本轮 operation:' + text(currentHostOperation.id), + '本轮状态:' + operationStatusLabel(currentHostOperation.status), + '本轮阶段:' + (lastErrorPhaseLabel(currentHostOperation.phase) || '未知阶段'), + '本轮检查点:' + (operationCheckpointLabels[currentHostOperation.checkpoint] + || operationCheckpointLabels.unknown), + '本轮原因:' + (operationReasonLabels[currentHostOperation.reason] + || operationReasonLabels.unknown), + '本轮更新时间:' + date(currentHostOperation.updated_at), + ] : []; fabric.append(compactLines([ '成员:' + flag(host.fabric_member), '状态:' + stateLabel(host.fabric_state), 'Transport:' + flag(host.transport_verified, '已验证', '未验证'), 'Observed revision:' + text(host.observed_revision), + ...operationLines, ...(lastErrorPhase ? ['上次 Fabric 失败阶段:' + lastErrorPhase] : []), ])); row.append(identity, platform, probe, manager, wireguard, publicPath, fabric, @@ -678,6 +798,8 @@ function renderReadback(region) { const conflicts = Array.isArray(region.fabric_conflicts) ? region.fabric_conflicts.filter(item => item && item.fabric_id).slice(0, 8) : []; + const operation = operationOf(region.operation) + || state.operationsByRegion.get(regionIdOf(region)) || null; const values = [ ['Fabric ID', text(region.fabric_id, '尚未自动配置')], ['Fabric 地区', text(region.fabric_region)], @@ -690,6 +812,16 @@ function renderReadback(region) { ['未映射 Fabric 冲突', conflicts.length ? conflicts.map(item => String(item.fabric_id)).join('、') : '无'], + ['本轮 operation', operation ? text(operation.id, '标识无效') : '无'], + ['本轮操作 / 状态', operation + ? (operationKindLabels[operation.kind] || operationKindLabels.unknown) + + ' / ' + operationStatusLabel(operation.status) + : '无'], + ['本轮更新时间', operation ? date(operation.updated_at) : '无'], + ['宿主机日志命令', operation && operation.id + ? 'journalctl --utc -u virt-cloud-fabric-apply-' + operation.id + + '.service --no-pager -o short-iso-precise' + : '无'], ]; values.forEach(pair => { const column = el('div', 'col-sm-6 col-xl-3'); @@ -740,6 +872,114 @@ function mergeRegionProjection(region) { else state.regions[index] = region; return true; } +function rememberOperation(regionId, value) { + const operation = operationOf(value); + if (!regionId || !operation || !operation.id) return null; + if (operationRunning(operation)) state.operationsByRegion.set(regionId, operation); + else state.operationsByRegion.delete(regionId); + return operation; +} +function adoptRegionOperations() { + state.regions.forEach(region => { + const regionId = regionIdOf(region); + const operation = operationOf(region.operation); + if (operation && operation.id) rememberOperation(regionId, operation); + }); + if (state.operationsByRegion.size) scheduleOperationPoll(); +} +function scheduleOperationPoll(delay = 2000) { + if (state.operationPollTimer || !state.operationsByRegion.size) return; + state.operationPollTimer = window.setTimeout(() => { + state.operationPollTimer = 0; + pollOperations(); + }, delay); +} +function terminalOperationMessage(region, operation) { + const prefix = regionName(region) + ':operation ' + operation.id + ' '; + if (operation.status === 'succeeded') { + return { + kind: 'success', + text: prefix + (region && region.ready === true + ? '已成功并通过全部门禁。' + : operation.kind === 'apply' + ? '宿主机任务已成功;请按当前向导重新检测并完成地区映射核对。' + : '宿主机任务已成功;请按当前向导完成最终回读确认。'), + }; + } + return { + kind: 'error', + text: prefix + operationStatusLabel(operation.status) + + ';请查看宿主机清单中的阶段、检查点和安全原因。', + }; +} +async function pollOperations() { + if (!state.operationsByRegion.size) return; + try { + const payload = await api('/api/v1/admin/fabric'); + const regions = regionsOf(payload); + if (payload && payload.engine_available === false) { + throw new Error(text(payload.engine_error, 'Fabric 引擎状态暂时无法读取。')); + } + // An empty list is still an authoritative successful projection. If a + // region disappears while an operation is being tracked, retaining the + // previous list would poll that stale operation forever instead of + // stopping with an outcome-unknown readback. + state.regions = regions; + renderRegionOptions(state.regions); + state.operationPollFailures = 0; + const terminal = []; + const mismatched = []; + for (const [regionId, tracked] of [...state.operationsByRegion.entries()]) { + const region = state.regions.find(item => regionIdOf(item) === regionId) || null; + const observed = operationOf(region && region.operation); + if (!observed || observed.id !== tracked.id) { + // The tracked write can no longer be correlated to the authoritative + // projection. Stop polling this stale ID and require a fresh, explicit + // readback; never adopt a replacement operation or submit another POST. + state.operationsByRegion.delete(regionId); + state.outcomeUnknownRegionIds.add(regionId); + mismatched.push({ region, operation: tracked }); + continue; + } + if (operationRunning(observed)) { + state.operationsByRegion.set(regionId, observed); + } else { + state.operationsByRegion.delete(regionId); + state.outcomeUnknownRegionIds.delete(regionId); + terminal.push({ region, operation: observed }); + } + } + renderSelectedRegion(); + const selectedTerminal = terminal.find(item => + regionIdOf(item.region) === state.selectedRegionId); + const selectedMismatch = mismatched.find(item => + regionIdOf(item.region) === state.selectedRegionId); + if (selectedMismatch) { + notice(regionName(selectedMismatch.region) + ':operation ' + + selectedMismatch.operation.id + + ' 已无法与服务端当前回读对应;已停止自动轮询,且不会重复提交。请刷新后按向导重新核对。', + 'error'); + } else if (selectedTerminal) { + const message = terminalOperationMessage( + selectedTerminal.region, selectedTerminal.operation + ); + notice(message.text, message.kind); + } else if (state.operationsByRegion.has(state.selectedRegionId)) { + const operation = state.operationsByRegion.get(state.selectedRegionId); + notice(regionName(selectedRegion()) + ':operation ' + operation.id + + ' ' + operationStatusLabel(operation.status) + ';正在自动读取状态。'); + } + } catch (error) { + state.operationPollFailures += 1; + if (state.operationPollFailures >= 12) { + notice('Fabric operation 状态连续读取失败;任务不会被重复提交,请刷新页面继续只读核对。', 'error'); + return; + } + } + if (state.operationsByRegion.size) { + scheduleOperationPoll(state.operationPollFailures ? 5000 : 2000); + } +} function applyActionProjection(payload, originRegionId, originSelectionVersion) { const regions = regionsOf(payload); let applied = false; @@ -766,6 +1006,7 @@ async function load() { if (version !== state.loadVersion) return false; state.regions = regionsOf(payload); renderRegionOptions(state.regions); + adoptRegionOperations(); if (payload && payload.engine_available === false) { notice(text(payload.engine_error, 'Fabric 引擎状态暂时无法读取。'), 'error'); @@ -848,19 +1089,40 @@ async function runRegionAction(action) { try { const payload = await api('/api/v1/admin/fabric/regions/' + encodeURIComponent(regionId) + '/' + action, { method: 'POST', body: '{}' }); - if (!applyActionProjection(payload, regionId, originSelectionVersion) - && !(await load())) { - throw new Error('操作响应已返回,但最新 readiness 未能读取,请使用“重新核对”确认状态。'); - } if (payload && payload.engine_available === false) { throw new Error(text(payload.engine_error, '操作已返回,但 Fabric 引擎最新状态无法读取;请稍后重新核对。')); } - const projected = state.regions.find(item => regionIdOf(item) === regionId) || null; + const appliedProjection = applyActionProjection( + payload, regionId, originSelectionVersion + ); + let projected = state.regions.find(item => regionIdOf(item) === regionId) || null; + const acceptedOperation = operationOf(payload && payload.operation); + if (acceptedOperation && acceptedOperation.id && projected) { + state.outcomeUnknownRegionIds.delete(regionId); + projected.operation = acceptedOperation; + rememberOperation(regionId, acceptedOperation); + if (state.selectedRegionId === regionId) renderSelectedRegion(); + if (operationRunning(acceptedOperation)) { + scheduleOperationPoll(); + notice(originName + ':已受理 operation ' + acceptedOperation.id + + ',宿主机任务将异步执行;页面正在只读轮询状态。', 'success'); + return; + } + } + if (!appliedProjection && !(await load())) { + throw new Error('操作响应已返回,但最新 readiness 未能读取,请使用“重新核对”确认状态。'); + } + projected = state.regions.find(item => regionIdOf(item) === regionId) || null; if (!projected) { throw new Error('操作已返回,但目标地区的权威状态缺失,请刷新后重新核对。'); } state.outcomeUnknownRegionIds.delete(regionId); + if (acceptedOperation && acceptedOperation.id) { + const terminal = terminalOperationMessage(projected, acceptedOperation); + notice(terminal.text, terminal.kind); + return; + } if (state.selectedRegionId === regionId) renderSelectedRegion(); const outcome = actionOutcome(action, projected); const suffix = state.selectionVersion === originSelectionVersion diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index a71b5ed6..ca8cc9ac 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100903' scope='global'} +{assign var=venix_asset_version value='2026100904' scope='global'} diff --git a/web/tests/AdminFabricContractTest.php b/web/tests/AdminFabricContractTest.php index 43d07174..c3f4c655 100644 --- a/web/tests/AdminFabricContractTest.php +++ b/web/tests/AdminFabricContractTest.php @@ -116,6 +116,21 @@ $assert(!str_contains($service, 'public static function apply(') && str_contains($client, 'function fabricApply') && str_contains($client, 'function fabricReconcile'), 'Generic PHP plan writes survived or the region-owned engine boundary was removed.'); +$applyWorkflow = $section($service, + 'public static function applyRegion(', + '/** Reconcile only the fixed desired Fabric; never generate a new plan. */'); +$reconcileWorkflow = $section($service, + 'public static function reconcileRegion(', + '/** Return immediately without a second Engine round trip after accept. */'); +$assert(str_contains($applyWorkflow, "['operation'] ?? null, ['apply']") + && str_contains($applyWorkflow, 'return self::operationReceipt($operation);') + && !str_contains($applyWorkflow, 'saveRegionFabric') + && str_contains($reconcileWorkflow, 'saveRegionFabric') + && str_contains($service, 'private static function mutationOperation(') + && str_contains($service, "preg_match('/^[0-9a-f]{32}$/D'") + && str_contains($service, + 'Fabric operation 回执无效,已阻止发布地区映射'), + 'Fabric writes must require a bounded operation receipt and defer mapping to reconcile.'); $listingProjection = $section($service, 'public static function listing(', 'public static function detail('); $detailProjection = $section($service, @@ -137,7 +152,7 @@ foreach (['stage', 'can_probe', 'can_apply', 'can_reconcile', } foreach (['engine_unavailable', 'no_hosts', 'needs_probe', 'blocked', 'ready_to_apply', 'needs_reconcile', 'active', 'migration_required', - 'recovery_required'] as $stage) { + 'recovery_required', 'operation_running'] as $stage) { $assert(str_contains($workflowProjection, "'{$stage}'"), 'Workflow projection stage is missing: ' . $stage); } @@ -169,6 +184,15 @@ $assert(!str_contains($service, "'private_key'") 'Fabric admin projection must not accept or expose private credentials or raw commands.'); $assert(str_contains($service, "private const ERROR_PHASES = ['identity', 'observe', 'apply'];") + && str_contains($service, 'private const OPERATION_KINDS') + && str_contains($service, 'private const OPERATION_STATES') + && str_contains($service, 'private const NODE_OPERATION_STATES') + && str_contains($service, 'private const OPERATION_CHECKPOINTS') + && str_contains($service, 'private const OPERATION_REASONS') + && str_contains($service, "'operation' => self::operation(") + && str_contains($service, "'operation' => \$fabric['operation'] ?? null") + && str_contains($controller, "['queued', 'running']") + && str_contains($controller, 'operationStatus($payload)') && str_contains($service, "\$lastErrorPhase = self::errorPhase(\$node['last_error_phase'] ?? null)") && str_contains($service, "'last_error_phase' => \$lastErrorPhase") @@ -183,6 +207,22 @@ $assert(str_contains($service, && str_contains($script, "'上次 Fabric 失败阶段:' + lastErrorPhase") && !str_contains($script, '本次探测失败阶段'), 'Fabric failure phases are not safely projected as persisted diagnostics.'); +$assert(str_contains($script, 'operationsByRegion: new Map()') + && str_contains($script, 'function pollOperations()') + && str_contains($script, "api('/api/v1/admin/fabric')") + && str_contains($script, 'operationForHost(region, host)') + && str_contains($script, 'hostOperation.id === rootOperation.id') + && str_contains($script, "unknown: '未知检查点'") + && str_contains($script, "unknown: '未识别原因(已隐藏原始值)'") + && str_contains($script, 'fabric_operation_not_found') + && str_contains($script, 'fabric_operation_reconcile_required') + && str_contains($script, 'fabric_operation_status_timeout') + && str_contains($script, "'本轮 operation:'") + && str_contains($script, "'本轮检查点:'") + && !str_contains($script, 'operation.stderr') + && !str_contains($script, 'operation.command') + && !str_contains($script, 'operation.path'), + 'Fabric asynchronous operations lost polling, correlation, redaction or safe labels.'); $assert(str_contains($script, "iproute2_missing: '缺少 ip 命令(Debian 包 iproute2 / AlmaLinux 包 iproute)'") && str_contains($script, diff --git a/web/tests/AdminFabricOperationProjectionTest.php b/web/tests/AdminFabricOperationProjectionTest.php new file mode 100644 index 00000000..f3f1ad87 --- /dev/null +++ b/web/tests/AdminFabricOperationProjectionTest.php @@ -0,0 +1,96 @@ + + $method->invoke(null, $value, $node); + +$root = $invoke([ + 'id' => str_repeat('a', 32), + 'kind' => 'apply', + 'status' => 'running', + 'started_at' => 1791501000, + 'updated_at' => 1791501010, + 'finished_at' => null, + 'stderr' => 'must-not-cross-boundary', + 'command' => 'must-not-cross-boundary', +], false); +$assert($root === [ + 'id' => str_repeat('a', 32), + 'status' => 'running', + 'started_at' => 1791501000, + 'updated_at' => 1791501010, + 'finished_at' => null, + 'kind' => 'apply', +], 'Root operation projection is not exact or leaked an unreviewed field.'); + +$node = $invoke([ + 'id' => str_repeat('a', 32), + 'status' => 'running', + 'phase' => 'apply', + 'checkpoint' => 'future_checkpoint:/root/private', + 'reason' => 'future_reason --private-key', + 'started_at' => 1791501000, + 'updated_at' => 1791501010, + 'finished_at' => null, +], true); +$assert(($node['checkpoint'] ?? null) === 'unknown' + && ($node['reason'] ?? null) === 'unknown' + && !in_array('future_checkpoint:/root/private', $node, true) + && !in_array('future_reason --private-key', $node, true), + 'Unknown node diagnostics were not replaced by fixed markers.'); + +$invalid = $invoke([ + 'id' => '../not-an-operation', + 'kind' => 'future_kind', + 'status' => 'future_status', + 'started_at' => true, + 'updated_at' => '1791501010', + 'finished_at' => -1, +], false); +$assert($invalid === [ + 'id' => null, + 'status' => 'unknown', + 'started_at' => null, + 'updated_at' => null, + 'finished_at' => null, + 'kind' => 'unknown', +], 'Malformed root operation values were not safely normalized.'); + +$mutationMethod = new ReflectionMethod( + CloudAdminFabricService::class, 'mutationOperation' +); +$mutation = static fn ($value, array $kinds): array => + $mutationMethod->invoke(null, $value, $kinds); +$assert($mutation($root, ['apply']) === $root, + 'A valid asynchronous apply receipt was rejected.'); + +foreach ([ + 'missing' => null, + 'invalid-id' => array_replace($root, ['id' => null]), + 'wrong-kind' => array_replace($root, ['kind' => 'reconcile']), + 'unknown-status' => array_replace($root, ['status' => 'unknown']), +] as $label => $receipt) { + try { + $mutation($receipt, ['apply']); + } catch (CloudError $error) { + $assert($error->httpStatus === 502, + 'Malformed ' . $label . ' receipt returned the wrong status.'); + continue; + } + throw new RuntimeException( + 'Malformed ' . $label . ' receipt did not fail closed.' + ); +} + +echo "Administrator Fabric operation projection contracts passed.\n"; diff --git a/web/tests/AdminFabricReadinessWorkflowTest.php b/web/tests/AdminFabricReadinessWorkflowTest.php index 288bdde3..5b015980 100644 --- a/web/tests/AdminFabricReadinessWorkflowTest.php +++ b/web/tests/AdminFabricReadinessWorkflowTest.php @@ -355,6 +355,14 @@ $fabricStatus = static function (array $hostIds) use ($hkOverlay): array { 'state' => 'active', 'next_stage_allowed' => true, 'updated_at' => 1770000200, + 'operation' => [ + 'id' => str_repeat('b', 32), + 'kind' => 'apply', + 'status' => 'succeeded', + 'started_at' => 1770000180, + 'updated_at' => 1770000200, + 'finished_at' => 1770000200, + ], 'nodes' => $nodes, ]; }; @@ -1046,10 +1054,13 @@ CloudRegionFabric::where('region_id', 2)->delete(); // Automatic configuration: the browser supplies only the region action while // PHP deterministically creates the Fabric identity, overlay and sorted node -// plan. Simulate apply success followed by a stale exact-readback gate: the -// mapping must remain absent until the explicit reconcile workflow recovers it. -$staleReadback = $status; -$staleReadback['next_stage_allowed'] = false; +// plan. Apply only admits one asynchronous operation and never publishes the +// region mapping; explicit reconcile owns the later exact readback/activation. +$queuedApply = $status; +$queuedApply['state'] = 'applying'; +$queuedApply['next_stage_allowed'] = false; +$queuedApply['operation']['status'] = 'queued'; +$queuedApply['operation']['finished_at'] = null; $history = []; $client = $engine([ $response(['hosts' => [ @@ -1057,15 +1068,14 @@ $client = $engine([ $probeHost(2), ]]), $response([]), - $response($status), - $response($staleReadback), + $response($queuedApply), ], $history); -$assertCloudError( - static fn () => CloudAdminFabricService::applyRegion('1', $actor, $client), - 409, - 'A non-exact post-apply readback incorrectly created the region mapping' -); -$assert(count($history) === 4, +$accepted = CloudAdminFabricService::applyRegion('1', $actor, $client); +$assert(($accepted['operation']['id'] ?? null) === str_repeat('b', 32) + && ($accepted['operation']['kind'] ?? null) === 'apply' + && ($accepted['operation']['status'] ?? null) === 'queued', + 'Automatic configuration did not return the bounded async receipt.'); +$assert(count($history) === 3, 'Automatic configuration performed an unexpected engine request sequence.'); $paths = array_map(static fn (array $entry): string => $entry['request']->getMethod() . ' ' . $entry['request']->getUri()->getPath(), @@ -1074,8 +1084,7 @@ $assert($paths === [ 'POST /internal/v1/fabric/probe', 'GET /internal/v1/fabric', 'POST /internal/v1/fabric/apply', - 'GET /internal/v1/fabric/fabric-hk', -], 'Automatic configuration lost its probe -> plan -> exact-readback ordering.'); +], 'Automatic configuration lost its probe -> plan -> async-admission ordering.'); $plan = json_decode((string) $history[2]['request']->getBody(), true, 32, JSON_THROW_ON_ERROR); $assert(array_keys($plan) === [ diff --git a/web/tests/AdminFabricWizardBehaviorTest.mjs b/web/tests/AdminFabricWizardBehaviorTest.mjs index 9066f9e8..2f6e8327 100644 --- a/web/tests/AdminFabricWizardBehaviorTest.mjs +++ b/web/tests/AdminFabricWizardBehaviorTest.mjs @@ -69,6 +69,16 @@ function preview(code = 'hk') { }; } +function operation(status = 'running', kind = 'apply', changes = {}) { + return { + id: 'a'.repeat(32), kind, status, + started_at: 1791501000, updated_at: 1791501010, + finished_at: ['succeeded', 'failed', 'uncertain', 'interrupted'].includes(status) + ? 1791501020 : null, + ...changes, + }; +} + function fixture(initialRegions, canManage = true) { const ids = [...source.matchAll(/byId\('([^']+)'\)/g)].map(match => match[1]); ids.push('fabric-detect-hosts', 'fabric-auto-configure', 'fabric-reconcile'); @@ -261,6 +271,105 @@ function fixture(initialRegions, canManage = true) { assert.equal(test.nodes['fabric-reconcile'].disabled, false); } +// Apply/reconcile host writes are accepted as asynchronous operations. The +// page correlates node evidence to the root operation id, exposes only fixed +// labels, disables all writes, and polls the existing read endpoint until a +// terminal state is observed. +{ + const ready = region(1, 'ready_to_apply', { plan_preview: preview() }); + const test = fixture([ready]); + await test.respond(test.requests[0], { regions: test.initialRegions, engine_available: true }); + test.nodes['fabric-auto-configure'].dispatch('click'); await flush(); + const rootOperation = operation('running'); + const matchedHost = { + host_id: '1', host_name: 'matched', fabric_member: true, + fabric_state: 'applying', readiness_state: 'uncertain', capabilities: {}, + operation: { + id: rootOperation.id, status: 'running', phase: 'apply', + checkpoint: 'future_untrusted_checkpoint', reason: 'future_untrusted_reason', + started_at: 1791501000, updated_at: 1791501010, finished_at: null, + }, + }; + const staleHost = { + ...matchedHost, host_id: '2', host_name: 'stale', + operation: { ...matchedHost.operation, id: 'b'.repeat(32), checkpoint: 'nft_install' }, + }; + const running = region(1, 'operation_running', { + operation: rootOperation, hosts: [matchedHost, staleHost], + plan_preview: { ...preview(), mode: 'existing' }, + }); + await test.respond(test.requests[1], { + operation: rootOperation, regions: [running], engine_available: true, + }, 202); + assert.match(test.nodes['fabric-notice'].textContent, + new RegExp('已受理 operation ' + rootOperation.id)); + assert.equal(test.actions.every(button => button.disabled), true); + const runningCopy = test.nodes['fabric-hosts-body'].textContent; + assert.equal((runningCopy.match(/本轮 operation:/g) || []).length, 1); + assert.match(runningCopy, /本轮检查点:未知检查点/); + assert.match(runningCopy, /本轮原因:未识别原因(已隐藏原始值)/); + assert.doesNotMatch(runningCopy, /future_untrusted/); + + await test.advance(2000); + assert.equal(test.requests[2].url, '/api/v1/admin/fabric'); + await test.respond(test.requests[2], { regions: [running], engine_available: true }); + await test.advance(2000); + const completedOperation = operation('succeeded'); + const completed = region(1, 'needs_probe', { operation: completedOperation }); + await test.respond(test.requests[3], { regions: [completed], engine_available: true }); + assert.match(test.nodes['fabric-notice'].textContent, /宿主机任务已成功/); + assert.equal(test.nodes['fabric-detect-hosts'].disabled, false); + assert.match(test.nodes['fabric-readback-summary'].textContent, + new RegExp(completedOperation.id)); + assert.match(test.nodes['fabric-readback-summary'].textContent, /succeeded(成功)/); + assert.match(test.nodes['fabric-readback-summary'].textContent, + new RegExp('journalctl --utc -u virt-cloud-fabric-apply-' + + completedOperation.id + '\\.service --no-pager')); +} + +// A missing or replaced authoritative operation cannot leave the browser +// polling a stale id forever. It stops the old read-only loop, marks the +// outcome unknown, and never adopts or POSTs the replacement operation. +{ + const rootOperation = operation('running'); + const running = region(1, 'operation_running', { + operation: rootOperation, plan_preview: { ...preview(), mode: 'existing' }, + }); + const test = fixture([running]); + await test.respond(test.requests[0], { regions: [running], engine_available: true }); + await test.advance(2000); + const replacement = operation('running', 'reconcile', { id: 'b'.repeat(32) }); + const replaced = region(1, 'operation_running', { + operation: replacement, plan_preview: { ...preview(), mode: 'existing' }, + }); + await test.respond(test.requests[1], { regions: [replaced], engine_available: true }); + assert.match(test.nodes['fabric-notice'].textContent, + new RegExp('operation ' + rootOperation.id + ' 已无法与服务端当前回读对应')); + assert.match(test.nodes['fabric-notice'].textContent, /不会重复提交/); + assert.equal(test.requests.filter(request => request.options.method === 'POST').length, 0); + await test.advance(10000); + assert.equal(test.requests.length, 2); +} + +// An empty successful region projection is authoritative too. If the region +// was removed while its operation was running, polling must stop instead of +// retaining the stale in-memory row forever. +{ + const rootOperation = operation('running'); + const running = region(1, 'operation_running', { + operation: rootOperation, plan_preview: { ...preview(), mode: 'existing' }, + }); + const test = fixture([running]); + await test.respond(test.requests[0], { regions: [running], engine_available: true }); + await test.advance(2000); + await test.respond(test.requests[1], { regions: [], engine_available: true }); + assert.match(test.nodes['fabric-notice'].textContent, + new RegExp('operation ' + rootOperation.id + ' 已无法与服务端当前回读对应')); + assert.equal(test.requests.filter(request => request.options.method === 'POST').length, 0); + await test.advance(10000); + assert.equal(test.requests.length, 2); +} + // A region change while a request is in flight cannot redirect the returned // projection into the newly selected region or redraw that region as active. { diff --git a/web/tests/CloudFirewallUiContractTest.php b/web/tests/CloudFirewallUiContractTest.php index fe21a8d3..a1e0cb95 100644 --- a/web/tests/CloudFirewallUiContractTest.php +++ b/web/tests/CloudFirewallUiContractTest.php @@ -18,7 +18,7 @@ $assert(str_contains($template, 'data-instance-setting-tab="firewall"') && str_contains($template, 'id="vm-firewall-rules"'), 'Instance settings must expose the integrated firewall tab and whole-policy editor.'); -$assert(str_contains($assets, "venix_asset_version value='2026100903'"), +$assert(str_contains($assets, "venix_asset_version value='2026100904'"), 'Shared Venix asset cache key must publish the firewall JavaScript and CSS.'); $assert(str_contains($template, '反欺骗保护始终开启') diff --git a/web/tests/CloudHostFabricEndpointContractTest.php b/web/tests/CloudHostFabricEndpointContractTest.php index 0e763f85..a0ada30e 100644 --- a/web/tests/CloudHostFabricEndpointContractTest.php +++ b/web/tests/CloudHostFabricEndpointContractTest.php @@ -97,7 +97,7 @@ $assert(str_contains($fabricClient, 'function endpointSource(value)') && str_contains($fabricClient, 'firewall_competing_service_unknown') && str_contains($fabricClient, 'firewall_manager_conflict'), 'Fabric readiness UI does not distinguish explicit and SSH-IPv4 fallback endpoints.'); -$assert(str_contains($assets, "venix_asset_version value='2026100903'"), +$assert(str_contains($assets, "venix_asset_version value='2026100904'"), 'Changed host/Fabric browser assets did not advance the shared cache key.'); echo "Cloud host Fabric endpoint contracts passed.\n";