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/runtime.js

2074 lines
109 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.

import { toast } from './toast.js?v=2026100102';
import {
announceTaskAccepted, observeTask, recoveryTaskFailureNotice,
resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl,
} from './task-observer.js?v=2026102102';
// PHP owns authentication, authorisation, ownership and purchasing. No Agent
// address, token, host credential or unrestricted create API exists in this UI.
const byId = (id) => document.getElementById(id);
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false);
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
let vmStatusRequest = null;
let vmStatusGeneration = 0;
const activeTaskObservers = new Set();
// Keep the historical storage key so an interrupted deployment can still
// reconcile to the same opening invoice.
const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
const CLOUD_PATHS = Object.freeze({
instances: '/user/cloud/instances',
deploy: '/user/cloud/deploy',
keys: '/user/cloud/ssh-keys',
invoices: '/user/cloud/invoices',
});
const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`;
const navigate = (path) => location.assign(path);
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
function readBootstrap(id) {
const source = byId(id);
if (!source) return null;
let payload;
try { payload = JSON.parse(source.textContent || '{}'); }
catch { throw new Error('页面初始数据无效,请刷新后重试。'); }
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('页面初始数据缺失,请刷新后重试。');
return payload;
}
function bootstrapItems(payload, ...names) {
for (const name of names) if (Array.isArray(payload?.[name])) return payload[name];
return [];
}
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
async function copyText(value) { if (navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(value); return; } catch {} } const area = document.createElement('textarea'); area.value = value; area.style.position = 'fixed'; area.style.opacity = '0'; document.body.append(area); area.select(); try { if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。'); } finally { area.value = ''; area.remove(); } }
function requireSecureTransport() { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 使用登录凭据和虚拟机控制功能。'); }
async function api(path, options = {}) {
const expectedStatuses = options.expectedStatus === undefined ? null
: (Array.isArray(options.expectedStatus) ? options.expectedStatus : [options.expectedStatus]);
const requireTaskReceipt = options.requireTaskReceipt === true;
const requestOptions = { ...options };
delete requestOptions.expectedStatus;
delete requestOptions.requireTaskReceipt;
const method = (options.method || 'GET').toUpperCase();
const headers = new Headers({ Accept: 'application/json', ...options.headers });
if (!['GET', 'HEAD'].includes(method)) { requireSecureTransport(); headers.set('X-CSRF-Token', state.csrfToken); if (options.body !== undefined) headers.set('Content-Type', 'application/json'); }
const response = await fetch(path, { ...requestOptions, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : JSON.stringify(options.body) });
let payload = null;
if (response.status !== 204) { try { payload = await response.json(); } catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); } }
if (response.status === 401) { clearCredential(); closeConsole(); location.assign('/auth/login'); throw new Error('登录已过期。'); }
if (!response.ok || payload?.ret === 0) { const detail = Array.isArray(payload?.detail) ? payload.detail.map(item => item.msg || '输入错误').join(';') : payload?.detail; const error = new Error(String(detail || payload?.message || payload?.msg || payload?.error || `请求失败 (${response.status})`)); error.status = response.status; throw error; }
if (expectedStatuses && !expectedStatuses.includes(response.status)) {
const error = new Error(`请求已送达,但服务返回了意外状态 (${response.status})。请勿重复提交,并联系管理员核查。`);
error.status = response.status;
error.mutationMayHaveApplied = true;
throw error;
}
if (requireTaskReceipt && !taskUrl(payload)) {
const error = new Error('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。');
error.status = response.status;
error.mutationMayHaveApplied = true;
throw error;
}
return payload;
}
function normalizeVm(vm) {
const legacyMutation = vm.can_mutate !== false;
const canOperate = vm.can_operate === undefined ? legacyMutation : vm.can_operate === true;
const canDelete = vm.can_delete === undefined ? legacyMutation : vm.can_delete === true;
const canViewCredential = vm.can_view_credential !== false;
return { ...vm, uuid: String(vm.uuid || vm.id || ''), api_id: String(vm.id || vm.uuid || ''), vcpu: vm.vcpu ?? vm.cpu_cores,
memory_mib: vm.memory_mib, public_ip_cidr: vm.public_ip_cidr || vm.public_ip || '', can_operate: canOperate, can_delete: canDelete,
can_view_credential: canViewCredential, password_available: canViewCredential
&& (vm.password_available === true || vm.has_initial_root_password === true) };
}
function firstNumber(...values) {
for (const value of values) {
if (value === null || value === undefined || value === '') continue;
const number = Number(value);
if (Number.isFinite(number) && number >= 0) return number;
}
return null;
}
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') return String(value).trim();
}
return '';
}
function vmServiceData(vm) {
const period = vm?.current_period && typeof vm.current_period === 'object' ? vm.current_period
: vm?.service_period && typeof vm.service_period === 'object' ? vm.service_period : {};
const service = vm?.service && typeof vm.service === 'object' ? vm.service : period;
const billing = vm?.billing && typeof vm.billing === 'object' ? vm.billing : {};
const traffic = vm?.traffic && typeof vm.traffic === 'object' ? vm.traffic : (service.traffic && typeof service.traffic === 'object' ? service.traffic : {});
const trafficGib = firstNumber(vm?.traffic_gib, service.traffic_gib, period.traffic_gib, billing.traffic_gib);
const quota = firstNumber(vm?.traffic_quota_bytes, service.traffic_quota_bytes, period.traffic_quota_bytes, billing.traffic_quota_bytes, traffic.quota_bytes,
trafficGib === null ? null : trafficGib * 1024 ** 3);
const rx = firstNumber(vm?.traffic_download_bytes, vm?.traffic_rx_bytes, vm?.download_rx_bytes, vm?.network_rx_total_bytes,
service.traffic_download_bytes, service.traffic_rx_bytes, period.traffic_download_bytes, period.traffic_rx_bytes, traffic.rx_bytes, traffic.download_bytes);
const tx = firstNumber(vm?.traffic_upload_bytes, vm?.traffic_tx_bytes, vm?.upload_tx_bytes, vm?.network_tx_total_bytes,
service.traffic_upload_bytes, service.traffic_tx_bytes, period.traffic_upload_bytes, period.traffic_tx_bytes, traffic.tx_bytes, traffic.upload_bytes);
const used = firstNumber(vm?.traffic_used_bytes, vm?.traffic_total_bytes, service.traffic_used_bytes, period.traffic_used_bytes, traffic.used_bytes, traffic.total_bytes,
rx !== null && tx !== null ? rx + tx : null);
const remaining = firstNumber(vm?.traffic_remaining_bytes, service.traffic_remaining_bytes, period.traffic_remaining_bytes, traffic.remaining_bytes,
quota !== null && used !== null ? Math.max(0, quota - used) : null);
const serviceExpiresAt = vm?.service_expires_at ?? vm?.expires_at
?? service.service_expires_at ?? service.expires_at ?? billing.expires_at ?? null;
const status = firstText(vm?.service_status, service.status, period.status, billing.status, vm?.subscription_status);
const networkStatus = firstText(vm?.network_status, service.network_status, period.network_status, traffic.network_status);
return { quota, rx, tx, used, remaining, serviceExpiresAt, status, networkStatus };
}
function formatBytes(value) {
if (value === null || !Number.isFinite(value) || value < 0) return '暂未提供';
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
let amount = value; let unit = 0;
while (amount >= 1024 && unit < units.length - 1) { amount /= 1024; unit += 1; }
const precision = unit === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2;
return `${amount.toFixed(precision)} ${units[unit]}`;
}
function formatTrafficQuota(value) { return value === 0 ? '不限流量' : formatBytes(value); }
function serviceTimestamp(value) {
if (value === null || value === undefined || value === '') return null;
if (typeof value === 'number' || /^\d+$/.test(String(value).trim())) {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return null;
return numeric < 1e12 ? numeric * 1000 : numeric;
}
const parsed = Date.parse(String(value));
return Number.isFinite(parsed) ? parsed : null;
}
function formatServiceDate(value) {
const timestamp = serviceTimestamp(value);
return timestamp === null ? '暂未提供' : new Date(timestamp).toLocaleString('zh-CN', { hour12: false });
}
function serviceStatusInfo(data) {
let status = data.status.toLowerCase().replace(/[\s-]+/g, '_');
if (!status && serviceTimestamp(data.serviceExpiresAt) !== null) status = serviceTimestamp(data.serviceExpiresAt) <= Date.now() ? 'expired' : 'active';
const labels = {
active: ['服务有效', 'active'], pending: ['待生效', 'warning'], renewing: ['续费处理中', 'warning'],
grace: ['已到期,处于删除宽限期', 'warning'], expired_grace: ['已到期,处于删除宽限期', 'warning'], grace_expired: ['已到期,处于删除宽限期', 'warning'],
resume_pending: ['等待恢复服务', 'warning'], resuming: ['正在恢复服务', 'warning'], resume_failed: ['服务恢复失败,请联系管理员', 'stopped'], suspending: ['正在暂停', 'warning'],
suspending_expired: ['到期停机中', 'warning'], suspended_expired: ['已因到期停机', 'stopped'], expired: ['已到期', 'stopped'],
suspend_failed: ['到期停机失败,请联系管理员', 'stopped'],
deletion_pending: ['等待永久删除', 'warning'], delete_pending: ['等待永久删除', 'warning'], deleting: ['正在永久删除', 'warning'], deleting_expired: ['正在永久删除', 'warning'],
purge_pending: ['等待永久删除', 'warning'], purge_stopping: ['删除前正在关机', 'warning'], purge_force_required: ['等待管理员确认强制删除', 'stopped'], purge_deleting: ['正在永久删除', 'warning'], purging: ['正在永久删除', 'warning'],
delete_failed: ['自动删除失败,请联系管理员', 'stopped'], purge_stop_failed: ['删除前关机失败,请联系管理员', 'stopped'], purge_failed: ['自动删除失败,请联系管理员', 'stopped'],
suspended_traffic: ['已因流量用尽暂停', 'stopped'], traffic_exhausted: ['流量已用尽', 'stopped'], exempt: ['不受套餐限制', 'active'],
};
const [label, className] = labels[status] || [data.status || '暂未提供', 'unknown'];
return { label, className };
}
function networkStatusInfo(value) {
const status = value.toLowerCase().replace(/[\s-]+/g, '_');
const labels = {
active: ['网络正常', 'active'], blocking: ['正在暂停网络', 'warning'], blocking_expired: ['到期断网处理中', 'warning'],
blocked_traffic: ['本期流量用尽,已断网', 'stopped'], blocked_expired: ['实例已到期,网络已停用', 'stopped'],
block_failed: ['网络停用失败,请联系管理员', 'stopped'], restore_pending: ['等待恢复网络', 'warning'], restoring: ['正在恢复网络', 'warning'],
expiry_block_failed: ['到期断网失败,请联系管理员', 'stopped'], block_expired_failed: ['到期断网失败,请联系管理员', 'stopped'],
restore_failed: ['网络恢复失败,请联系管理员', 'stopped'], exempt: ['网络不受套餐限制', 'active'],
};
const [label, className] = labels[status] || [value || '暂未提供', 'unknown'];
return { label, className };
}
function selectedVm() { return state.vms.find(vm => vm.uuid === state.selectedVmId); }
function vmPath(vm = selectedVm()) { if (!vm) throw new Error('请先选择虚拟机。'); return `/api/v1/vms/${encodeURIComponent(vm.api_id)}`; }
function clearCredential() {
clearTimeout(state.credentialTimer);
state.credentialPassword = '';
state.credentialVisible = false;
if (byId('vm-detail-root-password')) text('vm-detail-root-password', '********');
byId('vm-detail-password-reveal')?.setAttribute('aria-pressed', 'false');
}
const VM_DETAIL_TABS = ['operations', 'performance', 'operations-log', 'settings'];
function setVmDetailTab(tab, focus = false) {
const requested = tab === 'traffic' ? 'performance' : tab;
const next = VM_DETAIL_TABS.includes(requested) ? requested : 'operations';
state.detailTab = next;
for (const name of VM_DETAIL_TABS) {
const button = byId(`vm-detail-tab-${name}`);
const active = name === next;
button.classList.toggle('active', active);
button.setAttribute('aria-selected', String(active));
button.tabIndex = active ? 0 : -1;
byId(`vm-detail-${name}-panel`).hidden = !active;
}
stopVmMetrics();
stopVmTrafficDaily();
if (state.view === 'detail') {
if (next === 'performance') {
startVmMetrics();
startVmTrafficDaily();
}
}
if (focus) byId(`vm-detail-tab-${next}`).focus();
}
async function loadVms() {
if (state.loadingVMs) return;
state.loadingVMs = true;
try {
state.vms = items(await api('/api/v1/vms')).map(normalizeVm);
showError('cloud-page-error', '');
if (byId('vm-table-body')) renderVMs();
const vm = selectedVm();
if (vm && state.view === 'detail') renderVmDetail(vm);
else if (state.selectedVmId && !vm && ['detail', 'reinstall', 'rescue'].includes(state.view)) throw new Error('虚拟机不存在或当前账户无权访问。');
}
catch (error) { showError('cloud-page-error', error.message); if (!state.vms.length && byId('vm-table-body')) renderVMs(true); }
finally { state.loadingVMs = false; }
}
async function loadVm(apiId = selectedVm()?.api_id || document.body.dataset.vmId, raise = false) {
const id = String(apiId || '');
if (!id) {
const error = new Error('虚拟机标识缺失。');
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
}
if (state.loadingVMs) return selectedVm() || null;
state.loadingVMs = true;
try {
const vm = normalizeVm(await api(`/api/v1/vms/${encodeURIComponent(id)}`));
state.vms = [vm];
state.selectedVmId = vm.uuid;
showError('cloud-page-error', '');
if (state.view === 'detail') renderVmDetail(vm);
return vm;
} catch (error) {
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
} finally {
state.loadingVMs = false;
}
}
function applyCloudUser(user = {}) {
state.csrfToken = String(user.csrf_token || '');
if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。');
state.userId = String(user.user_id || '');
if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。');
state.username = user.username || user.user_name || user.email || '用户';
state.admin = user.admin === true || user.is_admin === true || Number(user.is_admin) === 1;
if (byId('current-username')) text('current-username', state.username);
for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) {
const link = byId(id);
if (link) link.hidden = !state.admin;
}
}
function hydrateVmDetailBootstrap(payload) {
if (!payload || typeof payload !== 'object' || !payload.vm || typeof payload.vm !== 'object') {
throw new Error('实例详情初始数据缺失,请刷新后重试。');
}
state.view = 'detail';
applyCloudUser(payload.user || {});
const vm = normalizeVm(payload.vm);
if (!vm.api_id || !vm.uuid) throw new Error('实例标识缺失,请返回实例列表。');
state.vms = [vm];
state.selectedVmId = vm.uuid;
return vm;
}
async function settleVmStatusRequest(promise, raise) {
try {
return await promise;
} catch (error) {
if (error?.name === 'AbortError') return null;
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
}
}
async function loadVmStatus(apiId = selectedVm()?.api_id || document.body.dataset.vmId, options = {}) {
const settings = typeof options === 'boolean' ? { raise: options } : (options || {});
const raise = settings.raise === true;
const live = settings.live === true;
const force = settings.force === true;
const id = String(apiId || '');
if (!id) {
const error = new Error('实例标识缺失。');
showError('cloud-page-error', error.message);
if (raise) throw error;
return null;
}
const active = vmStatusRequest;
if (active && active.apiId === id && !force && (!live || active.live)) {
return settleVmStatusRequest(active.promise, raise);
}
active?.controller.abort();
const controller = new AbortController();
const generation = ++vmStatusGeneration;
const request = { apiId: id, live, controller, promise: null };
request.promise = (async () => {
try {
const liveQuery = live ? '?live=1' : '';
const payload = await api(`/api/v1/vms/${encodeURIComponent(id)}/status${liveQuery}`, { signal: controller.signal });
if (controller.signal.aborted || generation !== vmStatusGeneration) return null;
const current = selectedVm();
if (!current) throw new Error('实例初始数据已失效,请刷新页面。');
if (String(current.api_id) !== id) return null;
const update = payload?.vm && typeof payload.vm === 'object' ? payload.vm : payload;
if (!update || typeof update !== 'object') throw new Error('实例实时状态格式无效。');
const vm = normalizeVm({ ...current, ...update, id: current.api_id, uuid: current.uuid });
state.vms = [vm];
state.selectedVmId = vm.uuid;
showError('cloud-page-error', '');
if (state.view === 'detail') renderVmDetail(vm);
return vm;
} catch (error) {
// Superseded requests must be silent even when fetch had already
// produced a non-abort error before the newer request took ownership.
if (controller.signal.aborted || generation !== vmStatusGeneration) return null;
throw error;
} finally {
if (vmStatusRequest === request) vmStatusRequest = null;
}
})();
vmStatusRequest = request;
return settleVmStatusRequest(request.promise, raise);
}
function localPowerMutation(vm) {
const mutation = state.powerMutation;
return mutation && vm && String(mutation.vmId) === String(vm.api_id) ? mutation : null;
}
function powerTransition(vm) {
const local = localPowerMutation(vm);
if (local) return local.action;
if (vm?.state_transitioning !== true) return '';
return String(vm.state_transition || '').toLowerCase();
}
function renderVmDetail(vm) {
const display = detailStateDisplay(vm);
text('vm-detail-name-value', vm.name); text('vm-detail-state', display.label); byId('vm-detail-state').className = `state-pill ${display.category}`;
const syncElement = byId('vm-detail-state-sync');
if (syncElement) {
syncElement.textContent = display.note;
syncElement.className = `vm-state-sync ${display.noteClass}`.trim();
syncElement.hidden = !display.note;
}
for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm));
for (const id of ['vm-detail-ip', 'vm-detail-header-ip']) text(id, vmIp(vm));
text('vm-detail-header-created-at', vmCreatedAgo(vm)); const system = vmSystemInfo(vm); text('vm-detail-os-label', system.label); text('vm-detail-os', system.value);
text('vm-detail-spec', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`); text('vm-detail-disk', diskLabel(vm)); text('vm-detail-ssh-user', vm.login_name || (vm.os_source === 'cloud_template' ? 'root' : '未记录'));
const settingsHostname = byId('vm-detail-settings-current-hostname');
if (settingsHostname) settingsHostname.textContent = vm.guest_hostname || '未记录';
byId('vm-detail-ip-copy').hidden = vmIp(vm) === '未获取';
text('vm-detail-root-password', !vm.can_view_credential ? '无权查看' : vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : '未记录');
for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available;
renderVmService(vm);
const category = stateCategory(vm.state); const running = category === 'running'; const stopped = category === 'stopped';
const transition = powerTransition(vm); const powerBusy = localPowerMutation(vm) !== null;
const consoleAvailable = running || transition === 'shutdown';
const stateKnown = !['', 'unknown', 'nostate'].includes(String(vm.state || '').toLowerCase().replace(/[_\s-]+/g, ''));
const primary = byId('vm-detail-primary-actions'); const danger = byId('vm-detail-danger-actions'); primary.replaceChildren(); danger.replaceChildren();
danger.closest('section').hidden = !vm.can_operate && !vm.can_delete;
if (vm.can_operate) {
primary.append(actionButton('控制台', () => openConsole(vm), { disabled: !consoleAvailable }), actionButton('开机', () => powerAction('start'), { disabled: powerBusy || !stopped }), actionButton('正常关机', () => powerAction('shutdown'), { disabled: powerBusy || !running }), actionButton('重启', () => powerAction('reboot'), { disabled: powerBusy || !running }));
danger.append(actionButton('重装系统', () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: powerBusy || !stateKnown || vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => navigate(vmPagePath(vm.api_id, 'rescue')), { variant: 'danger', disabled: powerBusy || !stateKnown }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: powerBusy || !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: powerBusy || !stateKnown || stopped }));
} else {
primary.append(makeElement('p', 'muted', vm.is_owner || vm.can_delete
? '实例服务已到期或正在执行策略;日常操作暂不可用。'
: '这是其他用户的实例;当前管理员账户只有查看权限。'));
}
if (vm.can_delete) danger.append(actionButton('删除虚拟机', deleteVm, { variant: 'danger', disabled: powerBusy || !stopped }));
if (state.mutationBusy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; });
}
function renderVmService(vm) {
const data = vmServiceData(vm);
const status = serviceStatusInfo(data);
const statusElement = byId('vm-detail-service-status');
statusElement.textContent = status.label;
statusElement.className = `service-pill ${status.className}`;
const networkStatus = networkStatusInfo(data.networkStatus);
const networkStatusElement = byId('vm-detail-network-status');
networkStatusElement.textContent = networkStatus.label;
networkStatusElement.className = `service-pill ${networkStatus.className}`;
text('vm-detail-service-expiry', formatServiceDate(data.serviceExpiresAt));
text('vm-detail-traffic-rx', formatBytes(data.rx));
text('vm-detail-traffic-tx', formatBytes(data.tx));
text('vm-detail-traffic-used', formatBytes(data.used));
text('vm-detail-traffic-total-remaining', `${formatTrafficQuota(data.quota)} / ${data.quota === 0 ? '不限流量' : formatBytes(data.remaining)}`);
const progress = byId('vm-detail-traffic-progress');
const ratio = data.quota !== null && data.quota > 0 && data.used !== null ? Math.max(0, Math.min(100, data.used / data.quota * 100)) : null;
progress.hidden = ratio === null;
if (ratio !== null) {
progress.setAttribute('aria-valuenow', String(Math.round(ratio * 10) / 10));
byId('vm-detail-traffic-progress-bar').style.width = `${ratio}%`;
progress.classList.toggle('is-exhausted', ratio >= 100);
} else {
progress.removeAttribute('aria-valuenow');
byId('vm-detail-traffic-progress-bar').style.width = '0';
progress.classList.remove('is-exhausted');
}
}
function taskFailureMessage(task, fallback = '任务执行失败。') {
const message = task?.error || fallback;
const resolvedNotice = resolvedTaskFailureNotice(task);
if (resolvedNotice) return resolvedNotice;
const recoveryNotice = recoveryTaskFailureNotice(task);
if (recoveryNotice) return recoveryNotice;
if (task?.effect_may_have_applied) {
return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并在任务中心查看任务编号后交由管理员核查。`;
}
return task?.safe_to_resubmit === false
? `${message} 任务已失败且相关资源已锁定,请勿再次提交,并联系管理员核查。` : message;
}
function observeAcceptedTask(result, detail = {}, handlers = {}) {
if (!taskUrl(result)) return null;
announceTaskAccepted(result, detail);
const handle = observeTask(result, handlers);
if (!handle.url) return null;
activeTaskObservers.add(handle);
void handle.done.finally(() => activeTaskObservers.delete(handle));
return handle;
}
async function powerAction(action, dangerous = false) {
const vm = selectedVm();
if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error');
if (state.mutationBusy || state.powerMutation) return;
if (dangerous) {
const resetting = action === 'reset';
const confirmed = await requestUserConfirmation({
title: resetting ? '强制重置实例' : '强制断电',
message: resetting
? `实例“${vm.name}”将立即断电并重新启动,未写入磁盘的数据可能丢失。`
: `实例“${vm.name}”将立即断电,未保存的数据可能丢失。`,
confirmText: resetting ? '强制重置' : '强制断电',
tone: 'danger',
});
if (!confirmed) return;
}
const mutation = { vmId: vm.api_id, action };
state.powerMutation = mutation;
renderVmDetail(vm);
try {
const result = await api(`${vmPath(vm)}/actions`, {
method: 'POST', body: { action }, expectedStatus: 202, requireTaskReceipt: true,
});
const observer = observeAcceptedTask(result, { title: '电源任务' }, {
onTerminal: task => {
if (!taskSucceededWithoutRecovery(task)) {
toast(taskFailureMessage(task), 'error', '电源任务需恢复');
}
void loadVmStatus(vm.api_id, { live: true, force: true });
},
});
toast(observer
? '任务已接收,可在任务中心查看结果。'
: '任务请求已送达,但回执协议无效。请勿再次提交,并联系管理员核查。',
observer ? 'success' : 'error', '电源任务');
} catch (error) {
toast(error.message, 'error');
void loadVmStatus(vm.api_id, { live: true, force: true });
} finally {
if (state.powerMutation === mutation) state.powerMutation = null;
if (selectedVm()) renderVmDetail(selectedVm());
}
}
async function deleteVm() {
const vm = selectedVm();
if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error');
if (state.mutationBusy || state.powerMutation) return;
const confirmed = await requestUserConfirmation({
title: '永久删除实例',
message: `实例“${vm.name}”及面板管理的虚拟磁盘将被永久删除,此操作无法恢复。`,
confirmText: '永久删除',
tone: 'danger',
requiredText: vm.name,
requiredLabel: '输入完整实例名称以确认永久删除',
});
if (!confirmed) return;
state.mutationBusy = true;
setDetailBusy(true);
try {
const result = await api(vmPath(vm), {
method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true },
expectedStatus: 202, requireTaskReceipt: true,
});
announceTaskAccepted(result, { title: '删除实例' });
toast('任务已接收,可在任务中心查看结果。', 'success', '删除实例');
navigate(CLOUD_PATHS.instances);
} catch (error) {
toast(error.message, 'error');
} finally {
state.mutationBusy = false;
setDetailBusy(false);
}
}
function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); }
async function credential(copy = false) {
const vm = selectedVm(); if (!vm?.can_view_credential || !vm.password_available) return;
if (!copy && state.credentialVisible) return clearCredential();
const id = vm.api_id;
try { const result = await api(`${vmPath(vm)}/credential`, { method: 'POST' }); if (selectedVm()?.api_id !== id || state.view !== 'detail') return; if (!result?.password) throw new Error('没有可查看的初始密码。'); if (copy) { await copyText(result.password); toast('初始密码已复制。', 'success'); } else { state.credentialPassword = result.password; state.credentialVisible = true; text('vm-detail-root-password', result.password); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'true'); clearTimeout(state.credentialTimer); state.credentialTimer = setTimeout(clearCredential, 30000); } } catch (error) { toast(error.message, 'error'); }
}
async function loadKeys() {
state.sshKeys = items(await api('/api/v1/ssh-keys'));
if (byId('ssh-keys-list')) renderKeys();
if (byId('vm-guest-ssh-key-cards')) renderKeyCards('create');
if (byId('reinstall-ssh-key-cards')) renderKeyCards('reinstall');
}
function renderKeys() {
const container = byId('ssh-keys-list'); container.replaceChildren();
if (!state.sshKeys.length) return container.append(makeElement('p', 'muted', '还没有公钥。'));
for (const key of state.sshKeys) { const row = makeElement('div', 'ssh-key-row'); const details = makeElement('div', 'ssh-key-details'); details.append(makeElement('strong', '', key.name), makeElement('small', '', key.fingerprint || '')); const actions = makeElement('div', 'ssh-key-actions'); const button = actionButton('删除', async () => { const confirmed = await requestUserConfirmation({ title: '删除 SSH 公钥', message: `确定删除“${key.name}”?已经创建的实例不会受到影响。`, confirmText: '删除公钥', tone: 'danger' }); if (!confirmed) return; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(key.id)}`, { method: 'DELETE' }); await loadKeys(); } catch (error) { toast(error.message, 'error'); } }); button.classList.add('ssh-key-delete'); actions.append(button); row.append(details, actions); container.append(row); }
}
function renderKeyCards(kind) {
const id = kind === 'create' ? 'vm-guest-ssh-key-cards' : 'reinstall-ssh-key-cards'; const container = byId(id); if (!container) return; container.replaceChildren();
if (!state.sshKeys.some(key => String(key.id) === state.selectedKeys[kind])) state.selectedKeys[kind] = '';
for (const key of state.sshKeys) {
const keyId = String(key.id);
const selected = state.selectedKeys[kind] === keyId;
const fingerprint = String(key.fingerprint || '').trim();
const button = makeElement('button', 'ssh-key-option');
button.type = 'button';
button.dataset.keyId = keyId;
button.dataset.keyFingerprint = fingerprint;
button.setAttribute('aria-pressed', String(selected));
button.setAttribute('aria-label', `${selected ? '取消选择' : '选择'} SSH 公钥 ${key.name},指纹 ${fingerprint || '未记录'}`);
const icon = makeElement('i', 'mdi mdi-key-variant ssh-key-choice-icon');
icon.setAttribute('aria-hidden', 'true');
const copy = makeElement('span', 'ssh-key-choice-copy');
const fingerprintLabel = makeElement('small', 'ssh-key-choice-fingerprint', fingerprint || '指纹未记录');
if (fingerprint) fingerprintLabel.title = fingerprint;
copy.append(makeElement('strong', 'ssh-key-choice-label', key.name), fingerprintLabel);
const check = makeElement('span', 'ssh-key-choice-check', '✓');
check.setAttribute('aria-hidden', 'true');
button.append(icon, copy, check);
button.addEventListener('click', () => {
state.selectedKeys[kind] = state.selectedKeys[kind] === keyId ? '' : keyId;
container.querySelectorAll('.ssh-key-option').forEach((option) => {
const optionSelected = option.dataset.keyId === state.selectedKeys[kind];
const optionName = option.querySelector('.ssh-key-choice-label')?.textContent || '';
const optionFingerprint = option.dataset.keyFingerprint || '未记录';
option.setAttribute('aria-pressed', String(optionSelected));
option.setAttribute('aria-label', `${optionSelected ? '取消选择' : '选择'} SSH 公钥 ${optionName},指纹 ${optionFingerprint}`);
});
});
container.append(button);
}
if (!state.sshKeys.length) container.append(makeElement('p', 'muted', '暂无公钥,可先到“公钥管理”添加。'));
}
function flagForCountry(code) {
const normalized = String(code || '').trim().toUpperCase();
if (!/^[A-Z]{2}$/.test(normalized)) return '🌐';
return String.fromCodePoint(...Array.from(normalized, character => 127397 + character.charCodeAt(0)));
}
function saleRegions() {
const regions = [];
const seen = new Set();
for (const region of state.regions) {
const id = String(region?.id ?? '');
if (!/^[1-9]\d*$/.test(id) || seen.has(id)) continue;
seen.add(id);
regions.push({
id,
countryCode: String(region.country_code || '').trim().toUpperCase(),
name: String(region.name || '地区未设置').trim() || '地区未设置',
});
}
return regions;
}
function saleLines(regionId = state.selectedRegionId) {
const lines = [];
const seen = new Set();
for (const line of state.lines) {
const id = String(line?.id ?? '');
if (!/^[1-9]\d*$/.test(id) || seen.has(id)
|| String(line?.region_id ?? '') !== String(regionId)
|| (!state.linesEnabled && line?.is_default !== true)) continue;
seen.add(id);
lines.push({
id,
regionId: String(line.region_id),
name: String(line.name || '线路未设置').trim() || '线路未设置',
isDefault: line.is_default === true,
});
}
return lines;
}
function saleOffers(regionId = state.selectedRegionId, lineId = state.selectedLineId) {
return state.offers.filter(offer => /^[1-9]\d*$/.test(String(offer?.id ?? ''))
&& String(offer?.region_id ?? '') === String(regionId)
&& String(offer?.line_id ?? '') === String(lineId)
&& String(offer?.currency || '').toUpperCase() === 'USD');
}
function isOfferSellable(offer) { return offer?.sellable === true; }
function defaultSaleLine(lines) { return lines.find(line => line.isDefault) || lines[0] || null; }
function applySaleCatalog(catalog) {
state.regions = bootstrapItems(catalog, 'regions');
state.lines = bootstrapItems(catalog, 'lines');
state.offers = bootstrapItems(catalog, 'offers');
state.linesEnabled = catalog?.lines_enabled === true;
const regions = saleRegions();
const requestedRegionId = String(catalog?.default_region_id ?? '');
state.selectedRegionId = regions.some(region => region.id === requestedRegionId)
? requestedRegionId : (regions[0]?.id || '');
const lines = saleLines(state.selectedRegionId);
const requestedLineId = String(catalog?.default_line_id ?? '');
state.selectedLineId = lines.some(line => line.id === requestedLineId)
? requestedLineId : (defaultSaleLine(lines)?.id || '');
byId('vm-region').value = state.selectedRegionId;
byId('vm-line').value = state.selectedLineId;
}
function setDeploymentStepEnabled(id, enabled) {
const step = byId(id);
if (!step) return;
step.classList.toggle('is-disabled', !enabled);
step.setAttribute('aria-disabled', String(!enabled));
}
function updateCreateAvailability() {
const offer = saleOffers().find(item => String(item.id) === byId('vm-offer')?.value);
const validMedia = Boolean(byId('vm-template')?.value);
if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia;
}
function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); }
function formatUsd(value) {
const amount = Number(value);
if (!Number.isFinite(amount) || amount < 0) return '$— USD';
return `$${amount.toFixed(2)} USD`;
}
function formatMemoryGiB(memoryMib) {
const amount = Number(memoryMib);
if (!Number.isFinite(amount) || amount < 0) return '— GB';
return `${(amount / 1024).toLocaleString('en-US', { maximumFractionDigits: 1 })} GB`;
}
function formatTrafficTiB(trafficTiB) {
const amount = Number(trafficTiB);
if (!Number.isFinite(amount) || amount < 0) return '—';
if (amount === 0) return '不限';
return `${amount.toFixed(10).replace(/\.?0+$/, '')} TB`;
}
function resetInstallChoices() {
state.resourceController?.abort();
state.resourceController = null;
state.resources = null;
state.templates = [];
const templateInput = byId('vm-template');
const templateCatalog = byId('vm-template-catalog');
templateInput.value = '';
templateInput.disabled = true;
templateCatalog.removeAttribute('aria-busy');
templateCatalog.replaceChildren();
byId('vm-name').disabled = true;
byId('vm-root-password').disabled = true;
setDeploymentStepEnabled('vm-source-step', false);
setDeploymentStepEnabled('vm-config-step', false);
updateCreateAvailability();
}
function renderRegionPicker() {
const container = byId('vm-region-picker');
const cards = saleRegions().map(region => {
const button = makeElement('button', 'region-option');
button.type = 'button';
button.dataset.regionId = region.id;
button.setAttribute('aria-pressed', String(state.selectedRegionId === region.id));
button.setAttribute('aria-label', `选择地区 ${region.name}`);
button.append(makeElement('span', 'region-flag', flagForCountry(region.countryCode)), makeElement('strong', '', region.name));
button.addEventListener('click', () => void selectRegion(region.id));
return button;
});
if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', '暂无可部署地区,请联系管理员配置在售商品。'));
container.replaceChildren(...cards);
byId('vm-region').value = state.selectedRegionId;
}
function renderLinePicker() {
const container = byId('vm-line-picker');
if (!container) return;
const cards = saleLines().map(line => {
const button = makeElement('button', 'line-option');
button.type = 'button';
button.dataset.lineId = line.id;
button.setAttribute('aria-pressed', String(state.selectedLineId === line.id));
button.setAttribute('aria-label', `选择线路 ${line.name}`);
button.append(makeElement('strong', '', line.name));
button.addEventListener('click', () => void selectLine(line.id));
return button;
});
if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', '当前地区暂无可用线路。'));
container.replaceChildren(...cards);
}
function renderOfferPicker() {
const container = byId('vm-offer-picker');
const offerInput = byId('vm-offer');
let selectedOfferId = offerInput.value;
const offers = saleOffers();
if (!offers.length) {
container.replaceChildren(makeElement('p', 'template-catalog-empty', '当前选择暂无可用实例规格。'));
return;
}
if (!offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))) {
offerInput.value = '';
selectedOfferId = '';
}
const header = makeElement('div', 'offer-table-head');
['名称', 'CPU', '内存', '硬盘', '每期流量', '价格'].forEach(label => header.append(makeElement('span', '', label)));
const rows = offers.map(offer => {
const button = makeElement('button', 'offer-option');
const memory = formatMemoryGiB(offer.memory_mib);
const traffic = formatTrafficTiB(offer.traffic_tib);
const price = formatUsd(offer.price);
const sellable = isOfferSellable(offer);
const name = makeElement('strong', 'offer-option-name', offer.name);
if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄'));
button.type = 'button';
button.dataset.offerId = String(offer.id);
button.classList.toggle('is-sold-out', !sellable);
button.disabled = !sellable;
button.setAttribute('aria-disabled', String(!sellable));
button.setAttribute('aria-pressed', String(sellable && selectedOfferId === String(offer.id)));
button.setAttribute('aria-label', sellable
? `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}`
: `实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price},暂时售罄`);
button.append(
name,
makeElement('span', 'offer-option-value', `${offer.cpu_cores} vCPU`),
makeElement('span', 'offer-option-value', memory),
makeElement('span', 'offer-option-value', `${offer.disk_gib} GB`),
makeElement('span', 'offer-option-value', traffic),
makeElement('strong', 'offer-option-price', price),
);
if (sellable) button.addEventListener('click', () => void selectOffer(String(offer.id)));
return button;
});
container.replaceChildren(header, ...rows);
}
async function selectRegion(regionId) {
if (state.mutationBusy) return;
const normalized = String(regionId || '');
if (!saleRegions().some(region => region.id === normalized)) return;
if (state.selectedRegionId === normalized) return;
state.selectedRegionId = normalized;
state.selectedLineId = defaultSaleLine(saleLines(normalized))?.id || '';
byId('vm-region').value = state.selectedRegionId;
byId('vm-line').value = state.selectedLineId;
byId('vm-offer').value = '';
renderRegionPicker();
renderLinePicker();
renderOfferPicker();
setDeploymentStepEnabled('vm-line-step', state.linesEnabled);
setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId));
showError('create-error', '');
updateCreateAvailability();
}
async function selectLine(lineId) {
if (state.mutationBusy) return;
const line = saleLines().find(item => item.id === String(lineId));
if (!line || state.selectedLineId === line.id) return;
state.selectedLineId = line.id;
byId('vm-line').value = line.id;
byId('vm-offer').value = '';
byId('vm-line-picker')?.querySelectorAll('.line-option').forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.lineId === line.id));
});
renderOfferPicker();
setDeploymentStepEnabled('vm-offer-step', true);
showError('create-error', '');
updateCreateAvailability();
}
async function selectOffer(offerId) {
if (state.mutationBusy) return;
const offer = saleOffers().find(item => String(item.id) === String(offerId));
if (!isOfferSellable(offer)) return;
byId('vm-offer').value = String(offer.id);
byId('vm-offer-picker').querySelectorAll('.offer-option').forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.offerId === String(offer.id)));
});
showError('create-error', '');
updateCreateAvailability();
}
async function openCreate(bootstrap = null) {
state.view = 'create'; state.selectedVmId = null; showError('create-error', '');
byId('vm-offer').value = '';
if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions)
&& Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) {
applySaleCatalog(bootstrap);
state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates');
state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true;
state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys');
state.resources = { templates: state.templates };
state.selectedKeys.create = '';
renderRegionPicker();
renderLinePicker();
renderOfferPicker();
renderTemplateCatalog('vm-template');
renderKeyCards('create');
byId('vm-template').disabled = !state.templates.some(item => item?.id);
byId('vm-name').disabled = false;
byId('vm-root-password').disabled = false;
setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId));
setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId));
setDeploymentStepEnabled('vm-source-step', true);
setDeploymentStepEnabled('vm-config-step', true);
updateCreateAvailability();
return;
}
state.regions = []; state.lines = []; state.offers = []; state.linesEnabled = false;
state.selectedRegionId = ''; state.selectedLineId = '';
byId('vm-region').value = ''; byId('vm-line').value = '';
setDeploymentStepEnabled('vm-line-step', false);
setDeploymentStepEnabled('vm-offer-step', false);
resetInstallChoices();
const results = await Promise.allSettled([
api('/api/v1/catalog').then(catalog => {
applySaleCatalog(catalog);
renderRegionPicker();
renderLinePicker();
renderOfferPicker();
setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId));
setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId));
updateCreateAvailability();
}),
loadKeys(),
loadGlobalTemplates(),
]);
const failure = results.find(result => result.status === 'rejected');
if (failure) showError('create-error', failure.reason?.message || '部署信息加载失败,请刷新页面重试。');
}
async function loadGlobalTemplates() {
state.resourceController?.abort();
const controller = new AbortController();
state.resourceController = controller;
renderTemplateCatalogStatus('vm-template', '正在加载系统镜像…', true);
setDeploymentStepEnabled('vm-source-step', true);
try {
const resources = await api('/api/v1/resources', { signal: controller.signal });
if (controller !== state.resourceController) return;
state.resources = resources;
state.templateCatalogUnavailable = false;
state.templates = items(resources.templates || resources.cloud_templates);
renderTemplateCatalog('vm-template');
byId('vm-template').disabled = !state.templates.some(item => item?.id);
byId('vm-name').disabled = false;
byId('vm-root-password').disabled = false;
setDeploymentStepEnabled('vm-source-step', true);
setDeploymentStepEnabled('vm-config-step', true);
updateCreateAvailability();
} catch (error) {
if (controller === state.resourceController && error.name !== 'AbortError') {
renderTemplateCatalogStatus('vm-template', '系统镜像加载失败,请刷新页面后重试。');
showError('create-error', error.message);
}
throw error;
} finally {
if (controller === state.resourceController) {
state.resourceController = null;
}
}
}
function provisionInvoiceStorageKey() { return `${PROVISION_INVOICE_STORAGE_PREFIX}${state.userId || 'unknown'}`; }
async function provisionInvoiceFingerprint(body) {
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持安全账单核对,请更新浏览器。');
const canonical = {}; for (const key of Object.keys(body).sort()) canonical[key] = body[key];
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(canonical)));
return Array.from(new Uint8Array(digest), value => value.toString(16).padStart(2, '0')).join('');
}
async function pendingProvisionInvoiceKey(fingerprint) {
if (state.provisionIdempotency && state.provisionFingerprint === fingerprint) return state.provisionIdempotency;
let saved = null;
try { saved = JSON.parse(sessionStorage.getItem(provisionInvoiceStorageKey()) || 'null'); } catch {}
let key = saved && saved.fingerprint === fingerprint ? String(saved.key || '') : '';
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
state.provisionIdempotency = key;
state.provisionFingerprint = fingerprint;
try { sessionStorage.setItem(provisionInvoiceStorageKey(), JSON.stringify({ key, fingerprint })); } catch {}
return key;
}
function clearPendingProvisionInvoiceKey() {
state.provisionIdempotency = '';
state.provisionFingerprint = '';
try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } catch {}
}
async function existingProvisionInvoice(key) {
try { return await api(`/api/v1/invoices/by-request/${encodeURIComponent(key)}`); }
catch (error) { if (error.status === 404) return null; throw error; }
}
async function buy(event) {
event.preventDefault(); if (state.mutationBusy) return;
const password = byId('vm-root-password').value;
if (!strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。');
if (!byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
if (!byId('vm-offer').value) return showError('create-error', '请先选择可用实例规格。');
const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value);
if (!selectedOffer) return showError('create-error', '地区、线路与实例规格不匹配,请重新选择。');
if (!isOfferSellable(selectedOffer)) return showError('create-error', '该实例规格暂时售罄,请选择其他规格。');
state.mutationBusy = true;
const formBody = byId('create-form')?.querySelector('.workspace-form-body');
if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); }
byId('create-submit').disabled = true; showError('create-error', '');
const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(), source: 'cloud', template_id: byId('vm-template').value };
if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create;
if (password) body.root_password = password;
try {
const fingerprint = await provisionInvoiceFingerprint(body);
const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint);
body.idempotency_key = invoiceIdempotency;
const recovered = await existingProvisionInvoice(invoiceIdempotency);
const result = recovered || await api('/api/v1/invoices', { method: 'POST', body });
const invoiceId = result?.invoice?.id;
if (!invoiceId) throw new Error('开通账单已生成,但账单编号缺失,请刷新账单页面查看。');
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
navigate(`${CLOUD_PATHS.invoices}/${encodeURIComponent(String(invoiceId))}`);
}
catch (error) {
// A timeout or 409 can mean the first request committed but its response
// was lost. Reconcile by the same durable key before reporting failure.
try {
const invoiceIdempotency = state.provisionIdempotency;
const recovered = invoiceIdempotency ? await existingProvisionInvoice(invoiceIdempotency) : null;
if (recovered) {
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
const invoiceId = recovered?.invoice?.id;
if (!invoiceId) throw new Error('已找到开通账单,但账单编号缺失,请刷新账单页面查看。');
navigate(`${CLOUD_PATHS.invoices}/${encodeURIComponent(String(invoiceId))}`);
return;
}
} catch {}
showError('create-error', `${error.message} 可再次点击提交安全核对同一张账单。`);
}
finally {
delete body.root_password; state.mutationBusy = false;
if (formBody) { formBody.inert = false; formBody.removeAttribute('aria-busy'); }
updateCreateAvailability();
}
}
function clearReinstallPasswordCard(dismissed = false) {
state.reinstallPassword = '';
if (dismissed) state.reinstallPasswordDismissed = true;
const card = byId('reinstall-password-card');
if (!card) return;
card.hidden = true;
const value = byId('reinstall-password-card-value');
if (value) value.textContent = '';
}
function showReinstallPasswordCard(password, generated = true) {
if (state.reinstallPasswordDismissed || typeof password !== 'string' || password === '') return false;
const card = byId('reinstall-password-card');
const value = byId('reinstall-password-card-value');
if (!card || !value) return false;
state.reinstallPassword = password;
state.reinstallPasswordDismissed = false;
value.textContent = password;
text('reinstall-password-card-title', generated ? '重装任务已接收' : '重装密码已接收');
text('reinstall-password-card-message', generated
? '系统已生成本次重装的 root 密码,请先复制保存。'
: '已按你填写的密码提交重装任务,请确认已保存。');
text('reinstall-password-card-note', '密码会在重装成功后生效;关闭此卡片不会取消后台任务。');
card.hidden = false;
card.focus({ preventScroll: true });
return true;
}
async function loadReinstallCredential(vm) {
if (state.reinstallPassword || state.reinstallPasswordDismissed || !vm) return;
try {
const result = await api(`${vmPath(vm)}/credential`, { method: 'POST' });
showReinstallPasswordCard(result?.password, false);
} catch (error) {
toast('重装已完成,但密码暂时无法读取,请到实例详情查看。', 'warning', '密码提示');
}
}
function syncReinstallControls(vm = selectedVm()) {
const allowed = vm?.can_operate === true;
const fields = byId('reinstall-fields');
const submit = byId('reinstall-submit');
if (fields) {
fields.inert = !allowed;
if (allowed) fields.removeAttribute('aria-disabled');
else fields.setAttribute('aria-disabled', 'true');
}
if (submit) submit.disabled = !allowed;
return allowed;
}
function trackReinstallJob(vm, result) {
observeAcceptedTask(result, { title: '重装系统' }, {
onUpdate: () => text('reinstall-phase', '任务正在后台执行,可在任务中心查看结果。'),
onTerminal: task => {
void (async () => {
byId('reinstall-progress').hidden = true;
const refreshed = await loadVm(vm.api_id);
syncReinstallControls(refreshed || selectedVm());
if (taskSucceededWithoutRecovery(task)) {
await loadReinstallCredential(refreshed || vm);
if (state.reinstallPassword) text('reinstall-password-card-note', '重装任务已成功。请将密码保存到安全位置。');
return;
}
const message = taskFailureMessage(task, '重装任务失败。');
showError('reinstall-error', message);
if (state.reinstallPassword) {
if (task.effect_resolution === 'applied') {
text('reinstall-password-card-note', '重装原任务失败,但系统已确认重装已生效,资源锁已解除。请保存密码。');
} else if (task.effect_resolution === 'not_applied') {
text('reinstall-password-card-note', '重装原任务失败,但系统已确认重装未生效,资源锁已解除,可修正设置后重新提交。');
} else {
text('reinstall-password-card-note', task.effect_may_have_applied || task.safe_to_resubmit === false
? '重装任务已失败且资源已锁定。请保存密码、勿重复提交,并联系管理员核查。'
: '重装任务失败,可修正设置后重新提交。');
}
}
toast(message, 'error', '重装任务失败');
})();
},
onStop: reason => {
if (reason === 'pagehide') return;
void (async () => {
byId('reinstall-progress').hidden = true;
const refreshed = await loadVm(vm.api_id);
syncReinstallControls(refreshed || selectedVm());
showError('reinstall-error', '任务自动观察已停止,已按服务端最新状态更新操作入口;请在任务中心查看最终结果。');
})();
},
});
}
async function openReinstall(vm, bootstrap = null) {
state.view = 'reinstall'; state.reinstallPasswordDismissed = false; clearReinstallPasswordCard(); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false;
const currentName = String(vm.name ?? '');
const nameValue = byId('reinstall-confirm-name-value');
const nameInput = byId('reinstall-confirm-name');
const copyName = byId('reinstall-copy-name');
if (nameValue) nameValue.textContent = currentName || '未记录';
const syncNameConfirmation = () => {
const matches = currentName !== '' && nameInput?.value === currentName;
const hasInput = Boolean(nameInput?.value);
nameInput?.classList.toggle('is-match', matches);
nameInput?.classList.toggle('is-mismatch', hasInput && !matches);
};
if (nameInput) nameInput.oninput = syncNameConfirmation;
if (copyName) {
copyName.disabled = !currentName;
copyName.onclick = async () => {
if (!currentName) return;
try { await copyText(currentName); toast('虚拟机名称已复制。', 'success'); }
catch (error) { toast(error.message, 'error'); }
};
}
const passwordCardClose = byId('reinstall-password-card-close');
const passwordCardSaved = byId('reinstall-password-card-saved');
const passwordCardCopy = byId('reinstall-password-card-copy');
if (passwordCardClose) passwordCardClose.onclick = () => clearReinstallPasswordCard(true);
if (passwordCardSaved) passwordCardSaved.onclick = () => clearReinstallPasswordCard(true);
if (passwordCardCopy) {
passwordCardCopy.onclick = async () => {
if (!state.reinstallPassword) return;
try { await copyText(state.reinstallPassword); toast('重装密码已复制,请妥善保存。', 'success'); }
catch (error) { toast(error.message, 'error'); }
};
}
syncNameConfirmation();
if (!vm?.can_operate) {
byId('reinstall-fields').inert = true;
byId('reinstall-fields').setAttribute('aria-disabled', 'true');
byId('reinstall-submit').disabled = true;
showError('reinstall-error', '实例服务已到期或正在执行策略,当前不能重装系统。');
return;
}
byId('reinstall-fields').inert = false;
byId('reinstall-fields').removeAttribute('aria-disabled');
byId('reinstall-submit').disabled = false;
if (bootstrap && Array.isArray(bootstrap.templates)) {
state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates');
state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true;
state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys');
state.selectedKeys.reinstall = '';
renderTemplateCatalog('reinstall-template');
renderKeyCards('reinstall');
return;
}
try { const resources = await api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`); state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('reinstall-template'); await loadKeys(); } catch (error) { showError('reinstall-error', error.message); }
}
async function reinstall(event) {
event.preventDefault(); const vm = selectedVm(); if (!vm || state.mutationBusy) return;
if (byId('reinstall-confirm-name').value !== vm.name) return showError('reinstall-error', '请输入完整虚拟机名称确认。');
const password = byId('reinstall-root-password').value; if (!strongPassword(password)) return showError('reinstall-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。');
const template = byId('reinstall-template').value; if (!template) return showError('reinstall-error', '请选择系统镜像版本。');
state.mutationBusy = true; byId('reinstall-submit').disabled = true;
const body = { template_id: template, confirmation_name: vm.name }; if (state.selectedKeys.reinstall) body.ssh_key_id = state.selectedKeys.reinstall; if (password) body.root_password = password;
let submitted = false;
try {
const result = await api(`${vmPath(vm)}/reinstall`, {
method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true,
});
submitted = true;
showReinstallPasswordCard(password, false);
toast('任务已接收,可在任务中心查看结果。', 'success', '重装系统');
byId('reinstall-root-password').value = '';
byId('reinstall-progress').hidden = false;
text('reinstall-phase', '任务已接收,正在后台执行;你可以离开当前页面。');
byId('reinstall-fields').inert = false;
byId('reinstall-fields').removeAttribute('aria-disabled');
trackReinstallJob(vm, result);
}
catch (error) {
showError('reinstall-error', error.message);
const refreshed = await loadVm(vm.api_id);
syncReinstallControls(refreshed || selectedVm());
}
finally {
delete body.root_password;
state.mutationBusy = false;
if (!submitted) byId('reinstall-progress').hidden = true;
}
}
async function openRescue(vm) { if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); state.view = 'rescue'; text('rescue-subtitle', `${vm.name} · 挂载救援 ISO 并启动救援环境。`); byId('rescue-confirm-name').value = ''; byId('rescue-template-id').value = ''; showError('rescue-error', ''); try { const [resources, status] = await Promise.all([api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`), api(`${vmPath(vm)}/rescue`)]); const container = byId('rescue-template-cards'); container.replaceChildren(); for (const template of items(resources.rescue_templates)) { const button = makeElement('button', 'ssh-key-option', template.name); button.type = 'button'; button.dataset.templateId = String(template.id); button.setAttribute('aria-pressed', 'false'); button.addEventListener('click', () => { byId('rescue-template-id').value = template.id; container.querySelectorAll('button').forEach(item => item.setAttribute('aria-pressed', String(item === button))); }); container.append(button); } if (!container.children.length) container.append(makeElement('p', 'muted', '暂无救援模板,请联系管理员。')); renderRescueStatus(status); } catch (error) { showError('rescue-error', error.message); } }
function renderRescueStatus(status) { state.rescueActive = status.active === true || status.rescue_mode === true; state.rescueStaged = status.staged === true || status.rescue_staged === true; text('rescue-status', status.message || (state.rescueActive ? '当前已进入救援模式。' : state.rescueStaged ? '救援镜像已预挂载,正常关机失败时可以强制冷启动进入救援。' : '尚未挂载救援镜像。')); byId('rescue-force-start').hidden = !state.rescueStaged; byId('rescue-exit').hidden = !state.rescueActive && !state.rescueStaged; }
async function rescueAction(action) {
const vm = selectedVm(); if (!vm || state.mutationBusy) return; if (byId('rescue-confirm-name').value !== vm.name) return showError('rescue-error', '请输入完整虚拟机名称确认。');
if (action === 'load' && !byId('rescue-template-id').value) return showError('rescue-error', '请选择救援模板。');
if (action === 'force-start') {
const confirmed = await requestUserConfirmation({
title: '强制进入救援环境',
message: `实例“${vm.name}”正常关机未成功。继续会强制断电并冷启动进入已挂载的救援环境,未保存的数据可能丢失。`,
confirmText: '强制进入救援',
tone: 'danger',
});
if (!confirmed) return;
}
state.mutationBusy = true; showError('rescue-error', '');
try { const body = { confirmation_name: vm.name }; if (action === 'load') { body.template_id = byId('rescue-template-id').value; body.ack_data_loss = true; } if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true }); const rescueLabels = { load: '救援', 'force-start': '强制进入救援', exit: '退出救援' }; const title = rescueLabels[action] || '救援'; const observer = observeAcceptedTask(result, { title }, { onTerminal: task => { if (!taskSucceededWithoutRecovery(task)) showError('rescue-error', taskFailureMessage(task, `${title}任务失败。`)); void api(`${vmPath(vm)}/rescue`).then(renderRescueStatus).catch(error => showError('rescue-error', error.message)); } }); if (observer) { toast('任务已接收,可在任务中心查看结果。', 'success', title); text('rescue-status', '任务已接收,正在后台执行;你可以离开当前页面。'); } else { showError('rescue-error', '请求已送达,但任务回执协议无效。请勿再次提交,并联系管理员核查。'); } }
catch (error) { showError('rescue-error', error.message); }
finally { state.mutationBusy = false; }
}
function closeConsole() {
state.consoleToken++;
state.rfb?.disconnect();
state.rfb = null;
if (byId('console-modal')) byId('console-modal').hidden = true;
if (byId('console-password-form')) byId('console-password-form').hidden = true;
if (byId('console-password')) byId('console-password').value = '';
if (byId('console-cad')) byId('console-cad').disabled = true;
}
async function openConsole(vm) {
if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error');
closeConsole(); const token = ++state.consoleToken; byId('console-modal').hidden = false; text('console-title', `${vm.name} · 控制台`); text('console-status', '正在申请短期控制台连接…'); const placeholder = byId('console-placeholder'); placeholder.hidden = false;
try { const [ticket, module] = await Promise.all([api(`${vmPath(vm)}/console-ticket`, { method: 'POST' }), import('/cloud/vendor/novnc/core/rfb.js')]); if (token !== state.consoleToken) return; const url = new URL(ticket.websocket_path, location.href); if (url.origin !== location.origin || url.pathname !== '/engine-console' || url.search || url.hash || typeof ticket.ticket !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ticket.ticket)) throw new Error('控制台地址或票据无效。'); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const rfb = new module.default(byId('console-stage'), url.href, { shared: true, wsProtocols: ['cloud-ticket.' + ticket.ticket] }); state.rfb = rfb; rfb.scaleViewport = true; rfb.resizeSession = false; placeholder.hidden = true; rfb.addEventListener('connect', () => { if (state.rfb !== rfb) return; text('console-status', '已连接'); byId('console-cad').disabled = false; }); rfb.addEventListener('disconnect', event => { if (state.rfb !== rfb) return; text('console-status', event.detail?.clean ? '连接已关闭' : '连接已中断,请关闭后重试。'); byId('console-cad').disabled = true; }); rfb.addEventListener('credentialsrequired', () => { if (state.rfb !== rfb) return; byId('console-password-form').hidden = false; byId('console-password').focus(); text('console-status', '请输入 VNC 密码'); }); } catch (error) { if (token === state.consoleToken) { text('console-status', `连接失败:${error.message}`); placeholder.hidden = false; } }
}
function stateCategory(value) {
const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, "");
if (normalized === "running" || normalized === "blocked") return "running";
if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped";
return "other";
}
function stateLabel(value) {
const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, "");
const labels = {
running: "运行中", blocked: "运行中", shutoff: "已关机", stopped: "已关机",
shutdown: "关机中", crashed: "已崩溃", paused: "已暂停", pmsuspended: "已挂起",
nostate: "等待宿主机同步", unknown: "等待宿主机同步",
};
return labels[normalized] || "等待宿主机同步";
}
function detailStateDisplay(vm) {
const transition = powerTransition(vm);
if (transition === 'shutdown') {
return {
label: '关机中', category: 'other', note: '', noteClass: '',
};
}
const sync = String(vm?.state_sync_status || '').toLowerCase();
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) {
return { label: '暂时无法同步', category: 'other', note: '', noteClass: 'offline' };
}
const normalized = String(vm?.state || '').toLowerCase().replace(/[_\s-]+/g, '');
if (['', 'unknown', 'nostate'].includes(normalized) || ['pending', 'never'].includes(sync)) {
const hint = String(vm?.state_label_hint || '').trim()
|| (['creating', 'provisioning', 'deploying'].includes(String(vm?.instance_status || ''))
? '部署中' : '等待宿主机同步');
return { label: hint, category: 'other', note: '', noteClass: '' };
}
const fresh = vm?.state_fresh === true || sync === 'fresh';
return {
label: stateLabel(vm.state),
category: stateCategory(vm.state),
note: fresh ? '' : '状态同步中',
noteClass: fresh ? '' : 'stale',
};
}
function diskLabel(vm) {
if (Array.isArray(vm.disks) && vm.disks.length) {
const size = vm.disks.reduce((sum, disk) => {
const capacity = Number(disk.capacity_gib ?? disk.size_gib ?? 0);
return sum + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0);
}, 0);
if (size > 0) return `${Math.round(size * 100) / 100} GiB`;
}
if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`;
return "—";
}
function vmSystemInfo(vm) {
if (vm.os_source === "iso") return { label: "安装镜像", value: String(vm.install_iso || "未识别") };
if (vm.os_source === "cloud_template") return { label: "系统镜像", value: String(vm.os_name || "未识别") };
return { label: "系统", value: String(vm.os_name || "未识别") };
}
function vmRegion(vm) {
return String(vm.region || "").trim() || "未设置";
}
function vmIp(vm) {
return String(vm.public_ip_cidr || "").trim().split("/")[0] || "未获取";
}
function vmCreatedAt(vm) {
const value = typeof vm.created_at === "string" ? vm.created_at.trim() : "";
if (!value) return "未记录";
const date = new Date(value);
if (!Number.isFinite(date.getTime())) return "未记录";
const pad = (number) => String(number).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function vmCreatedAgo(vm, now = Date.now()) {
const value = typeof vm.created_at === "string" ? vm.created_at.trim() : "";
if (!value) return "未记录";
const created = Date.parse(value);
if (!Number.isFinite(created)) return "未记录";
const elapsed = Math.max(0, now - created);
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const month = 30 * day;
if (elapsed < minute) return "创建于刚刚";
if (elapsed < hour) return `创建于 ${Math.floor(elapsed / minute)} 分钟前`;
if (elapsed < day) return `创建于 ${Math.floor(elapsed / hour)} 小时前`;
if (elapsed < month) return `创建于 ${Math.floor(elapsed / day)} 天前`;
return `创建于 ${Math.floor(elapsed / month)} 个月前`;
}
function makeCell(row, className = "") {
const cell = document.createElement("td");
if (className) cell.className = className;
row.append(cell);
return cell;
}
function makeElement(tag, className, content) {
const element = document.createElement(tag);
if (className) element.className = className;
if (content !== undefined) element.textContent = String(content);
return element;
}
function makeCopyIconButton(value, label) {
const button = makeElement("button", "vm-copy-icon");
button.type = "button";
button.title = `复制${label}`;
button.setAttribute("aria-label", `复制${label}`);
const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
icon.setAttribute("viewBox", "0 0 24 24");
icon.setAttribute("aria-hidden", "true");
const back = document.createElementNS("http://www.w3.org/2000/svg", "rect");
for (const [name, attribute] of Object.entries({ x: "8", y: "8", width: "12", height: "12", rx: "2" })) {
back.setAttribute(name, attribute);
}
const front = document.createElementNS("http://www.w3.org/2000/svg", "path");
front.setAttribute("d", "M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2");
icon.append(back, front);
button.append(icon);
button.addEventListener("click", async () => {
try {
await copyText(value);
toast(`${label}已复制。`, "success");
} catch (error) {
toast(error.message, "error");
}
});
return button;
}
function actionButton(label, handler, options = {}) {
const button = makeElement("button", `row-button ${options.variant || ""}`, label);
button.type = "button";
button.disabled = Boolean(options.disabled);
if (options.key) button.dataset.vmAction = options.key;
if (options.title) button.title = options.title;
button.addEventListener("click", handler);
return button;
}
function renderVMs(connectionError = false) {
const all = state.vms;
const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length;
const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length;
text("stat-total", String(all.length));
text("stat-running", String(runningCount));
text("stat-stopped", String(stoppedCount));
const query = byId("search-input").value.trim().toLocaleLowerCase();
const filter = byId("state-filter").value;
const filtered = all.filter((vm) => {
const matchesText = !query || [vm.name, vm.uuid, vm.public_ip_cidr, vm.region, vm.os_name, vm.install_iso]
.some((value) => String(value || "").toLocaleLowerCase().includes(query));
return matchesText && (filter === "all" || stateCategory(vm.state) === filter);
});
text("inventory-count", `${filtered.length} 台虚拟机${filtered.length !== all.length ? ` · 共 ${all.length} 台` : ""}`);
const tbody = byId("vm-table-body");
const focusedVmId = document.activeElement?.classList.contains("vm-name-link")
? document.activeElement.dataset.vmUuid : null;
tbody.replaceChildren();
const empty = byId("empty-state");
empty.hidden = filtered.length !== 0;
if (!filtered.length) {
if (connectionError) {
text("empty-title", "无法加载虚拟机");
text("empty-description", "请检查面板与宿主机的连接,然后点击刷新。");
} else if (all.length) {
text("empty-title", "没有匹配的虚拟机");
text("empty-description", "尝试更换搜索词或状态筛选。");
} else {
text("empty-title", "还没有虚拟机");
text("empty-description", "点击右上角“部署实例”开始。");
}
return;
}
for (const vm of filtered) {
const uuid = String(vm.uuid || "");
const category = stateCategory(vm.state);
const row = document.createElement("tr");
const identity = makeElement("div", "vm-identity");
identity.append(makeElement("div", "vm-icon", "▣"));
const identityText = makeElement("div");
const nameLink = makeElement("a", "vm-name-link", vm.name || "未命名虚拟机");
nameLink.href = vmPagePath(vm.api_id);
nameLink.dataset.vmUuid = uuid;
nameLink.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`);
identityText.append(nameLink);
const uuidRow = makeElement("span", "vm-uuid-row");
const uuidText = makeElement("span", "vm-id", uuid || "UUID 未知");
if (uuid) uuidText.title = uuid;
uuidRow.append(uuidText);
if (uuid) uuidRow.append(makeCopyIconButton(uuid, "UUID"));
identityText.append(uuidRow);
identity.append(identityText);
const identityCell = makeCell(row);
identityCell.dataset.label = "虚拟机";
identityCell.append(identity);
const stateCell = makeCell(row);
stateCell.dataset.label = "状态";
stateCell.append(makeElement("span", `state-pill ${category}`, stateLabel(vm.state)));
const regionCell = makeCell(row);
regionCell.dataset.label = "地区";
regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm)));
const system = vmSystemInfo(vm);
const systemCell = makeCell(row);
systemCell.dataset.label = system.label;
systemCell.append(makeElement("span", "vm-metadata", system.value));
const ipCell = makeCell(row);
ipCell.dataset.label = "已配置公网 IP";
const ip = vmIp(vm);
const ipRow = makeElement("span", "vm-ip-copy-row");
ipRow.append(makeElement("span", "vm-metadata vm-ip", ip));
if (ip !== "未获取") ipRow.append(makeCopyIconButton(ip, "公网 IP"));
ipCell.append(ipRow);
const spec = makeElement("div", "vm-spec");
spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`));
spec.append(makeElement("small", "", "计算资源"));
const specCell = makeCell(row);
specCell.dataset.label = "规格";
specCell.append(spec);
const diskCell = makeCell(row);
diskCell.dataset.label = "磁盘";
diskCell.append(makeElement("span", "vm-spec", diskLabel(vm)));
tbody.append(row);
}
if (focusedVmId) {
const replacement = Array.from(tbody.querySelectorAll(".vm-name-link"))
.find((button) => button.dataset.vmUuid === focusedVmId);
replacement?.focus({ preventScroll: true });
}
}
const VM_METRICS_RANGE_SECONDS = { "1h": 3600, "24h": 86400, "7d": 604800, "30d": 2592000 };
const VM_METRIC_CHARTS = [
{ id: "cpu", title: "CPU 使用率", unit: "percent", series: [{ key: "cpu_percent", color: "#0f9eaa" }] },
{ id: "memory", title: "内存用量", unit: "memory", series: [{ key: "memory_used_mib", color: "#4781cf" }, { key: "memory_total_mib", color: "#a4b7d7", dash: "6 5" }] },
{ id: "disk", title: "磁盘 I/O", unit: "rate", series: [{ key: "disk_read_bps", color: "#477dc9" }, { key: "disk_write_bps", color: "#e59c46" }] },
{ id: "network", title: "网络速率", unit: "rate", series: [{ key: "network_rx_bps", color: "#17a685" }, { key: "network_tx_bps", color: "#926ed0" }] },
];
let metricsLoopActive = false;
function metricViewVisible() {
return state.view === "detail" && state.detailTab === "performance" && Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden
&& !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden;
}
function stopVmMetrics() {
metricsLoopActive = false;
if (state.metricsPollTimer) window.clearTimeout(state.metricsPollTimer);
state.metricsPollTimer = null;
if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer);
state.metricsResizeTimer = null;
state.metricsRequest?.controller.abort();
state.metricsRequest = null;
}
async function runVmMetricsLoop() {
if (!metricsLoopActive || !metricViewVisible()) return;
await loadVmMetrics();
if (!metricsLoopActive || !metricViewVisible() || state.metricsPollTimer) return;
state.metricsPollTimer = window.setTimeout(() => {
state.metricsPollTimer = null;
void runVmMetricsLoop();
}, 60000);
}
function startVmMetrics() {
if (!metricViewVisible() || metricsLoopActive) return;
metricsLoopActive = true;
void runVmMetricsLoop();
}
function setVmMetricsStatus(message, warning = false) {
const status = byId("vm-metrics-status");
status.textContent = message;
status.classList.toggle("warning", warning);
}
function clearVmMetrics(message) {
state.metricsPayload = null;
setVmMetricsStatus(message);
for (const chart of VM_METRIC_CHARTS) {
text(`vm-metric-${chart.id}-summary`, "—");
byId(`vm-metric-${chart.id}-plot`).replaceChildren(makeElement("p", "vm-metric-empty", message));
}
}
async function loadVmMetrics() {
if (!metricViewVisible()) return;
const vmId = state.selectedVmId;
const range = state.metricsRange;
const previous = state.metricsRequest;
if (previous?.vmId === vmId && previous.range === range) return;
previous?.controller.abort();
const request = { vmId, range, controller: new AbortController() };
state.metricsRequest = request;
setVmMetricsStatus("正在更新性能数据…");
try {
const payload = await api(`${vmPath()}/metrics?range=${encodeURIComponent(range)}`, {
signal: request.controller.signal,
});
if (request !== state.metricsRequest || !metricViewVisible()) return;
if (!Array.isArray(payload?.points)) {
throw new Error("性能数据格式无效。");
}
renderVmMetrics(payload);
} catch (error) {
if (request !== state.metricsRequest || request.controller.signal.aborted || !metricViewVisible()) return;
setVmMetricsStatus(`性能数据暂时无法加载:${error.message}。已显示的数据可能不是最新。`, true);
} finally {
if (request === state.metricsRequest) state.metricsRequest = null;
}
}
function metricNumber(value) {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
}
function formatMetricRate(value) {
if (value === null) return "无统计";
const units = ["B/s", "KB/s", "MB/s", "GB/s", "TB/s"];
let amount = value;
let index = 0;
while (amount >= 1000 && index < units.length - 1) { amount /= 1000; index += 1; }
return `${amount.toFixed(index === 0 ? (amount < 1 && amount > 0 ? 2 : 0) : amount < 10 ? 2 : 1)} ${units[index]}`;
}
function formatMetricMemory(value) {
if (value === null) return "无统计";
return value >= 1024 ? `${(value / 1024).toFixed(value < 10240 ? 2 : 1)} GiB` : `${Math.round(value)} MiB`;
}
function formatMetricValue(value, unit) {
if (value === null) return "无统计";
if (unit === "percent") return `${value.toFixed(1)}%`;
if (unit === "memory") return formatMetricMemory(value);
return formatMetricRate(value);
}
function formatMetricTime(timestamp) {
return new Date(timestamp * 1000).toLocaleString("zh-CN", {
month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit",
});
}
function metricSummary(chart, points) {
const latest = [...points].reverse().find((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null));
if (!latest) return "暂无统计";
const value = (key) => metricNumber(latest[key]);
if (chart.id === "cpu") return formatMetricValue(value("cpu_percent"), "percent");
if (chart.id === "memory") return `已使用(估算)${formatMetricMemory(value("memory_used_mib"))} · 总量 ${formatMetricMemory(value("memory_total_mib"))}`;
if (chart.id === "disk") return `读取 ${formatMetricRate(value("disk_read_bps"))} · 写入 ${formatMetricRate(value("disk_write_bps"))}`;
return `接收 ${formatMetricRate(value("network_rx_bps"))} · 发送 ${formatMetricRate(value("network_tx_bps"))}`;
}
function metricChartEmptyText(chart) {
if (chart.id === "memory") return "暂无内存统计;虚拟机可能未提供气球驱动数据。";
if (chart.id === "disk" || chart.id === "network") return "暂无速率数据;首次采样或停机时无法计算速率。";
return "当前时间范围内暂无 CPU 采样数据。";
}
function metricNiceMax(value) {
if (value <= 0) return 1;
const base = 10 ** Math.floor(Math.log10(value));
for (const step of [1, 1.5, 2, 2.5, 5, 10]) {
if (value <= step * base) return step * base;
}
return 10 * base;
}
function metricSvgElement(tag, attributes = {}) {
const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value));
return element;
}
function drawMetricChart(chart, points, start, end, intervalSeconds) {
const plot = byId(`vm-metric-${chart.id}-plot`);
const summary = metricSummary(chart, points);
text(`vm-metric-${chart.id}-summary`, summary);
const hasData = points.some((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null));
if (!hasData) {
plot.replaceChildren(makeElement("p", "vm-metric-empty", metricChartEmptyText(chart)));
return;
}
const values = points.flatMap((point) => chart.series.map((series) => metricNumber(point[series.key]))).filter((value) => value !== null);
const maximum = chart.unit === "percent" ? Math.max(100, metricNiceMax(Math.max(...values))) : metricNiceMax(Math.max(...values));
// A fixed 640px viewBox shrinks axis text to ~4px inside a phone card.
const width = Math.max(240, Math.floor(plot.clientWidth || 640));
const height = Math.max(180, Math.floor(plot.clientHeight || 216));
const left = 64;
const right = 18;
const top = 14;
const bottom = 37;
const plotWidth = width - left - right;
const plotHeight = height - top - bottom;
const x = (timestamp) => left + Math.max(0, Math.min(1, (timestamp - start) / (end - start))) * plotWidth;
const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight;
const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": `${chart.title},${byId("vm-metrics-range").selectedOptions[0]?.textContent || "当前范围"};最近记录:${summary}` });
for (const fraction of [1, 0.5, 0]) {
const lineY = top + (1 - fraction) * plotHeight;
svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" }));
const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" });
label.textContent = formatMetricValue(fraction * maximum, chart.unit);
svg.append(label);
}
for (const [fraction, anchor] of [[0, "start"], [0.5, "middle"], [1, "end"]]) {
const label = metricSvgElement("text", { x: left + fraction * plotWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" });
label.textContent = formatMetricTime(start + fraction * (end - start));
svg.append(label);
}
const maxGap = intervalSeconds * 2.5;
for (const series of chart.series) {
const segments = [];
let segment = [];
for (const point of points) {
const value = metricNumber(point[series.key]);
if (value === null) {
if (segment.length) segments.push(segment);
segment = [];
continue;
}
if (segment.length && point.timestamp - segment[segment.length - 1].timestamp > maxGap) {
segments.push(segment);
segment = [];
}
segment.push({ timestamp: point.timestamp, value });
}
if (segment.length) segments.push(segment);
for (const group of segments) {
if (group.length > 1) {
const path = metricSvgElement("path", {
d: group.map((point, index) => `${index ? "L" : "M"}${x(point.timestamp).toFixed(2)} ${y(point.value).toFixed(2)}`).join(" "),
fill: "none", stroke: series.color, "stroke-width": 2.6,
"stroke-linecap": "round", "stroke-linejoin": "round",
...(series.dash ? { "stroke-dasharray": series.dash } : {}),
});
svg.append(path);
}
const last = group[group.length - 1];
svg.append(metricSvgElement("circle", { cx: x(last.timestamp), cy: y(last.value), r: group.length === 1 ? 3.8 : 2.8, fill: series.color }));
}
}
plot.replaceChildren(svg);
}
function renderVmMetrics(payload) {
state.metricsPayload = payload;
const intervalSeconds = Math.max(1, Number(payload.interval_seconds) || 60);
const rangeSeconds = VM_METRICS_RANGE_SECONDS[state.metricsRange];
const now = Math.floor(Date.now() / 1000);
const points = payload.points
.filter((point) => Number.isFinite(Number(point?.timestamp)) && Number(point.timestamp) >= now - rangeSeconds - intervalSeconds && Number(point.timestamp) <= now + intervalSeconds)
.map((point) => ({ ...point, timestamp: Number(point.timestamp) }))
.sort((a, b) => a.timestamp - b.timestamp);
const end = Math.max(now, points.length ? points[points.length - 1].timestamp : now);
const start = end - rangeSeconds;
const visiblePoints = points.filter((point) => point.timestamp >= start && point.timestamp <= end);
for (const chart of VM_METRIC_CHARTS) drawMetricChart(chart, visiblePoints, start, end, intervalSeconds);
if (!visiblePoints.length) {
setVmMetricsStatus("当前时间范围内没有采样记录。虚拟机运行后,通常需等待下一次后台采样。", true);
return;
}
const latest = visiblePoints[visiblePoints.length - 1].timestamp;
// Bucket width grows for long ranges; freshness still follows the 60s
// collector cadence, not the downsampling bucket width.
const stale = end - latest > 60 * 2.5;
setVmMetricsStatus(`${visiblePoints.length} 个采样点 · ${stale ? "最近历史记录" : "最近采样"} ${formatMetricTime(latest)} · 每分钟自动刷新${stale ? "(当前无新数据)" : ""}`, stale);
}
function trafficDailyViewVisible() {
return state.view === "detail" && state.detailTab === "performance" && Boolean(state.selectedVmId) && !document.hidden
&& !byId("dashboard-view").hidden && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden;
}
function stopVmTrafficDaily() {
state.trafficDailyRequest?.controller.abort();
state.trafficDailyRequest = null;
if (state.trafficDailyResizeTimer) window.clearTimeout(state.trafficDailyResizeTimer);
state.trafficDailyResizeTimer = null;
}
function setVmTrafficDailyStatus(message, warning = false) {
const status = byId("vm-traffic-daily-status");
status.textContent = message;
status.classList.toggle("warning", warning);
}
function clearVmTrafficDaily(message) {
stopVmTrafficDaily();
state.trafficDailyPayload = null;
state.trafficDailyVmId = "";
state.trafficDailyLoadedAt = 0;
setVmTrafficDailyStatus(message);
byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", message));
}
function trafficDailyItems(payload) {
if (Array.isArray(payload)) return payload;
for (const value of [payload?.points, payload?.days, payload?.items, payload?.daily, payload?.data?.points, payload?.data?.days, payload?.data]) {
if (Array.isArray(value)) return value;
}
return null;
}
function trafficDailyDate(point) {
const value = point?.date ?? point?.day ?? point?.bucket_date ?? point?.observed_date ?? point?.day_start ?? point?.timestamp ?? point?.time;
const dateText = typeof value === "string" ? value.trim() : "";
if (/^\d{4}-\d{2}-\d{2}$/.test(dateText)) {
return { timestamp: Date.parse(`${dateText}T00:00:00Z`), label: dateText };
}
const timestamp = serviceTimestamp(value);
if (timestamp === null) return null;
const date = new Date(timestamp);
return { timestamp, label: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}` };
}
function normalizeTrafficDailyPoints(payload) {
const values = trafficDailyItems(payload);
if (values === null) throw new Error("每日流量数据格式无效");
const points = [];
for (const point of values) {
const date = trafficDailyDate(point);
if (!date) continue;
const download = firstNumber(point?.download_bytes, point?.rx_bytes, point?.traffic_download_bytes, point?.download, point?.rx);
const upload = firstNumber(point?.upload_bytes, point?.tx_bytes, point?.traffic_upload_bytes, point?.upload, point?.tx);
points.push({ ...date, download, upload });
}
return points.sort((a, b) => a.timestamp - b.timestamp).slice(-30);
}
function trafficDailyShortDate(point) {
return point.label.slice(5).replace("-", "/");
}
function drawVmTrafficDaily(payload) {
const plot = byId("vm-traffic-daily-plot");
const points = normalizeTrafficDailyPoints(payload);
if (!points.length) {
plot.replaceChildren(makeElement("p", "vm-metric-empty", "最近 30 天暂无每日流量记录。"));
setVmTrafficDailyStatus("最近 30 天暂无每日流量记录。", true);
return;
}
const values = points.flatMap(point => [point.download, point.upload]).filter(value => value !== null);
if (!values.length) {
plot.replaceChildren(makeElement("p", "vm-metric-empty", "最近 30 天暂无每日流量采样。"));
setVmTrafficDailyStatus("最近 30 天暂无每日流量采样。", true);
return;
}
const maximum = metricNiceMax(Math.max(...values));
const width = Math.max(300, Math.floor(plot.clientWidth || 800));
const height = Math.max(220, Math.floor(plot.clientHeight || 290));
const left = 68;
const right = 18;
const top = 18;
const bottom = 38;
const plotWidth = width - left - right;
const plotHeight = height - top - bottom;
const groupWidth = plotWidth / points.length;
const barWidth = Math.max(2, Math.min(12, groupWidth * .32));
const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight;
const totalDownload = points.reduce((sum, point) => sum + (point.download ?? 0), 0);
const totalUpload = points.reduce((sum, point) => sum + (point.upload ?? 0), 0);
const sampledDays = points.filter(point => point.download !== null || point.upload !== null).length;
const svg = metricSvgElement("svg", {
viewBox: `0 0 ${width} ${height}`,
role: "img",
"aria-label": `最近 ${points.length} 天每日流量;下载 ${formatBytes(totalDownload)},上传 ${formatBytes(totalUpload)}`,
});
for (const fraction of [1, .5, 0]) {
const lineY = top + (1 - fraction) * plotHeight;
svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" }));
const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" });
label.textContent = formatBytes(fraction * maximum);
svg.append(label);
}
points.forEach((point, index) => {
const center = left + (index + .5) * groupWidth;
for (const [value, className, offset] of [[point.download, "download", -barWidth], [point.upload, "upload", 0]]) {
if (value === null) continue;
const topY = y(value);
const bar = metricSvgElement("rect", {
x: center + offset,
y: topY,
width: barWidth,
height: Math.max(1, top + plotHeight - topY),
rx: Math.min(2, barWidth / 3),
class: `vm-traffic-daily-bar ${className}`,
});
const title = metricSvgElement("title");
title.textContent = `${point.label} ${className === "download" ? "下载" : "上传"} ${formatBytes(value)}`;
bar.append(title);
svg.append(bar);
}
});
const labelIndexes = [...new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])];
for (const index of labelIndexes) {
const anchor = index === 0 ? "start" : index === points.length - 1 ? "end" : "middle";
const label = metricSvgElement("text", { x: left + (index + .5) * groupWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" });
label.textContent = trafficDailyShortDate(points[index]);
svg.append(label);
}
plot.replaceChildren(svg);
setVmTrafficDailyStatus(`最近 ${points.length} 天 · ${sampledDays} 天有采样 · 下载 ${formatBytes(totalDownload)} · 上传 ${formatBytes(totalUpload)}`);
}
async function loadVmTrafficDaily(force = false) {
if (!trafficDailyViewVisible()) return;
const vmId = state.selectedVmId;
if (!force && state.trafficDailyPayload && state.trafficDailyVmId === vmId
&& Date.now() - state.trafficDailyLoadedAt < 60000) return;
if (state.trafficDailyRequest?.vmId === vmId) return;
state.trafficDailyRequest?.controller.abort();
const request = { vmId, controller: new AbortController() };
state.trafficDailyRequest = request;
setVmTrafficDailyStatus("正在加载最近 30 天每日流量…");
try {
const payload = await api(`${vmPath()}/traffic/daily?days=30`, { signal: request.controller.signal });
if (request !== state.trafficDailyRequest || !trafficDailyViewVisible()) return;
state.trafficDailyPayload = payload;
state.trafficDailyVmId = vmId;
state.trafficDailyLoadedAt = Date.now();
drawVmTrafficDaily(payload);
} catch (error) {
if (request !== state.trafficDailyRequest || request.controller.signal.aborted || !trafficDailyViewVisible()) return;
setVmTrafficDailyStatus(`每日流量暂时无法加载:${error.message}。`, true);
if (!state.trafficDailyPayload || state.trafficDailyVmId !== vmId) {
byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", "每日流量暂时无法加载。"));
}
} finally {
if (request === state.trafficDailyRequest) state.trafficDailyRequest = null;
}
}
function startVmTrafficDaily() {
if (!trafficDailyViewVisible()) return;
if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId) drawVmTrafficDaily(state.trafficDailyPayload);
void loadVmTrafficDaily();
}
const TEMPLATE_FAMILY_NAMES = {
almalinux: "AlmaLinux",
debian: "Debian",
centos: "CentOS Stream",
centosstream: "CentOS Stream",
ubuntu: "Ubuntu",
};
const TEMPLATE_ICON_PATHS = {
AlmaLinux: "/cloud/almalinux-icon.svg",
Debian: "/cloud/debian-icon.svg",
"CentOS Stream": "/cloud/centos-icon.svg",
Ubuntu: "/cloud/ubuntu-icon.svg",
};
const TEMPLATE_FAMILY_ORDER = new Map([
["AlmaLinux", 0], ["Debian", 1], ["CentOS Stream", 2], ["Ubuntu", 3],
]);
function compareTemplateVersions(left, right) {
const leftParts = String(left || "0").split(".").map((part) => Number(part) || 0);
const rightParts = String(right || "0").split(".").map((part) => Number(part) || 0);
const length = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < length; index += 1) {
const difference = (leftParts[index] || 0) - (rightParts[index] || 0);
if (difference) return difference;
}
return 0;
}
function templateSystem(item) {
const id = String(item?.id || "");
const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, "");
const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey)
? TEMPLATE_FAMILY_NAMES[familyKey] : "";
const idMatch = /^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/.exec(id);
const idFamily = ({ alma: "AlmaLinux", debian: "Debian", ubuntu: "Ubuntu", centosstream: "CentOS Stream" })[idMatch?.[1]] || "";
const rawIdVersion = idMatch?.[2] || "";
const idVersion = idMatch?.[1] === "ubuntu" && rawIdVersion.length === 4
? `${rawIdVersion.slice(0, 2)}.${rawIdVersion.slice(2)}` : rawIdVersion;
const family = namedFamily || idFamily || "其他系统";
const providedVersion = String(item?.os_version || "");
const version = /^[0-9]+(?:\.[0-9]+){0,2}$/.test(providedVersion) ? providedVersion : idVersion;
return { family, version };
}
function templateIcon(family, className) {
const logoPath = TEMPLATE_ICON_PATHS[family];
const icon = makeElement("span", `${className}${logoPath ? " system" : ""}`);
icon.setAttribute("aria-hidden", "true");
if (logoPath) {
const logo = makeElement("img", "template-system-logo");
logo.src = logoPath;
logo.alt = "";
icon.append(logo);
} else {
icon.textContent = "◈";
}
return icon;
}
function renderTemplateCatalogStatus(inputId, message, busy = false) {
const input = byId(inputId);
const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog");
if (!input || !container) return;
input.value = "";
input.disabled = true;
container.setAttribute("aria-busy", String(busy));
const status = makeElement("p", "template-catalog-status", message);
status.setAttribute("role", "status");
container.replaceChildren(status);
}
function closeTemplateVersionMenus(except = null) {
document.querySelectorAll(".template-family-card[open]").forEach((card) => {
if (card !== except) card.open = false;
});
}
function bindTemplateVersionMenu(card, container) {
card.addEventListener("toggle", () => {
const family = String(card.dataset.family || "系统镜像");
const summary = card.querySelector("summary");
const selection = card.querySelector(".template-family-selection");
if (!card.open) {
const selectedName = String(selection?.title || "");
summary?.setAttribute("aria-label", selectedName
? `${family},已选择 ${selectedName},展开更改版本`
: `${family},展开选择版本`);
return;
}
summary?.setAttribute("aria-label", `${family},收起版本列表`);
container.querySelectorAll(".template-family-card[open]").forEach((other) => {
if (other !== card) other.open = false;
});
requestAnimationFrame(() => {
if (!card.open) return;
const option = card.querySelector('.template-version-option[aria-pressed="true"]')
|| card.querySelector(".template-version-option");
option?.focus({ preventScroll: true });
});
});
}
function updateTemplateFamilySelection(card, selectedName = "", selectedVersion = "") {
const family = String(card.dataset.family || "系统镜像");
const summary = card.querySelector("summary");
const label = card.querySelector(".template-family-selection");
const selected = Boolean(selectedName);
const fallbackVersion = String(selectedName).startsWith(family)
? String(selectedName).slice(family.length).replace(/^[-_\s]+/, "")
: String(selectedName);
const versionLabel = String(selectedVersion || fallbackVersion).trim();
card.classList.toggle("has-selection", selected);
if (label) {
label.textContent = selected ? versionLabel : "";
label.title = selected ? selectedName : "";
}
summary?.setAttribute("aria-label", selected
? `${family},已选择 ${selectedName},展开更改版本`
: `${family},展开选择版本`);
}
function renderTemplateCatalog(inputId) {
const input = byId(inputId);
const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog");
container.removeAttribute("aria-busy");
const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family));
const groups = new Map();
for (const item of state.templates) {
if (!item?.id) continue;
const { family, version } = templateSystem(item);
if (!groups.has(family)) groups.set(family, []);
groups.get(family).push({ item, version });
}
if (!groups.size) {
input.value = "";
container.replaceChildren(makeElement("p", "template-catalog-empty",
state.templateCatalogUnavailable
? "系统镜像目录暂时无法读取,请稍后刷新。"
: state.admin
? "暂无云镜像,请先到“云镜像模板”页面导入。"
: "暂无可用云镜像,请联系管理员导入模板。"));
return;
}
if (!state.templates.some((item) => String(item.id) === input.value)) input.value = "";
const cards = [];
const orderedGroups = Array.from(groups.entries()).sort(([left], [right]) =>
(TEMPLATE_FAMILY_ORDER.get(left) ?? 100) - (TEMPLATE_FAMILY_ORDER.get(right) ?? 100)
|| left.localeCompare(right, "zh-CN"));
for (const [family, entries] of orderedGroups) {
entries.sort((a, b) => compareTemplateVersions(b.version, a.version)
|| String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN"));
const card = makeElement("details", "template-family-card");
card.dataset.family = family;
card.setAttribute("name", `${inputId}-family`);
card.open = opened.has(family);
bindTemplateVersionMenu(card, container);
const summary = makeElement("summary", "template-family-summary");
const selectedMark = makeElement("span", "template-family-selected-mark", "✓");
selectedMark.setAttribute("aria-hidden", "true");
const icon = templateIcon(family, "template-family-icon");
const selection = makeElement("span", "template-family-selection");
selection.setAttribute("aria-hidden", "true");
const arrow = makeElement("span", "template-family-arrow");
arrow.setAttribute("aria-hidden", "true");
const footer = makeElement("span", "template-family-footer");
footer.append(selection, arrow);
summary.append(selectedMark, icon, makeElement("strong", "", family), footer);
const versions = makeElement("div", "template-versions");
versions.setAttribute("role", "group");
versions.setAttribute("aria-label", `${family} 可用版本`);
for (const { item, version } of entries) {
const id = String(item.id);
const name = String(item.name || id);
const option = makeElement("button", "template-version-option");
option.type = "button";
option.dataset.templateId = id;
option.setAttribute("aria-pressed", String(input.value === id));
option.setAttribute("aria-label", `选择模板 ${name}`);
option.append(makeElement("strong", "", name));
option.addEventListener("click", () => {
input.value = id;
container.querySelectorAll(".template-version-option").forEach((button) => {
button.setAttribute("aria-pressed", String(button.dataset.templateId === id));
});
container.querySelectorAll(".template-family-card").forEach((familyCard) => {
updateTemplateFamilySelection(familyCard,
familyCard === card ? name : "", familyCard === card ? version : "");
});
card.open = false;
summary.focus({ preventScroll: true });
if (inputId === "vm-template") { showError("create-error", ""); updateCreateAvailability(); }
else showError("reinstall-error", "");
});
versions.append(option);
}
card.append(summary, versions);
const selectedEntry = entries.find(({ item }) => String(item.id) === input.value);
updateTemplateFamilySelection(card,
selectedEntry ? String(selectedEntry.item.name || selectedEntry.item.id) : "",
selectedEntry?.version || "");
cards.push(card);
}
container.replaceChildren(...cards);
}
document.addEventListener("click", (event) => {
if (!(event.target instanceof Element) || !event.target.closest(".template-family-card")) {
closeTemplateVersionMenus();
}
});
document.addEventListener("focusin", (event) => {
const openCard = document.querySelector(".template-family-card[open]");
if (!openCard || (event.target instanceof Element && openCard.contains(event.target))) return;
closeTemplateVersionMenus();
});
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
const openCard = document.querySelector(".template-family-card[open]");
if (!openCard) return;
closeTemplateVersionMenus();
openCard.querySelector("summary")?.focus({ preventScroll: true });
});
async function initializeSession(view, bootstrapUser = null) {
state.view = view;
if (bootstrapUser && typeof bootstrapUser === 'object') {
if (bootstrapUser.authenticated === false) { location.assign('/auth/login'); return false; }
applyCloudUser(bootstrapUser);
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
return true;
}
const session = await api('/api/v1/session');
if (session.authenticated === false) { location.assign('/auth/login'); return false; }
applyCloudUser(session);
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
return true;
}
async function selectVmByApiId(apiId, bootstrapVm = null) {
if (bootstrapVm && typeof bootstrapVm === 'object') {
const vm = normalizeVm(bootstrapVm);
if (!vm.api_id || String(vm.api_id) !== String(apiId || '')) throw new Error('实例初始数据与当前地址不匹配,请刷新后重试。');
state.vms = [vm];
state.selectedVmId = vm.uuid;
return vm;
}
const vm = await loadVm(apiId, true);
if (!vm) throw new Error('虚拟机不存在或当前账户无权访问。');
return vm;
}
function bindPageCleanup() {
window.addEventListener('pagehide', () => {
clearCredential();
clearReinstallPasswordCard();
stopVmMetrics();
stopVmTrafficDaily();
closeConsole();
state.resourceController?.abort();
vmStatusGeneration += 1;
vmStatusRequest?.controller.abort();
vmStatusRequest = null;
for (const observer of activeTaskObservers) observer.stop('pagehide');
activeTaskObservers.clear();
});
}
export {
CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential,
clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential,
drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession,
loadGlobalTemplates, loadKeys, loadVmMetrics, loadVmTrafficDaily,
loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall,
readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm,
setVmDetailTab, showError, state, stopVmMetrics,
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,
vmPagePath,
};