|
|
// PHP owns authentication, authorisation, ownership and purchasing. No engine
|
|
|
// address, token, host credential or unrestricted create API exists in this UI.
|
|
|
const byId = (id) => document.getElementById(id);
|
|
|
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), 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, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
|
|
|
// Keep the historical storage key so an interrupted deployment made just
|
|
|
// before an online update can still reconcile to the same opening invoice.
|
|
|
const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
|
|
|
const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:';
|
|
|
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
|
|
|
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
|
|
|
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
|
|
|
let toastTimer;
|
|
|
function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); }
|
|
|
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 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, { ...options, 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; }
|
|
|
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 periodEndsAt = vm?.current_period_ends_at ?? vm?.current_period_end ?? service.current_period_ends_at ?? service.current_period_end ?? period.ends_at ?? period.end_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, periodEndsAt, 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.periodEndsAt) !== null) status = serviceTimestamp(data.periodEndsAt) <= 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_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; text('vm-detail-root-password', '********'); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'false'); }
|
|
|
const VM_DETAIL_TABS = ['operations', 'performance', 'traffic'];
|
|
|
function setVmDetailTab(tab, focus = false) {
|
|
|
const next = VM_DETAIL_TABS.includes(tab) ? tab : '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();
|
|
|
if (next === 'traffic') startVmTrafficDaily();
|
|
|
}
|
|
|
if (focus) byId(`vm-detail-tab-${next}`).focus();
|
|
|
}
|
|
|
function showView(view) {
|
|
|
clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); state.view = view;
|
|
|
if (view !== 'invoices' && state.invoicePollTimers.size) stopInvoicePoll();
|
|
|
byId('vm-workspace').hidden = ['keys', 'invoices'].includes(view);
|
|
|
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('invoices-workspace').hidden = view !== 'invoices';
|
|
|
const sections = { list: 'vm-list-view', detail: 'vm-detail-view', create: 'create-view', reinstall: 'reinstall-view', rescue: 'rescue-view' };
|
|
|
for (const [name, id] of Object.entries(sections)) byId(id).hidden = view !== name;
|
|
|
const navigationView = ['detail', 'reinstall', 'rescue'].includes(view) ? 'list' : view;
|
|
|
document.querySelectorAll('[data-view]').forEach(button => {
|
|
|
const active = button.dataset.view === navigationView;
|
|
|
button.classList.toggle('active', active);
|
|
|
if (active) button.setAttribute('aria-current', 'page');
|
|
|
else button.removeAttribute('aria-current');
|
|
|
});
|
|
|
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', invoices: '账单信息' })[view]);
|
|
|
const hash = ({ list: '', create: 'plans', keys: 'keys', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
|
|
|
history.replaceState(null, '', `${location.pathname}${location.search}${hash ? '#' + hash : ''}`);
|
|
|
window.scrollTo({ top: 0, behavior: 'auto' });
|
|
|
if (view === 'detail') setVmDetailTab(state.detailTab);
|
|
|
}
|
|
|
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders' || target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
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', ''); renderVMs(); const vm = selectedVm(); if (vm && state.view === 'detail') renderVmDetail(vm); else if (!vm && ['detail', 'reinstall', 'rescue'].includes(state.view)) showView('list'); }
|
|
|
catch (error) { showError('cloud-page-error', error.message); if (!state.vms.length) renderVMs(true); }
|
|
|
finally { state.loadingVMs = false; }
|
|
|
}
|
|
|
function openVmDetail(uuid) { const vm = state.vms.find(item => item.uuid === String(uuid)); if (!vm) return toast('虚拟机不存在,请刷新。', 'error'); state.selectedVmId = vm.uuid; state.detailTab = 'operations'; clearVmMetrics('打开“性能监控”页签后加载监控数据。'); clearVmTrafficDaily('打开“流量信息”页签后加载最近 30 天数据。'); renderVmDetail(vm); showView('detail'); }
|
|
|
function renderVmDetail(vm) {
|
|
|
text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`;
|
|
|
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' : '未记录'));
|
|
|
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 running = stateCategory(vm.state) === 'running'; const stopped = stateCategory(vm.state) === 'stopped';
|
|
|
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: !running }), actionButton('开机', () => powerAction('start'), { disabled: !stopped }), actionButton('正常关机', () => powerAction('shutdown'), { disabled: !running }), actionButton('重启', () => powerAction('reboot'), { disabled: !running }));
|
|
|
danger.append(actionButton('重装系统', () => openReinstall(vm), { variant: 'danger', disabled: vm.os_source !== 'cloud_template' }), actionButton('紧急救援', () => openRescue(vm), { variant: 'danger' }), actionButton('强制重置', () => powerAction('reset', true), { variant: 'danger', disabled: !running }), actionButton('强制断电', () => powerAction('poweroff', true), { variant: 'danger', disabled: stopped }));
|
|
|
} else {
|
|
|
primary.append(makeElement('p', 'muted', vm.is_owner || vm.can_delete
|
|
|
? '实例服务已到期或正在执行策略;日常操作暂不可用。'
|
|
|
: '这是其他用户的实例;当前管理员账户只有查看权限。'));
|
|
|
}
|
|
|
if (vm.can_delete) danger.append(actionButton('删除虚拟机', deleteVm, { variant: 'danger', disabled: !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-period-end', formatServiceDate(data.periodEndsAt));
|
|
|
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');
|
|
|
}
|
|
|
}
|
|
|
async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
|
|
|
async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); if (state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); toast('虚拟机删除已完成。', 'success'); state.selectedVmId = null; showView('list'); await loadVms(); } 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')); renderKeys(); renderKeyCards('create'); 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', 'muted', key.fingerprint || '')); const actions = makeElement('div', 'ssh-key-actions'); const button = actionButton('删除', async () => { if (!confirm(`删除公钥“${key.name}”?已创建的虚拟机不受影响。`)) 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); container.replaceChildren();
|
|
|
if (!state.sshKeys.some(key => String(key.id) === state.selectedKeys[kind])) state.selectedKeys[kind] = '';
|
|
|
for (const key of state.sshKeys) { const button = makeElement('button', 'ssh-key-option'); button.type = 'button'; button.setAttribute('aria-pressed', String(state.selectedKeys[kind] === String(key.id))); button.append(makeElement('strong', 'ssh-key-choice-label', key.name)); button.addEventListener('click', () => { state.selectedKeys[kind] = state.selectedKeys[kind] === String(key.id) ? '' : String(key.id); renderKeyCards(kind); }); container.append(button); }
|
|
|
if (!state.sshKeys.length) container.append(makeElement('p', 'muted', '暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。'));
|
|
|
}
|
|
|
function sourceMode() { return byId('create-form').querySelector('[name="source"]:checked').value; }
|
|
|
function updateSource() { const cloud = sourceMode() === 'cloud'; byId('vm-iso-field').hidden = cloud; byId('vm-iso').required = !cloud; byId('vm-iso').disabled = cloud; byId('vm-template-field').hidden = !cloud; byId('vm-template').disabled = !cloud; byId('vm-cloud-fields').hidden = !cloud; byId('vm-root-password').disabled = !cloud; byId('create-iso-tip').hidden = cloud; byId('create-cloud-tip').hidden = !cloud; }
|
|
|
function strongPassword(value) { return !value || (value.length >= 12 && new TextEncoder().encode(value).length <= 256 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9\s]/.test(value) && !/[\r\n\0]/.test(value)); }
|
|
|
function planValidityDays(plan) { return firstNumber(plan?.validity_days, plan?.service_days, plan?.period_days); }
|
|
|
function planTrafficBytes(plan) {
|
|
|
const gib = firstNumber(plan?.traffic_gib);
|
|
|
return firstNumber(plan?.traffic_quota_bytes, gib === null ? null : gib * 1024 ** 3);
|
|
|
}
|
|
|
function planBillingLabel(plan) {
|
|
|
const days = planValidityDays(plan);
|
|
|
const traffic = planTrafficBytes(plan);
|
|
|
return `${days === null ? '账期未提供' : `${Math.floor(days)} 天/期`} · ${traffic === null ? '每期流量未提供' : `每期流量 ${formatTrafficQuota(traffic)}`}`;
|
|
|
}
|
|
|
async function openCreate() {
|
|
|
state.selectedVmId = null; showView('create'); showError('create-error', '');
|
|
|
try { const [plans] = await Promise.all([api('/api/v1/plans'), loadKeys()]); state.plans = items(plans); const select = byId('vm-plan'); const previous = select.value; select.replaceChildren(makeElement('option', '', state.plans.length ? '请选择套餐' : '暂无可售套餐')); select.firstElementChild.value = ''; for (const plan of state.plans) { const days = planValidityDays(plan); const option = makeElement('option', '', `${plan.name} · ¥${plan.price}${days === null ? '' : ` / ${Math.floor(days)} 天`}`); option.value = String(plan.id); select.append(option); } select.value = previous; if (!select.value && state.plans.length === 1) select.value = String(state.plans[0].id); await loadPlanResources(); updateSource(); } catch (error) { showError('create-error', error.message); }
|
|
|
}
|
|
|
async function loadPlanResources() {
|
|
|
const planId = byId('vm-plan').value; const plan = state.plans.find(item => String(item.id) === planId); const epoch = ++state.formEpoch;
|
|
|
state.resourceController?.abort(); state.resourceController = new AbortController(); state.resources = null; state.templates = []; renderTemplateCatalog('vm-template'); byId('vm-iso').replaceChildren(makeElement('option', '', '请选择套餐')); byId('vm-iso').firstElementChild.value = '';
|
|
|
byId('create-submit').disabled = true;
|
|
|
if (!plan) { text('vm-plan-summary', '选择套餐后显示资源规格、每期价格、账期和每期流量额度。'); return; }
|
|
|
text('vm-plan-summary', `${plan.cpu_cores} vCPU · ${plan.memory_mib} MiB · ${plan.disk_gib} GiB · ${plan.bandwidth_mbps} Mbps · ${plan.region || '地区未设置'} · ${planBillingLabel(plan)} · 每期 ¥${plan.price}`);
|
|
|
try { const resources = await api(`/api/v1/resources?plan_id=${encodeURIComponent(planId)}`, { signal: state.resourceController.signal }); if (epoch !== state.formEpoch) return; state.resources = resources; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); const isos = items(resources.isos || resources.iso_images); const select = byId('vm-iso'); select.replaceChildren(makeElement('option', '', isos.length ? '选择安装镜像' : '没有可用 ISO')); select.firstElementChild.value = ''; for (const iso of isos) { const path = typeof iso === 'string' ? iso : iso.path || iso.name; if (!path) continue; const option = makeElement('option', '', typeof iso === 'string' ? iso.split('/').pop() : iso.name || iso.path.split('/').pop()); option.value = path; select.append(option); } byId('create-submit').disabled = false; }
|
|
|
catch (error) { if (epoch === state.formEpoch && error.name !== 'AbortError') showError('create-error', error.message); }
|
|
|
}
|
|
|
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 {}
|
|
|
}
|
|
|
function invoicePaymentStorageKey(invoiceId, methodId) {
|
|
|
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
|
|
|
}
|
|
|
function pendingInvoicePaymentKey(invoiceId, methodId) {
|
|
|
const storageKey = invoicePaymentStorageKey(invoiceId, methodId);
|
|
|
let key = '';
|
|
|
try { key = String(sessionStorage.getItem(storageKey) || ''); } catch {}
|
|
|
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
|
|
|
try { sessionStorage.setItem(storageKey, key); } catch {}
|
|
|
return key;
|
|
|
}
|
|
|
function clearInvoicePaymentKey(invoiceId, methodId) {
|
|
|
try { sessionStorage.removeItem(invoicePaymentStorageKey(invoiceId, methodId)); } catch {}
|
|
|
}
|
|
|
function clearInvoicePaymentKeys(invoiceId) {
|
|
|
const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`;
|
|
|
try {
|
|
|
const keys = [];
|
|
|
for (let index = 0; index < sessionStorage.length; index += 1) {
|
|
|
const key = sessionStorage.key(index);
|
|
|
if (key?.startsWith(prefix)) keys.push(key);
|
|
|
}
|
|
|
keys.forEach(key => sessionStorage.removeItem(key));
|
|
|
} 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 cloud = sourceMode() === 'cloud'; const password = byId('vm-root-password').value;
|
|
|
if (!strongPassword(password)) return showError('create-error', '密码需至少 12 个字符,包含大写、小写、数字和符号。');
|
|
|
if (cloud && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
|
|
|
if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。');
|
|
|
const selectedPlan = state.plans.find(plan => String(plan.id) === byId('vm-plan').value);
|
|
|
const purchaseSummary = selectedPlan ? `¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
|
|
|
if (!confirm(`确认为该实例生成开通账单?账单金额 ${purchaseSummary}。支付完成后才会开始创建实例。`)) return;
|
|
|
state.mutationBusy = true; byId('create-submit').disabled = true; showError('create-error', '');
|
|
|
const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode() };
|
|
|
if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_path = byId('vm-iso').value;
|
|
|
try {
|
|
|
const fingerprint = await provisionInvoiceFingerprint(body);
|
|
|
const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint);
|
|
|
body.idempotency_key = invoiceIdempotency;
|
|
|
const recovered = await existingProvisionInvoice(invoiceIdempotency);
|
|
|
if (!recovered) await api('/api/v1/invoices', { method: 'POST', body });
|
|
|
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
|
|
|
toast(recovered ? '已找回之前生成的开通账单,没有重复创建。' : '开通账单已生成,请完成支付。', 'success');
|
|
|
showView('invoices'); await loadInvoices();
|
|
|
}
|
|
|
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 = '';
|
|
|
toast('已核对到开通账单,没有重复创建。', 'success'); showView('invoices'); await loadInvoices(); return;
|
|
|
}
|
|
|
} catch {}
|
|
|
showError('create-error', `${error.message} 可再次点击提交安全核对同一张账单。`);
|
|
|
}
|
|
|
finally { delete body.root_password; state.mutationBusy = false; byId('create-submit').disabled = !state.resources; }
|
|
|
}
|
|
|
function formatOrderDate(value) { const date = new Date(typeof value === 'number' ? value * 1000 : value); return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; }
|
|
|
function invoicePurpose(invoice) {
|
|
|
const value = firstText(invoice?.purpose, invoice?.kind, invoice?.invoice_type, invoice?.type).toLowerCase();
|
|
|
return ['provision', 'provisioning', 'initial', 'create'].includes(value) ? 'provision' : 'renewal';
|
|
|
}
|
|
|
function provisionInvoiceData(invoice) {
|
|
|
const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' ? invoice.fulfillment : {};
|
|
|
return {
|
|
|
orderId: firstText(fulfillment.order_id, invoice?.order_id),
|
|
|
status: firstText(fulfillment.status, fulfillment.fulfillment_status, invoice?.fulfillment_status,
|
|
|
fulfillment.order_status, invoice?.order_status, fulfillment.job_status, invoice?.job_status).toLowerCase(),
|
|
|
jobId: firstText(fulfillment.job_id, invoice?.job_id),
|
|
|
jobStatus: firstText(fulfillment.job_status, invoice?.job_status).toLowerCase(),
|
|
|
instanceId: firstText(fulfillment.instance_id, invoice?.instance_id),
|
|
|
instanceUuid: firstText(fulfillment.instance_uuid, fulfillment.vm_uuid, invoice?.instance_uuid, invoice?.vm_uuid),
|
|
|
phase: firstText(fulfillment.phase, invoice?.phase),
|
|
|
error: firstText(fulfillment.error, invoice?.error),
|
|
|
};
|
|
|
}
|
|
|
function provisionStatusInfo(invoice) {
|
|
|
const data = provisionInvoiceData(invoice);
|
|
|
const status = data.status || data.jobStatus;
|
|
|
const values = {
|
|
|
awaiting_payment: ['等待支付', 'warning'], payment_pending: ['等待支付', 'warning'], draft: ['等待支付', 'warning'],
|
|
|
queued: ['等待创建', 'warning'], pending: ['等待创建', 'warning'], provisioning: ['创建中', 'warning'], running: ['创建中', 'warning'],
|
|
|
completed: ['已开通', 'running'], succeeded: ['已开通', 'running'], active: ['已开通', 'running'],
|
|
|
failed: ['创建失败', 'failed'], refunded: ['开通失败,已退款', 'failed'],
|
|
|
needs_attention: ['需要管理员核查', 'failed'], uncertain: ['需要管理员核查', 'failed'],
|
|
|
};
|
|
|
return { data, status, display: values[status] || [status || '等待支付', 'warning'] };
|
|
|
}
|
|
|
function provisionFinished(invoice) {
|
|
|
const { status } = provisionStatusInfo(invoice);
|
|
|
return ['completed', 'succeeded', 'active', 'failed', 'refunded', 'needs_attention', 'uncertain'].includes(status);
|
|
|
}
|
|
|
function invoiceStatusInfo(status) {
|
|
|
const values = {
|
|
|
open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'],
|
|
|
paid: ['已支付', 'running'], refunded: ['已退款', 'other'], void: ['已失效', 'other'], expired: ['已失效', 'failed'],
|
|
|
deleting: ['实例删除中', 'failed'], delete_failed: ['自动删除失败', 'failed'],
|
|
|
purge_pending: ['等待永久删除', 'failed'], purge_stopping: ['删除前正在关机', 'failed'],
|
|
|
purge_deleting: ['实例删除中', 'failed'], purge_stop_failed: ['删除前关机失败', 'failed'], purge_failed: ['自动删除失败', 'failed'],
|
|
|
};
|
|
|
return values[String(status || '').toLowerCase()] || [String(status || '未知'), 'other'];
|
|
|
}
|
|
|
function invoiceDeletionTimestamp(invoice) {
|
|
|
return serviceTimestamp(invoice?.deletion_at ?? invoice?.delete_at ?? invoice?.grace_ends_at ?? null);
|
|
|
}
|
|
|
function invoicePaymentDeadlineTimestamp(invoice) {
|
|
|
return serviceTimestamp(invoice?.payment_deadline_at ?? invoice?.payable_until ?? invoice?.payment_due_at ?? null);
|
|
|
}
|
|
|
function invoiceCanPay(invoice) {
|
|
|
if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false;
|
|
|
if (invoice?.payable === false) return false;
|
|
|
if (invoice?.payable === true) return true;
|
|
|
const deadline = invoicePurpose(invoice) === 'provision'
|
|
|
? invoicePaymentDeadlineTimestamp(invoice) : invoiceDeletionTimestamp(invoice);
|
|
|
return deadline === null || Date.now() < deadline;
|
|
|
}
|
|
|
function validPaymentUrl(value) {
|
|
|
try {
|
|
|
const url = new URL(String(value || ''));
|
|
|
return ['https:', 'weixin:', 'alipays:', 'alipayqr:'].includes(url.protocol) ? url.href : '';
|
|
|
}
|
|
|
catch { return ''; }
|
|
|
}
|
|
|
function appendPaymentQr(container, value) {
|
|
|
if (!value || typeof window.QRCode !== 'function') return false;
|
|
|
const qr = makeElement('div', 'cloud-payment-qr');
|
|
|
try {
|
|
|
const levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
|
|
|
new window.QRCode(qr, {
|
|
|
text: String(value), width: 196, height: 196,
|
|
|
correctLevel: String(value).length > 1200 ? levels.L : levels.M,
|
|
|
});
|
|
|
if (!qr.children.length) return false;
|
|
|
container.append(qr);
|
|
|
return true;
|
|
|
} catch { return false; }
|
|
|
}
|
|
|
function stopInvoicePoll(invoiceId = null) {
|
|
|
if (invoiceId !== null) {
|
|
|
const key = String(invoiceId);
|
|
|
const timer = state.invoicePollTimers.get(key);
|
|
|
if (timer !== undefined) clearTimeout(timer);
|
|
|
state.invoicePollTimers.delete(key);
|
|
|
return;
|
|
|
}
|
|
|
for (const timer of state.invoicePollTimers.values()) clearTimeout(timer);
|
|
|
state.invoicePollTimers.clear();
|
|
|
}
|
|
|
function scheduleInvoicePoll(invoiceId) {
|
|
|
const key = String(invoiceId);
|
|
|
stopInvoicePoll(key);
|
|
|
const started = Date.now();
|
|
|
const poll = async () => {
|
|
|
if (state.view !== 'invoices') return stopInvoicePoll(key);
|
|
|
try {
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}`);
|
|
|
const invoice = result.invoice || {};
|
|
|
const status = String(invoice.status || '').toLowerCase();
|
|
|
if (status === 'paid') {
|
|
|
await loadInvoices(); await loadVms();
|
|
|
if (invoicePurpose(invoice) !== 'provision') {
|
|
|
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); return;
|
|
|
}
|
|
|
if (provisionFinished(invoice)) {
|
|
|
const { status: provisionStatus } = provisionStatusInfo(invoice);
|
|
|
stopInvoicePoll(key);
|
|
|
if (['completed', 'succeeded', 'active'].includes(provisionStatus)) toast('实例已创建完成。', 'success');
|
|
|
else if (provisionStatus === 'refunded') toast('实例创建失败,款项已退回账户余额。', 'error');
|
|
|
else toast('实例开通未完成,请在账单中查看任务状态。', 'error');
|
|
|
return;
|
|
|
}
|
|
|
}
|
|
|
if (['void', 'expired'].includes(status)) {
|
|
|
stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
|
|
|
}
|
|
|
if (status === 'refunded') {
|
|
|
stopInvoicePoll(key); toast('实例创建失败,款项已退回账户余额。', 'error'); await loadInvoices(); return;
|
|
|
}
|
|
|
if (!invoiceCanPay(invoice) && status !== 'paid') {
|
|
|
const message = invoicePurpose(invoice) === 'provision'
|
|
|
? '开通账单已超过支付截止时间。' : '续费宽限期已经结束,到账金额会保留在账户余额中。';
|
|
|
stopInvoicePoll(key); toast(message, 'error'); await loadInvoices(); return;
|
|
|
}
|
|
|
} catch {}
|
|
|
if (Date.now() - started < 10 * 60 * 1000) {
|
|
|
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
|
|
|
} else {
|
|
|
stopInvoicePoll(key);
|
|
|
await loadInvoices();
|
|
|
}
|
|
|
};
|
|
|
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
|
|
|
}
|
|
|
function renderOnlinePayment(container, payment) {
|
|
|
let box = container.querySelector('.cloud-payment-instructions');
|
|
|
if (!box) { box = makeElement('div', 'cloud-payment-instructions'); container.append(box); }
|
|
|
box.replaceChildren();
|
|
|
if (payment.payment_kind === 'usdt') {
|
|
|
box.append(makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`),
|
|
|
makeElement('code', '', payment.receive_address || '收款地址不可用'),
|
|
|
makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`));
|
|
|
appendPaymentQr(box, payment.receive_address || '');
|
|
|
const copy = actionButton('复制收款地址', async () => {
|
|
|
try { await copyText(payment.receive_address || ''); toast('USDT 收款地址已复制。', 'success'); }
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
});
|
|
|
box.append(copy);
|
|
|
} else {
|
|
|
const url = validPaymentUrl(payment.payment_value);
|
|
|
box.append(makeElement('strong', '', `${payment.label || '在线支付'}订单已生成`));
|
|
|
appendPaymentQr(box, payment.payment_value || '');
|
|
|
if (url) {
|
|
|
const link = makeElement('a', 'button button-primary small', '前往支付');
|
|
|
link.href = url; link.target = '_blank'; link.rel = 'noopener noreferrer'; box.append(link);
|
|
|
} else {
|
|
|
box.append(makeElement('code', '', payment.payment_value || '支付信息暂不可用'));
|
|
|
const copy = actionButton('复制支付信息', async () => {
|
|
|
try { await copyText(payment.payment_value || ''); toast('支付信息已复制。', 'success'); }
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
});
|
|
|
box.append(copy);
|
|
|
}
|
|
|
box.append(makeElement('small', '', '完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。'));
|
|
|
}
|
|
|
scheduleInvoicePoll(payment.invoice_id);
|
|
|
}
|
|
|
async function payInvoiceBalance(invoice, row) {
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
? '开通账单已失效,不能支付。' : '续费宽限期已经结束,账单不可支付。', 'error');
|
|
|
if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 ${invoice.invoice_no},金额 ¥${invoice.amount}?`)) return;
|
|
|
state.mutationBusy = true;
|
|
|
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
|
|
|
try {
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
|
|
|
method: 'POST', body: { idempotency_key: crypto.randomUUID() },
|
|
|
});
|
|
|
const paid = result.invoice || invoice;
|
|
|
if (invoicePurpose(paid) === 'provision') {
|
|
|
toast('账单已支付,实例已进入创建队列。', 'success'); await loadInvoices(); await loadVms(); scheduleInvoicePoll(paid.id || invoice.id);
|
|
|
} else {
|
|
|
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
|
|
|
}
|
|
|
} catch (error) { toast(error.message, 'error'); }
|
|
|
finally {
|
|
|
state.mutationBusy = false;
|
|
|
row.querySelectorAll('button').forEach(button => { button.disabled = false; });
|
|
|
}
|
|
|
}
|
|
|
async function createInvoicePayment(invoice, method, row) {
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
? '开通账单已失效,不能再生成支付订单。' : '续费宽限期已经结束,不能再生成支付订单。', 'error');
|
|
|
if (state.mutationBusy || !confirm(`确认通过“${method.name}”生成 ¥${invoice.amount} 的支付订单?`)) return;
|
|
|
state.mutationBusy = true;
|
|
|
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
|
|
|
const idempotencyKey = pendingInvoicePaymentKey(invoice.id, method.id);
|
|
|
try {
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`, {
|
|
|
method: 'POST', body: { method: method.id, idempotency_key: idempotencyKey },
|
|
|
});
|
|
|
renderOnlinePayment(row, result.payment || {});
|
|
|
} catch (error) {
|
|
|
// A transport failure may hide a successfully created provider order, so
|
|
|
// retain the key and recover it on the next click. Only a definite 4xx
|
|
|
// rejection proves no ambiguous 5xx/network outcome needs reconciling.
|
|
|
const status = Number(error.status || 0);
|
|
|
const ambiguousHttpFailure = [408, 425, 429].includes(status);
|
|
|
if (status >= 400 && status < 500 && !ambiguousHttpFailure
|
|
|
&& !String(error.message).includes('正在创建')) {
|
|
|
clearInvoicePaymentKey(invoice.id, method.id);
|
|
|
}
|
|
|
toast(error.message, 'error');
|
|
|
}
|
|
|
finally { state.mutationBusy = false; row.querySelectorAll('button').forEach(button => { button.disabled = false; }); }
|
|
|
}
|
|
|
function appendProvisionInvoiceActions(invoice, detail, actions) {
|
|
|
const { data, status, display } = provisionStatusInfo(invoice);
|
|
|
if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0]));
|
|
|
if (data.jobId) actions.append(actionButton('查看创建进度', async () => {
|
|
|
let progress = detail.querySelector('.cloud-order-progress');
|
|
|
if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); }
|
|
|
try {
|
|
|
const job = await api(`/api/v1/jobs/${encodeURIComponent(data.jobId)}`);
|
|
|
progress.className = `cloud-order-progress ${job.error ? 'form-error' : 'muted'}`;
|
|
|
progress.textContent = job.error || job.phase || `任务状态:${job.status}`;
|
|
|
if (['completed', 'succeeded', 'failed', 'cancelled', 'needs_attention', 'uncertain'].includes(String(job.status || '').toLowerCase())) {
|
|
|
await loadInvoices(); await loadVms();
|
|
|
}
|
|
|
} catch (error) { toast(error.message, 'error'); }
|
|
|
}));
|
|
|
if (data.instanceId || data.instanceUuid) actions.append(actionButton('查看实例', async () => {
|
|
|
await loadVms();
|
|
|
const vm = state.vms.find(item => item.api_id === data.instanceId || item.uuid === data.instanceUuid);
|
|
|
if (vm) openVmDetail(vm.uuid); else toast('实例尚未出现在列表,请稍后刷新。');
|
|
|
}));
|
|
|
}
|
|
|
function renderInvoices() {
|
|
|
const container = byId('invoices-list'); container.replaceChildren();
|
|
|
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。'));
|
|
|
for (const invoice of state.invoices) {
|
|
|
const row = makeElement('article', 'cloud-order cloud-invoice');
|
|
|
const detail = makeElement('div', 'cloud-order-detail');
|
|
|
const purpose = invoicePurpose(invoice);
|
|
|
const provision = purpose === 'provision';
|
|
|
const invoiceStatus = String(invoice.status || '').toLowerCase();
|
|
|
const deletionAt = invoiceDeletionTimestamp(invoice);
|
|
|
const paymentDeadline = invoicePaymentDeadlineTimestamp(invoice);
|
|
|
const payable = invoiceCanPay(invoice);
|
|
|
const subject = provision
|
|
|
? invoice.requested_name || invoice.instance_name || '待创建实例'
|
|
|
: invoice.instance_name || '实例';
|
|
|
const dueText = provision
|
|
|
? `支付截止 ${formatServiceDate(paymentDeadline ?? invoice.due_at)}`
|
|
|
: `实例到期 ${formatOrderDate(invoice.due_at)}`;
|
|
|
detail.append(makeElement('strong', '', `${subject} · ¥${invoice.amount}`),
|
|
|
makeElement('p', 'muted', `${provision ? '开通账单' : '续费账单'} ${invoice.invoice_no} · ${dueText}`),
|
|
|
makeElement('p', 'cloud-order-message', provision
|
|
|
? `${invoice.plan_name || '云服务器套餐'} · 支付后创建 ${invoice.validity_days} 天服务期 · 每期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`
|
|
|
: `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
|
|
|
if (provision) {
|
|
|
const task = provisionInvoiceData(invoice);
|
|
|
if (task.phase || task.error) {
|
|
|
const progress = makeElement('p', `cloud-order-progress ${task.error ? 'form-error' : 'muted'}`, task.error || task.phase);
|
|
|
detail.append(progress);
|
|
|
} else if (invoiceStatus === 'paid' && !provisionFinished(invoice)) {
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '账单已支付,实例正在等待后台创建;关闭页面不会取消任务。'));
|
|
|
} else if (['void', 'expired'].includes(invoiceStatus)) {
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '开通账单已失效,不会创建实例。'));
|
|
|
}
|
|
|
} else if (['open', 'overdue'].includes(invoiceStatus) && deletionAt !== null) {
|
|
|
detail.append(makeElement('p', 'cloud-order-message', payable
|
|
|
? `实例到期后会立即停用网络;若在 ${formatServiceDate(deletionAt)} 前仍未支付,实例及系统盘将被永久删除。续费成功后网络会自动恢复。`
|
|
|
: '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
|
|
|
} else if (['delete_failed', 'purge_stop_failed', 'purge_failed'].includes(invoiceStatus)) {
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;自动清理尚未完成,请联系管理员处理。'));
|
|
|
} else if (['expired', 'deleting', 'purge_pending', 'purge_stopping', 'purge_deleting'].includes(invoiceStatus)) {
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
|
|
|
}
|
|
|
const actions = makeElement('div', 'cloud-order-actions');
|
|
|
const [label, className] = invoiceStatusInfo(invoiceStatus);
|
|
|
actions.append(makeElement('span', `state-pill ${className}`, label));
|
|
|
if (payable) {
|
|
|
actions.append(actionButton('余额支付', () => payInvoiceBalance(invoice, row)));
|
|
|
for (const method of state.invoicePaymentMethods) actions.append(actionButton(method.name, () => createInvoicePayment(invoice, method, row)));
|
|
|
} else if (['open', 'overdue'].includes(invoiceStatus)) {
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
actions.append(makeElement('span', 'muted', '已超过支付截止时间'));
|
|
|
} else if (invoiceStatus === 'paid') {
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
if (!provision) stopInvoicePoll(invoice.id);
|
|
|
actions.append(makeElement('span', 'muted', invoice.paid_at ? `支付于 ${formatOrderDate(invoice.paid_at)}` : '已结清'));
|
|
|
} else if (['refunded', 'void', 'expired', 'deleting', 'delete_failed', 'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting', 'purge_failed'].includes(invoiceStatus)) {
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
}
|
|
|
if (provision && ['paid', 'refunded'].includes(invoiceStatus)) appendProvisionInvoiceActions(invoice, detail, actions);
|
|
|
if (provision && invoiceStatus === 'paid' && !provisionFinished(invoice)
|
|
|
&& !state.invoicePollTimers.has(String(invoice.id))) scheduleInvoicePoll(invoice.id);
|
|
|
row.append(detail, actions); container.append(row);
|
|
|
}
|
|
|
}
|
|
|
async function loadInvoices() {
|
|
|
try {
|
|
|
const payload = await api('/api/v1/invoices');
|
|
|
state.invoices = (Array.isArray(payload.invoices) ? payload.invoices : []).slice()
|
|
|
.sort((left, right) => Number(right.created_at || 0) - Number(left.created_at || 0)
|
|
|
|| Number(right.id || 0) - Number(left.id || 0));
|
|
|
state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : [];
|
|
|
text('invoices-balance', `¥${payload.balance ?? '—'}`); renderInvoices(); showError('cloud-page-error', '');
|
|
|
} catch (error) { showError('cloud-page-error', error.message); }
|
|
|
}
|
|
|
async function openReinstall(vm) {
|
|
|
if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error');
|
|
|
showView('reinstall'); text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); 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;
|
|
|
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 pollJob(kind, id, phaseId, errorId) {
|
|
|
const path = `/api/v1/jobs/${encodeURIComponent(id)}`;
|
|
|
for (let attempt = 0; attempt < 600; attempt++) { if (document.visibilityState === 'hidden') await new Promise(resolve => setTimeout(resolve, 1000)); const job = await api(path); if (phaseId) text(phaseId, job.phase || job.status || '正在处理…'); if (['completed', 'succeeded', 'done'].includes(job.status)) return job; if (['failed', 'cancelled', 'needs_attention', 'uncertain'].includes(job.status)) throw new Error(job.error || job.message || '任务失败,请核查虚拟机状态。'); await new Promise(resolve => setTimeout(resolve, 2000)); }
|
|
|
throw new Error('任务仍在处理,可稍后刷新详情。不要重复提交。');
|
|
|
}
|
|
|
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 个字符,包含大写、小写、数字和符号。');
|
|
|
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;
|
|
|
try { const result = await api(`${vmPath(vm)}/reinstall`, { method: 'POST', body }); byId('reinstall-root-password').value = ''; byId('reinstall-progress').hidden = false; if (result.job_id) await pollJob('reinstall', result.job_id, 'reinstall-phase', 'reinstall-error'); toast('重装任务已完成,请等待系统初始化。', 'success'); await loadVms(); if (selectedVm()) openVmDetail(vm.uuid); }
|
|
|
catch (error) { showError('reinstall-error', error.message); }
|
|
|
finally { delete body.root_password; state.mutationBusy = false; byId('reinstall-submit').disabled = false; byId('reinstall-progress').hidden = true; }
|
|
|
}
|
|
|
async function openRescue(vm) { if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); showView('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' && !confirm('正常关机未成功。强制断电并冷启动进入已挂载的救援环境可能丢失数据,确认继续?')) 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; if (action === 'force-start') body.ack_data_loss = true; const result = await api(`${vmPath(vm)}/rescue${action === 'load' ? '' : '/' + action}`, { method: 'POST', body }); if (result.job_id) await pollJob('rescue', result.job_id, 'rescue-status', 'rescue-error'); toast('救援操作完成。', 'success'); }
|
|
|
catch (error) { showError('rescue-error', error.message); }
|
|
|
finally { state.mutationBusy = false; try { renderRescueStatus(await api(`${vmPath(vm)}/rescue`)); } catch (error) { showError('rescue-error', error.message); } await loadVms(); }
|
|
|
}
|
|
|
function closeConsole() { state.consoleToken++; state.rfb?.disconnect(); state.rfb = null; byId('console-modal').hidden = true; byId('console-password-form').hidden = true; byId('console-password').value = ''; 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] || String(value || "未知");
|
|
|
}
|
|
|
|
|
|
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 nameButton = makeElement("button", "vm-name-link", vm.name || "未命名虚拟机");
|
|
|
nameButton.type = "button";
|
|
|
nameButton.disabled = !uuid;
|
|
|
nameButton.dataset.vmUuid = uuid;
|
|
|
nameButton.setAttribute("aria-label", `管理虚拟机 ${vm.name || uuid}`);
|
|
|
nameButton.addEventListener("click", () => openVmDetail(uuid));
|
|
|
identityText.append(nameButton);
|
|
|
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" }] },
|
|
|
];
|
|
|
|
|
|
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() {
|
|
|
if (state.metricsPollTimer) window.clearInterval(state.metricsPollTimer);
|
|
|
state.metricsPollTimer = null;
|
|
|
if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer);
|
|
|
state.metricsResizeTimer = null;
|
|
|
state.metricsRequest?.controller.abort();
|
|
|
state.metricsRequest = null;
|
|
|
}
|
|
|
|
|
|
function startVmMetrics() {
|
|
|
if (!metricViewVisible()) return;
|
|
|
void loadVmMetrics();
|
|
|
if (!state.metricsPollTimer) {
|
|
|
state.metricsPollTimer = window.setInterval(() => {
|
|
|
if (metricViewVisible()) void loadVmMetrics();
|
|
|
}, 60000);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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 === "traffic" && 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",
|
|
|
centosstream: "CentOS",
|
|
|
ubuntu: "Ubuntu",
|
|
|
};
|
|
|
|
|
|
const TEMPLATE_ICON_PATHS = {
|
|
|
AlmaLinux: "/cloud/almalinux-icon.svg",
|
|
|
Debian: "/cloud/debian-icon.svg",
|
|
|
CentOS: "/cloud/centos-icon.svg",
|
|
|
Ubuntu: "/cloud/ubuntu-icon.svg",
|
|
|
};
|
|
|
|
|
|
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 family = namedFamily
|
|
|
|| (/^alma(?:9|10)-/.test(id) ? "AlmaLinux" : "其他系统");
|
|
|
const oldVersion = /^alma(9|10)-/.exec(id)?.[1] || "";
|
|
|
const version = /^[0-9]+$/.test(String(item?.os_version || ""))
|
|
|
? String(item.os_version) : oldVersion;
|
|
|
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 renderTemplateCatalog(inputId) {
|
|
|
const input = byId(inputId);
|
|
|
const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog");
|
|
|
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.admin
|
|
|
? "暂无云镜像,请先到“云镜像模板”页面导入。"
|
|
|
: "暂无可用云镜像,请联系管理员导入模板。"));
|
|
|
return;
|
|
|
}
|
|
|
if (!state.templates.some((item) => String(item.id) === input.value)) input.value = "";
|
|
|
const cards = [];
|
|
|
for (const [family, entries] of groups) {
|
|
|
entries.sort((a, b) => Number(b.version || 0) - Number(a.version || 0)
|
|
|
|| String(a.item.name || "").localeCompare(String(b.item.name || ""), "zh-CN"));
|
|
|
const card = makeElement("details", "template-family-card");
|
|
|
card.dataset.family = family;
|
|
|
card.open = opened.has(family) || entries.some(({ item }) => String(item.id) === input.value);
|
|
|
const summary = makeElement("summary", "template-family-summary");
|
|
|
const icon = templateIcon(family, "template-family-icon");
|
|
|
summary.append(icon, makeElement("strong", "", family), makeElement("span", "template-family-arrow", "⌄"));
|
|
|
const versions = makeElement("div", "template-versions");
|
|
|
versions.setAttribute("role", "group");
|
|
|
versions.setAttribute("aria-label", `${family} 可用版本`);
|
|
|
for (const { item } 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));
|
|
|
});
|
|
|
if (inputId === "vm-template") showError("create-error", "");
|
|
|
else showError("reinstall-error", "");
|
|
|
});
|
|
|
versions.append(option);
|
|
|
}
|
|
|
card.append(summary, versions);
|
|
|
cards.push(card);
|
|
|
}
|
|
|
container.replaceChildren(...cards);
|
|
|
}
|
|
|
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
|
|
|
byId('refresh-button').addEventListener('click', loadVms);
|
|
|
byId('vm-detail-refresh-button').addEventListener('click', async () => {
|
|
|
await loadVms();
|
|
|
if (trafficDailyViewVisible()) await loadVmTrafficDaily(true);
|
|
|
});
|
|
|
byId('create-button').addEventListener('click', openCreate); byId('create-back').addEventListener('click', () => showView('list')); byId('vm-detail-back-button').addEventListener('click', () => { state.selectedVmId = null; showView('list'); }); byId('ssh-keys-back-button').addEventListener('click', () => showView('list'));
|
|
|
for (const id of ['reinstall-back', 'reinstall-cancel', 'rescue-back']) byId(id).addEventListener('click', () => { if (!state.mutationBusy) { const vm = selectedVm(); if (vm) openVmDetail(vm.uuid); else showView('list'); } });
|
|
|
byId('search-input').addEventListener('input', () => renderVMs()); byId('state-filter').addEventListener('change', () => renderVMs()); byId('vm-plan').addEventListener('change', () => { void loadPlanResources(); }); byId('create-form').querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource));
|
|
|
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('invoices-refresh').addEventListener('click', loadInvoices);
|
|
|
for (const id of ['vm-open-ssh-keys', 'reinstall-open-ssh-keys']) byId(id).addEventListener('click', async () => { showView('keys'); try { await loadKeys(); } catch (error) { toast(error.message, 'error'); } });
|
|
|
byId('ssh-key-form').addEventListener('submit', async event => { event.preventDefault(); const button = byId('ssh-key-save-button'); button.disabled = true; showError('ssh-key-form-error', ''); try { await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim() } }); byId('ssh-key-form').reset(); await loadKeys(); toast('公钥已保存。', 'success'); } catch (error) { showError('ssh-key-form-error', error.message); } finally { button.disabled = false; } });
|
|
|
byId('ssh-key-file').addEventListener('change', async event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); const content = await file.text(); if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); byId('ssh-key-public-key').value = content.trim(); });
|
|
|
byId('vm-detail-ip-copy').addEventListener('click', async () => { try { await copyText(vmIp(selectedVm())); toast('公网 IP 已复制。'); } catch (error) { toast(error.message, 'error'); } }); byId('vm-detail-password-reveal').addEventListener('click', () => credential()); byId('vm-detail-password-copy').addEventListener('click', () => credential(true));
|
|
|
document.querySelectorAll('[data-detail-tab]').forEach(button => {
|
|
|
button.addEventListener('click', () => setVmDetailTab(button.dataset.detailTab));
|
|
|
button.addEventListener('keydown', event => {
|
|
|
const current = VM_DETAIL_TABS.indexOf(button.dataset.detailTab);
|
|
|
let next = current;
|
|
|
if (event.key === 'ArrowRight') next = (current + 1) % VM_DETAIL_TABS.length;
|
|
|
else if (event.key === 'ArrowLeft') next = (current - 1 + VM_DETAIL_TABS.length) % VM_DETAIL_TABS.length;
|
|
|
else if (event.key === 'Home') next = 0;
|
|
|
else if (event.key === 'End') next = VM_DETAIL_TABS.length - 1;
|
|
|
else return;
|
|
|
event.preventDefault();
|
|
|
setVmDetailTab(VM_DETAIL_TABS[next], true);
|
|
|
});
|
|
|
});
|
|
|
byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange = byId('vm-metrics-range').value; state.metricsRequest?.controller.abort(); state.metricsRequest = null; void loadVmMetrics(); }); window.addEventListener('resize', () => {
|
|
|
clearTimeout(state.metricsResizeTimer);
|
|
|
clearTimeout(state.trafficDailyResizeTimer);
|
|
|
state.metricsResizeTimer = setTimeout(() => { if (state.metricsPayload && metricViewVisible()) renderVmMetrics(state.metricsPayload); }, 150);
|
|
|
state.trafficDailyResizeTimer = setTimeout(() => { if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId && trafficDailyViewVisible()) drawVmTrafficDaily(state.trafficDailyPayload); }, 150);
|
|
|
});
|
|
|
byId('console-modal').querySelector('[data-close-modal]').addEventListener('click', closeConsole); byId('console-cad').addEventListener('click', () => state.rfb?.sendCtrlAltDel()); byId('console-fullscreen').addEventListener('click', () => { byId('console-stage').requestFullscreen?.().catch(error => toast(error.message, 'error')); }); byId('console-password-form').addEventListener('submit', event => { event.preventDefault(); state.rfb?.sendCredentials({ password: byId('console-password').value }); byId('console-password').value = ''; byId('console-password-form').hidden = true; }); window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); });
|
|
|
document.addEventListener('visibilitychange', () => { if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); } else { void loadVms(); if (state.view === 'detail') setVmDetailTab(state.detailTab); if (state.view === 'invoices') void loadInvoices(); } }); window.addEventListener('pagehide', () => { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/user/logout'); });
|
|
|
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; 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; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
window.addEventListener('hashchange', () => { if (state.csrfToken) void routeHash(); });
|
|
|
void initialize();
|