|
|
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 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; }
|
|
|
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-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, 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'; }
|
|
|
async function loadCatalog() {
|
|
|
const hostId = byId('catalog-host').value; state.selectedHost = hostId; const epoch = ++state.epoch; const list = byId('catalog-list'); list.replaceChildren(); if (!hostId) return list.append(element('p', 'text-muted', '请先添加宿主机。'));
|
|
|
notice('正在读取所选宿主机的模版…');
|
|
|
try { const entries = collection(await api(`${catalogPath()}?host_id=${encodeURIComponent(hostId)}`), '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; row.append(name, save, remove, element('small', 'cloud-admin-meta', `${entry.os_family || '镜像'} ${entry.os_version || ''} · ${entry.size_bytes ? (entry.size_bytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`));
|
|
|
if (root.dataset.cloudAdmin === 'rescue') { name.readOnly = true; save.hidden = true; save.disabled = true; }
|
|
|
row.addEventListener('submit', async event => { event.preventDefault(); if (root.dataset.cloudAdmin === 'rescue') return; save.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`, { method: 'PATCH', body: { host_id: Number(hostId), name: name.value.trim() } }); notice('名称已保存。'); } catch (error) { notice(error.message, true); } finally { save.disabled = !canManage; } });
|
|
|
remove.addEventListener('click', async () => { if (!confirm(`删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。`)) return; remove.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`, { method: 'DELETE' }); await loadCatalog(); } catch (error) { notice(error.message, true); remove.disabled = !canManage; } }); list.append(row);
|
|
|
} notice(`已加载 ${entries.length} 个模版。`);
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
async function importProgress(result) {
|
|
|
if (!result?.job_id) return;
|
|
|
const url = result.status_url || `${catalogPath()}/import-jobs/${encodeURIComponent(result.job_id)}?host_id=${encodeURIComponent(state.selectedHost)}`;
|
|
|
if (!url.startsWith('/api/v1/')) throw new Error('导入状态地址无效。');
|
|
|
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 hostId = byId('catalog-host').value; if (!hostId) return notice('请选择宿主机。', true);
|
|
|
const sha256 = byId('template-sha256').value.trim().toLowerCase();
|
|
|
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
|
|
|
const body = { host_id: Number(hostId), 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; byId('catalog-host').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; byId('catalog-host').disabled = false; }
|
|
|
}
|
|
|
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 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 : ''}`];
|
|
|
for (const field of fields) row.append(element('td', '', field ?? '—'));
|
|
|
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 loadHosts(); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); 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; }); notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); }
|
|
|
else if (['templates', 'rescue'].includes(root.dataset.cloudAdmin)) { 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); if (byId('template-import')) byId('template-import').addEventListener('submit', importTemplate); if (byId('rescue-upload')) 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();
|