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

270 lines
24 KiB
JavaScript

This file contains ambiguous Unicode characters!

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

const root = document.querySelector('[data-cloud-admin]');
const byId = id => document.getElementById(id);
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', scanned: null, scanTarget: '', busy: false, epoch: 0 };
const canManage = window.ADMIN_CAN_MANAGE === true;
const collection = (payload, key = 'items') => Array.isArray(payload) ? payload : Array.isArray(payload?.[key]) ? payload[key] : Array.isArray(payload?.items) ? payload.items : [];
function element(tag, className = '', content) { const node = document.createElement(tag); node.className = className; if (content !== undefined) node.textContent = String(content); return node; }
function notice(message, error = false) { const box = byId('cloud-admin-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; }
function errorMessage(payload, status) { if (Array.isArray(payload?.detail)) return payload.detail.map(item => item.msg || '输入错误').join(';'); return String(payload?.detail || payload?.message || payload?.msg || `请求失败 (${status})`); }
async function api(path, options = {}) {
const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' });
if (!['GET', 'HEAD'].includes(method)) { if (!canManage) throw new Error('当前管理员仅可查看,不能修改配置。'); if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 修改宿主机及镜像配置。'); headers.set('X-CSRF-Token', state.csrf); headers.set('Content-Type', options.raw ? 'application/octet-stream' : 'application/json'); }
const response = await fetch(path, { ...options, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : options.raw ? options.body : 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) { location.assign('/auth/login'); throw new Error('登录已过期。'); }
if (!response.ok || payload?.ret === 0) throw new Error(errorMessage(payload, response.status)); return payload;
}
function uploadApi(path, file, onProgress) {
if (!canManage) return Promise.reject(new Error('当前管理员仅可查看,不能修改配置。'));
if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) return Promise.reject(new Error('请通过 HTTPS 上传云镜像。'));
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('POST', path, true);
request.withCredentials = true;
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('X-CSRF-Token', state.csrf);
request.setRequestHeader('Content-Type', 'application/octet-stream');
request.upload.addEventListener('progress', event => {
if (event.lengthComputable && typeof onProgress === 'function') onProgress(event.loaded, event.total);
});
request.addEventListener('load', () => {
let payload = null;
try { payload = request.responseText ? JSON.parse(request.responseText) : null; }
catch {
reject(new Error(request.status === 413
? '上传被 Web 服务器拒绝,请提高 PHP 与反代的请求体上限。'
: '服务返回非 JSON 响应,请检查 PHP 和反代配置。'));
return;
}
if (request.status === 401) { location.assign('/auth/login'); reject(new Error('登录已过期。')); return; }
if (request.status < 200 || request.status >= 300 || payload?.ret === 0) { reject(new Error(errorMessage(payload, request.status))); return; }
resolve(payload);
});
request.addEventListener('error', () => reject(new Error('云镜像上传失败,请检查网络或反代限制。')));
request.addEventListener('abort', () => reject(new Error('云镜像上传已取消。')));
request.send(file);
});
}
function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); }
function profile(host) { return { ...host, ...(host.profile || host.config || {}) }; }
function orderStatus(value) {
return ({ awaiting_payment: '等待账单支付', expired: '账单已失效', queued: '等待创建', running: '创建中', succeeded: '已开通', failed: '已失败', uncertain: '待核对' })[value] || value || '—';
}
function unixTime(value) {
const seconds = Number(value);
if (!Number.isFinite(seconds) || seconds <= 0) return '—';
return new Date(seconds * 1000).toLocaleString('zh-CN', { hour12: false });
}
async function loadHosts() { state.hosts = collection(await api('/api/v1/admin/hosts'), 'hosts').map(profile); return state.hosts; }
async function loadUserIsoSettings() {
const settings = await api('/api/v1/admin/user-iso/settings');
byId('user-iso-enabled').checked = settings?.enabled === true;
}
async function saveUserIsoSettings(event) {
event.preventDefault();
if (state.busy) return;
const button = byId('user-iso-settings-save');
state.busy = true;
button.disabled = true;
try {
const settings = await api('/api/v1/admin/user-iso/settings', {
method: 'PUT', body: { enabled: byId('user-iso-enabled').checked },
});
byId('user-iso-enabled').checked = settings?.enabled === true;
notice(settings?.enabled ? '用户 ISO 功能已开放。' : '用户 ISO 功能已关闭。');
} catch (error) {
notice(error.message, true);
} finally {
state.busy = false;
button.disabled = !canManage;
}
}
function resetScan() { state.scanned = null; state.scanTarget = ''; if (byId('host-fingerprint')) byId('host-fingerprint').textContent = ''; if (byId('host-fingerprint-confirm')) byId('host-fingerprint-confirm').checked = false; }
function fillHost(host) {
byId('host-form').reset(); resetScan(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机';
const fields = { 'host-name': h.name || '', 'host-country-code': h.country_code || '', 'host-region': h.region || '', 'host-address': h.host || '', 'host-port': h.port || 22, 'host-storage-pool': h.storage_pool || '/home/kvm', 'host-iso-pool': h.iso_pool || '/home/iso', 'host-rescue-pool': h.rescue_iso_pool || '/home/rescue-iso', 'host-network': h.default_network || 'bridge:br0', 'host-public-pool': h.public_pool_cidr || '', 'host-gateway': h.public_gateway || '', 'host-dns': Array.isArray(h.public_dns_servers) ? h.public_dns_servers.join(', ') : '1.1.1.1, 8.8.8.8', 'host-reserved': Array.isArray(h.public_reserved_ips) ? h.public_reserved_ips.join(', ') : '', 'host-vm-prefix': h.public_vm_prefix || '' };
for (const [id, value] of Object.entries(fields)) byId(id).value = value;
byId('host-private-key').value = ''; byId('host-passphrase').value = ''; byId('host-enabled').checked = h.enabled !== false; byId('host-form-error').textContent = '';
}
function renderHosts() {
const list = byId('host-list'); list.replaceChildren(); if (!state.hosts.length) list.append(element('p', 'text-muted', '暂无宿主机。'));
for (const host of state.hosts) { const button = element('button', 'btn btn-light cloud-admin-host'); button.type = 'button'; button.append(element('strong', '', host.name || `宿主机 ${host.id}`), element('div', 'text-muted', `${host.region || '地区未设置'} · #${host.id} · ${host.enabled ? '启用' : '停用'}`)); button.addEventListener('click', async () => { if (state.busy) return; try { fillHost(profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(host.id)}`))); notice('已读取配置。若需保存,请重新扫描并核对主机指纹。'); } catch (error) { notice(error.message, true); } }); list.append(button); }
}
async function scanHost() {
if (state.busy) return; const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); if (!host || port < 1 || port > 65535) return notice('请输入正确的 SSH 地址和端口。', true);
state.busy = true; byId('host-scan').disabled = true; resetScan(); notice('正在扫描 SSH 主机指纹…');
try { const result = await api('/api/v1/admin/hosts/scan', { method: 'POST', body: { host, port } }); if (byId('host-address').value.trim() !== host || Number(byId('host-port').value) !== port) throw new Error('扫描期间地址发生变化,请重新扫描。'); if (!result.host_key || !result.fingerprint) throw new Error('扫描响应缺少主机公钥或指纹。'); state.scanned = result; state.scanTarget = `${host}:${port}`; byId('host-fingerprint').textContent = `${result.key_type || 'SSH'}\n${result.fingerprint}`; notice('请通过宿主机控制台等可信渠道核对指纹,勾选确认后再保存。'); }
catch (error) { notice(error.message, true); } finally { state.busy = false; byId('host-scan').disabled = !canManage; }
}
async function saveHost(event) {
event.preventDefault(); if (state.busy) return;
const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); const id = byId('host-id').value;
if (!state.scanned || state.scanTarget !== `${host}:${port}` || !byId('host-fingerprint-confirm').checked) return notice('请先扫描并核对 SSH 主机指纹。', true);
if (!id && !byId('host-private-key').value.trim()) return notice('首次添加必须提供现有 SSH 私钥。', true);
const body = { name: byId('host-name').value.trim(), enabled: byId('host-enabled').checked, host, port, host_key: state.scanned.host_key, confirmed_fingerprint: state.scanned.fingerprint, private_key: byId('host-private-key').value.trim(), private_key_passphrase: byId('host-passphrase').value, country_code: byId('host-country-code').value, region: byId('host-region').value.trim(), storage_pool: byId('host-storage-pool').value.trim(), iso_pool: byId('host-iso-pool').value.trim(), rescue_iso_pool: byId('host-rescue-pool').value.trim(), default_network: byId('host-network').value.trim(), public_pool_cidr: byId('host-public-pool').value.trim(), public_gateway: byId('host-gateway').value.trim(), public_dns_servers: formList(byId('host-dns').value), public_reserved_ips: formList(byId('host-reserved').value), public_vm_prefix: byId('host-vm-prefix').value ? Number(byId('host-vm-prefix').value) : null };
state.busy = true; byId('host-save').disabled = true; notice('正在测试连接并保存…');
try {
const result = await api(`/api/v1/admin/hosts${id ? '/' + encodeURIComponent(id) : ''}`, { method: id ? 'PUT' : 'POST', body });
await loadHosts(); renderHosts(); fillHost(result?.id ? profile(result) : null);
const sync = result?.inventory_sync;
const scanned = Number(sync?.scanned || 0);
const imported = Number(sync?.imported || 0);
const existing = Number(sync?.existing || 0);
const warnings = Array.isArray(result?.warnings) ? result.warnings.filter(Boolean) : [];
const summary = sync
? `,已扫描 ${scanned} 台虚拟机,新导入 ${imported} 台,已存在 ${existing} 台`
: '';
notice(`宿主机配置已保存${summary}。套餐可在“商品管理”绑定此宿主机。${warnings.length ? ` 提示:${warnings.join(';')}` : ''}`, warnings.length > 0);
}
catch (error) { byId('host-form-error').textContent = error.message; notice(error.message, true); }
finally { delete body.private_key; delete body.private_key_passphrase; byId('host-private-key').value = ''; byId('host-passphrase').value = ''; state.busy = false; byId('host-save').disabled = !canManage; }
}
function catalogPath() { return root.dataset.cloudAdmin === 'rescue' ? '/api/v1/admin/rescue-templates' : '/api/v1/admin/cloud-templates'; }
function isRescueCatalog() { return root.dataset.cloudAdmin === 'rescue'; }
async function loadCatalog() {
const rescue = isRescueCatalog();
const hostId = rescue ? byId('catalog-host')?.value || '' : '';
state.selectedHost = hostId;
const epoch = ++state.epoch;
const list = byId('catalog-list');
list.replaceChildren();
if (rescue && !hostId) return list.append(element('p', 'text-muted', '请先添加宿主机。'));
notice(rescue ? '正在读取所选宿主机的模版…' : '正在读取全局云镜像目录…');
const url = rescue ? `${catalogPath()}?host_id=${encodeURIComponent(hostId)}` : catalogPath();
try { const entries = collection(await api(url), 'templates'); if (epoch !== state.epoch) return;
if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。'));
for (const entry of entries) { const row = element('form', 'cloud-admin-row'); const name = element('input', 'form-control'); name.value = entry.name || ''; name.maxLength = 64; name.required = true; name.setAttribute('aria-label', '模版名称'); name.disabled = !canManage; const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage; const remove = element('button', 'btn btn-outline-danger', '删除'); remove.type = 'button'; remove.disabled = !canManage; const imageBytes = Number(entry.image_bytes || entry.size_bytes || 0);
row.append(name, save, remove);
row.append(element('small', 'cloud-admin-meta', `${entry.os_family || '镜像'} ${entry.os_version || ''} · ${imageBytes > 0 ? (imageBytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`));
if (rescue) { name.readOnly = true; save.hidden = true; save.disabled = true; }
row.addEventListener('submit', async event => { event.preventDefault(); if (rescue) return; if (state.busy) return notice('请等待当前导入任务完成。', true); save.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, { method: 'PATCH', body: { name: name.value.trim() } }); notice('名称已保存。'); } catch (error) { notice(error.message, true); } finally { save.disabled = !canManage; } });
remove.addEventListener('click', async () => {
if (state.busy) return notice('请等待当前导入任务完成。', true);
const message = rescue
? `删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。`
: `删除全局云镜像模版“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`;
if (!confirm(message)) return;
remove.disabled = true;
const deleteUrl = rescue
? `${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`
: `${catalogPath()}/${encodeURIComponent(entry.id)}`;
try {
const result = await api(deleteUrl, rescue
? { method: 'DELETE' }
: { method: 'DELETE', body: { created_at: Number(entry.created_at) } });
await loadCatalog();
notice(result?.cache_cleanup_pending
? '云镜像模版已删除,宿主机缓存正在后台清理;离线宿主机会在恢复连接后继续清理。'
: '镜像模版已删除。');
} catch (error) {
notice(error.message, true);
remove.disabled = !canManage;
}
}); list.append(row);
} notice(rescue ? `已加载 ${entries.length} 个模版。` : `已加载 ${entries.length} 个全局云镜像。`);
} catch (error) { notice(error.message, true); }
}
async function importProgress(result) {
if (!result?.job_id) return;
const suffix = isRescueCatalog() ? `?host_id=${encodeURIComponent(state.selectedHost)}` : '';
const fallback = `${catalogPath()}/import-jobs/${encodeURIComponent(result.job_id)}${suffix}`;
const url = String(result.status_url || '').startsWith('/api/v1/') ? result.status_url : fallback;
for (let i = 0; i < 1800; i++) { const job = await api(url); notice(job.phase || `导入状态:${job.status}`); if (['succeeded', 'completed', 'done'].includes(job.status)) return; if (['failed', 'uncertain', 'cancelled'].includes(job.status)) throw new Error(job.error || '导入未完成,请核查宿主机状态后再操作。'); await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error('导入仍在进行,请稍后刷新查看。不要重复提交。');
}
async function importTemplate(event) {
event.preventDefault(); if (state.busy) return;
const sha256 = byId('template-sha256').value.trim().toLowerCase();
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
const body = { name: byId('template-name').value.trim(), url: byId('template-url').value.trim() };
if (sha256) body.sha256 = sha256;
const button = byId('template-import-button'); state.busy = true; button.disabled = true;
try { const result = await api('/api/v1/admin/cloud-templates/import', { method: 'POST', body }); await importProgress(result); await loadCatalog(); notice('镜像导入已完成。'); }
catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; }
}
async function uploadCloudTemplate(event) {
event.preventDefault();
if (state.busy) return;
const name = byId('template-upload-name').value.trim();
const selection = byId('template-upload-system').value;
const separator = selection.indexOf('|');
const osFamily = separator > 0 ? selection.slice(0, separator) : '';
const osVersion = separator > 0 ? selection.slice(separator + 1) : '';
const file = byId('template-upload-file').files?.[0];
if (!name || name.length > 64) return notice('请填写 1 至 64 个字符的模版名称。', true);
if (!osFamily || !osVersion) return notice('请选择镜像实际对应的系统和版本。', true);
if (!file || !file.name.toLowerCase().endsWith('.qcow2')) return notice('请选择扩展名为 .qcow2 的云镜像文件。', true);
if (file.size < 1024 ** 2 || file.size > 4 * 1024 ** 3) return notice('QCOW2 文件必须在 1 MiB 至 4 GiB 之间。', true);
const button = byId('template-upload-button');
const system = byId('template-upload-system');
const input = byId('template-upload-file');
state.busy = true;
button.disabled = true;
system.disabled = true;
input.disabled = true;
notice('正在上传云镜像,请勿关闭页面…');
const query = new URLSearchParams({ name, os_family: osFamily, os_version: osVersion, filename: file.name });
try {
const result = await uploadApi(`/api/v1/admin/cloud-templates/upload?${query}`, file, (loaded, total) => {
const percent = total > 0 ? Math.min(100, loaded * 100 / total) : 0;
notice(percent >= 100 ? '文件已上传至面板,正在校验并保存云镜像…' : `正在上传云镜像 ${percent.toFixed(1)}%,请勿关闭页面…`);
});
await importProgress(result);
input.value = '';
await loadCatalog();
notice('本地云镜像上传并导入完成。');
} catch (error) {
notice(error.message, true);
} finally {
state.busy = false;
button.disabled = !canManage;
system.disabled = !canManage;
input.disabled = !canManage;
}
}
async function uploadRescue(event) {
event.preventDefault(); if (state.busy) return; const hostId = byId('catalog-host').value; const file = byId('rescue-file').files?.[0]; if (!hostId || !file) return notice('请选择宿主机和 ISO。', true); if (!file.name.toLowerCase().endsWith('.iso') || file.size > 8 * 1024 ** 3 || file.size < 32768) return notice('请选择小于 8 GiB 的有效 ISO 文件。', true);
const button = byId('rescue-upload-button'); state.busy = true; button.disabled = true; byId('catalog-host').disabled = true; notice('正在上传救援 ISO,请勿关闭页面…');
try { const result = await api(`/api/v1/admin/rescue-templates/upload?host_id=${encodeURIComponent(hostId)}&name=${encodeURIComponent(byId('rescue-name').value.trim())}`, { method: 'POST', body: file, raw: true }); await importProgress(result); byId('rescue-file').value = ''; await loadCatalog(); notice('救援 ISO 导入已完成。'); }
catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; byId('catalog-host').disabled = false; }
}
async function records() {
const kind = root.dataset.cloudAdmin; notice('正在加载…');
try {
const payload = await api(`/api/v1/${kind === 'instances' ? 'vms' : 'orders'}`);
const entries = collection(payload, kind === 'instances' ? 'vms' : 'orders');
const tbody = byId('admin-records'); tbody.replaceChildren();
for (const record of entries) {
const row = element('tr');
const labels = kind === 'instances'
? ['实例', '用户', '宿主机', '状态', '公网 IP', '配置']
: ['任务', '用户', '套餐', '金额', '状态', '实例 / 引擎任务', '时间 / 错误'];
const fields = kind === 'instances'
? [record.name || record.id, record.owner_email || record.user_email || record.owner_user_id || record.user_id,
record.host_name || record.host_id, record.state || record.status,
String(record.public_ip_cidr || '').split('/')[0],
`${record.vcpu ?? record.cpu_cores ?? '—'} vCPU · ${record.memory_mib ?? '—'} MiB · ${record.disk_gib ?? '—'} GiB`]
: [record.id, record.user_email || record.user_id, record.plan_name || record.plan_id,
record.amount || record.price, orderStatus(record.status),
`${record.instance_id ? `实例 #${record.instance_id}` : '实例 —'} / ${record.job_id ? `任务 #${record.job_id}` : '任务 —'}${Number(record.attempts) > 0 ? ` · 尝试 ${record.attempts}` : ''}`,
`${unixTime(record.updated_at || record.created_at)}${record.error ? ' · ' + record.error : ''}`];
fields.forEach((field, index) => {
const cell = element('td', '', field ?? '—');
cell.dataset.label = labels[index];
row.append(cell);
});
tbody.append(row);
}
notice(`已加载 ${entries.length} 条记录。`);
} catch (error) { notice(error.message, true); }
}
async function initialize() {
if (!root) return;
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
if (root.dataset.cloudAdmin === 'hosts') { await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); } notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); }
else if (root.dataset.cloudAdmin === 'templates') { byId('template-import')?.addEventListener('submit', importTemplate); byId('template-upload')?.addEventListener('submit', uploadCloudTemplate); await loadCatalog(); }
else if (root.dataset.cloudAdmin === 'rescue') { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); byId('rescue-upload')?.addEventListener('submit', uploadRescue); await loadCatalog(); }
else { byId('admin-records-refresh').addEventListener('click', records); await records(); }
} catch (error) { notice(error.message, true); }
}
void initialize();