Run Fabric apply as host systemd operations

venix
admin 2 months ago
parent a39118ab8d
commit 5f69df48ad

@ -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-<operation_id>.service`(任务仍被 systemd
保留时)和 `journalctl -u virt-cloud-fabric-apply-<operation_id>.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/<operation_id>` 必须为 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`、

@ -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/<operation_id>/`,然后通过
`virt-cloud-fabric-apply-<operation_id>.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 漂移节点合并而成。断裂的成员关系、资源池/线路、

@ -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/<operation_id>`,再由有运行上限的 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-<operation_id>.service --no-pager -o short-iso-precise`,
并完成双宿主 WireGuard 握手、跨宿主 VPC 流量和重启恢复后,才能认定生产组网验收完成。
## 2026-10-09:真实宿主探针兼容修复
- AlmaLinux 10 现场证明配置的 endpoint 唯一属于 `br0`,firewalld 使用

@ -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"]},

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -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(

@ -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)
);
}
}

@ -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;
}
}

@ -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;

@ -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

@ -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'}

@ -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,

@ -0,0 +1,96 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAdminFabricService;
use App\Services\Cloud\CloudError;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$method = new ReflectionMethod(CloudAdminFabricService::class, 'operation');
$invoke = static fn ($value, bool $node): ?array =>
$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";

@ -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) === [

@ -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.
{

@ -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, '反欺骗保护始终开启')

@ -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";

Loading…
Cancel
Save