You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-fabric.js

1249 lines
59 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const root = document.querySelector('[data-admin-fabric]');
const canManage = root && root.dataset.canManage === '1';
const byId = id => document.getElementById(id);
const actionButtons = Array.from(document.querySelectorAll('[data-fabric-primary-action]'));
const state = {
regions: [],
selectedRegionId: '',
selectionVersion: 0,
loadVersion: 0,
loading: false,
pendingAction: '',
outcomeUnknownRegionIds: new Set(),
operationsByRegion: new Map(),
receiptRecoveriesByRegion: new Map(),
operationPollTimer: 0,
operationPollFailures: 0,
};
const receiptRecoveryInterval = 5000;
const receiptRecoveryMaxReads = 36;
const receiptRecoveryMaxDuration = 180000;
const workflowStages = new Set([
'engine_unavailable', 'no_hosts', 'needs_probe', 'blocked',
'ready_to_apply', 'needs_reconcile', 'active',
'migration_required', 'recovery_required', 'operation_running',
]);
const workflowStageCopy = {
engine_unavailable: {
title: '引擎状态不可用', help: '当前无法读取权威状态,所有写操作保持关闭。', step: 'probe',
},
no_hosts: {
title: '地区没有可配置宿主机', help: '请先在资源调度中为该地区配置宿主机。', step: 'probe',
},
needs_probe: {
title: '等待检测宿主机', help: '运行 fresh 检测后,服务端才会生成可执行的只读方案。', step: 'probe',
},
blocked: {
title: '检测存在阻断项', help: '请按阻断原因修复宿主机或平台配置,然后重新检测。', step: 'probe',
},
ready_to_apply: {
title: '检测通过,可以自动配置', help: '请核对服务端只读方案,然后执行自动配置。', step: 'apply',
},
needs_reconcile: {
title: '配置需要重新核对', help: '固定 desired state 已存在;请重新核对,不要重复创建计划。', step: 'reconcile',
},
active: {
title: '地区私网已就绪', help: '服务端映射、Fabric 和宿主机回读已通过全部门禁。', step: 'reconcile',
},
migration_required: {
title: '需要显式迁移', help: '现有成员或 Fabric 归属不能由自动向导直接改写。', step: 'apply',
},
recovery_required: {
title: '需要恢复固定方案', help: '请按服务端恢复指引处理,向导不会重新生成 desired state。', step: 'reconcile',
},
operation_running: {
title: '宿主机任务执行中', help: '页面正在只读轮询 operation 状态;请勿重复提交。', step: 'apply',
},
};
const stateLabels = {
active: 'active(活动)',
disabled: 'disabled(停用)',
ready: 'ready(就绪)',
blocked: 'blocked(阻断)',
unchecked: 'unchecked(未检测)',
not_checked: 'not_checked(未检测)',
unknown: 'unknown(未知)',
probing: 'probing(检测中)',
applying: 'applying(应用中)',
uncertain: 'uncertain(待核对)',
degraded: 'degraded(降级)',
failed: 'failed(失败)',
};
const errorLabels = {
fabric_apply_unconfirmed: '应用结果未确认',
fabric_host_capability_missing: '宿主机能力未通过核验',
fabric_host_capability_probe_failed: '宿主机能力探测失败',
fabric_host_capability_probe_invalid: '宿主机能力回读无效',
fabric_host_capability_probe_unsupported: '宿主机能力不支持',
fabric_probe_busy: '已有地区宿主机检测正在运行',
fabric_host_capability_unsupported: '宿主机能力不支持',
fabric_host_capability_invalid: '宿主机能力回读无效',
fabric_host_connection_failed: '宿主机连接失败',
fabric_host_probe_failed: '宿主机检测失败',
fabric_host_identity_mismatch: '宿主机身份回读不一致',
fabric_host_interface_conflict: '宿主机 WireGuard 接口冲突',
fabric_host_firewall_mode_conflict: '宿主机防火墙与 Fabric 部署模式冲突',
fabric_host_key_locked: '宿主机密钥仍锁定',
fabric_host_network_manager_conflict: '宿主机网络管理器冲突',
fabric_host_not_configured: '宿主机未配置',
fabric_host_unavailable: '宿主机不可用',
fabric_endpoint_vpc_conflict: 'Fabric 传输地址与现有 VPC CIDR 冲突',
fabric_vpc_record_corrupt: 'VPC 资源目录损坏,无法核验 Fabric 地址',
fabric_region_conflict: 'Fabric 地区不能直接变更,请走迁移流程',
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 = {
identity: 'identity(身份)',
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: '事务恢复', journal_dispatch: '调度事务恢复',
journal_artifact_restore: '恢复事务文件',
journal_nft_restore: '恢复 nft 规则', journal_runtime_restore: '恢复宿主机运行态',
journal_finalize: '收尾事务恢复', preflight: '执行前检查',
preflight_sysctl: '检查内核网络参数', preflight_tools: '检查必要工具',
preflight_artifacts: '检查配置文件归属', preflight_firewall: '检查防火墙归属',
preflight_vpc: '检查 VPC 状态', preflight_underlay: '检查传输网络',
preflight_routes: '检查路由', preflight_persistence: '检查持久化配置',
transaction: '事务准备',
nft_install: '安装 nft 规则', network_activate: '激活网络',
persistence: '安装持久化恢复', final_readback: '最终回读', complete: '完成',
unknown: '未知检查点',
};
const operationReasonLabels = {
none: '无', tool_missing: '缺少必要工具', ownership_conflict: '资源归属冲突',
journal_conflict: '事务记录冲突', sysctl_conflict: '内核网络参数不符合要求',
persistence_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: '面板宿主机记录缺失',
membership_conflict: '宿主机存在多个活动资源池成员关系',
scheduler_disabled: '宿主机调度成员未启用',
resource_pool_disabled: '资源池未启用',
network_line_disabled: '网络线路未启用',
region_disabled: '地区未启用',
workload_membership_mismatch: '现有工作负载与资源池成员关系不一致',
fabric_membership_drift: 'Fabric 成员与地区所需宿主机不一致',
fabric_identity_conflict: '地区存在未映射的 Fabric 身份',
fabric_endpoint_unavailable: '宿主机缺少可用的 IPv4 endpoint',
fabric_endpoint_invalid: '宿主机 Fabric 传输 IPv4 配置无效',
fabric_endpoint_missing: '宿主机缺少可用的 Fabric 传输 IPv4',
fabric_endpoint_mismatch: '当前地址与已固定 Fabric 计划不一致,需要版本化迁移',
fabric_endpoint_not_local: '配置的 Fabric 传输 IPv4 不属于该宿主机',
fabric_endpoint_interface_unverified: '无法唯一确认 Fabric endpoint 对应的宿主机接口',
fabric_endpoint_interface_unsafe_or_drifted: 'Fabric endpoint 接口不安全,或与固定配置发生漂移',
fabric_endpoint_rp_filter_unverified: '无法确认 Fabric endpoint 接口的 rp_filter 有效值',
fabric_endpoint_source_invalid: '宿主机 Fabric endpoint 来源缺失或不受信任',
fabric_endpoint_vpc_pool_conflict: 'Fabric endpoint 落入租户 VPC 地址池,请改用独立网段',
fabric_endpoint_duplicate: '多台宿主机使用了相同的 WireGuard endpoint',
host_capability_probe_missing: '引擎未返回该宿主机的检测结果',
scheduler_unavailable: '调度状态不可用',
pool_disabled: '资源池未启用',
line_disabled: '线路未启用',
host_not_configured: '宿主机未配置',
probe_required: '尚未完成检测',
host_unreachable: '宿主机不可达',
network_manager_unsupported: '网络管理器不受支持',
network_manager_mismatch: '网络管理器与预期不一致',
wireguard_unavailable: 'WireGuard 未就绪',
nftables_unavailable: 'nftables 未就绪',
ip_forward_disabled: 'IP forwarding 未启用',
rp_filter_invalid: 'rp_filter 不满足要求',
public_selector_missing: '缺少公网出口选择器',
public_not_verified: '公网出口尚未核验',
fabric_not_member: '尚未加入 Fabric',
fabric_not_active: 'Fabric 尚未 active',
transport_unverified: '跨宿主机传输尚未验证',
revision_mismatch: 'Fabric revision 回读不一致',
capability_probe_invalid: '能力探测协议回读无效',
unsupported_host_os: '宿主机操作系统不受支持',
wireguard_tool_missing: '缺少 WireGuard 工具',
wireguard_kernel_unavailable: '内核 WireGuard 不可用',
wireguard_fabric_interface_conflict: 'WireGuard 接口存在所有权冲突',
iproute2_missing: '缺少 ip 命令(Debian 包 iproute2 / AlmaLinux 包 iproute)',
iproute2_probe_failed: 'ip 命令 JSON 能力回读无效',
flock_missing: '缺少 flock',
nftables_tool_missing: '缺少 nftables 工具',
nftables_probe_failed: 'nftables 回读失败',
nftables_persistence_not_ready: 'nftables 持久化主配置缺失、不安全或存在冲突',
nftables_persistence_evidence_invalid: '无法安全核验 nftables 持久化主配置',
firewall_owner_not_nftables: '活动防火墙管理器不是 nftables',
firewall_owner_unsupported: '无法确定受支持的防火墙所有者',
firewall_mode_unsupported: '防火墙运行模式不受支持',
firewall_manager_conflict: 'firewalld 与 nftables 服务存在所有权冲突',
firewall_competing_service_unknown: '无法排除另一防火墙服务在重启后接管',
firewalld_unsupported_requires_maintenance: 'firewalld 已不受支持;请在维护窗口清理旧所有权状态并启用原生 nftables',
legacy_firewalld_state_requires_cleanup: '检测到旧 firewalld 规则或事务状态;请在维护窗口备份并清理后重建',
firewall_transaction_requires_recovery_or_cleanup: '检测到未收敛的防火墙事务;请先完成恢复或在维护窗口清理',
legacy_firewall_evidence_invalid: '无法安全核验宿主的旧防火墙状态;已禁止 VPC 变更',
nftables_service_not_active: 'nftables 服务未运行',
nftables_service_not_enabled: 'nftables 服务未启用',
ipv4_forwarding_disabled_or_unknown: 'IPv4 forwarding 未启用或无法核验',
rp_filter_not_compatible: 'rp_filter 必要回读缺失或无效,无法安全自动配置',
network_manager_conflict: '检测到多个网络管理器冲突',
network_manager_unknown: '无法确定网络管理器',
network_manager_policy_mismatch: '网络管理器与系统策略不匹配',
systemd_networkd_not_supported: '当前不支持 systemd-networkd',
networkmanager_nmcli_missing: 'NetworkManager 缺少 nmcli',
networkmanager_service_not_active: 'NetworkManager 服务未运行',
networkmanager_service_not_enabled: 'NetworkManager 服务未启用',
ifupdown_tools_missing: 'ifupdown 工具不完整',
ifupdown_configuration_missing: 'ifupdown 配置缺失',
ifupdown_interfaces_d_not_included: 'interfaces.d 未被主配置加载',
ifupdown_service_not_active_or_enabled: 'ifupdown networking 服务未就绪',
public_bridge_missing: '公网 bridge 不存在或未启用',
public_network_selector_invalid: '公网出口选择器无效',
engine_unavailable: 'Fabric 引擎状态不可用',
no_required_hosts: '地区没有必须参与私网的宿主机',
readiness_host_limit_exceeded: 'readiness 清单超过 128 台',
fabric_node_limit_exceeded: '自动配置只支持 2 至 64 台规范宿主机',
fabric_desired_missing: '已固定的 Fabric desired state 缺失',
fabric_plan_mismatch: '现有 Fabric 与服务端自动方案不一致',
vpc_fabric_pin_mismatch: '现有 VPC 固定的 Fabric 与地区映射不一致',
vpc_fabric_mapping_missing: '现有 VPC 缺少地区 Fabric 映射',
platform_gate_failed: '地区或宿主机平台门禁未通过',
fresh_probe_failed: 'fresh 宿主机检测未通过',
fabric_reconcile_required: '固定 desired state 需要重新核对',
fabric_operation_running: 'Fabric 宿主机任务正在执行',
};
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 integer(value, fallback = 0) {
const number = Number(value);
return Number.isInteger(number) && number >= 0 ? number : fallback;
}
function flag(value, yes = '是', no = '否', unknown = '未检测') {
return value === true ? yes : value === false ? no : unknown;
}
function endpointSource(value) {
return value === 'configured' ? '宿主机专用配置'
: value === 'ssh_host_ipv4' ? 'SSH IPv4 自动回退' : '未记录';
}
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 '未检测';
}
const number = Number(value);
if (!Number.isInteger(number) || ![0, 1, 2].includes(number)) return '未检测';
if (enabledValue === undefined) return String(number);
return number === enabledValue ? number + '(符合)' : number + '(不符合)';
}
function hasOwn(value, key) {
return value && typeof value === 'object'
&& Object.prototype.hasOwnProperty.call(value, key);
}
function rpFilterNumber(value) {
if (value === null || value === undefined || value === '' || typeof value === 'boolean') {
return null;
}
const number = Number(value);
return Number.isInteger(number) && [0, 1, 2].includes(number) ? number : null;
}
function rpFilterPair(raw, effective, strictMeaning) {
const rawValue = rpFilterNumber(raw);
const effectiveValue = rpFilterNumber(effective);
if (rawValue === null && effectiveValue === null) return '未检测';
const parts = [
'raw ' + (rawValue === null ? '未检测' : rawValue),
'effective ' + (effectiveValue === null ? '未检测' : effectiveValue),
];
if (effectiveValue === 0) parts[1] += '(关闭,兼容)';
if (effectiveValue === 2) parts[1] += '(loose,兼容)';
if (effectiveValue === 1) parts[1] += strictMeaning;
return parts.join(' · ');
}
function rpFilterLines(capabilities) {
const all = hasOwn(capabilities, 'rp_filter_all')
? capabilities.rp_filter_all : capabilities.rp_filter;
const underlay = text(capabilities.underlay_interface, '接口未记录');
const fabricReported = hasOwn(capabilities, 'rp_filter_fabric_raw')
|| hasOwn(capabilities, 'rp_filter_fabric_effective');
let fabric = '未检测';
if (fabricReported && capabilities.rp_filter_fabric_raw === null
&& capabilities.rp_filter_fabric_effective === null) {
fabric = '未创建(自动配置时由平台设为 2)';
} else if (fabricReported) {
fabric = rpFilterPair(capabilities.rp_filter_fabric_raw,
capabilities.rp_filter_fabric_effective,
'(strict,自动配置将收敛为 2)');
}
return [
'rp_filter all:' + rpFilterPair(all, all, '(strict,全局值只读)'),
'rp_filter default:' + rpFilterPair(capabilities.rp_filter_default,
capabilities.rp_filter_default_effective,
'(strict,发行版默认保留)'),
'Endpoint ' + underlay + ':' + rpFilterPair(capabilities.rp_filter_underlay_raw,
capabilities.rp_filter_underlay_effective,
'(strict,公网接口保留)'),
'wg-fabric0:' + fabric,
'策略:all/default/公网接口只读;仅平台自有 wg-fabric0 与 VPC bridge 设为 2',
];
}
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 stateLabel(value) { return stateLabels[value] || text(value); }
function errorLabel(value) { return errorLabels[value] || (value ? '错误码 ' + value : '无'); }
function reasonLabel(value) { return reasonLabels[value] || (value ? '原因代码 ' + value : '未说明'); }
function badge(value, tone = 'text-bg-light') { return el('span', 'badge ' + tone, value); }
function booleanBadge(value, yes = '已通过', no = '未通过') {
if (value === true) return badge(yes, 'bg-success-subtle text-success-emphasis');
if (value === false) return badge(no, 'bg-warning-subtle text-warning-emphasis');
return badge('未检测', 'bg-light text-dark');
}
function stateBadge(value) {
const tone = ['active', 'ready'].includes(value)
? 'bg-success-subtle text-success-emphasis'
: ['blocked', 'failed', 'degraded'].includes(value)
? 'bg-danger-subtle text-danger-emphasis'
: ['uncertain', 'applying', 'probing', 'unchecked', 'not_checked'].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 compactLines(values) {
const node = el('span', 'fabric-capability-list');
values.filter(value => value).forEach(value => node.append(el('span', '', value)));
return node;
}
function notice(message, kind = '') {
const node = byId('fabric-notice');
if (!node) return;
node.textContent = message;
node.className = 'admin-config-status'
+ (kind === 'error' ? ' is-error' : kind === 'success' ? ' is-success' : '');
node.setAttribute('role', kind === 'error' ? 'alert' : 'status');
}
async function api(path, options = {}) {
const controller = new AbortController();
const method = String(options.method || 'GET').toUpperCase();
let dispatched = false;
// PHP keeps a 180-second engine deadline for bounded multi-host writes.
// Let the server return its definitive/uncertain result before the browser
// times out, while still requiring an explicit readback after a timeout.
const timer = window.setTimeout(() => controller.abort('timeout'), method === 'GET' ? 30000 : 240000);
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;
}
dispatched = true;
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);
const failure = new Error(typeof message === 'string' && message
? message : '请求失败 (' + response.status + ')');
failure.httpStatus = response.status;
throw failure;
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') {
const failure = new Error('请求超时;操作结果尚未确认,请使用“重新核对”读取当前状态。');
failure.outcomeUnknown = true;
throw failure;
}
const httpStatus = Number.isInteger(error && error.httpStatus)
? error.httpStatus : null;
const serverFailure = httpStatus !== null
&& httpStatus >= 500 && httpStatus <= 599;
if (dispatched && method !== 'GET' && method !== 'HEAD'
&& (httpStatus === null || serverFailure)) {
const failure = new Error(httpStatus === null
? '网络连接中断;写操作结果尚未确认,请使用“重新核对”,切勿重复提交。'
: '服务端或网关返回 ' + httpStatus
+ ';写操作结果尚未确认,请使用“重新核对”,切勿重复提交。');
if (httpStatus !== null) failure.httpStatus = httpStatus;
failure.outcomeUnknown = true;
throw failure;
}
throw error;
} finally {
window.clearTimeout(timer);
}
}
function regionsOf(payload) {
return payload && Array.isArray(payload.regions)
? payload.regions.filter(region => region && typeof region === 'object').slice(0, 256)
: [];
}
function regionIdOf(region) {
const value = region && region.region_id;
return value === null || value === undefined ? '' : String(value);
}
function hostsOf(region) {
return region && Array.isArray(region.hosts)
? region.hosts.filter(host => host && typeof host === 'object').slice(0, 256)
: [];
}
function selectedRegion() {
return state.regions.find(region => regionIdOf(region) === state.selectedRegionId) || null;
}
function regionName(region) {
return text(region && (region.region_name || region.region_code || ('地区 #' + regionIdOf(region))));
}
function workflowOf(region) {
const source = region && region.workflow;
if (!source || typeof source !== 'object' || Array.isArray(source)
|| !workflowStages.has(source.stage)) {
return {
stage: 'engine_unavailable', can_probe: false, can_apply: false,
can_reconcile: false, blocking_reasons: ['engine_unavailable'], action_mode: 'none',
};
}
const reasons = Array.isArray(source.blocking_reasons)
? source.blocking_reasons.filter(value => typeof value === 'string' && value).slice(0, 32)
: [];
return {
stage: source.stage,
can_probe: source.can_probe === true,
can_apply: source.can_apply === true,
can_reconcile: source.can_reconcile === true,
blocking_reasons: reasons,
action_mode: ['probe', 'apply', 'reconcile', 'none'].includes(source.action_mode)
? source.action_mode : 'none',
};
}
function planPreviewOf(region) {
const source = region && region.plan_preview;
if (!source || typeof source !== 'object' || Array.isArray(source)
|| !['automatic', 'existing'].includes(source.mode)) return null;
return source;
}
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,
reconcile: workflow.can_reconcile,
};
const outcomeUnknown = hasRegion
&& state.outcomeUnknownRegionIds.has(regionIdOf(region));
const operationIsRunning = operationRunning(currentOperation);
actionButtons.forEach(button => {
const action = String(button.dataset.fabricAction || '');
const allowed = outcomeUnknown ? false : operationIsRunning
? action === 'reconcile' && permissions.reconcile === true
: permissions[action] === true;
button.disabled = !canManage || !hasRegion || !allowed
|| state.loading || state.pendingAction !== '';
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 (outcomeUnknown) {
button.title = '写操作结果未知;只读恢复期间禁止再次提交,请等待或刷新只读状态';
} else if (operationIsRunning && action !== 'reconcile') {
button.title = '宿主机任务正在执行,仅允许使用“重新核对”恢复同一 operation';
} else if (operationIsRunning) {
button.title = '使用同一 operation 标识重新核对宿主机任务';
} else if (!allowed) button.title = '服务端尚未允许执行此步骤';
else button.removeAttribute('title');
if (state.pendingAction === action) button.setAttribute('aria-busy', 'true');
else button.removeAttribute('aria-busy');
});
}
function renderSummary(region) {
const hosts = hostsOf(region);
const total = integer(region && region.host_count, hosts.length);
const ready = integer(region && region.ready_host_count,
hosts.filter(host => host.vpc_ready === true).length);
const blocked = integer(region && region.blocked_host_count, Math.max(0, total - ready));
byId('fabric-summary-region').textContent = region ? stateLabel(region.region_status) : '—';
byId('fabric-summary-ready').textContent = region
? flag(region.ready, '就绪', '未就绪', '未核对') : '—';
byId('fabric-summary-hosts').textContent = region ? ready + ' / ' + total : '—';
byId('fabric-summary-blocked').textContent = region ? String(blocked) : '—';
}
function wizardProgress(stage) {
if (stage === 'ready_to_apply' || stage === 'migration_required') return 2;
if (['needs_reconcile', 'recovery_required', 'active'].includes(stage)) return 3;
return 1;
}
function renderWizardSteps(region) {
const workflow = workflowOf(region);
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
? '上次写操作失去响应;页面只读取状态,不会重复提交。尚未确认本轮 operation 时所有写操作保持关闭;如只读恢复停止,请刷新页面查看权威状态。'
: copy.help;
const order = ['select', 'probe', 'apply', 'reconcile'];
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');
item.removeAttribute('aria-current');
if (index < currentIndex || (stage === 'active' && index <= currentIndex)) {
item.classList.add('is-complete');
}
if ((region ? String(item.dataset.fabricWizardStep) === copy.step : index === 0)) {
item.classList.add('is-current');
item.setAttribute('aria-current', 'step');
if (unknown || ['engine_unavailable', 'no_hosts', 'blocked',
'migration_required', 'recovery_required'].includes(stage)) {
item.classList.add('is-blocked');
}
}
});
byId('fabric-step-select-state').textContent = region
? regionName(region) + ' · ' + text(region.region_code) : '等待选择';
let probeState = '尚未检测';
if (stage === 'blocked') probeState = '检测存在阻断';
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'
? '等待执行' : 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)
? '等待重新核对' : stage === 'operation_running'
&& trackedOperation && trackedOperation.kind === 'reconcile'
? '宿主机任务执行中' : unknown ? '结果未知' : '等待配置';
}
function renderWizardBlockers(region) {
const box = byId('fabric-wizard-blockers');
const list = byId('fabric-wizard-blocker-list');
list.replaceChildren();
const reasons = region ? workflowOf(region).blocking_reasons : [];
if (!reasons.length) {
box.hidden = true;
return;
}
[...new Set(reasons)].forEach(reason => {
list.append(el('li', '', errorLabels[reason]
? errorLabel(reason) : reasonLabel(reason)));
});
box.hidden = false;
}
function renderPlanPreview(region) {
const preview = planPreviewOf(region);
const empty = byId('fabric-plan-preview-empty');
const grid = byId('fabric-plan-preview-grid');
const mode = byId('fabric-plan-preview-mode');
if (!preview) {
mode.textContent = '尚未生成';
mode.className = 'badge text-bg-light';
empty.hidden = false;
empty.textContent = region
? '服务端尚未提供可执行方案;请按当前阶段完成检测或处理阻断项。'
: '请先选择地区并检测宿主机。';
grid.hidden = true;
return;
}
mode.textContent = preview.mode === 'automatic' ? '自动生成' : '固定现有方案';
mode.className = 'badge bg-primary-subtle text-primary-emphasis';
empty.hidden = true;
grid.hidden = false;
byId('fabric-plan-id').textContent = text(preview.fabric_id);
byId('fabric-plan-region').textContent = text(preview.fabric_region);
byId('fabric-plan-revision').textContent = (preview.mode === 'automatic' ? '新建' : '现有')
+ ' / ' + text(preview.revision);
byId('fabric-plan-overlay').textContent = text(preview.overlay_cidr,
'由服务端执行时确定');
byId('fabric-plan-port').textContent = text(preview.listen_port);
byId('fabric-plan-hosts').textContent = integer(preview.host_count) + ' 台';
}
function readinessReasons(host) {
const values = Array.isArray(host && host.reasons)
? host.reasons.filter(value => typeof value === 'string' && value).slice(0, 16)
: [];
if (host && host.last_error_code && !values.includes(host.last_error_code)) {
values.push(host.last_error_code);
}
return values;
}
function renderReadinessCell(host) {
const cell = el('td');
const wrapper = el('span', 'fabric-capability-list');
wrapper.append(stateBadge(text(host.readiness_state, 'unchecked')));
wrapper.append(booleanBadge(host.vpc_ready, 'VPC 可用', 'VPC 不可用'));
const reasons = readinessReasons(host);
if (!reasons.length) {
wrapper.append(el('span', 'text-muted', host.vpc_ready === true ? '无阻断原因' : '尚无检测结果'));
} else {
reasons.forEach(value => wrapper.append(el('span', 'text-danger-emphasis',
errorLabels[value] ? errorLabel(value) : reasonLabel(value))));
}
cell.append(wrapper);
return cell;
}
function renderHosts(region) {
const body = byId('fabric-hosts-body');
body.replaceChildren();
const hosts = hostsOf(region);
byId('fabric-host-count').textContent = region ? hosts.length + ' 台宿主机' : '尚未选择地区';
if (!region) {
const row = el('tr');
const cell = el('td', 'text-center text-muted py-4', '尚未选择地区。');
cell.colSpan = 8; row.append(cell); body.append(row); return;
}
if (!hosts.length) {
const row = el('tr');
const cell = el('td', 'text-center text-muted py-4', '该地区没有可参与私网的宿主机。');
cell.colSpan = 8; row.append(cell); body.append(row); return;
}
hosts.forEach(host => {
const capabilities = host.capabilities && typeof host.capabilities === 'object'
? host.capabilities : {};
const row = el('tr');
const identity = el('td');
identity.append(stack(text(host.host_name, '宿主机 #' + text(host.host_id)),
'ID ' + text(host.host_id) + ' · 位置标签 ' + text(host.engine_region)));
const platform = el('td');
platform.append(compactLines([
'宿主机:' + flag(host.host_enabled, '已启用', '未启用', '未记录'),
'调度:' + text(host.scheduler_state),
'资源池:' + text(host.pool_name) + ' / ' + text(host.pool_status),
'线路:' + text(host.line_name) + ' / ' + text(host.line_status),
'平台门禁:' + flag(host.platform_ready, '通过', '未通过'),
]));
const probe = el('td');
probe.append(compactLines([
'连接配置:' + flag(host.configured, '已配置', '未配置', '未记录'),
'可达:' + flag(host.reachable),
'Endpoint:' + text(host.endpoint_ip),
'来源:' + endpointSource(host.endpoint_source),
'探测:' + flag(host.probe_checked, '已完成', '未完成'),
'时间:' + date(host.probed_at),
]));
const manager = el('td');
manager.append(compactLines([
'系统:' + text(capabilities.os_id) + ' ' + text(capabilities.os_version, ''),
'Manager:' + text(capabilities.network_manager),
'预期:' + text(capabilities.network_manager_expected),
'支持:' + flag(capabilities.network_manager_supported),
'部署:' + text(capabilities.deployment_mode),
'防火墙:' + text(capabilities.firewall_manager),
'防火墙模式:' + text(capabilities.firewall_mode),
]));
const wireguard = el('td');
wireguard.append(compactLines([
'WireGuard:' + flag(capabilities.wireguard_ready, '就绪', '未就绪'),
'接口归属:' + flag(capabilities.wireguard_owned, '平台', '冲突/未归属'),
'nftables:' + flag(capabilities.nftables_ready, '就绪', '未就绪'),
'stock nft 服务(仅观测):' + flag(capabilities.nftables_active),
'stock nft 开机启用(仅观测):' + flag(capabilities.nftables_persistent),
]));
const publicPath = el('td');
publicPath.append(compactLines([
'ip_forward:' + sysctl(capabilities.ip_forward, 1),
...rpFilterLines(capabilities),
'出口选择器:' + text(capabilities.public_selector),
'出口核验:' + flag(capabilities.public_verified, '通过', '未通过'),
]));
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,
renderReadinessCell(host));
body.append(row);
});
}
function renderReadback(region) {
const target = byId('fabric-readback-summary');
target.replaceChildren();
if (!region) {
target.append(el('div', 'col-12 text-center text-muted py-4', '尚未选择地区。'));
return;
}
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)],
['Revision', text(region.fabric_revision)],
['映射状态', stateLabel(region.mapping_state)],
['引擎状态', stateLabel(region.fabric_state)],
['宿主机集合', flag(region.host_set_matches, '完全一致', '不一致', '未核对')],
['下一阶段门禁', flag(region.next_stage_allowed, '允许', '未允许', '未核对')],
['地区 readiness', flag(region.ready, '就绪', '未就绪', '未核对')],
['未映射 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');
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]));
column.append(card); target.append(column);
});
}
function renderSelectedRegion() {
const region = selectedRegion();
renderWizardSteps(region);
renderWizardBlockers(region);
renderPlanPreview(region);
renderSummary(region);
renderHosts(region);
renderReadback(region);
syncControls();
}
function renderRegionOptions(regions) {
const select = byId('fabric-region-select');
select.replaceChildren();
if (!regions.length) {
const option = el('option', '', '没有可管理的地区');
option.value = ''; select.append(option); select.disabled = true;
state.selectedRegionId = ''; renderSelectedRegion(); return;
}
regions.forEach(region => {
const id = regionIdOf(region);
if (!id) return;
const option = el('option', '', regionName(region) + ' · ' + text(region.region_code));
option.value = id; select.append(option);
});
const exists = regions.some(region => regionIdOf(region) === state.selectedRegionId);
if (!exists) state.selectedRegionId = regionIdOf(regions[0]);
select.value = state.selectedRegionId;
select.disabled = false;
renderSelectedRegion();
}
function mergeRegionProjection(region) {
if (!region || typeof region !== 'object') return false;
const id = regionIdOf(region);
if (!id) return false;
const index = state.regions.findIndex(item => regionIdOf(item) === id);
if (index < 0) state.regions.push(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 startReceiptRecovery(regionId, action, previousOperation) {
// A lost HTTP receipt does not prove rejection. Preserve the pre-request
// identity so an unchanged historical failure cannot finish this attempt.
state.outcomeUnknownRegionIds.add(regionId);
state.operationsByRegion.delete(regionId);
if (state.operationPollTimer) {
window.clearTimeout(state.operationPollTimer);
state.operationPollTimer = 0;
}
state.receiptRecoveriesByRegion.set(regionId, {
action, previousOperation, reads: 0, startedAt: Date.now(),
});
scheduleOperationPoll(receiptRecoveryInterval);
}
function receiptRecoveryMatches(recovery, observed) {
if (!observed || !observed.id || observed.kind === 'unknown'
|| observed.started_at === null) return false;
const previous = recovery.previousOperation;
if (previous && observed.id === previous.id) {
// Explicit reconcile may resume the exact unsettled operation. A
// terminal old id, even if its diagnostic projection later changes,
// is never proof that a fresh request was accepted or completed.
return recovery.action === 'reconcile'
&& ['queued', 'running', 'uncertain', 'interrupted'].includes(previous.status)
&& observed.kind === previous.kind;
}
return observed.kind === recovery.action
&& (!previous || previous.updated_at === null
|| observed.started_at >= previous.updated_at);
}
function adoptRegionOperations() {
state.regions.forEach(region => {
const regionId = regionIdOf(region);
if (state.receiptRecoveriesByRegion.has(regionId)
|| state.outcomeUnknownRegionIds.has(regionId)) return;
const operation = operationOf(region.operation);
if (operation && operation.id) rememberOperation(regionId, operation);
});
if (state.operationsByRegion.size || state.receiptRecoveriesByRegion.size) {
scheduleOperationPoll();
}
}
function scheduleOperationPoll(delay = 2000) {
if (state.operationPollTimer
|| (!state.operationsByRegion.size && !state.receiptRecoveriesByRegion.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
? '已成功并通过全部门禁。'
: '宿主机任务已成功;请按当前向导完成最终回读确认。'),
};
}
return {
kind: 'error',
text: prefix + operationStatusLabel(operation.status)
+ ';请查看宿主机清单中的阶段、检查点和安全原因。',
};
}
async function pollOperations() {
if (!state.operationsByRegion.size && !state.receiptRecoveriesByRegion.size) return;
const expired = [];
for (const [regionId, recovery] of state.receiptRecoveriesByRegion) {
if (recovery.reads >= receiptRecoveryMaxReads
|| Date.now() - recovery.startedAt >= receiptRecoveryMaxDuration) {
state.receiptRecoveriesByRegion.delete(regionId);
expired.push(regionId);
}
}
if (expired.includes(state.selectedRegionId)) {
notice(regionName(selectedRegion())
+ ':只读恢复已达到上限,仍未确认本轮 operation;写操作保持关闭。请刷新页面读取权威状态,切勿重复提交。', 'error');
}
if (!state.operationsByRegion.size && !state.receiptRecoveriesByRegion.size) return;
const trackedOperations = [...state.operationsByRegion.entries()];
const receiptRecoveries = [...state.receiptRecoveriesByRegion.entries()];
receiptRecoveries.forEach(([, recovery]) => { recovery.reads += 1; });
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 = [];
const recovered = [];
for (const [regionId, tracked] of trackedOperations) {
if (state.receiptRecoveriesByRegion.has(regionId)) continue;
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);
if (['succeeded', 'failed'].includes(observed.status)) {
state.outcomeUnknownRegionIds.delete(regionId);
}
terminal.push({ region, operation: observed });
}
}
for (const [regionId, recovery] of receiptRecoveries) {
if (state.receiptRecoveriesByRegion.get(regionId) !== recovery) continue;
const region = state.regions.find(item => regionIdOf(item) === regionId) || null;
const observed = operationOf(region && region.operation);
if (!receiptRecoveryMatches(recovery, observed)) continue;
if (operationRunning(observed)) {
state.receiptRecoveriesByRegion.delete(regionId);
// Keep writes closed until this exact discovered operation settles.
rememberOperation(regionId, observed);
recovered.push({ region, operation: observed });
} else if (['succeeded', 'failed'].includes(observed.status)) {
state.receiptRecoveriesByRegion.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);
const selectedRecovery = recovered.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 (selectedRecovery) {
notice(regionName(selectedRecovery.region) + ':只读发现 operation '
+ selectedRecovery.operation.id + ',正在继续读取同一任务;不会重复提交。');
} else if (state.receiptRecoveriesByRegion.has(state.selectedRegionId)) {
notice(regionName(selectedRegion())
+ ':尚未确认本轮 operation;正在只读恢复接纳结果,不会把旧任务状态当成本轮结果,也不会重复提交。', 'error');
} 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) {
state.receiptRecoveriesByRegion.clear();
notice('Fabric operation 状态连续读取失败;未知结果的写操作保持关闭,任务不会被重复提交,请刷新页面继续只读核对。', 'error');
return;
}
}
if (state.operationsByRegion.size || state.receiptRecoveriesByRegion.size) {
scheduleOperationPoll(state.operationPollFailures || state.receiptRecoveriesByRegion.size
? receiptRecoveryInterval : 2000);
}
}
function applyActionProjection(payload, originRegionId, originSelectionVersion) {
const regions = regionsOf(payload);
let applied = false;
if (regions.length && state.selectionVersion === originSelectionVersion) {
state.regions = regions;
applied = true;
} else if (regions.length) {
const origin = regions.find(region => regionIdOf(region) === originRegionId);
applied = mergeRegionProjection(origin);
} else if (payload && payload.region && regionIdOf(payload.region) === originRegionId) {
applied = mergeRegionProjection(payload.region);
}
if (applied) renderRegionOptions(state.regions);
return applied;
}
async function load() {
const version = ++state.loadVersion;
state.loading = true;
syncControls();
notice('正在读取地区和宿主机 readiness…');
try {
const payload = await api('/api/v1/admin/fabric');
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');
// A caller may be using this load as the readback for a completed
// action. Do not let an HTTP 200 diagnostic shell turn into a success
// notice when the authoritative engine projection is unavailable.
return false;
} else if (!state.regions.length) {
notice('没有可管理的地区。');
} else {
notice('已读取 ' + state.regions.length + ' 个地区;请选择地区核对 readiness。', 'success');
}
return true;
} catch (error) {
if (version !== state.loadVersion) return false;
state.regions = [];
renderRegionOptions([]);
notice(error.message || '地区 readiness 读取失败。', 'error');
return false;
} finally {
if (version === state.loadVersion) {
state.loading = false;
syncControls();
}
}
}
const actionCopy = {
probe: {
running: '正在检测地区宿主机;此操作只读取能力和连通状态…',
},
apply: {
running: '正在自动配置地区私网;所有宿主机完成严格回读前不会标记为就绪…',
},
reconcile: {
running: '正在重新核对地区私网和所有宿主机回读…',
},
};
function actionOutcome(action, region) {
const stage = workflowOf(region).stage;
if (action === 'probe') {
if (stage === 'ready_to_apply') {
return { success: true, message: '宿主机检测通过;请核对服务端只读方案后自动配置。' };
}
if (stage === 'active') {
return { success: true, message: '宿主机检测已返回;地区私网仍保持 active。' };
}
if (stage === 'needs_reconcile') {
return { success: false, message: '宿主机检测已返回,但固定方案需要重新核对。' };
}
return { success: false, message: '宿主机检测已返回,但仍有阻断项;请按向导修复后重试。' };
}
if (stage === 'active') {
return { success: true, message: action === 'apply'
? '地区私网已完成配置并通过权威回读。'
: '地区私网已重新核对并通过全部门禁。' };
}
return { success: false, message: action === 'apply'
? '自动配置请求已返回,但地区尚未 active;切勿重复配置,请使用“重新核对”。'
: '重新核对已返回,但地区仍未 active;请按当前阻断原因处理。' };
}
async function runRegionAction(action) {
if (!canManage || state.pendingAction || !actionCopy[action]) return;
const region = selectedRegion();
const regionId = regionIdOf(region);
if (!regionId) return notice('请先选择地区。', 'error');
const workflow = workflowOf(region);
const outcomeUnknown = state.outcomeUnknownRegionIds.has(regionId);
const serverAllowed = action === 'probe' ? workflow.can_probe
: action === 'apply' ? workflow.can_apply : workflow.can_reconcile;
const allowed = !outcomeUnknown && serverAllowed;
if (!allowed) {
return notice(regionName(region) + ':服务端尚未允许执行此步骤。', 'error');
}
const originSelectionVersion = state.selectionVersion;
const originName = regionName(region);
const previousOperation = operationOf(region.operation)
|| state.operationsByRegion.get(regionId) || null;
state.pendingAction = action;
syncControls();
notice(originName + ':' + actionCopy[action].running);
try {
const payload = await api('/api/v1/admin/fabric/regions/' + encodeURIComponent(regionId) + '/' + action,
{ method: 'POST', body: '{}' });
if (payload && payload.engine_available === false) {
throw new Error(text(payload.engine_error,
'操作已返回,但 Fabric 引擎最新状态无法读取;请稍后重新核对。'));
}
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
? outcome.message : outcome.message + ' 当前仍显示您后来选择的地区。';
notice(originName + ':' + suffix, outcome.success ? 'success' : 'error');
} catch (error) {
if (error && error.outcomeUnknown === true && action !== 'probe') {
startReceiptRecovery(regionId, action, previousOperation);
if (state.selectedRegionId === regionId) renderSelectedRegion();
}
notice(originName + ':' + (error.message || '操作未完成,请重新核对。'), 'error');
} finally {
state.pendingAction = '';
syncControls();
}
}
byId('fabric-region-select')?.addEventListener('change', event => {
const next = String(event.currentTarget.value || '');
if (next === state.selectedRegionId) return;
state.selectedRegionId = next;
state.selectionVersion += 1;
renderSelectedRegion();
const region = selectedRegion();
if (region) notice('正在查看 ' + regionName(region) + ' 的 readiness。');
});
actionButtons.forEach(button => button.addEventListener('click', () => {
runRegionAction(String(button.dataset.fabricAction || ''));
}));
load();