Fabric 数量
—引擎 desired 记录
diff --git a/engine/tests/test_fabric.py b/engine/tests/test_fabric.py
index 013d6cab..d5ad527e 100644
--- a/engine/tests/test_fabric.py
+++ b/engine/tests/test_fabric.py
@@ -487,6 +487,7 @@ def test_recover_does_not_replay_an_interrupted_write():
def test_public_status_does_not_echo_nested_secrets_or_commands():
public = FabricCoordinator._public({
"fabric_id": "f", "state": "uncertain",
+ "listen_port": 51820,
"private_key": "secret",
"command": "rm -rf /",
"nodes": [{
@@ -501,6 +502,7 @@ def test_public_status_does_not_echo_nested_secrets_or_commands():
}],
})
serialized = json.dumps(public)
+ assert public["listen_port"] == 51820
assert "private_key" not in serialized
assert "command" not in serialized
assert KEY1 in serialized and KEY2 in serialized
diff --git a/engine/virsh_panel/fabric.py b/engine/virsh_panel/fabric.py
index 41820f8a..f12e5a41 100644
--- a/engine/virsh_panel/fabric.py
+++ b/engine/virsh_panel/fabric.py
@@ -3907,6 +3907,10 @@ class FabricCoordinator:
"updated_at"):
if key in value:
result[key] = value[key]
+ listen_port = value.get("listen_port")
+ if (isinstance(listen_port, int) and not isinstance(listen_port, bool)
+ and 1 <= listen_port <= 65535):
+ result["listen_port"] = listen_port
raw_nodes = value.get("nodes")
if isinstance(raw_nodes, list):
diff --git a/web/app/Controllers/Admin/CloudPageController.php b/web/app/Controllers/Admin/CloudPageController.php
index ae029b4c..6087b7fc 100644
--- a/web/app/Controllers/Admin/CloudPageController.php
+++ b/web/app/Controllers/Admin/CloudPageController.php
@@ -16,6 +16,33 @@ use App\Services\Cloud\CloudPlatformTestNetworkPolicy;
/** Admin pages use local or database-only first paints; JSON APIs repeat authorisation. */
final class CloudPageController extends AdminController
{
+ /**
+ * Fabric status is loaded through the PHP admin API after the page shell
+ * is rendered. Keeping the first paint free of engine SSH calls means a
+ * slow or unavailable host cannot block the administrator navigation.
+ */
+ public function fabric($request, $response, $args)
+ {
+ try {
+ $actor = CloudAccess::actor(false);
+ } catch (CloudError $exception) {
+ return $response->withStatus($exception->httpStatus)
+ ->withHeader('Cache-Control', 'private, no-store');
+ }
+ if (!($actor['is_admin'] ?? false)) {
+ return $response->withStatus(403)
+ ->withHeader('Cache-Control', 'private, no-store');
+ }
+
+ $response->getBody()->write($this->view()->assign([
+ 'fabric_can_manage' => ($actor['is_super_admin'] ?? false)
+ && ($actor['can_manage'] ?? false),
+ 'fabric_bootstrap_json' => 'null',
+ ])->fetch('admin/cloud/fabric.tpl'));
+ return $response->withStatus(200)
+ ->withHeader('Cache-Control', 'private, no-store');
+ }
+
public function resources($request, $response, $args)
{
try {
diff --git a/web/app/Controllers/CloudAdminFabricController.php b/web/app/Controllers/CloudAdminFabricController.php
new file mode 100644
index 00000000..ecaaa954
--- /dev/null
+++ b/web/app/Controllers/CloudAdminFabricController.php
@@ -0,0 +1,68 @@
+getAttribute('cloud_actor') ?? CloudAccess::actor(false);
+ if (!($actor['is_admin'] ?? false)) {
+ throw new CloudError('需要管理员权限', 403);
+ }
+ if ($write) {
+ CloudAccess::manage($actor);
+ if (!($actor['is_super_admin'] ?? false)) {
+ throw new CloudError('仅超级管理员可以修改 Fabric', 403);
+ }
+ }
+ return $actor;
+ }
+
+ private function json($response, array $payload, int $status = 200)
+ {
+ return $response->withJson($payload, $status)
+ ->withHeader('Cache-Control', 'private, no-store');
+ }
+
+ public function index($request, $response)
+ {
+ return $this->json($response,
+ CloudAdminFabricService::listing($this->actor($request)));
+ }
+
+ public function detail($request, $response, $args)
+ {
+ return $this->json($response,
+ CloudAdminFabricService::detail(
+ (string) ($args['fabric_id'] ?? ''), $this->actor($request)
+ ));
+ }
+
+ public function apply($request, $response)
+ {
+ $actor = $this->actor($request, true);
+ $body = CloudInput::object($request, 131072);
+ return $this->json($response,
+ CloudAdminFabricService::apply($body, $actor), 200);
+ }
+
+ public function reconcile($request, $response, $args)
+ {
+ $actor = $this->actor($request, true);
+ $body = trim((string) $request->getBody());
+ if ($body !== '' && $body !== '{}') {
+ throw new CloudError('Fabric reconcile 不接受请求体', 422);
+ }
+ return $this->json($response,
+ CloudAdminFabricService::reconcile(
+ (string) ($args['fabric_id'] ?? ''), $actor
+ ));
+ }
+}
diff --git a/web/app/Middleware/CloudApi.php b/web/app/Middleware/CloudApi.php
index 26704585..38eaba34 100644
--- a/web/app/Middleware/CloudApi.php
+++ b/web/app/Middleware/CloudApi.php
@@ -22,6 +22,7 @@ final class CloudApi
|| preg_match('#^/api/v1/admin/system-logs(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/platform-test-policy(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/(?:resources|regions|network-lines|resource-pools|resource-reservations)(?:/|$)#D', $path) === 1
+ || preg_match('#^/api/v1/admin/fabric(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/admin/hosts/[0-9]+/scheduling$#D', $path) === 1
|| preg_match('#^/api/v1/ssh-keys(?:/|$)#D', $path) === 1
|| preg_match('#^/api/v1/(?:jobs|reinstall-jobs|rescue-jobs)/[0-9]+$#D', $path) === 1
diff --git a/web/app/Services/Cloud/CloudAdminFabricService.php b/web/app/Services/Cloud/CloudAdminFabricService.php
new file mode 100644
index 00000000..9985ce04
--- /dev/null
+++ b/web/app/Services/Cloud/CloudAdminFabricService.php
@@ -0,0 +1,613 @@
+fabricStatuses($actor);
+ } catch (CloudError $exception) {
+ // Keep the platform-owned region mapping visible when a host or
+ // engine is unavailable. This is a diagnostic snapshot, never a
+ // claim that the Fabric is active.
+ return [
+ 'fabrics' => [],
+ 'mappings' => self::mappings([]),
+ 'generated_at' => time(),
+ 'engine_available' => false,
+ 'engine_error' => 'Fabric 引擎状态暂时无法读取,请稍后重试。',
+ ];
+ }
+ if (!is_array($raw)) {
+ throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
+ }
+ $hostNames = self::hostNames($raw);
+ $fabrics = [];
+ foreach ($raw as $item) {
+ if (!is_array($item)) {
+ continue;
+ }
+ $fabrics[] = self::project($item, $hostNames);
+ }
+ usort($fabrics, static fn (array $a, array $b): int =>
+ strcmp((string) $a['fabric_id'], (string) $b['fabric_id']));
+ return [
+ 'fabrics' => $fabrics,
+ 'mappings' => self::mappings($fabrics),
+ 'generated_at' => time(),
+ 'engine_available' => true,
+ ];
+ }
+
+ public static function detail(string $fabricId, array $actor,
+ ?CloudEngineClient $engine = null): array
+ {
+ self::assertReadActor($actor);
+ $fabricId = self::fabricId($fabricId);
+ $engine ??= new CloudEngineClient();
+ $raw = $engine->fabricStatus($fabricId, $actor);
+ if (!is_array($raw)) {
+ throw new CloudError('Fabric 状态响应无效,请稍后重试', 502);
+ }
+ $hostNames = self::hostNames([$raw]);
+ $fabric = self::project($raw, $hostNames);
+ return [
+ 'fabric' => $fabric,
+ 'mapping' => self::mappingForFabric($fabricId),
+ ];
+ }
+
+ public static function apply(array $body, array $actor,
+ ?CloudEngineClient $engine = null): array
+ {
+ self::assertWriteActor($actor);
+ $plan = self::plan($body);
+ self::assertMappedPlanCanApply($plan);
+ // Applying/reconciling runs a bounded host loop. Give it a longer
+ // transport window than a read, while still returning an explicit
+ // uncertain result if the PHP request itself loses the response.
+ $engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
+ $raw = $engine->fabricApply($plan, $actor);
+ if (!is_array($raw)) {
+ throw new CloudError('Fabric 应用响应无效,请稍后核对', 502);
+ }
+ $hostNames = self::hostNames([$raw]);
+ $fabric = self::project($raw, $hostNames);
+ return [
+ 'fabric' => $fabric,
+ 'mapping' => self::mappingForFabric((string) $fabric['fabric_id']),
+ ];
+ }
+
+ public static function reconcile(string $fabricId, array $actor,
+ ?CloudEngineClient $engine = null): array
+ {
+ self::assertWriteActor($actor);
+ $fabricId = self::fabricId($fabricId);
+ $engine ??= new CloudEngineClient(null, self::FABRIC_WRITE_TIMEOUT_SECONDS);
+ $raw = $engine->fabricReconcile($fabricId, $actor);
+ if (!is_array($raw)) {
+ throw new CloudError('Fabric 核对响应无效,请稍后刷新', 502);
+ }
+ $hostNames = self::hostNames([$raw]);
+ return [
+ 'fabric' => self::project($raw, $hostNames),
+ 'mapping' => self::mappingForFabric($fabricId),
+ ];
+ }
+
+ private static function assertReadActor(array $actor): void
+ {
+ if (!($actor['is_admin'] ?? false)) {
+ throw new CloudError('需要管理员权限', 403);
+ }
+ }
+
+ private static function assertWriteActor(array $actor): void
+ {
+ if (!($actor['is_admin'] ?? false)
+ || !($actor['is_super_admin'] ?? false)
+ || !($actor['can_manage'] ?? false)) {
+ throw new CloudError('仅超级管理员可以修改 Fabric', 403);
+ }
+ }
+
+ private static function fabricId($value): string
+ {
+ if (!is_string($value) || preg_match(self::FABRIC_ID, $value) !== 1) {
+ throw new CloudError('Fabric 标识无效', 422);
+ }
+ return $value;
+ }
+
+ /** Validate the exact engine plan vocabulary before forwarding it. */
+ private static function plan(array $body): array
+ {
+ CloudInput::only($body, [
+ 'schema_version', 'fabric_id', 'region', 'overlay_cidr',
+ 'revision', 'listen_port', 'nodes',
+ ]);
+ if (($body['schema_version'] ?? 1) !== 1) {
+ throw new CloudError('Fabric 计划版本不支持', 422);
+ }
+ $fabricId = self::fabricId($body['fabric_id'] ?? null);
+ $region = self::safeText($body['region'] ?? null, 'Fabric 地区', 64);
+ $network = self::network($body['overlay_cidr'] ?? null);
+ $revision = self::positiveInt($body['revision'] ?? null, 'Fabric 版本');
+ $listenPort = self::port($body['listen_port'] ?? 51820);
+ $nodes = $body['nodes'] ?? null;
+ if (!is_array($nodes) || array_is_list($nodes) !== true
+ || count($nodes) < 2 || count($nodes) > 64) {
+ throw new CloudError('Fabric 至少需要两个且最多支持 64 个宿主机', 422);
+ }
+ $seenHosts = [];
+ $seenIps = [];
+ $normalized = [];
+ foreach ($nodes as $node) {
+ if (!is_array($node)) {
+ throw new CloudError('Fabric 节点字段无效', 422);
+ }
+ CloudInput::only($node, ['host_id', 'overlay_ip', 'endpoint', 'listen_port']);
+ $hostId = $node['host_id'] ?? null;
+ if (!is_string($hostId) || preg_match(self::HOST_ID, $hostId) !== 1
+ || isset($seenHosts[$hostId])) {
+ throw new CloudError('Fabric 宿主机标识无效或重复', 422);
+ }
+ $overlayIp = self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址');
+ if (isset($seenIps[$overlayIp])) {
+ throw new CloudError('Fabric overlay 地址不能重复', 422);
+ }
+ if (!self::containsHost($network, $overlayIp)) {
+ throw new CloudError('Fabric overlay 地址必须位于 overlay CIDR 内', 422);
+ }
+ $endpoint = self::endpoint($node['endpoint'] ?? null);
+ [$endpointIp] = explode(':', $endpoint, 2);
+ if (self::containsAddress($network, $endpointIp)) {
+ throw new CloudError('WireGuard endpoint 不能位于 Fabric overlay 网段', 422);
+ }
+ $nodePort = self::port($node['listen_port'] ?? $listenPort);
+ $seenHosts[$hostId] = true;
+ $seenIps[$overlayIp] = true;
+ $normalized[] = [
+ 'host_id' => $hostId,
+ 'overlay_ip' => $overlayIp,
+ 'endpoint' => $endpoint,
+ 'listen_port' => $nodePort,
+ ];
+ }
+ usort($normalized, static fn (array $a, array $b): int =>
+ strcmp($a['host_id'], $b['host_id']));
+ return [
+ 'schema_version' => 1,
+ 'fabric_id' => $fabricId,
+ 'region' => $region,
+ 'overlay_cidr' => $network,
+ 'revision' => $revision,
+ 'listen_port' => $listenPort,
+ 'nodes' => $normalized,
+ ];
+ }
+
+ private static function assertMappedPlanCanApply(array $plan): void
+ {
+ $connection = (new CloudRegionFabric())->getConnection();
+ if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
+ return;
+ }
+ $mapping = CloudRegionFabric::where('fabric_id', $plan['fabric_id'])->first();
+ if ($mapping === null || (string) $mapping->state !== 'active') {
+ return;
+ }
+ if ((string) $mapping->fabric_region !== $plan['region']
+ || (int) $mapping->fabric_revision !== (int) $plan['revision']) {
+ throw new CloudError(
+ '活动 Fabric 映射仍引用其他地区或版本,请先停用映射并完成迁移', 409
+ );
+ }
+ }
+
+ private static function project(array $value, array $hostNames): array
+ {
+ $fabricId = self::fabricId($value['fabric_id'] ?? null);
+ $region = self::safeText($value['region'] ?? null, 'Fabric 地区', 64);
+ $overlay = self::network($value['overlay_cidr'] ?? null);
+ $revision = self::positiveInt($value['revision'] ?? null, 'Fabric 版本');
+ $state = self::choice($value['state'] ?? null, self::STATES, 'Fabric 状态');
+ $result = [
+ 'fabric_id' => $fabricId,
+ 'region' => $region,
+ 'overlay_cidr' => $overlay,
+ 'revision' => $revision,
+ 'listen_port' => self::port($value['listen_port'] ?? 51820),
+ 'plan_digest' => self::digest($value['plan_digest'] ?? null),
+ 'interface' => self::safeText($value['interface'] ?? 'wg-fabric0', 'Fabric 网卡', 32),
+ 'state' => $state,
+ 'next_stage_allowed' => ($value['next_stage_allowed'] ?? false) === true,
+ 'updated_at' => max(0, (int) ($value['updated_at'] ?? 0)),
+ 'nodes' => [],
+ ];
+ $nodes = $value['nodes'] ?? [];
+ if (!is_array($nodes) || count($nodes) > 64) {
+ throw new CloudError('Fabric 节点状态无效', 502);
+ }
+ foreach ($nodes as $node) {
+ if (!is_array($node)) {
+ continue;
+ }
+ $hostId = self::safeText($node['host_id'] ?? null, '宿主机标识', 64);
+ $row = [
+ 'host_id' => $hostId,
+ 'host_name' => $hostNames[$hostId]['name'] ?? null,
+ 'host_region' => $hostNames[$hostId]['region'] ?? null,
+ 'overlay_ip' => self::ipv4($node['overlay_ip'] ?? null, 'Fabric overlay 地址'),
+ 'endpoint' => self::endpoint($node['endpoint'] ?? null),
+ 'listen_port' => self::port($node['listen_port'] ?? 51820),
+ 'public_key' => self::key($node['public_key'] ?? null),
+ 'state' => self::choice($node['state'] ?? null, self::STATES, 'Fabric 节点状态'),
+ 'transport_verified' => ($node['transport_verified'] ?? false) === true,
+ 'observed_revision' => max(0, (int) ($node['observed_revision'] ?? 0)),
+ 'observed_plan_digest' => self::nullableDigest($node['observed_plan_digest'] ?? null),
+ 'last_error_code' => self::errorCode($node['last_error_code'] ?? null),
+ 'observed' => self::observed($node['observed'] ?? []),
+ ];
+ $result['nodes'][] = $row;
+ }
+ return $result;
+ }
+
+ private static function observed($value): array
+ {
+ if (!is_array($value)) {
+ return [];
+ }
+ $result = [];
+ foreach ([
+ 'owner', 'config_fabric', 'config_revision', 'config_digest',
+ 'config_network', 'config_overlay', 'config_ok', 'interface',
+ 'listen_port', 'enabled', 'service_active', 'timer_enabled',
+ 'timer_active', 'nft_guard', 'key_secure', 'nft_persistence',
+ 'config_secure', 'helper_marker', 'unit_marker', 'repair_marker',
+ 'timer_marker', 'manager_mode', 'manager_owner', 'manager_active',
+ 'admin_state', 'vpc_state', 'peer_allowed_exact', 'vpc_nft_state',
+ 'vpc_nft_exact',
+ ] as $key) {
+ if (array_key_exists($key, $value)) {
+ $item = $value[$key];
+ $result[$key] = is_string($item)
+ ? substr($item, 0, 128)
+ : (is_scalar($item) ? $item : null);
+ }
+ }
+ foreach ([
+ 'addresses', 'routes', 'paths', 'pings', 'endpoint_paths',
+ 'config_routes', 'route_overlaps', 'vpc_tenants', 'vpc_nft_ips',
+ ] as $key) {
+ if (!is_array($value[$key] ?? null)) {
+ continue;
+ }
+ $result[$key] = array_values(array_filter(
+ array_map(static fn ($item): ?string => is_string($item)
+ ? substr($item, 0, 128) : null, $value[$key]),
+ static fn ($item): bool => $item !== null
+ ));
+ }
+ foreach (['sysctls', 'rp_filters'] as $key) {
+ if (!is_array($value[$key] ?? null)) {
+ continue;
+ }
+ $result[$key] = [];
+ foreach ($value[$key] as $name => $item) {
+ if (is_string($name) && strlen($name) <= 64
+ && in_array((string) $item, ['0', '1', '2', 'unknown'], true)) {
+ $result[$key][$name] = (string) $item;
+ }
+ }
+ }
+ foreach (['config_peers', 'peers', 'overlay_peers'] as $key) {
+ if (!is_array($value[$key] ?? null)) {
+ continue;
+ }
+ $result[$key] = [];
+ foreach ($value[$key] as $item) {
+ if (!is_array($item) || count($item) !== 3) {
+ continue;
+ }
+ $result[$key][] = array_map(static fn ($part): string =>
+ substr((string) $part, 0, 128), array_values($item));
+ }
+ }
+ if (is_array($value['handshakes'] ?? null)) {
+ $result['handshakes'] = [];
+ foreach ($value['handshakes'] as $key => $stamp) {
+ if (is_string($key) && strlen($key) <= 128 && is_numeric($stamp)) {
+ $result['handshakes'][$key] = (int) $stamp;
+ }
+ }
+ }
+ return $result;
+ }
+
+ private static function mappings(array $fabrics): array
+ {
+ $connection = (new CloudRegionFabric())->getConnection();
+ if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
+ return [];
+ }
+ $regions = CloudRegion::orderBy('id')->get();
+ $byFabric = [];
+ foreach ($fabrics as $fabric) {
+ $byFabric[(string) $fabric['fabric_id']] = $fabric;
+ }
+ $fabricRows = CloudRegionFabric::get()->keyBy('region_id');
+ $rows = [];
+ foreach ($regions as $region) {
+ $row = $fabricRows[(int) $region->id] ?? null;
+ if ($row === null) {
+ $rows[] = self::unconfiguredMapping($region);
+ continue;
+ }
+ $fabric = $byFabric[(string) $row->fabric_id] ?? null;
+ $rows[] = self::mappingRow($row, $region, $fabric);
+ }
+ return $rows;
+ }
+
+ private static function mappingForFabric(string $fabricId): ?array
+ {
+ $connection = (new CloudRegionFabric())->getConnection();
+ if (!$connection->getSchemaBuilder()->hasTable('cloud_region_fabrics')) {
+ return null;
+ }
+ $row = CloudRegionFabric::where('fabric_id', $fabricId)->first();
+ if ($row === null) {
+ return null;
+ }
+ $region = CloudRegion::find((int) $row->region_id);
+ return self::mappingRow($row, $region, null);
+ }
+
+ private static function mappingRow($row, $region, ?array $fabric): array
+ {
+ return [
+ 'region_id' => (int) $row->region_id,
+ 'region_code' => (string) ($region->code ?? ''),
+ 'region_name' => (string) ($region->name ?? ''),
+ 'region_status' => (string) ($region->status ?? 'disabled'),
+ 'fabric_id' => (string) $row->fabric_id,
+ 'fabric_region' => (string) $row->fabric_region,
+ 'fabric_revision' => (int) $row->fabric_revision,
+ 'state' => (string) $row->state,
+ 'engine_state' => is_array($fabric) ? ($fabric['state'] ?? null) : null,
+ 'engine_revision' => is_array($fabric) ? ($fabric['revision'] ?? null) : null,
+ 'next_stage_allowed' => is_array($fabric)
+ ? ($fabric['next_stage_allowed'] ?? false) : false,
+ 'updated_at' => (int) $row->updated_at,
+ ];
+ }
+
+ private static function unconfiguredMapping($region): array
+ {
+ return [
+ 'region_id' => (int) ($region->id ?? 0),
+ 'region_code' => (string) ($region->code ?? ''),
+ 'region_name' => (string) ($region->name ?? ''),
+ 'region_status' => (string) ($region->status ?? 'disabled'),
+ 'fabric_id' => null,
+ 'fabric_region' => null,
+ 'fabric_revision' => null,
+ 'state' => 'unconfigured',
+ 'engine_state' => null,
+ 'engine_revision' => null,
+ 'next_stage_allowed' => false,
+ 'updated_at' => null,
+ ];
+ }
+
+ private static function hostNames(array $fabrics): array
+ {
+ $ids = [];
+ foreach ($fabrics as $fabric) {
+ foreach (($fabric['nodes'] ?? []) as $node) {
+ $id = is_array($node) ? (string) ($node['host_id'] ?? '') : '';
+ if (ctype_digit($id) && (int) $id > 0) {
+ $ids[(int) $id] = true;
+ }
+ }
+ }
+ if ($ids === []) {
+ return [];
+ }
+ $result = [];
+ foreach (CloudHost::whereIn('id', array_keys($ids))->get() as $host) {
+ $result[(string) $host->id] = [
+ 'name' => (string) $host->name,
+ 'region' => (string) $host->region,
+ ];
+ }
+ return $result;
+ }
+
+ private static function network($value): string
+ {
+ if (!is_string($value)) {
+ throw new CloudError('Fabric overlay CIDR 无效', 422);
+ }
+ [$ip, $prefix] = array_pad(explode('/', trim($value), 2), 2, null);
+ $prefix = filter_var($prefix, FILTER_VALIDATE_INT);
+ if ($prefix === false || $prefix < 10 || $prefix > 24
+ || self::ipv4($ip, 'Fabric overlay CIDR') !== $ip) {
+ throw new CloudError('Fabric overlay CIDR 无效', 422);
+ }
+ $parts = array_map('intval', explode('.', $ip));
+ if ($parts[0] !== 100 || $parts[1] < 64 || $parts[1] > 127) {
+ throw new CloudError('Fabric overlay 必须位于 100.64.0.0/10 内', 422);
+ }
+ $mask = $prefix === 0 ? 0 : (0xffffffff << (32 - $prefix)) & 0xffffffff;
+ $number = (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
+ if (($number & $mask) !== $number) {
+ throw new CloudError('Fabric overlay CIDR 必须使用规范网络地址', 422);
+ }
+ return $ip . '/' . $prefix;
+ }
+
+ private static function containsHost(string $network, string $ip): bool
+ {
+ if (!self::containsAddress($network, $ip)) {
+ return false;
+ }
+ [$base, $prefix] = explode('/', $network);
+ $toInt = static function (string $value): int {
+ $parts = array_map('intval', explode('.', $value));
+ return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
+ };
+ $mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
+ $value = $toInt($ip);
+ $baseValue = $toInt($base);
+ return (($value & $mask) === $baseValue) && $value !== $baseValue
+ && $value !== ($baseValue | ((1 << (32 - (int) $prefix)) - 1));
+ }
+
+ private static function containsAddress(string $network, string $ip): bool
+ {
+ [$base, $prefix] = explode('/', $network);
+ $toInt = static function (string $value): int {
+ $parts = array_map('intval', explode('.', $value));
+ return (($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3]) & 0xffffffff;
+ };
+ $mask = (0xffffffff << (32 - (int) $prefix)) & 0xffffffff;
+ return (($toInt($ip) & $mask) === $toInt($base));
+ }
+
+ private static function ipv4($value, string $label): string
+ {
+ if (!is_string($value) || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
+ throw new CloudError($label . '无效', 422);
+ }
+ return $value;
+ }
+
+ private static function endpoint($value): string
+ {
+ if (!is_string($value) || substr_count($value, ':') !== 1) {
+ throw new CloudError('WireGuard endpoint 无效', 422);
+ }
+ [$ip, $port] = explode(':', $value, 2);
+ $ip = self::ipv4($ip, 'WireGuard endpoint 地址');
+ $parts = array_map('intval', explode('.', $ip));
+ if ($ip === '0.0.0.0' || $parts[0] === 127 || $parts[0] >= 224
+ || ($parts[0] === 169 && $parts[1] === 254)) {
+ throw new CloudError('WireGuard endpoint 地址不可路由', 422);
+ }
+ $port = self::port($port);
+ return $ip . ':' . $port;
+ }
+
+ private static function port($value): int
+ {
+ if (is_string($value) && ctype_digit($value)) {
+ $value = (int) $value;
+ }
+ if (is_bool($value) || !is_int($value) || $value < 1 || $value > 65535) {
+ throw new CloudError('WireGuard 端口无效', 422);
+ }
+ return $value;
+ }
+
+ private static function positiveInt($value, string $label): int
+ {
+ if (is_string($value) && ctype_digit($value)) {
+ $value = (int) $value;
+ }
+ if (is_bool($value) || !is_int($value) || $value < 1 || $value > 9223372036854775807) {
+ throw new CloudError($label . '无效', 422);
+ }
+ return $value;
+ }
+
+ private static function safeText($value, string $label, int $maximum): string
+ {
+ if (!is_string($value) || $value === '' || strlen($value) > $maximum
+ || trim($value) !== $value || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
+ throw new CloudError($label . '无效', 422);
+ }
+ return $value;
+ }
+
+ private static function choice($value, array $choices, string $label): string
+ {
+ if (!is_string($value) || !in_array($value, $choices, true)) {
+ throw new CloudError($label . '无效', 502);
+ }
+ return $value;
+ }
+
+ private static function key($value): ?string
+ {
+ if ($value === null) {
+ return null;
+ }
+ if (!is_string($value) || preg_match(self::KEY, $value) !== 1) {
+ throw new CloudError('Fabric 公钥回读无效', 502);
+ }
+ return $value;
+ }
+
+ private static function digest($value): ?string
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+ if (!is_string($value) || preg_match('/^[0-9a-f]{64}$/D', $value) !== 1) {
+ throw new CloudError('Fabric 摘要回读无效', 502);
+ }
+ return $value;
+ }
+
+ private static function nullableDigest($value): ?string
+ {
+ return $value === null || $value === '' ? null : self::digest($value);
+ }
+
+ private static function errorCode($value): ?string
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+ if (!is_string($value) || !in_array($value, self::ERROR_CODES, true)) {
+ return 'fabric_readback_invalid';
+ }
+ return $value;
+ }
+}
diff --git a/web/app/Services/Cloud/CloudEngineClient.php b/web/app/Services/Cloud/CloudEngineClient.php
index 5e131e0f..c6e207e5 100644
--- a/web/app/Services/Cloud/CloudEngineClient.php
+++ b/web/app/Services/Cloud/CloudEngineClient.php
@@ -143,8 +143,12 @@ final class CloudEngineClient
'#^/internal/v1/vpcs(?:/(?:apply|[0-9a-f]{32}(?:/reconcile)?))?$#D',
$route
) === 1;
+ $fabric = preg_match(
+ '#^/internal/v1/fabric(?:/(?:apply|[A-Za-z0-9][A-Za-z0-9_.-]{0,63}/reconcile|[A-Za-z0-9][A-Za-z0-9_.-]{0,63}))?$#D',
+ $route
+ ) === 1;
if (!$update && !$userIso && !$vmTemplate && !$host
- && !$hostNetworkPool && !$vpc) {
+ && !$hostNetworkPool && !$vpc && !$fabric) {
return null;
}
if ($hostNetworkPool) {
@@ -161,6 +165,11 @@ final class CloudEngineClient
? self::safeVpcErrorMessage($result['error_code'] ?? null)
: null;
}
+ if ($fabric) {
+ return in_array($status, [400, 404, 409, 422], true)
+ ? self::safeFabricErrorMessage($result['error_code'] ?? null)
+ : null;
+ }
if ($host) {
// Host errors may describe validation failures, SSH transport
// failures or damaged engine state with the same fallback code.
@@ -250,6 +259,40 @@ final class CloudEngineClient
][$value] ?? null;
}
+ private static function safeFabricErrorMessage($value): ?string
+ {
+ if (!is_string($value)) {
+ return null;
+ }
+ return [
+ 'fabric_invalid' => 'Fabric 计划无效',
+ 'fabric_not_found' => 'Fabric 不存在',
+ 'fabric_record_corrupt' => 'Fabric 持久化记录损坏,请联系管理员处理',
+ 'fabric_revision_conflict' => 'Fabric 版本冲突,请提升 revision 后重试',
+ 'fabric_membership_conflict' => 'Fabric 参与宿主机集合不能直接变更',
+ 'fabric_host_interface_conflict' => '参与宿主机已加入其他 Fabric',
+ 'fabric_overlay_conflict' => 'Fabric overlay 网段与已有 Fabric 冲突',
+ 'fabric_region_mismatch' => 'Fabric 参与宿主机必须属于同一地区',
+ 'fabric_host_unavailable' => 'Fabric 参与宿主机暂不可用',
+ 'fabric_host_capability_probe_unsupported' => '宿主机不支持能力重新探测',
+ 'fabric_host_capability_probe_failed' => '宿主机能力重新探测失败',
+ 'fabric_host_capability_probe_invalid' => '宿主机能力探测结果无效',
+ 'fabric_host_not_configured' => 'Fabric 参与宿主机尚未完成配置',
+ 'fabric_host_identity_mismatch' => 'Fabric 宿主机身份不一致',
+ 'fabric_host_capability_missing' => '宿主机未通过 Fabric 能力核验',
+ 'fabric_host_network_manager_conflict' => '宿主机网络管理器与 Fabric 部署模式冲突',
+ 'fabric_identity_conflict' => 'Fabric 宿主机公钥身份冲突',
+ 'fabric_identity_invalid' => 'Fabric 宿主机公钥回读无效',
+ 'fabric_apply_unconfirmed' => '宿主机未确认 Fabric 应用结果',
+ 'fabric_readback_invalid' => 'Fabric 宿主机回读结果无效',
+ 'fabric_host_connection_failed' => 'Fabric 宿主机连接失败',
+ 'fabric_host_key_locked' => 'Fabric 宿主机 SSH 私钥仍锁定',
+ 'fabric_runner_unsupported' => '宿主机不支持 Fabric 执行器',
+ 'fabric_remote_command_failed' => '宿主机 Fabric 命令执行失败',
+ 'fabric_plan_corrupt' => 'Fabric 计划损坏',
+ ][$value] ?? null;
+ }
+
public static function safeVmTemplateMessage($value): ?string
{
if (!is_string($value)) {
@@ -410,20 +453,51 @@ final class CloudEngineClient
}
/**
- * Read one engine-global Fabric status through the bounded admin route.
- * Region mapping is an administrator operation, so callers must provide
- * the already-authenticated super-admin actor; tenant actors are never
- * promoted inside this client.
+ * Read engine-global Fabric status through the bounded admin route.
+ * Read access is available to administrators; mutation methods below
+ * enforce the separate super-admin/manage capability.
*/
+ public function fabricStatuses(array $actor): array
+ {
+ if (!($actor['is_admin'] ?? false)) {
+ throw new CloudError('Fabric 状态查询参数无效', 422);
+ }
+ return $this->request('GET', '/internal/v1/fabric', $actor);
+ }
+
public function fabricStatus(string $fabricId, array $actor): array
{
if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $fabricId)
- || !($actor['is_admin'] ?? false)
- || !($actor['is_super_admin'] ?? false)
- || !($actor['can_manage'] ?? false)) {
+ || !($actor['is_admin'] ?? false)) {
throw new CloudError('Fabric 状态查询参数无效', 422);
}
return $this->request('GET', '/internal/v1/fabric/' . $fabricId, $actor);
}
+ public function fabricApply(array $plan, array $actor): array
+ {
+ self::assertFabricWriteActor($actor);
+ return $this->request('POST', '/internal/v1/fabric/apply', $actor, $plan);
+ }
+
+ public function fabricReconcile(string $fabricId, array $actor): array
+ {
+ if (!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $fabricId)) {
+ throw new CloudError('Fabric 标识无效', 422);
+ }
+ self::assertFabricWriteActor($actor);
+ return $this->request(
+ 'POST', '/internal/v1/fabric/' . $fabricId . '/reconcile', $actor, []
+ );
+ }
+
+ private static function assertFabricWriteActor(array $actor): void
+ {
+ if (!($actor['is_admin'] ?? false)
+ || !($actor['is_super_admin'] ?? false)
+ || !($actor['can_manage'] ?? false)) {
+ throw new CloudError('仅超级管理员可以修改 Fabric', 403);
+ }
+ }
+
}
diff --git a/web/config/routes.php b/web/config/routes.php
index 4dfdeafd..e0b8854c 100644
--- a/web/config/routes.php
+++ b/web/config/routes.php
@@ -164,6 +164,7 @@ $app->group('/admin', function () {
$this->get('', 'App\Controllers\AdminController:index');
$this->get('/', 'App\Controllers\AdminController:index');
$this->get('/resources', 'App\Controllers\Admin\CloudPageController:resources');
+ $this->get('/fabric', 'App\Controllers\Admin\CloudPageController:fabric');
// Host preparation (admin only; backend integration is not enabled yet)
$this->get('/hosts', 'App\Controllers\Admin\CloudPageController:hosts');
$this->get('/cloud/templates', 'App\Controllers\Admin\CloudPageController:templates');
diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php
index b6828798..ea2b2163 100644
--- a/web/config/routes_cloud.php
+++ b/web/config/routes_cloud.php
@@ -101,6 +101,14 @@ $app->group('/api/v1', function () {
$this->get('/admin/billing/payments',
'App\Controllers\CloudAdminBillingController:payments');
$this->get('/admin/resources', 'App\Controllers\CloudAdminResourceController:resources');
+ // Static apply must precede the dynamic Fabric detail route: Fabric IDs
+ // share the same safe identifier alphabet and "apply" is a valid ID.
+ $this->post('/admin/fabric/apply', 'App\Controllers\CloudAdminFabricController:apply');
+ $this->get('/admin/fabric', 'App\Controllers\CloudAdminFabricController:index');
+ $this->get('/admin/fabric/{fabric_id:[A-Za-z0-9][A-Za-z0-9_.-]{0,63}}',
+ 'App\Controllers\CloudAdminFabricController:detail');
+ $this->post('/admin/fabric/{fabric_id:[A-Za-z0-9][A-Za-z0-9_.-]{0,63}}/reconcile',
+ 'App\Controllers\CloudAdminFabricController:reconcile');
$this->get('/admin/platform-test-policy',
'App\Controllers\CloudAdminPlatformPolicyController:index');
$this->post('/admin/platform-test-policy/rules',
diff --git a/web/public/cloud/admin-fabric.js b/web/public/cloud/admin-fabric.js
new file mode 100644
index 00000000..422bd473
--- /dev/null
+++ b/web/public/cloud/admin-fabric.js
@@ -0,0 +1,421 @@
+const root = document.querySelector('[data-admin-fabric]');
+const canManage = root && root.dataset.canManage === '1';
+const byId = id => document.getElementById(id);
+const state = { payload: null, selected: null };
+
+const stateLabels = {
+ active: 'active(活动)', applying: 'applying(应用中)',
+ uncertain: 'uncertain(待核对)', degraded: 'degraded(降级)',
+ disabled: 'disabled(停用)', failed: 'failed(失败)',
+};
+const errorLabels = {
+ fabric_not_found: 'Fabric 不存在',
+ fabric_record_corrupt: 'Fabric 持久化记录损坏',
+ fabric_revision_conflict: 'Revision 冲突',
+ fabric_membership_conflict: '参与宿主机集合冲突',
+ fabric_host_interface_conflict: '宿主机 WireGuard 接口冲突',
+ fabric_overlay_conflict: 'Overlay 网段冲突',
+ fabric_host_connection_failed: '宿主机连接失败',
+ fabric_host_capability_probe_failed: '宿主机能力探测失败',
+ fabric_host_capability_probe_unsupported: '宿主机能力不支持',
+ fabric_host_capability_probe_invalid: '宿主机能力回读无效',
+ fabric_host_capability_unsupported: '宿主机能力不支持',
+ fabric_host_capability_invalid: '宿主机能力回读无效',
+ fabric_host_capability_missing: '宿主机能力未通过核验',
+ fabric_host_not_configured: '宿主机未配置',
+ fabric_host_network_manager_conflict: '宿主机网络管理器冲突',
+ fabric_host_identity_mismatch: '宿主机身份不一致',
+ fabric_host_key_locked: '宿主机密钥仍锁定',
+ fabric_identity_conflict: '宿主机公钥冲突',
+ fabric_identity_invalid: '宿主机公钥回读无效',
+ fabric_apply_unconfirmed: '应用结果未确认',
+ fabric_readback_invalid: '回读结果无效',
+ fabric_remote_command_failed: '宿主机命令执行失败',
+ fabric_runner_unsupported: '宿主机执行器不支持',
+ fabric_plan_corrupt: 'Fabric 计划损坏',
+ fabric_region_mismatch: 'Fabric 地区不一致',
+ fabric_not_active: 'Fabric 尚未 active',
+};
+
+function el(tag, className, value) {
+ const node = document.createElement(tag);
+ if (className) node.className = className;
+ if (value !== undefined) node.textContent = String(value);
+ return node;
+}
+function text(value, fallback = '未记录') {
+ return value === null || value === undefined || String(value).trim() === '' ? fallback : String(value);
+}
+function bool(value) { return value === true ? '是' : value === false ? '否' : '—'; }
+function stateLabel(value) { return stateLabels[value] || text(value); }
+function errorLabel(value) { return errorLabels[value] || (value ? '错误码 ' + value : '无'); }
+function date(value) {
+ const number = Number(value);
+ if (!Number.isFinite(number) || number <= 0) return '未记录';
+ const parsed = new Date(number * 1000);
+ return Number.isFinite(parsed.getTime()) ? parsed.toLocaleString('zh-CN') : '未记录';
+}
+function notice(message, error) {
+ const node = byId('fabric-notice');
+ if (!node) return;
+ node.textContent = message;
+ node.className = 'admin-config-status ' + (error ? 'is-error' : 'is-success');
+ node.setAttribute('role', error ? 'alert' : 'status');
+}
+function operationNotice(id, message, error) {
+ const node = byId(id);
+ if (!node) return;
+ node.textContent = message;
+ node.className = 'admin-config-status ' + (error ? 'is-error' : 'is-success');
+ node.setAttribute('role', error ? 'alert' : 'status');
+}
+
+async function api(path, options = {}) {
+ const controller = new AbortController();
+ const method = String(options.method || 'GET').toUpperCase();
+ const timer = window.setTimeout(() => controller.abort('timeout'), method === 'GET' ? 30000 : 120000);
+ try {
+ const headers = Object.assign({ Accept: 'application/json' }, options.headers || {});
+ const request = { method, credentials: 'same-origin', cache: 'no-store', signal: controller.signal, headers };
+ if (method !== 'GET' && method !== 'HEAD') {
+ if (!window.ADMIN_CSRF_TOKEN) throw new Error('页面安全令牌缺失,请刷新后重试。');
+ headers['X-CSRF-Token'] = window.ADMIN_CSRF_TOKEN;
+ headers['Content-Type'] = 'application/json';
+ request.body = options.body === undefined ? '{}' : options.body;
+ }
+ const response = await fetch(path, request);
+ let payload = null;
+ try { payload = await response.json(); } catch (ignore) {}
+ if (!response.ok) {
+ const message = payload && (payload.detail || payload.error || payload.message);
+ throw new Error(typeof message === 'string' && message ? message : '请求失败 (' + response.status + ')');
+ }
+ return payload;
+ } catch (error) {
+ if (controller.signal.reason === 'timeout') throw new Error('请求超时;操作可能仍在引擎中执行,请刷新核对。');
+ throw error;
+ } finally { window.clearTimeout(timer); }
+}
+
+function fabricsOf(payload) {
+ if (Array.isArray(payload)) return payload;
+ if (Array.isArray(payload && payload.fabrics)) return payload.fabrics;
+ if (payload && payload.fabric && typeof payload.fabric === 'object') return [payload.fabric];
+ return [];
+}
+function mappingsOf(payload) {
+ return payload && Array.isArray(payload.mappings) ? payload.mappings : [];
+}
+function idOf(item) { return text(item && item.fabric_id, ''); }
+function nodeCount(item) { return Array.isArray(item && item.nodes) ? item.nodes.length : 0; }
+function badge(value, tone) {
+ return el('span', 'badge ' + (tone || 'text-bg-light'), value);
+}
+function stateBadge(value) {
+ const tone = value === 'active' ? 'bg-success-subtle text-success-emphasis'
+ : ['uncertain', 'degraded', 'applying'].includes(value)
+ ? 'bg-warning-subtle text-warning-emphasis' : 'bg-light text-dark';
+ return badge(stateLabel(value), tone);
+}
+function stack(primary, secondary) {
+ const node = el('span', 'admin-checkout-user');
+ node.append(el('strong', '', primary));
+ if (secondary) node.append(el('span', '', secondary));
+ return node;
+}
+function observed(node) {
+ return node && node.observed && typeof node.observed === 'object' ? node.observed : {};
+}
+
+function renderSummary(fabrics, mappings) {
+ const activeReady = fabrics.filter(item => item && item.state === 'active' && item.next_stage_allowed === true).length;
+ const attention = fabrics.filter(item => item && ['uncertain', 'degraded', 'applying'].includes(item.state)).length;
+ byId('fabric-summary-total').textContent = String(fabrics.length);
+ byId('fabric-summary-active').textContent = fabrics.filter(item => item && item.state === 'active').length + ' / ' + activeReady;
+ byId('fabric-summary-attention').textContent = String(attention);
+ byId('fabric-summary-mappings').textContent = String(mappings.filter(item => item && item.state === 'active').length);
+ byId('fabric-list-count').textContent = String(fabrics.length) + ' 个 Fabric';
+}
+
+function renderFabricList(fabrics) {
+ const body = byId('fabric-list-body');
+ body.replaceChildren();
+ if (!fabrics.length) {
+ body.append(el('tr', '', el('td', 'text-center text-muted py-4', '引擎没有 Fabric desired 记录。')));
+ return;
+ }
+ fabrics.forEach(item => {
+ const id = idOf(item);
+ const row = el('tr');
+ row.append(
+ el('td', '', stack(id, text(item.region))),
+ el('td', 'admin-mono', text(item.overlay_cidr) + ' · ' + text(item.interface)),
+ el('td', '', text(item.revision)),
+ el('td', '', stateBadge(item.state)),
+ el('td', '', item.next_stage_allowed === true ? badge('允许', 'bg-success-subtle text-success-emphasis') : badge('未通过', 'bg-warning-subtle text-warning-emphasis')),
+ el('td', '', String(nodeCount(item))),
+ el('td', '', date(item.updated_at)),
+ );
+ const action = el('td');
+ const button = el('button', 'btn btn-light btn-sm', '查看');
+ button.type = 'button'; button.dataset.fabricId = id; button.dataset.fabricSelect = '1';
+ action.append(button); row.append(action); body.append(row);
+ });
+}
+
+function renderMappings(mappings, fabrics) {
+ const body = byId('fabric-mappings-body');
+ body.replaceChildren();
+ if (!mappings.length) {
+ body.append(el('tr', '', el('td', 'text-center text-muted py-4', '尚未建立地区到 Fabric 映射。')));
+ return;
+ }
+ mappings.forEach(mapping => {
+ const fabric = fabrics.find(item => idOf(item) === String(mapping.fabric_id || ''));
+ const row = el('tr');
+ row.append(
+ el('td', '', stack(text(mapping.region_name || mapping.region_code || mapping.region_id), text(mapping.region_code))),
+ el('td', 'admin-mono', text(mapping.fabric_id)),
+ el('td', '', text(mapping.fabric_region)),
+ el('td', '', text(mapping.fabric_revision)),
+ el('td', '', badge(text(mapping.state), mapping.state === 'active' ? 'bg-success-subtle text-success-emphasis' : 'bg-light text-dark')),
+ el('td', '', fabric ? stateBadge(fabric.state) : badge('未读取', 'bg-warning-subtle text-warning-emphasis')),
+ el('td', '', fabric && fabric.next_stage_allowed === true ? badge('允许', 'bg-success-subtle text-success-emphasis') : badge('未通过', 'bg-warning-subtle text-warning-emphasis')),
+ );
+ const action = el('td');
+ if (fabric) {
+ const view = el('button', 'btn btn-light btn-sm me-1', '查看');
+ view.type = 'button'; view.dataset.fabricId = idOf(fabric); view.dataset.fabricSelect = '1'; action.append(view);
+ }
+ if (canManage && mapping.region_id) {
+ const edit = el('button', 'btn btn-light btn-sm', '编辑');
+ edit.type = 'button'; edit.dataset.mappingEdit = String(mapping.region_id); action.append(edit);
+ }
+ row.append(action); body.append(row);
+ });
+}
+
+function capabilitySummary(node) {
+ const value = observed(node);
+ const fields = [
+ ['manager', text(value.manager_mode) + ' / ' + bool(value.manager_active)],
+ ['service', bool(value.service_active)],
+ ['timer', bool(value.timer_enabled) + ' / ' + bool(value.timer_active)],
+ ['nft', bool(value.nft_guard) + ' / ' + bool(value.nft_persistence)],
+ ['config', bool(value.config_secure) + ' / ' + bool(value.key_secure)],
+ ];
+ const list = el('span', 'fabric-capability-list');
+ fields.forEach(pair => list.append(el('span', '', pair[0] + ': ' + pair[1])));
+ return list;
+}
+function renderNodes(fabric) {
+ const body = byId('fabric-nodes-body');
+ body.replaceChildren();
+ const nodes = Array.isArray(fabric && fabric.nodes) ? fabric.nodes : [];
+ if (!nodes.length) {
+ body.append(el('tr', '', el('td', 'text-center text-muted py-4', '没有参与宿主机回读。')));
+ return;
+ }
+ nodes.forEach(node => {
+ const observedRevision = node.observed_revision === undefined ? '—' : node.observed_revision;
+ const row = el('tr');
+ row.append(
+ el('td', '', stack(text(node.host_name || '宿主机 #' + node.host_id), text(node.host_region || node.host_id))),
+ el('td', '', stack(text(node.overlay_ip), text(node.endpoint))),
+ el('td', '', stateBadge(node.state)),
+ el('td', '', node.transport_verified === true ? badge('已验证', 'bg-success-subtle text-success-emphasis') : badge('未验证', 'bg-warning-subtle text-warning-emphasis')),
+ el('td', 'admin-mono', text(node.revision || fabric.revision) + ' / ' + text(observedRevision)),
+ el('td', '', capabilitySummary(node)),
+ el('td', '', node.last_error_code ? badge(errorLabel(node.last_error_code), 'bg-danger-subtle text-danger-emphasis') : el('span', 'text-muted', '无')),
+ );
+ body.append(row);
+ });
+}
+function tupleText(item) {
+ if (Array.isArray(item)) return item.map(value => text(value)).join(' · ');
+ if (item && typeof item === 'object') return Object.entries(item).map(pair => pair[0] + '=' + text(pair[1])).join(' · ');
+ return text(item);
+}
+function renderList(containerId, values, empty) {
+ const container = byId(containerId); container.replaceChildren();
+ if (!Array.isArray(values) || !values.length) {
+ container.append(el('p', 'text-muted mb-0', empty)); return;
+ }
+ const list = el('ul', 'list-unstyled mb-0 fabric-detail-list-items');
+ values.slice(0, 100).forEach(value => list.append(el('li', 'admin-mono', tupleText(value))));
+ container.append(list);
+}
+function renderEvidence(fabric) {
+ const nodes = Array.isArray(fabric && fabric.nodes) ? fabric.nodes : [];
+ const peers = []; const routes = []; const handshakes = [];
+ nodes.forEach(node => {
+ const host = text(node.host_name || '宿主机 #' + node.host_id);
+ const value = observed(node);
+ (value.peers || value.overlay_peers || value.config_peers || []).forEach(item => peers.push(host + ': ' + tupleText(item)));
+ (value.routes || value.config_routes || []).forEach(item => routes.push(host + ': ' + tupleText(item)));
+ if (value.handshakes && typeof value.handshakes === 'object') {
+ Object.entries(value.handshakes).forEach(pair => handshakes.push({ host, peer: pair[0], stamp: pair[1] }));
+ }
+ });
+ renderList('fabric-peers', peers, '没有可展示的 peer 回读。');
+ renderList('fabric-routes', routes, '没有可展示的 route 回读。');
+ const target = byId('fabric-handshakes'); target.replaceChildren();
+ if (!handshakes.length) {
+ target.append(el('p', 'text-muted mb-0', '没有握手时间戳回读。')); return;
+ }
+ const list = el('ul', 'list-unstyled mb-0 fabric-detail-list-items');
+ const now = Math.floor(Date.now() / 1000);
+ handshakes.slice(0, 100).forEach(item => {
+ const stamp = Number(item.stamp);
+ const stale = !Number.isFinite(stamp) || stamp <= 0 || now - stamp > 600;
+ list.append(el('li', stale ? 'admin-mono text-warning-emphasis' : 'admin-mono', item.host + ' · ' + item.peer + ' · ' + date(stamp) + ' · ' + (stale ? 'stale' : 'fresh')));
+ });
+ target.append(list);
+}
+
+function renderDetail(fabric) {
+ state.selected = fabric;
+ byId('fabric-detail').hidden = false;
+ byId('fabric-detail-title').textContent = 'Fabric ' + idOf(fabric);
+ byId('fabric-detail-subtitle').textContent = text(fabric.region) + ' · 引擎更新时间 ' + date(fabric.updated_at);
+ const summary = byId('fabric-detail-summary'); summary.replaceChildren();
+ [['Overlay', text(fabric.overlay_cidr) + ' · ' + text(fabric.interface)],
+ ['Revision / Digest', text(fabric.revision) + ' · ' + text(fabric.plan_digest).slice(0, 16)],
+ ['状态', stateLabel(fabric.state)],
+ ['下一阶段门禁', fabric.next_stage_allowed === true ? '允许' : '未允许']].forEach(pair => {
+ const col = el('div', 'col-sm-6 col-xl-3');
+ const card = el('div', 'border rounded p-3 h-100');
+ card.append(el('div', 'text-muted fs-13', pair[0]), el('strong', 'd-block mt-1 admin-mono', pair[1]));
+ col.append(card); summary.append(col);
+ });
+ const errors = (fabric.nodes || []).map(node => node.last_error_code).filter(Boolean);
+ const errorBox = byId('fabric-detail-error');
+ if (errors.length || ['uncertain', 'degraded', 'failed'].includes(fabric.state)) {
+ errorBox.hidden = false;
+ errorBox.textContent = errors.length ? '失败原因:' + [...new Set(errors)].map(errorLabel).join('、') : 'Fabric 当前状态:' + stateLabel(fabric.state);
+ } else { errorBox.hidden = true; errorBox.textContent = ''; }
+ renderNodes(fabric); renderEvidence(fabric);
+ const form = byId('fabric-apply-form');
+ if (form && fabric.nodes && fabric.nodes.length) {
+ form.elements.namedItem('fabric_id').value = fabric.fabric_id || '';
+ form.elements.namedItem('region').value = fabric.region || '';
+ form.elements.namedItem('overlay_cidr').value = fabric.overlay_cidr || '';
+ form.elements.namedItem('revision').value = fabric.revision || '';
+ form.elements.namedItem('listen_port').value = fabric.listen_port || fabric.nodes[0].listen_port || '';
+ form.elements.namedItem('nodes').value = JSON.stringify(fabric.nodes.map(node => ({
+ host_id: node.host_id, overlay_ip: node.overlay_ip, endpoint: node.endpoint,
+ ...(node.listen_port ? { listen_port: node.listen_port } : {}),
+ })), null, 2);
+ }
+}
+
+async function selectFabric(id) {
+ if (!id) return;
+ notice('正在读取 ' + id + '…');
+ try {
+ const payload = await api('/api/v1/admin/fabric/' + encodeURIComponent(id));
+ const fabric = payload && payload.fabric ? payload.fabric : payload;
+ if (!fabric || typeof fabric !== 'object') throw new Error('引擎返回的 Fabric 状态无效。');
+ renderDetail(fabric); notice('已读取 ' + id + ' 的引擎回读');
+ } catch (error) { notice(error.message || 'Fabric 详情读取失败。', true); }
+}
+async function load() {
+ notice('正在读取 Fabric 状态…');
+ try {
+ const payload = await api('/api/v1/admin/fabric');
+ state.payload = payload;
+ const fabrics = fabricsOf(payload); const mappings = mappingsOf(payload);
+ renderSummary(fabrics, mappings); renderFabricList(fabrics); renderMappings(mappings, fabrics);
+ if (state.selected && fabrics.some(item => idOf(item) === idOf(state.selected))) await selectFabric(idOf(state.selected));
+ else if (fabrics[0]) await selectFabric(idOf(fabrics[0]));
+ else if (payload && payload.engine_available === false) notice(payload.engine_error || 'Fabric 引擎状态不可用。', true);
+ else notice('没有 Fabric desired 记录');
+ } catch (error) {
+ renderSummary([], []); renderFabricList([]); renderMappings([], []);
+ notice(error.message || 'Fabric 状态读取失败。', true);
+ }
+}
+function openDialog(dialog) {
+ if (!dialog) return;
+ if (window.VenixDrawerMotion && window.VenixDrawerMotion.openDrawerWithMotion) window.VenixDrawerMotion.openDrawerWithMotion(dialog);
+ else dialog.showModal();
+}
+function closeDialog(dialog) {
+ if (!dialog || !dialog.open) return;
+ if (window.VenixDrawerMotion && window.VenixDrawerMotion.closeDrawerWithMotion) window.VenixDrawerMotion.closeDrawerWithMotion(dialog);
+ else dialog.close();
+}
+function editMapping(regionId) {
+ const mapping = mappingsOf(state.payload).find(item => String(item.region_id) === String(regionId));
+ const dialog = byId('fabric-mapping-editor'); const form = byId('fabric-mapping-form');
+ if (!mapping || !dialog || !form) return notice('找不到地区映射,请刷新后重试。', true);
+ form.elements.namedItem('region_id').value = mapping.region_id;
+ form.elements.namedItem('fabric_id').value = mapping.fabric_id || '';
+ form.elements.namedItem('fabric_region').value = mapping.fabric_region || '';
+ form.elements.namedItem('fabric_revision').value = mapping.fabric_revision || '';
+ form.elements.namedItem('state').value = mapping.state === 'active' ? 'active' : 'disabled';
+ form.dataset.existing = mapping.fabric_id ? '1' : '0';
+ operationNotice('fabric-mapping-notice', '等待提交'); openDialog(dialog);
+}
+
+root && root.addEventListener('click', event => {
+ const select = event.target.closest('[data-fabric-select]');
+ if (select) selectFabric(select.dataset.fabricId);
+ const edit = event.target.closest('[data-mapping-edit]');
+ if (edit) editMapping(edit.dataset.mappingEdit);
+});
+byId('fabric-refresh')?.addEventListener('click', load);
+byId('fabric-reconcile')?.addEventListener('click', async () => {
+ const id = idOf(state.selected);
+ if (!id || !canManage) return;
+ const button = byId('fabric-reconcile'); button.disabled = true;
+ notice('reconcile 已提交,正在等待引擎回读…');
+ try {
+ await api('/api/v1/admin/fabric/' + encodeURIComponent(id) + '/reconcile', { method: 'POST', body: '{}' });
+ await load(); notice('reconcile 已返回;请以当前 state 和 next_stage_allowed 判断结果。');
+ } catch (error) { notice(error.message || 'reconcile 未完成,请刷新核对。', true); }
+ finally { button.disabled = false; }
+});
+byId('fabric-apply-form')?.addEventListener('submit', async event => {
+ event.preventDefault();
+ const form = event.currentTarget;
+ if (!form.reportValidity()) return;
+ let nodes;
+ try { nodes = JSON.parse(form.elements.namedItem('nodes').value); }
+ catch (error) { return operationNotice('fabric-apply-notice', '参与宿主机必须是有效 JSON 数组。', true); }
+ if (!Array.isArray(nodes)) return operationNotice('fabric-apply-notice', '参与宿主机必须是数组。', true);
+ nodes = nodes.map(node => {
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return node;
+ return Object.assign({}, node, { host_id: node.host_id === undefined ? node.host_id : String(node.host_id) });
+ });
+ const body = { schema_version: 1, fabric_id: form.elements.namedItem('fabric_id').value.trim(),
+ region: form.elements.namedItem('region').value.trim(), overlay_cidr: form.elements.namedItem('overlay_cidr').value.trim(),
+ revision: Number(form.elements.namedItem('revision').value), listen_port: Number(form.elements.namedItem('listen_port').value), nodes };
+ const submit = byId('fabric-apply-submit'); submit.disabled = true;
+ operationNotice('fabric-apply-notice', '正在提交;引擎完成所有宿主机回读前不会显示为成功。');
+ try { await api('/api/v1/admin/fabric/apply', { method: 'POST', body: JSON.stringify(body) });
+ operationNotice('fabric-apply-notice', '引擎已返回,正在重新读取状态。'); await load();
+ } catch (error) { operationNotice('fabric-apply-notice', error.message || 'apply 未完成,请刷新核对。', true); }
+ finally { submit.disabled = false; }
+});
+byId('fabric-apply-clear')?.addEventListener('click', () => { byId('fabric-apply-form')?.reset(); operationNotice('fabric-apply-notice', '等待提交'); });
+byId('fabric-mapping-close')?.addEventListener('click', () => closeDialog(byId('fabric-mapping-editor')));
+byId('fabric-mapping-editor')?.addEventListener('cancel', event => { event.preventDefault(); closeDialog(event.currentTarget); });
+byId('fabric-mapping-form')?.addEventListener('submit', async event => {
+ event.preventDefault();
+ const form = event.currentTarget;
+ if (!form.reportValidity()) return;
+ const regionId = form.elements.namedItem('region_id').value;
+ const body = { fabric_id: form.elements.namedItem('fabric_id').value.trim(),
+ fabric_region: form.elements.namedItem('fabric_region').value.trim(),
+ fabric_revision: Number(form.elements.namedItem('fabric_revision').value), state: form.elements.namedItem('state').value };
+ const submit = byId('fabric-mapping-submit'); submit.disabled = true;
+ operationNotice('fabric-mapping-notice', '正在保存并核对引擎门禁。');
+ try {
+ await api('/api/v1/admin/regions/' + encodeURIComponent(regionId) + '/fabric',
+ { method: form.dataset.existing === '1' ? 'PATCH' : 'PUT', body: JSON.stringify(body) });
+ closeDialog(byId('fabric-mapping-editor')); await load();
+ } catch (error) { operationNotice('fabric-mapping-notice', error.message || '地区映射保存失败。', true); }
+ finally { submit.disabled = false; }
+});
+load();
diff --git a/web/public/cloud/admin.css b/web/public/cloud/admin.css
index f7060fae..d710131d 100644
--- a/web/public/cloud/admin.css
+++ b/web/public/cloud/admin.css
@@ -4,6 +4,48 @@
color: #1d2939;
}
+[data-admin-fabric] {
+ padding-bottom: 24px;
+}
+
+[data-admin-fabric] .fabric-detail-list {
+ min-height: 84px;
+ overflow-wrap: anywhere;
+}
+
+[data-admin-fabric] .fabric-detail-list-items {
+ max-height: 280px;
+ overflow: auto;
+}
+
+[data-admin-fabric] .fabric-detail-list-items li {
+ padding: 7px 0;
+ border-bottom: 1px solid #eef2f6;
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+[data-admin-fabric] .fabric-detail-list-items li:last-child {
+ border-bottom: 0;
+}
+
+[data-admin-fabric] .fabric-capability-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 8px;
+ min-width: 190px;
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+[data-admin-fabric] .fabric-capability-list span {
+ white-space: nowrap;
+}
+
+[data-admin-fabric] .table-responsive {
+ min-height: 0;
+}
+
.cloud-admin *,
.cloud-admin *::before,
.cloud-admin *::after {
diff --git a/web/resources/views/venix/admin/cloud/fabric.tpl b/web/resources/views/venix/admin/cloud/fabric.tpl
new file mode 100644
index 00000000..af053e3a
--- /dev/null
+++ b/web/resources/views/venix/admin/cloud/fabric.tpl
@@ -0,0 +1,104 @@
+{assign var=admin_title value='WireGuard Fabric'}
+{assign var=admin_active value='fabric'}
+{include file='admin/static_header.tpl'}
+
+
+ Private Network Fabric 查看跨宿主机 L3 Fabric 的拓扑、能力探测、peer、路由、握手和 desired / observed 回读。这里的状态来自引擎安全投影,不包含私钥、SSH 命令或原始主机输出。 引擎 desired 记录 必须通过所有宿主机回读 不会作为私网成功门禁 平台拥有的销售地区绑定 先选择一个 Fabric 查看参与宿主机和数据面回读。更新时间是引擎记录时间,不代表公网 UDP 已被防火墙放行。 选择 Fabric 后显示安全回读。 节点状态、manager、WireGuard、nftables 和路由回读均来自引擎白名单字段。 允许地址和 endpoint 由引擎回读。 包含配置路由、实际路由和冲突标记。 超过 10 分钟的握手显示为 stale。 仅提交结构化计划;引擎会重新探测能力、校验成员和路由,并在所有宿主机完成回读后才允许进入下一阶段。不要填写公钥、私钥、命令或 nftables 规则。 启用映射时 PHP 会再次核对引擎的 fabric_id、地区、revision、active 和 next_stage_allowed;有存量 VPC 时不能直接更换绑定。WireGuard Fabric 管理
+ Fabric 数量
—活动 / 可进入下一阶段
—待核对或降级
—地区映射
—Fabric 拓扑
+
+ Fabric / 地区 Overlay Revision 状态 下一阶段 参与宿主机 更新时间 操作
+ 正在读取引擎状态… Fabric 详情
参与宿主机与能力探测
宿主机 Overlay / Endpoint 状态 Transport Desired / Observed 能力摘要 失败原因 尚未选择 Fabric。 Peer
Route
Handshake
Apply Fabric 计划
地区到 Fabric 映射
地区 Fabric Fabric 地区 映射 Revision 映射状态 引擎状态 下一阶段 操作 正在读取映射…