|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const {
|
|
|
announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl,
|
|
|
taskSucceededWithoutRecovery,
|
|
|
} = await import(versionedModuleUrl('./task-observer.js'));
|
|
|
|
|
|
const root = document.querySelector('[data-admin-instances]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const columns = ['实例', '用户', '所在位置', '公网 IP', '配置', '状态', '用量与期限', '操作'];
|
|
|
const tabs = ['basic', 'service', 'backups', 'jobs', 'invoices'];
|
|
|
const filterNames = ['q', 'user_id', 'host_id', 'service_status', 'expiry', 'attention', 'sort', 'per_page'];
|
|
|
const state = {
|
|
|
items: [], pagination: { page: 1, per_page: 20, total: 0, total_pages: 1 },
|
|
|
request: null, serial: 0, loading: false, hasData: false, active: true, timer: null,
|
|
|
statusRequest: null, statusFailures: 0, detailRequest: null, detailId: null, detailClosing: false,
|
|
|
opener: null, scroll: null, networkRequest: null, networkOptionsRequest: null,
|
|
|
networkPollRequest: null, networkPollTimer: null, networkPollResolve: null, networkSerial: 0,
|
|
|
settingsRequest: null, settingsPollRequest: null, settingsPollTimer: null,
|
|
|
settingsPollResolve: null, settingsSerial: 0, networkObserver: null, settingsObserver: null,
|
|
|
backupRequest: null, backupMutationRequest: null, backupObserver: null,
|
|
|
backupSerial: 0, backupLoadedFor: null,
|
|
|
libraryRequest: null, libraryObserver: null, librarySerial: 0,
|
|
|
libraryPage: 1, libraryPagination: { page: 1, total_pages: 1, total: 0 },
|
|
|
libraryClosing: false,
|
|
|
};
|
|
|
|
|
|
function el(tag, className = '', text) {
|
|
|
const node = document.createElement(tag);
|
|
|
node.className = className;
|
|
|
if (text !== undefined) node.textContent = String(text);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function text(...values) {
|
|
|
return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—';
|
|
|
}
|
|
|
|
|
|
function stack(primary, secondary) {
|
|
|
const node = el('span', 'admin-checkout-user');
|
|
|
node.append(primary instanceof Node ? primary : el('strong', '', text(primary)));
|
|
|
if (secondary) node.append(el('span', '', secondary));
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function safeLink(value, label, className = '') {
|
|
|
try {
|
|
|
const url = new URL(value, location.origin);
|
|
|
if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) throw new Error('Unsafe URL');
|
|
|
const link = el('a', className, label);
|
|
|
link.href = url.pathname + url.search + url.hash;
|
|
|
return link;
|
|
|
} catch { return el('span', className, label); }
|
|
|
}
|
|
|
|
|
|
function date(value, short = false) {
|
|
|
if (!value) return '未记录';
|
|
|
const numeric = Number(value);
|
|
|
const timestamp = Number.isFinite(numeric) ? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(value);
|
|
|
const parsed = new Date(timestamp);
|
|
|
if (!Number.isFinite(parsed.getTime())) return '未记录';
|
|
|
return short ? parsed.toLocaleDateString('zh-CN') : parsed.toLocaleString('zh-CN', { hour12: false });
|
|
|
}
|
|
|
|
|
|
function parseIPv4(value) {
|
|
|
const parts = String(value ?? '').trim().split('.');
|
|
|
if (parts.length !== 4 || parts.some(part => !/^\d{1,3}$/.test(part))) return null;
|
|
|
const octets = parts.map(Number);
|
|
|
return octets.every(part => part >= 0 && part <= 255) ? octets : null;
|
|
|
}
|
|
|
|
|
|
function ipv4Number(octets) {
|
|
|
return (((octets[0] << 24) >>> 0) + (octets[1] << 16) + (octets[2] << 8) + octets[3]) >>> 0;
|
|
|
}
|
|
|
|
|
|
function normalizeCidr(value, fallbackPrefix = 24) {
|
|
|
const raw = String(value ?? '').trim();
|
|
|
if (!raw) return null;
|
|
|
const parts = raw.split('/');
|
|
|
if (parts.length > 2) return null;
|
|
|
if (parts.length === 2 && !/^\d+$/.test(parts[1])) return null;
|
|
|
const octets = parseIPv4(parts[0]);
|
|
|
if (!octets) return null;
|
|
|
const prefix = parts.length === 2 && parts[1] !== '' ? Number(parts[1]) : Number(fallbackPrefix);
|
|
|
if (!Number.isInteger(prefix) || prefix < 1 || prefix > 30) return null;
|
|
|
return { address: octets.join('.'), prefix, value: `${octets.join('.')}/${prefix}` };
|
|
|
}
|
|
|
|
|
|
function cidrContains(cidr, address) {
|
|
|
const network = normalizeCidr(cidr, null);
|
|
|
const ip = parseIPv4(address);
|
|
|
if (!network || !ip) return false;
|
|
|
const mask = network.prefix === 32 ? 0xffffffff : (0xffffffff << (32 - network.prefix)) >>> 0;
|
|
|
return (ipv4Number(parseIPv4(network.address)) & mask) === (ipv4Number(ip) & mask);
|
|
|
}
|
|
|
|
|
|
function publicPoolKey(value) {
|
|
|
const key = String(value ?? '').trim();
|
|
|
return /^[a-f0-9]{32}$/.test(key) ? key : '';
|
|
|
}
|
|
|
|
|
|
function networkOptionsFromVm(vm) {
|
|
|
const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24);
|
|
|
const prefix = current?.prefix || 24;
|
|
|
return {
|
|
|
configured: false,
|
|
|
current_ip_cidr: current?.value || '',
|
|
|
guest_prefix: prefix,
|
|
|
gateway: vm.gateway || '',
|
|
|
dns_servers: Array.isArray(vm.dns_servers) ? vm.dns_servers : [],
|
|
|
current_public_pool_key: '',
|
|
|
public_pool_cidr: '',
|
|
|
available_count: 0,
|
|
|
available_ips: [],
|
|
|
available_ip_options: [],
|
|
|
pools: [],
|
|
|
configuration_state: 'not_configured',
|
|
|
can_change: false,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function networkOptionsPayload(payload, vm) {
|
|
|
const source = payload?.network_options || payload?.network || payload || {};
|
|
|
const fallback = networkOptionsFromVm(vm);
|
|
|
const current = normalizeCidr(source.current_ip_cidr || vm.public_ip_cidr || vm.public_ip, fallback.guest_prefix);
|
|
|
const guestPrefix = Number(source.guest_prefix ?? source.public_vm_prefix ?? current?.prefix ?? fallback.guest_prefix);
|
|
|
const dns = Array.isArray(source.dns_servers) ? source.dns_servers.filter(value => parseIPv4(value)) : fallback.dns_servers;
|
|
|
const normalizedGuestPrefix = Number.isInteger(guestPrefix) && guestPrefix >= 24 && guestPrefix <= 30
|
|
|
? guestPrefix : fallback.guest_prefix;
|
|
|
const pools = [];
|
|
|
const poolsByKey = new Map();
|
|
|
for (const value of Array.isArray(source.pools) ? source.pools : []) {
|
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
|
|
|
const key = publicPoolKey(value.public_pool_key || value.pool_key);
|
|
|
const poolCidr = normalizeCidr(value.pool_cidr, null);
|
|
|
const poolPrefix = Number(value.guest_prefix);
|
|
|
const poolGateway = parseIPv4(value.gateway)?.join('.') || '';
|
|
|
if (!key || !poolCidr || !Number.isInteger(poolPrefix)
|
|
|
|| poolPrefix < 24 || poolPrefix > 30 || !poolGateway) continue;
|
|
|
const pool = {
|
|
|
public_pool_key: key,
|
|
|
pool_cidr: poolCidr.value,
|
|
|
guest_prefix: poolPrefix,
|
|
|
gateway: poolGateway,
|
|
|
dns_servers: Array.isArray(value.dns_servers)
|
|
|
? value.dns_servers.map(item => parseIPv4(item)?.join('.')).filter(Boolean) : [],
|
|
|
available_count: Math.max(0, Number(value.available_count) || 0),
|
|
|
};
|
|
|
pools.push(pool);
|
|
|
poolsByKey.set(key, pool);
|
|
|
}
|
|
|
const availableOptions = [];
|
|
|
const seenOptions = new Set();
|
|
|
for (const value of Array.isArray(source.available_ip_options) ? source.available_ip_options : []) {
|
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
|
|
|
const key = publicPoolKey(value.public_pool_key || value.pool_key);
|
|
|
const pool = poolsByKey.get(key);
|
|
|
const cidr = normalizeCidr(value.public_ip_cidr || value.cidr, pool?.guest_prefix);
|
|
|
const optionKey = cidr ? `${key}:${cidr.value}` : '';
|
|
|
if (!pool || !cidr || cidr.prefix !== pool.guest_prefix
|
|
|
|| !cidrContains(pool.pool_cidr, cidr.address) || seenOptions.has(optionKey)) continue;
|
|
|
seenOptions.add(optionKey);
|
|
|
availableOptions.push({ public_pool_key: key, public_ip_cidr: cidr.value });
|
|
|
}
|
|
|
const availableIps = availableOptions.map(value => value.public_ip_cidr);
|
|
|
return {
|
|
|
...fallback,
|
|
|
...source,
|
|
|
current_ip_cidr: current?.value || fallback.current_ip_cidr,
|
|
|
current_public_pool_key: publicPoolKey(source.current_public_pool_key),
|
|
|
guest_prefix: normalizedGuestPrefix,
|
|
|
public_pool_cidr: String(source.public_pool_cidr || source.pool_cidr || '').trim(),
|
|
|
gateway: String(source.gateway || fallback.gateway || '').trim(),
|
|
|
dns_servers: dns,
|
|
|
available_count: Number.isFinite(Number(source.available_count))
|
|
|
? Math.max(0, Number(source.available_count)) : availableIps.length,
|
|
|
available_ips: availableIps,
|
|
|
available_ip_options: availableOptions,
|
|
|
pools,
|
|
|
configuration_state: ['ready', 'not_configured', 'invalid', 'drift', 'unavailable']
|
|
|
.includes(source.configuration_state) ? source.configuration_state : 'unavailable',
|
|
|
can_change: source.can_change === true,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function networkOptionSummary(options, selectedPool = null) {
|
|
|
const pools = Array.isArray(options.pools) ? options.pools : [];
|
|
|
const selected = selectedPool || (pools.length === 1 ? pools[0] : null);
|
|
|
const pool = selected?.pool_cidr || (pools.length > 1 ? `${pools.length} 个启用地址池`
|
|
|
: (options.public_pool_cidr
|
|
|
|| (options.configuration_state === 'not_configured' ? '未配置' : '提交时由 Agent 校验')));
|
|
|
const prefix = selected?.guest_prefix ? `/${selected.guest_prefix}`
|
|
|
: (pools.length > 1 ? '按所选地址池' : (options.guest_prefix ? `/${options.guest_prefix}` : '未记录'));
|
|
|
const gateway = selected?.gateway || (pools.length > 1 ? '按所选地址池'
|
|
|
: (options.gateway || '提交时由宿主机配置决定'));
|
|
|
const dnsValues = selected?.dns_servers || (pools.length > 1 ? [] : options.dns_servers);
|
|
|
const dns = dnsValues?.length ? dnsValues.join('、')
|
|
|
: (pools.length > 1 ? '按所选地址池' : '宿主机默认 DNS');
|
|
|
const available = options.available_ip_options?.length
|
|
|
? `${options.available_ip_options.length} 个` : '暂无可用地址';
|
|
|
return { pool, prefix, gateway, dns, available };
|
|
|
}
|
|
|
|
|
|
function bytes(value) {
|
|
|
const number = Number(value);
|
|
|
if (value === null || value === undefined || !Number.isFinite(number) || number < 0) return '未记录';
|
|
|
if (number === 0) return '0 B';
|
|
|
const exponent = Math.min(4, Math.floor(Math.log(number) / Math.log(1024)));
|
|
|
return `${(number / 1024 ** exponent).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${['B', 'KiB', 'MiB', 'GiB', 'TiB'][exponent]}`;
|
|
|
}
|
|
|
|
|
|
function notice(message, error = false) {
|
|
|
const node = byId('instances-notice');
|
|
|
node.textContent = message;
|
|
|
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
|
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
async function api(path, controller) {
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
|
|
|
try {
|
|
|
const response = await fetch(path, {
|
|
|
headers: { Accept: 'application/json' }, credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
|
|
});
|
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录后刷新。');
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); }
|
|
|
if (!response.ok || payload?.ret === 0) {
|
|
|
const error = new Error(typeof payload?.detail === 'string' ? payload.detail : (payload?.message || `请求失败 (${response.status})`));
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timeout); }
|
|
|
}
|
|
|
|
|
|
async function mutate(path, body, controller, method = 'PATCH') {
|
|
|
if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
|
|
|
throw new Error('请通过 HTTPS 修改实例配置。');
|
|
|
}
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
|
|
|
try {
|
|
|
const response = await fetch(path, {
|
|
|
method,
|
|
|
headers: {
|
|
|
Accept: 'application/json',
|
|
|
'Content-Type': 'application/json',
|
|
|
'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '',
|
|
|
'Idempotency-Key': globalThis.crypto?.randomUUID?.()
|
|
|
|| `admin-${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,
|
|
|
},
|
|
|
credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
|
|
body: JSON.stringify(body),
|
|
|
});
|
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { 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(typeof detail === 'string' ? detail : (payload?.message || `请求失败 (${response.status})`));
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
if (response.status !== 202 || !taskUrl(payload)) {
|
|
|
const error = new Error('请求已送达,但任务回执协议无效。请勿重复提交,并联系管理员核查。');
|
|
|
error.status = response.status;
|
|
|
error.mutationMayHaveApplied = true;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') {
|
|
|
const timeoutError = new Error('请求超时,结果无法确认。请勿重复提交,并联系管理员核查。');
|
|
|
timeoutError.mutationMayHaveApplied = true;
|
|
|
throw timeoutError;
|
|
|
}
|
|
|
if (error?.status >= 500 || (!error?.status && error?.name !== 'AbortError')) {
|
|
|
error.mutationMayHaveApplied = true;
|
|
|
}
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timeout); }
|
|
|
}
|
|
|
|
|
|
function copyButton(value, label = '复制') {
|
|
|
const button = el('button', 'btn btn-light btn-sm');
|
|
|
button.type = 'button';
|
|
|
button.dataset.copy = String(value);
|
|
|
button.setAttribute('aria-label', `${label} ${value}`);
|
|
|
const icon = el('i', 'mdi mdi-content-copy');
|
|
|
icon.setAttribute('aria-hidden', 'true');
|
|
|
button.append(icon);
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function powerInfo(value, sync = '') {
|
|
|
const normalizedSync = String(sync || '').toLowerCase();
|
|
|
if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(normalizedSync)) {
|
|
|
return ['暂时无法同步', 'secondary'];
|
|
|
}
|
|
|
if (['pending', 'never'].includes(normalizedSync)) {
|
|
|
return ['等待宿主机同步', 'secondary'];
|
|
|
}
|
|
|
const normalized = String(value || '').toLowerCase().replace(/[_\s-]+/g, '');
|
|
|
return ({
|
|
|
running: ['运行中', 'success'], blocked: ['运行中', 'success'],
|
|
|
shutoff: ['已关机', 'secondary'], stopped: ['已关机', 'secondary'],
|
|
|
shutdown: ['关机中', 'warning'], paused: ['已暂停', 'warning'],
|
|
|
pmsuspended: ['已挂起', 'warning'], crashed: ['已崩溃', 'danger'],
|
|
|
})[normalized] || ['等待宿主机同步', 'secondary'];
|
|
|
}
|
|
|
|
|
|
function paintPower(node, vm) {
|
|
|
const sync = String(vm?.state_sync_status || '').toLowerCase();
|
|
|
const [label, tone] = powerInfo(vm?.state, sync);
|
|
|
const stale = !['', 'fresh'].includes(sync)
|
|
|
&& !['pending', 'never', 'unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync);
|
|
|
node.textContent = `电源:${label}${stale ? ' · 状态同步中' : ''}`;
|
|
|
node.className = `badge bg-${tone}-subtle text-${tone}-emphasis`;
|
|
|
node.title = sync === 'offline' || sync === 'unavailable'
|
|
|
? '宿主机暂时无法同步;保留最近一次状态,不表示已关机。'
|
|
|
: vm.live_state_available === true || sync === 'fresh'
|
|
|
? '来自运行状态缓存的最近成功同步结果'
|
|
|
: '尚未获取成功状态,或状态已超过有效期。';
|
|
|
}
|
|
|
|
|
|
function jobStatus(task) {
|
|
|
if (task?.completed === false && task.status === 'active') return '执行中';
|
|
|
if (task?.completed === true) {
|
|
|
if (task.recovery?.pending === true) {
|
|
|
const code = String(task.recovery?.code || task.finalization_error_code || '');
|
|
|
if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') {
|
|
|
return '派发账本异常 · 待修复';
|
|
|
}
|
|
|
if (task.dispatch_state === 'not_dispatched') return 'PHP 本地账本收尾中';
|
|
|
return task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中';
|
|
|
}
|
|
|
return ({ succeeded: '已成功', failed: '已失败' })[task.status]
|
|
|
|| '任务状态协议无效';
|
|
|
}
|
|
|
return '任务状态协议无效';
|
|
|
}
|
|
|
|
|
|
function mutationBlockMessage(task, action) {
|
|
|
if (task?.blocks_mutation !== true) return '';
|
|
|
const id = task?.id || '—';
|
|
|
if (task.completed === false && task.status === 'active') {
|
|
|
return `实例已有任务 #${id}(执行中),完成前不能${action}。`;
|
|
|
}
|
|
|
if (task.completed === true && task.recovery?.pending === true) {
|
|
|
const code = String(task.recovery?.code || task.finalization_error_code || '');
|
|
|
if (code === 'recovery_dispatch_ledger_conflict' || task.dispatch_state === 'invalid') {
|
|
|
return `任务 #${id} 的派发账本异常,资源保持安全锁定;修复账本并完成核验前不能${action}。`;
|
|
|
}
|
|
|
if (task.dispatch_state === 'not_dispatched') {
|
|
|
return `任务 #${id} 已确认未派发到宿主机,但 PHP 本地账本收尾尚未完成;收尾成功前不能${action}。`;
|
|
|
}
|
|
|
return `任务 #${id} 尚在持续恢复,资源保持安全锁定;恢复收敛前不能${action}。`;
|
|
|
}
|
|
|
if (task.completed === true && task.status === 'failed') {
|
|
|
return `任务 #${id} 已失败,资源安全锁定,需管理员人工处理后才能${action}。`;
|
|
|
}
|
|
|
return `任务 #${id} 状态协议无效,资源安全锁定,需管理员人工处理后才能${action}。`;
|
|
|
}
|
|
|
|
|
|
function taskFailureMessage(task, fallback) {
|
|
|
const message = task?.error || fallback;
|
|
|
const recoveryNotice = recoveryTaskFailureNotice(task);
|
|
|
if (recoveryNotice) return recoveryNotice;
|
|
|
if (task?.effect_may_have_applied) {
|
|
|
return `${message} 任务已失败,操作效果可能已经发生,相关资源已锁定。请勿再次提交,并将任务编号交由管理员核查。`;
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? `${message} 任务已失败且相关资源已锁定,请勿再次提交,并联系管理员核查。` : message;
|
|
|
}
|
|
|
|
|
|
function row(vm) {
|
|
|
const tr = el('tr');
|
|
|
tr.dataset.instanceId = String(vm.id);
|
|
|
const ip = el('span', 'admin-instance-ip');
|
|
|
ip.append(el('span', 'admin-mono', text(vm.public_ip, '未记录')));
|
|
|
if (vm.public_ip) ip.append(copyButton(vm.public_ip, '复制公网 IP'));
|
|
|
const statuses = el('div', 'admin-instance-status');
|
|
|
const power = el('span');
|
|
|
power.dataset.powerStatus = '';
|
|
|
paintPower(power, vm);
|
|
|
statuses.append(power, el('span', 'fs-12', `服务:${text(vm.display?.service)}`),
|
|
|
el('span', 'fs-12', `网络:${text(vm.display?.network)}`));
|
|
|
if (vm.active_job) {
|
|
|
const locked = vm.active_job.blocks_mutation === true;
|
|
|
statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job)}${locked ? ' · 资源安全锁定' : ''}`));
|
|
|
}
|
|
|
const detail = el('button', 'btn btn-primary btn-sm', '查看详情');
|
|
|
detail.type = 'button';
|
|
|
detail.dataset.instanceDetail = String(vm.id);
|
|
|
detail.setAttribute('aria-label', `查看 ${text(vm.name)} 的详情`);
|
|
|
const usage = stack(vm.display?.traffic, vm.display?.expiry);
|
|
|
if (vm.service_expires_at && vm.service_status !== 'exempt') usage.append(el('span', '', `到期 ${date(vm.service_expires_at, true)}`));
|
|
|
const cells = [
|
|
|
stack(text(vm.name), `#${vm.id} · ${text(vm.os_name, '系统未记录')}`),
|
|
|
stack(vm.user_url ? safeLink(vm.user_url, text(vm.user_name, `用户 #${vm.user_id}`)) : text(vm.user_name), `ID ${vm.user_id}`),
|
|
|
stack(text(vm.host_name, `宿主机 #${vm.host_id}`), text(vm.region, '地区未记录')),
|
|
|
ip, stack(vm.display?.configuration, text(vm.plan_name, '无关联套餐')),
|
|
|
statuses, usage, detail,
|
|
|
];
|
|
|
cells.forEach((content, index) => {
|
|
|
const td = el('td');
|
|
|
td.dataset.label = columns[index];
|
|
|
td.append(content);
|
|
|
tr.append(td);
|
|
|
});
|
|
|
return tr;
|
|
|
}
|
|
|
|
|
|
function renderRows() {
|
|
|
const body = byId('instances-body');
|
|
|
body.replaceChildren();
|
|
|
state.items.forEach(vm => body.append(row(vm)));
|
|
|
if (!state.items.length) {
|
|
|
const tr = el('tr');
|
|
|
const td = el('td', 'text-center text-muted py-4', '没有符合条件的实例。');
|
|
|
td.colSpan = columns.length;
|
|
|
tr.append(td); body.append(tr);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function renderPagination() {
|
|
|
const page = state.pagination;
|
|
|
byId('instances-count').textContent = state.hasData ? `共 ${page.total} 台` : '数据未获取';
|
|
|
byId('instances-page-label').textContent = state.hasData
|
|
|
? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 台` : '实例数据暂不可用';
|
|
|
byId('instances-previous').disabled = !state.hasData || state.loading || page.page <= 1;
|
|
|
byId('instances-next').disabled = !state.hasData || state.loading || page.page >= page.total_pages;
|
|
|
byId('instances-refresh').disabled = state.loading;
|
|
|
byId('instances-body').setAttribute('aria-busy', String(state.loading));
|
|
|
}
|
|
|
|
|
|
function syncForm(payload) {
|
|
|
const form = byId('instances-filter');
|
|
|
const hosts = form.elements.namedItem('host_id');
|
|
|
hosts.replaceChildren(new Option('全部宿主机', ''));
|
|
|
for (const host of payload.hosts || []) hosts.add(new Option(`${host.name}${host.region ? ` · ${host.region}` : ''}`, host.id));
|
|
|
for (const name of filterNames) {
|
|
|
const control = form.elements.namedItem(name);
|
|
|
const value = String(name === 'per_page' ? payload.pagination.per_page : (payload.filters?.[name] ?? ''));
|
|
|
if (control instanceof HTMLSelectElement && value && !Array.from(control.options).some(option => option.value === value)) {
|
|
|
control.add(new Option(value, value));
|
|
|
}
|
|
|
control.value = value || ({ expiry: 'all', attention: 'all', sort: 'newest' })[name] || '';
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function applyPayload(payload, replaceRows = true) {
|
|
|
if (!Array.isArray(payload?.items) || !payload?.pagination) throw new Error('实例数据格式无效,请重试。');
|
|
|
state.items = payload.items;
|
|
|
state.pagination = payload.pagination;
|
|
|
state.hasData = true;
|
|
|
for (const key of ['total', 'expiring', 'network_restricted', 'attention']) {
|
|
|
byId(`instances-${key.replaceAll('_', '-')}`).textContent = Number(payload.summary?.[key] ?? 0).toLocaleString('zh-CN');
|
|
|
}
|
|
|
syncForm(payload);
|
|
|
if (replaceRows) renderRows();
|
|
|
renderPagination();
|
|
|
}
|
|
|
|
|
|
function formUrl(page = 1) {
|
|
|
const url = new URL(location.pathname, location.origin);
|
|
|
const form = byId('instances-filter');
|
|
|
for (const key of filterNames) {
|
|
|
const value = form.elements.namedItem(key).value.trim();
|
|
|
if (value && value !== 'all' && !(key === 'sort' && value === 'newest')) url.searchParams.set(key, value);
|
|
|
}
|
|
|
if (page > 1) url.searchParams.set('page', String(page));
|
|
|
return url;
|
|
|
}
|
|
|
|
|
|
function stopStatuses() {
|
|
|
clearTimeout(state.timer);
|
|
|
state.timer = null;
|
|
|
state.statusRequest?.abort();
|
|
|
state.statusRequest = null;
|
|
|
}
|
|
|
|
|
|
function scheduleStatuses() {
|
|
|
clearTimeout(state.timer);
|
|
|
if (!state.active || document.hidden || !state.items.length || state.loading) return;
|
|
|
state.timer = setTimeout(refreshStatuses, Math.min(120000, 30000 * 2 ** state.statusFailures));
|
|
|
}
|
|
|
|
|
|
async function refreshStatuses() {
|
|
|
if (!state.active || document.hidden || state.loading || state.statusRequest || !state.items.length) return;
|
|
|
const controller = new AbortController();
|
|
|
state.statusRequest = controller;
|
|
|
const serial = state.serial;
|
|
|
byId('instances-live-status').textContent = '正在更新当前页电源状态…';
|
|
|
try {
|
|
|
const ids = state.items.map(vm => vm.id).join(',');
|
|
|
const payload = await api(`/api/v1/vms/statuses?ids=${encodeURIComponent(ids)}`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.serial) return;
|
|
|
const updates = Array.isArray(payload?.vms) ? payload.vms : [];
|
|
|
let syncing = 0;
|
|
|
for (const vm of state.items) {
|
|
|
const update = updates.find(item => String(item.api_id ?? item.id) === String(vm.id) && item.uuid === vm.uuid);
|
|
|
const candidate = String(update?.state || update?.status || '').trim();
|
|
|
const normalized = candidate.toLowerCase().replace(/[_\s-]+/g, '');
|
|
|
const hasState = candidate !== '' && !['unknown', 'nostate'].includes(normalized);
|
|
|
if (hasState) vm.state = candidate;
|
|
|
vm.live_state_available = update?.live_state_available === true;
|
|
|
vm.state_fresh = update?.state_fresh === true || update?.fresh === true
|
|
|
|| update?.fresh === 1 || update?.fresh === '1' || vm.live_state_available;
|
|
|
vm.state_sync_status = String(update?.state_sync_status ?? update?.sync_status
|
|
|
?? (vm.live_state_available ? 'fresh' : vm.state_sync_status || 'pending')).toLowerCase();
|
|
|
if (!['', 'fresh'].includes(vm.state_sync_status)) syncing += 1;
|
|
|
const rowNode = Array.from(byId('instances-body').rows).find(node => node.dataset.instanceId === String(vm.id));
|
|
|
const badge = rowNode?.querySelector('[data-power-status]');
|
|
|
if (badge) paintPower(badge, vm);
|
|
|
}
|
|
|
state.statusFailures = 0;
|
|
|
byId('instances-live-status').textContent = `电源状态更新于 ${new Date().toLocaleTimeString('zh-CN')}${syncing ? ` · ${syncing} 台状态同步中` : ''}`;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial !== state.serial) return;
|
|
|
state.statusFailures = Math.min(2, state.statusFailures + 1);
|
|
|
for (const vm of state.items) {
|
|
|
vm.live_state_available = false;
|
|
|
vm.state_sync_status = 'offline';
|
|
|
}
|
|
|
state.items.forEach(vm => {
|
|
|
const rowNode = Array.from(byId('instances-body').rows)
|
|
|
.find(node => node.dataset.instanceId === String(vm.id));
|
|
|
const badge = rowNode?.querySelector('[data-power-status]');
|
|
|
if (badge) paintPower(badge, vm);
|
|
|
});
|
|
|
byId('instances-live-status').textContent = `${error.message} 列表已保留,电源状态暂时无法同步。`;
|
|
|
} finally {
|
|
|
if (state.statusRequest === controller) { state.statusRequest = null; scheduleStatuses(); }
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadPage(url, historyMode = 'push') {
|
|
|
state.request?.abort();
|
|
|
stopStatuses();
|
|
|
const controller = new AbortController();
|
|
|
state.request = controller;
|
|
|
const serial = ++state.serial;
|
|
|
state.loading = true;
|
|
|
renderPagination();
|
|
|
notice('正在读取实例数据…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/instances${url.search}`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.serial) return;
|
|
|
applyPayload(payload);
|
|
|
const canonical = formUrl(payload.pagination.page);
|
|
|
if (historyMode === 'push' && canonical.href !== location.href) history.pushState(null, '', canonical);
|
|
|
notice(`已读取 ${payload.pagination.total} 台实例 · ${new Date().toLocaleTimeString('zh-CN')}`);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial === state.serial) notice(`${error.message} 已保留原列表。`, true);
|
|
|
} finally {
|
|
|
if (serial === state.serial) {
|
|
|
state.loading = false;
|
|
|
state.request = null;
|
|
|
renderPagination();
|
|
|
void refreshStatuses();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function infoList(entries) {
|
|
|
const list = el('dl', 'admin-instance-details');
|
|
|
entries.forEach(([label, value]) => {
|
|
|
list.append(el('dt', '', label));
|
|
|
const dd = el('dd');
|
|
|
dd.append(value instanceof Node ? value : document.createTextNode(String(text(value))));
|
|
|
list.append(dd);
|
|
|
});
|
|
|
return list;
|
|
|
}
|
|
|
|
|
|
function chooseTab(name, focus = false) {
|
|
|
tabs.forEach(tab => {
|
|
|
const button = byId(`instance-tab-${tab}`);
|
|
|
button.setAttribute('aria-selected', String(tab === name));
|
|
|
button.tabIndex = tab === name ? 0 : -1;
|
|
|
byId(`instance-panel-${tab}`).hidden = tab !== name;
|
|
|
});
|
|
|
if (focus) byId(`instance-tab-${name}`).focus();
|
|
|
if (name === 'backups' && state.detailId) void loadBackups(state.detailId);
|
|
|
}
|
|
|
|
|
|
function detailNotice(message, error = false) {
|
|
|
const node = byId('instance-detail-notice');
|
|
|
node.textContent = message;
|
|
|
node.hidden = !message;
|
|
|
node.className = `alert alert-${error ? 'danger' : 'info'}`;
|
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function setNetworkFeedback(section, message, tone = 'muted') {
|
|
|
const node = section?.querySelector('.admin-instance-network-feedback');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message;
|
|
|
node.className = `admin-instance-network-feedback text-${tone} fs-13 mb-2`;
|
|
|
node.textContent = message || '';
|
|
|
}
|
|
|
|
|
|
function cancelNetworkActivity(reason = 'cancelled') {
|
|
|
clearTimeout(state.networkPollTimer);
|
|
|
state.networkPollTimer = null;
|
|
|
state.networkPollResolve?.(false);
|
|
|
state.networkPollResolve = null;
|
|
|
state.networkOptionsRequest?.abort(reason);
|
|
|
state.networkPollRequest?.abort(reason);
|
|
|
state.networkRequest?.abort(reason);
|
|
|
state.networkOptionsRequest = null;
|
|
|
state.networkPollRequest = null;
|
|
|
state.networkRequest = null;
|
|
|
state.networkObserver?.stop(reason);
|
|
|
state.networkObserver = null;
|
|
|
state.networkSerial += 1;
|
|
|
}
|
|
|
|
|
|
function setSettingsFeedback(section, message, tone = 'muted') {
|
|
|
const node = section?.querySelector('[data-settings-feedback]');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message;
|
|
|
node.className = `admin-instance-settings-feedback text-${tone} fs-13 mb-2`;
|
|
|
node.textContent = message || '';
|
|
|
}
|
|
|
|
|
|
function cancelSettingsActivity(reason = 'cancelled') {
|
|
|
clearTimeout(state.settingsPollTimer);
|
|
|
state.settingsPollTimer = null;
|
|
|
state.settingsPollResolve?.(false);
|
|
|
state.settingsPollResolve = null;
|
|
|
state.settingsPollRequest?.abort(reason);
|
|
|
state.settingsRequest?.abort(reason);
|
|
|
state.settingsPollRequest = null;
|
|
|
state.settingsRequest = null;
|
|
|
state.settingsObserver?.stop(reason);
|
|
|
state.settingsObserver = null;
|
|
|
state.settingsSerial += 1;
|
|
|
}
|
|
|
|
|
|
function cancelBackupActivity(reason = 'cancelled') {
|
|
|
state.backupSerial += 1;
|
|
|
state.backupRequest?.abort(reason);
|
|
|
state.backupMutationRequest?.abort(reason);
|
|
|
state.backupRequest = null;
|
|
|
state.backupMutationRequest = null;
|
|
|
state.backupObserver?.stop(reason);
|
|
|
state.backupObserver = null;
|
|
|
state.backupLoadedFor = null;
|
|
|
}
|
|
|
|
|
|
function backupStatus(value) {
|
|
|
return ({
|
|
|
creating: ['正在备份', 'warning'], ready: ['可恢复', 'success'],
|
|
|
restoring: ['正在恢复', 'warning'], failed: ['备份失败', 'danger'],
|
|
|
uncertain: ['效果待核对', 'danger'], deleting: ['正在删除', 'warning'],
|
|
|
delete_uncertain: ['删除待核对', 'danger'],
|
|
|
delete_attention: ['清理需人工处理', 'danger'], deleted: ['已删除', 'secondary'],
|
|
|
})[String(value || '').toLowerCase()] || ['状态未知', 'secondary'];
|
|
|
}
|
|
|
|
|
|
function backupConsistency(value) {
|
|
|
return value === 'filesystem' ? '文件系统一致' : '崩溃一致';
|
|
|
}
|
|
|
|
|
|
function backupTargets(payload, backup) {
|
|
|
const values = Array.isArray(backup?.restore_targets) ? backup.restore_targets
|
|
|
: (Array.isArray(payload?.restore_targets) ? payload.restore_targets
|
|
|
: (Array.isArray(payload?.target_hosts) ? payload.target_hosts : []));
|
|
|
return values.filter(value => value && typeof value === 'object'
|
|
|
&& /^[1-9][0-9]*$/.test(String(value.host_id ?? value.id ?? '')));
|
|
|
}
|
|
|
|
|
|
function backupFeedback(section, message, tone = 'muted') {
|
|
|
const node = section.querySelector('[data-backup-feedback]');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message;
|
|
|
node.className = `text-${tone} fs-13 mb-2`;
|
|
|
node.textContent = message || '';
|
|
|
}
|
|
|
|
|
|
function backupMutationUrl(vmId, backupId, action = '', library = false) {
|
|
|
const base = library
|
|
|
? `/api/v1/admin/backups/${encodeURIComponent(backupId)}`
|
|
|
: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups/${encodeURIComponent(backupId)}`;
|
|
|
return action ? `${base}/${action}` : base;
|
|
|
}
|
|
|
|
|
|
function refreshBackupSurface(vmId, library) {
|
|
|
if (library) void loadBackupLibrary(state.libraryPage, true);
|
|
|
else void loadBackups(vmId, true);
|
|
|
}
|
|
|
|
|
|
function backupSurfaceNotice(message, error, library) {
|
|
|
if (library) libraryNotice(message, error);
|
|
|
else detailNotice(message, error);
|
|
|
}
|
|
|
|
|
|
async function deleteBackupObject(vmId, backup, controller, library = false) {
|
|
|
if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
|
|
|
throw new Error('请通过 HTTPS 删除备份。');
|
|
|
}
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
|
|
|
try {
|
|
|
const response = await fetch(
|
|
|
backupMutationUrl(vmId, backup.id, '', library),
|
|
|
{
|
|
|
method: 'DELETE',
|
|
|
headers: {
|
|
|
Accept: 'application/json',
|
|
|
'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '',
|
|
|
'Idempotency-Key': globalThis.crypto?.randomUUID?.()
|
|
|
|| `admin-${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,
|
|
|
},
|
|
|
credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
|
|
},
|
|
|
);
|
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); }
|
|
|
if (!response.ok || payload?.ret === 0) {
|
|
|
const error = new Error(typeof payload?.detail === 'string'
|
|
|
? payload.detail : (payload?.message || `请求失败 (${response.status})`));
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
if (payload?.deleted !== true && payload?.requires_reconciliation !== true
|
|
|
&& payload?.requires_attention !== true) {
|
|
|
const error = new Error('删除回执状态无效,请勿重复删除,先刷新核对。');
|
|
|
error.mutationMayHaveApplied = true;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') {
|
|
|
const timeoutError = new Error('删除请求超时,结果无法确认。请刷新后使用“核对删除状态”,不要重复删除。');
|
|
|
timeoutError.mutationMayHaveApplied = true;
|
|
|
throw timeoutError;
|
|
|
}
|
|
|
if (error?.status >= 500 || (!error?.status && error?.name !== 'AbortError')) {
|
|
|
error.mutationMayHaveApplied = true;
|
|
|
}
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timeout); }
|
|
|
}
|
|
|
|
|
|
function backupDeleteButton(vmId, backup, library = false) {
|
|
|
const reconcile = backup.delete_action === 'reconcile';
|
|
|
const button = el('button', reconcile ? 'btn btn-warning btn-sm' : 'btn btn-outline-danger btn-sm',
|
|
|
reconcile ? '核对删除状态' : '删除备份');
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
if (state.backupMutationRequest || backup.can_delete !== true) return;
|
|
|
if (!reconcile && !window.confirm(`确定删除备份“${String(backup.name || backup.id)}”吗?对象存储中的系统盘对象将被删除,且无法恢复。`)) return;
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller; button.disabled = true;
|
|
|
backupSurfaceNotice(reconcile
|
|
|
? '正在核对准确对象版本;只有两次间隔证据一致才会创建新的删除代次。'
|
|
|
: '正在删除对象存储备份,请勿重复提交。', false, library);
|
|
|
try {
|
|
|
const result = await deleteBackupObject(vmId, backup, controller, library);
|
|
|
backupSurfaceNotice(result.deleted === true
|
|
|
? '备份对象已确认删除。'
|
|
|
: (result.requires_attention === true
|
|
|
? '自动清理已达到三次上限,请到对象存储的“对象清理异常”中核查。'
|
|
|
: '删除结果仍不确定;系统将按稳定证据继续受控核对。'),
|
|
|
result.deleted !== true, library);
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
backupSurfaceNotice(error.message, true, library);
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
button.disabled = false;
|
|
|
}
|
|
|
});
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function backupWorkspaceCleanupButton(vmId, backup, library = false) {
|
|
|
const button = el('button', 'btn btn-outline-warning btn-sm', '核对并清理临时工作区');
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
if (state.backupMutationRequest || backup.can_cleanup_workspace !== true) return;
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller; button.disabled = true;
|
|
|
backupSurfaceNotice('正在读取原备份操作的最新宿主机证据并创建精确清理任务。', false, library);
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
`/api/v1/admin/backups/${encodeURIComponent(backup.id)}/cleanup-workspace`,
|
|
|
{}, controller, 'POST',
|
|
|
);
|
|
|
backupSurfaceNotice(`工作区清理任务 #${receipt.task_id || '—'} 已接收。`, false, library);
|
|
|
if (!library) watchBackupTask(vmId, receipt, '清理备份工作区');
|
|
|
else announceTaskAccepted(receipt, { title: '清理备份工作区' });
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
backupSurfaceNotice(error.message, true, library);
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
button.disabled = false;
|
|
|
}
|
|
|
});
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function watchBackupTask(vmId, receipt, title) {
|
|
|
const serial = state.backupSerial;
|
|
|
const taskId = receipt?.task_id || '—';
|
|
|
announceTaskAccepted(receipt, { title });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onTerminal: task => {
|
|
|
if (serial !== state.backupSerial || state.detailId !== String(vmId)) return;
|
|
|
state.backupObserver = null;
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
detailNotice(succeeded
|
|
|
? `${title}任务 #${taskId} 已成功。`
|
|
|
: taskFailureMessage(task, `${title}任务 #${taskId} 执行失败。`), !succeeded);
|
|
|
void loadBackups(vmId, true);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.backupObserver === handle) state.backupObserver = null;
|
|
|
if (reason === 'pagehide' || reason === 'closed' || reason === 'replaced'
|
|
|
|| serial !== state.backupSerial) return;
|
|
|
detailNotice(`${title}任务 #${taskId} 的自动观察已停止,请在任务记录查看最终结果。`, true);
|
|
|
void loadBackups(vmId, true);
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
detailNotice('任务已接收,但任务回执协议无效。请勿重复提交,并联系管理员核查。', true);
|
|
|
return;
|
|
|
}
|
|
|
state.backupObserver?.stop('replaced');
|
|
|
state.backupObserver = handle;
|
|
|
}
|
|
|
|
|
|
function watchLibraryBackupTask(receipt, title) {
|
|
|
const serial = state.librarySerial;
|
|
|
const taskId = receipt?.task_id || '—';
|
|
|
announceTaskAccepted(receipt, { title });
|
|
|
const handle = observeTask(receipt, {
|
|
|
onTerminal: task => {
|
|
|
if (serial !== state.librarySerial || !byId('backup-library')?.open) return;
|
|
|
state.libraryObserver = null;
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
libraryNotice(succeeded
|
|
|
? `${title}任务 #${taskId} 已成功。`
|
|
|
: taskFailureMessage(task, `${title}任务 #${taskId} 执行失败。`), !succeeded);
|
|
|
void loadBackupLibrary(state.libraryPage, true);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.libraryObserver === handle) state.libraryObserver = null;
|
|
|
if (reason === 'pagehide' || reason === 'closed' || reason === 'replaced'
|
|
|
|| serial !== state.librarySerial) return;
|
|
|
libraryNotice(`${title}任务 #${taskId} 的自动观察已停止,请在任务记录查看最终结果。`, true);
|
|
|
void loadBackupLibrary(state.libraryPage, true);
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
libraryNotice('任务已接收,但任务回执协议无效。请勿重复提交,并联系管理员核查。', true);
|
|
|
return;
|
|
|
}
|
|
|
state.libraryObserver?.stop('replaced');
|
|
|
state.libraryObserver = handle;
|
|
|
}
|
|
|
|
|
|
function restoreForm(vmId, backup, targets, mutationBlocked, library = false) {
|
|
|
const form = el('form', 'mt-3');
|
|
|
form.noValidate = true;
|
|
|
const grid = el('div', 'row g-2');
|
|
|
const hostLabel = el('label', 'col-12 col-lg-6');
|
|
|
hostLabel.append(el('span', 'form-label d-block', '恢复到宿主机'));
|
|
|
const host = el('select', 'form-select');
|
|
|
host.name = 'target_host_id'; host.required = true;
|
|
|
host.append(new Option(targets.length ? '请选择目标宿主机' : '暂无符合条件的宿主机', ''));
|
|
|
targets.forEach(target => {
|
|
|
const id = String(target.host_id ?? target.id);
|
|
|
const name = text(target.host_name, target.name, `宿主机 #${id}`);
|
|
|
const region = String(target.region || target.region_name || '').trim();
|
|
|
const available = Number(target.available_ip_count ?? target.available_count);
|
|
|
const suffix = Number.isFinite(available) ? ` · ${available} 个可用 IP` : '';
|
|
|
const source = target.is_source_host === true ? ' · 原宿主机' : '';
|
|
|
host.append(new Option(`${name}${region ? ` · ${region}` : ''}${source}${suffix}`, id));
|
|
|
});
|
|
|
host.disabled = mutationBlocked || targets.length === 0;
|
|
|
hostLabel.append(host);
|
|
|
const nameLabel = el('label', 'col-12 col-lg-6');
|
|
|
nameLabel.append(el('span', 'form-label d-block', '新实例名称'));
|
|
|
const name = el('input', 'form-control');
|
|
|
name.name = 'name'; name.type = 'text'; name.maxLength = 63;
|
|
|
name.placeholder = `${String(backup.name || 'backup').slice(0, 48)}-restore`;
|
|
|
name.required = true; name.disabled = mutationBlocked || targets.length === 0;
|
|
|
nameLabel.append(name); grid.append(hostLabel, nameLabel); form.append(grid);
|
|
|
const confirmLabel = el('label', 'admin-instance-settings-confirm mt-3');
|
|
|
const confirm = document.createElement('input');
|
|
|
confirm.type = 'checkbox'; confirm.name = 'confirm_new_instance';
|
|
|
confirm.disabled = mutationBlocked || targets.length === 0;
|
|
|
confirmLabel.append(confirm, document.createTextNode(
|
|
|
'我确认这会创建一台免计费的独立新实例,使用 br0 并分配全新公网 IP;不会继承原 IP、账单、到期时间或流量周期。'));
|
|
|
form.append(confirmLabel);
|
|
|
const feedback = el('p', 'text-muted fs-13 mb-2');
|
|
|
feedback.dataset.restoreFeedback = ''; feedback.hidden = true;
|
|
|
feedback.setAttribute('role', 'status'); form.append(feedback);
|
|
|
const actions = el('div', 'd-flex justify-content-end mt-2');
|
|
|
const submit = el('button', 'btn btn-primary btn-sm', '创建恢复实例');
|
|
|
submit.type = 'submit'; submit.disabled = mutationBlocked || targets.length === 0;
|
|
|
actions.append(submit); form.append(actions);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.backupMutationRequest || mutationBlocked) return;
|
|
|
const targetHostId = String(host.value || '');
|
|
|
const instanceName = String(name.value || '').trim();
|
|
|
const show = (message, tone = 'danger') => {
|
|
|
feedback.hidden = false; feedback.className = `text-${tone} fs-13 mb-2`;
|
|
|
feedback.textContent = message;
|
|
|
};
|
|
|
if (!/^[1-9][0-9]*$/.test(targetHostId)) return show('请选择目标宿主机。');
|
|
|
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/.test(instanceName)) {
|
|
|
return show('新实例名称需为 1 至 63 位英文、数字、点、下划线或连字符,并以英文或数字开头。');
|
|
|
}
|
|
|
if (!confirm.checked) return show('请确认新实例、br0 和全新公网 IP 的恢复规则。');
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller;
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
show('正在预留目标资源并创建恢复任务,请勿重复提交…', 'muted');
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
backupMutationUrl(vmId, backup.id, 'restore', library),
|
|
|
{ target_host_id: Number(targetHostId), name: instanceName, confirm_new_instance: true },
|
|
|
controller,
|
|
|
'POST',
|
|
|
);
|
|
|
show(`恢复任务 #${receipt.task_id || '—'} 已接收。`, 'muted');
|
|
|
backupSurfaceNotice('恢复任务已接收;目标资源会保持预留,直到任务得到明确结果。', false, library);
|
|
|
if (library) watchLibraryBackupTask(receipt, '备份恢复');
|
|
|
else watchBackupTask(vmId, receipt, '备份恢复');
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
show(error.message);
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
backupSurfaceNotice(error.message, true, library);
|
|
|
refreshBackupSurface(vmId, library);
|
|
|
} else {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
|
|
|
if (!targets.length) { host.disabled = true; submit.disabled = true; confirm.disabled = true; }
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
}
|
|
|
});
|
|
|
return form;
|
|
|
}
|
|
|
|
|
|
function maintenanceMigrationSection(payload, vmId) {
|
|
|
const section = el('section', 'card mb-3');
|
|
|
const body = el('div', 'card-body');
|
|
|
body.append(el('h3', 'h6 fw-semibold', '维护迁移'));
|
|
|
const migration = payload?.maintenance_migration;
|
|
|
if (migration && typeof migration === 'object') {
|
|
|
const progress = migration?.progress && typeof migration.progress === 'object'
|
|
|
? migration.progress : {};
|
|
|
const stateLabel = text(progress.label, '状态未知');
|
|
|
body.append(infoList([
|
|
|
['状态', stateLabel],
|
|
|
['迁移方向', `宿主机 #${text(migration.source_host_id)} → #${text(migration.target_host_id)}`],
|
|
|
['源副本策略', migration.cleanup_mode === 'delete' ? '目标验证后自动清理' : '保留并由管理员稍后清理'],
|
|
|
['切换时间', date(migration.cutover_at)],
|
|
|
['完成时间', date(migration.completed_at)],
|
|
|
]));
|
|
|
const progressSteps = Array.isArray(progress.steps) ? progress.steps : [];
|
|
|
if (progressSteps.length) {
|
|
|
const progressBox = el('div', 'mb-3');
|
|
|
const currentStage = progress?.current_stage;
|
|
|
const currentIndex = Number(currentStage?.index);
|
|
|
const stageCount = Number(progress?.stage_count);
|
|
|
const heading = currentStage && Number.isInteger(currentIndex)
|
|
|
&& currentIndex > 0 && Number.isInteger(stageCount) && stageCount > 0
|
|
|
? `当前阶段 ${currentIndex}/${stageCount} · ${text(currentStage.label)}`
|
|
|
: text(currentStage?.label, stateLabel);
|
|
|
progressBox.append(el('p', 'fw-semibold fs-13 mb-2', heading));
|
|
|
const stepList = el('div', 'd-flex flex-wrap gap-2');
|
|
|
const tones = {
|
|
|
completed: 'text-success', running: 'text-primary',
|
|
|
attention_required: 'text-danger', available: 'text-warning',
|
|
|
interrupted: 'text-danger', skipped: 'text-muted', pending: 'text-muted',
|
|
|
};
|
|
|
progressSteps.forEach(step => {
|
|
|
if (!step || typeof step !== 'object') return;
|
|
|
const status = String(step.status || 'pending');
|
|
|
const item = el('span',
|
|
|
`d-inline-flex align-items-center gap-1 border rounded-pill px-2 py-1 fs-13 ${tones[status] || 'text-muted'}`);
|
|
|
item.append(el('span', 'fw-semibold', text(step.label, '未知阶段')),
|
|
|
el('span', '', text(step.status_label, '等待中')));
|
|
|
stepList.append(item);
|
|
|
});
|
|
|
progressBox.append(stepList);
|
|
|
if (currentStage?.key === 'transfer'
|
|
|
&& progress.byte_progress_available !== true) {
|
|
|
progressBox.append(el('p', 'text-muted fs-13 mb-0 mt-2',
|
|
|
'当前协议提供可靠的阶段进度;尚未提供可持久化的字节传输百分比。'));
|
|
|
}
|
|
|
body.append(progressBox);
|
|
|
}
|
|
|
if (migration.state === 'attention_required') {
|
|
|
body.append(el('p', 'alert alert-danger fs-13',
|
|
|
'系统不会自动重放不确定操作。请等待原操作编号收敛;只有确认可重试时,下方才会显示恢复按钮。'));
|
|
|
} else if (migration.source_retained === true) {
|
|
|
body.append(el('p', migration.recovery_action === 'reconcile_cleanup'
|
|
|
? 'alert alert-danger fs-13' : 'alert alert-warning fs-13',
|
|
|
migration.recovery_action === 'reconcile_cleanup'
|
|
|
? '源副本删除效果正在按原操作编号核对,资源保持占用且不会盲目重放删除。'
|
|
|
: '目标实例已经接管原账单、到期时间和流量周期;源宿主机副本及原公网 IP 仍被保留并占用资源。'));
|
|
|
}
|
|
|
const recoveryOptions = Array.isArray(migration.recovery_options)
|
|
|
? migration.recovery_options.filter(option => option
|
|
|
&& typeof option === 'object'
|
|
|
&& /^[a-z_]+$/.test(String(option.action || ''))
|
|
|
&& String(option.label || '').trim()) : [];
|
|
|
if (recoveryOptions.length) {
|
|
|
const recoveryBox = el('div', 'd-flex flex-wrap justify-content-end gap-2 mb-2');
|
|
|
recoveryOptions.forEach(option => {
|
|
|
const action = String(option.action);
|
|
|
const label = String(option.label).trim();
|
|
|
const aborting = option.destructive === true;
|
|
|
const button = el('button', aborting
|
|
|
? 'btn btn-outline-danger btn-sm' : 'btn btn-outline-primary btn-sm', label);
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
const warning = aborting
|
|
|
? '确定中止本次迁移并将源实例恢复到迁移前电源与自启状态吗?'
|
|
|
: `确定${label}吗?`;
|
|
|
if (state.backupMutationRequest || !window.confirm(warning)) return;
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller;
|
|
|
for (const item of recoveryBox.querySelectorAll('button')) item.disabled = true;
|
|
|
detailNotice(`正在创建“${label}”任务,请勿重复提交。`);
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
`/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations/recover`,
|
|
|
{ action, confirm_recovery: true }, controller, 'POST');
|
|
|
watchBackupTask(vmId, receipt, label);
|
|
|
void loadBackups(vmId, true);
|
|
|
} catch (error) {
|
|
|
if (!(controller.signal.aborted && controller.signal.reason !== 'timeout')) {
|
|
|
detailNotice(error.message, true); void loadBackups(vmId, true);
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
for (const item of recoveryBox.querySelectorAll('button')) item.disabled = false;
|
|
|
}
|
|
|
});
|
|
|
recoveryBox.append(button);
|
|
|
});
|
|
|
body.append(recoveryBox);
|
|
|
}
|
|
|
if (migration.can_cleanup === true) {
|
|
|
const cleanup = el('button', 'btn btn-outline-danger btn-sm', '清理源宿主机副本');
|
|
|
cleanup.type = 'button';
|
|
|
cleanup.addEventListener('click', async () => {
|
|
|
if (state.backupMutationRequest
|
|
|
|| !window.confirm('确定删除源宿主机上的旧虚拟机及其托管磁盘吗?目标实例和账单不会删除。')) return;
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller; cleanup.disabled = true;
|
|
|
detailNotice('正在创建源副本清理任务,请勿重复提交。');
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
`/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations/cleanup`,
|
|
|
{ confirm_source_cleanup: true }, controller, 'POST');
|
|
|
watchBackupTask(vmId, receipt, '清理迁移源副本');
|
|
|
void loadBackups(vmId, true);
|
|
|
} catch (error) {
|
|
|
if (!(controller.signal.aborted && controller.signal.reason !== 'timeout')) {
|
|
|
detailNotice(error.message, true); void loadBackups(vmId, true);
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
cleanup.disabled = false;
|
|
|
}
|
|
|
});
|
|
|
const cleanupActions = el('div', 'd-flex justify-content-end');
|
|
|
cleanupActions.append(cleanup); body.append(cleanupActions);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
const targets = Array.isArray(payload?.migration_targets)
|
|
|
? payload.migration_targets : [];
|
|
|
const form = el('form', 'row g-2 align-items-end'); form.noValidate = true;
|
|
|
const hostLabel = el('label', 'col-12 col-lg-5');
|
|
|
hostLabel.append(el('span', 'form-label d-block', '目标宿主机'));
|
|
|
const host = el('select', 'form-select'); host.required = true;
|
|
|
host.append(new Option(targets.length ? '请选择同资源池宿主机' : '暂无可迁移宿主机', ''));
|
|
|
targets.forEach(target => host.append(new Option(
|
|
|
`${text(target.host_name, `宿主机 #${target.host_id}`)}${target.region ? ` · ${target.region}` : ''} · ${Number(target.available_ip_count) || 1} 个可用 IP`,
|
|
|
String(target.host_id))));
|
|
|
hostLabel.append(host);
|
|
|
const modeLabel = el('label', 'col-12 col-lg-5');
|
|
|
modeLabel.append(el('span', 'form-label d-block', '目标验证后的源副本'));
|
|
|
const mode = el('select', 'form-select');
|
|
|
mode.append(new Option('自动清理源副本(推荐)', 'delete'),
|
|
|
new Option('保留源副本,稍后手动清理', 'retain'));
|
|
|
modeLabel.append(mode);
|
|
|
const actions = el('div', 'col-12 col-lg-2 d-grid');
|
|
|
const submit = el('button', 'btn btn-primary', '开始迁移'); submit.type = 'submit';
|
|
|
actions.append(submit); form.append(hostLabel, modeLabel, actions);
|
|
|
const confirmLabel = el('label', 'admin-instance-settings-confirm mt-3');
|
|
|
const confirm = document.createElement('input'); confirm.type = 'checkbox';
|
|
|
confirmLabel.append(confirm, document.createTextNode(
|
|
|
'我确认迁移会先正常关闭源实例,目标实例使用原账单、到期时间和流量周期,但会分配新的公网 IP。'));
|
|
|
const feedback = el('p', 'text-muted fs-13 mb-0 mt-2');
|
|
|
feedback.dataset.migrationFeedback = ''; feedback.hidden = true;
|
|
|
const blocked = payload?.can_migrate !== true;
|
|
|
const migrationBlocksNew = migration?.progress?.blocks_new_migration === true;
|
|
|
for (const control of [host, mode, submit, confirm]) control.disabled = blocked;
|
|
|
if (blocked && (!migration || !migrationBlocksNew)) {
|
|
|
feedback.hidden = false; feedback.className = 'text-warning fs-13 mb-0 mt-2';
|
|
|
feedback.textContent = targets.length
|
|
|
? text(payload?.create_block_reason, '当前实例不能开始维护迁移。')
|
|
|
: '暂无同资源池且具备容量、br0 和可用公网 IP 的其他宿主机。';
|
|
|
}
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.backupMutationRequest || blocked) return;
|
|
|
if (!/^[1-9][0-9]*$/.test(String(host.value || ''))) {
|
|
|
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
|
|
|
feedback.textContent = '请选择目标宿主机。'; return;
|
|
|
}
|
|
|
if (!confirm.checked) {
|
|
|
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
|
|
|
feedback.textContent = '请确认冷迁移、原服务账本和新公网 IP 规则。'; return;
|
|
|
}
|
|
|
const controller = new AbortController(); state.backupMutationRequest = controller;
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
feedback.hidden = false; feedback.className = 'text-muted fs-13 mb-0 mt-2';
|
|
|
feedback.textContent = '正在创建 PeerMigration V3 冷迁移任务,请勿重复提交…';
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
`/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations`,
|
|
|
{ target_host_id: Number(host.value), cleanup_mode: mode.value,
|
|
|
confirm_maintenance_migration: true }, controller, 'POST');
|
|
|
feedback.textContent = `维护迁移任务 #${receipt.task_id || '—'} 已接收。`;
|
|
|
watchBackupTask(vmId, receipt, '维护迁移'); void loadBackups(vmId, true);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
feedback.className = 'text-danger fs-13 mb-0 mt-2'; feedback.textContent = error.message;
|
|
|
if (error?.mutationMayHaveApplied === true) void loadBackups(vmId, true);
|
|
|
else for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
}
|
|
|
});
|
|
|
body.append(form, confirmLabel, feedback); section.append(body); return section;
|
|
|
}
|
|
|
|
|
|
function renderBackups(payload, vmId) {
|
|
|
const panel = byId('instance-panel-backups');
|
|
|
panel.replaceChildren();
|
|
|
const intro = el('div', 'alert alert-info');
|
|
|
intro.append(el('strong', 'd-block mb-1', '可移植系统盘备份'),
|
|
|
document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选宿主机创建独立实例;可选择原宿主机或其他合格宿主机,并统一接入 br0、分配全新公网 IP。'));
|
|
|
panel.append(intro);
|
|
|
panel.append(maintenanceMigrationSection(payload, vmId));
|
|
|
|
|
|
const create = el('section', 'card mb-3');
|
|
|
const createBody = el('div', 'card-body');
|
|
|
createBody.append(el('h3', 'h6 fw-semibold', '创建备份'));
|
|
|
const form = el('form', 'row g-2 align-items-end'); form.noValidate = true;
|
|
|
const nameLabel = el('label', 'col-12 col-lg-6');
|
|
|
nameLabel.append(el('span', 'form-label d-block', '备份名称'));
|
|
|
const name = el('input', 'form-control'); name.name = 'name'; name.type = 'text';
|
|
|
name.required = true; name.maxLength = 64; name.placeholder = '例如 迁移前备份'; nameLabel.append(name);
|
|
|
const consistencyLabel = el('label', 'col-12 col-lg-4');
|
|
|
consistencyLabel.append(el('span', 'form-label d-block', '一致性模式'));
|
|
|
const consistency = el('select', 'form-select'); consistency.name = 'consistency_mode';
|
|
|
consistency.append(
|
|
|
new Option('自动(优先文件系统一致)', 'filesystem', true, true),
|
|
|
new Option('强制崩溃一致(不冻结文件系统)', 'crash'),
|
|
|
);
|
|
|
const consistencyHelp = el('small', 'form-text text-muted',
|
|
|
'自动模式在 QGA 不可用时降级为崩溃一致;备份列表会显示最终实际使用的一致性模式。');
|
|
|
consistencyLabel.append(consistency, consistencyHelp);
|
|
|
const actions = el('div', 'col-12 col-lg-2 d-grid');
|
|
|
const submit = el('button', 'btn btn-primary', '开始备份'); submit.type = 'submit'; actions.append(submit);
|
|
|
form.append(nameLabel, consistencyLabel, actions);
|
|
|
const feedback = el('p', 'text-muted fs-13 mb-0 mt-2');
|
|
|
feedback.dataset.backupFeedback = ''; feedback.hidden = true;
|
|
|
feedback.setAttribute('role', 'status');
|
|
|
createBody.append(form, feedback); create.append(createBody); panel.append(create);
|
|
|
const mutationBlocked = payload?.active_job?.blocks_mutation === true
|
|
|
|| payload?.can_create !== true;
|
|
|
if (mutationBlocked) {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
const reason = payload?.active_job?.blocks_mutation === true
|
|
|
? mutationBlockMessage(payload.active_job, '创建备份')
|
|
|
: text(payload?.create_block_reason, payload?.message,
|
|
|
'当前实例或对象存储尚未满足备份条件。');
|
|
|
backupFeedback(createBody, reason, 'warning');
|
|
|
}
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.backupMutationRequest || mutationBlocked) return;
|
|
|
const backupName = String(name.value || '').trim();
|
|
|
if (!backupName || [...backupName].length > 64) {
|
|
|
backupFeedback(createBody, '请输入 1 至 64 个字符的备份名称。', 'danger');
|
|
|
return;
|
|
|
}
|
|
|
const controller = new AbortController();
|
|
|
state.backupMutationRequest = controller;
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
backupFeedback(createBody, '正在创建对象存储备份任务,请勿重复提交…');
|
|
|
try {
|
|
|
const receipt = await mutate(
|
|
|
`/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups`,
|
|
|
{ name: backupName, consistency_mode: consistency.value === 'crash' ? 'crash' : 'filesystem' },
|
|
|
controller,
|
|
|
'POST',
|
|
|
);
|
|
|
backupFeedback(createBody, `备份任务 #${receipt.task_id || '—'} 已接收。`);
|
|
|
detailNotice('备份任务已接收;大容量系统盘可能需要较长时间,请在任务记录查看进度。');
|
|
|
watchBackupTask(vmId, receipt, '创建备份');
|
|
|
void loadBackups(vmId, true);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
backupFeedback(createBody, error.message, 'danger');
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
detailNotice(error.message, true);
|
|
|
void loadBackups(vmId, true);
|
|
|
} else {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.backupMutationRequest === controller) state.backupMutationRequest = null;
|
|
|
}
|
|
|
});
|
|
|
|
|
|
const heading = el('div', 'd-flex align-items-center justify-content-between gap-2 mb-2');
|
|
|
heading.append(el('h3', 'h6 fw-semibold mb-0', '已有备份'));
|
|
|
const refresh = el('button', 'btn btn-light btn-sm', '刷新'); refresh.type = 'button';
|
|
|
refresh.addEventListener('click', () => void loadBackups(vmId, true)); heading.append(refresh);
|
|
|
panel.append(heading);
|
|
|
const backups = Array.isArray(payload?.backups) ? payload.backups : [];
|
|
|
if (!backups.length) {
|
|
|
panel.append(el('p', 'text-muted py-3', '暂无可恢复的对象存储备份。'));
|
|
|
return;
|
|
|
}
|
|
|
backups.forEach(backup => {
|
|
|
const card = el('article', 'card mb-3');
|
|
|
const body = el('div', 'card-body');
|
|
|
const title = el('div', 'd-flex align-items-start justify-content-between gap-2 flex-wrap');
|
|
|
title.append(el('h4', 'h6 fw-semibold mb-0', text(backup.name, `备份 #${backup.id}`)));
|
|
|
const [statusLabel, tone] = backupStatus(backup.state);
|
|
|
title.append(el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, statusLabel));
|
|
|
body.append(title, infoList([
|
|
|
['一致性', backupConsistency(backup.consistency)],
|
|
|
['对象大小', backup.object_size_bytes === null || backup.object_size_bytes === undefined
|
|
|
? '等待完成' : bytes(backup.object_size_bytes)],
|
|
|
['虚拟磁盘容量', backup.virtual_size_bytes === null || backup.virtual_size_bytes === undefined
|
|
|
? '等待完成' : bytes(backup.virtual_size_bytes)],
|
|
|
['完整性校验', /^[a-f0-9]{64}$/.test(String(backup.sha256 || '')) ? 'SHA-256 已记录' : '等待校验'],
|
|
|
['创建时间', date(backup.created_at)],
|
|
|
['可恢复时间', date(backup.ready_at)],
|
|
|
]));
|
|
|
if (backup.error) body.append(el('p', 'text-danger fs-13', backup.error));
|
|
|
if (backup.cleanup_pending === true) {
|
|
|
body.append(el('p', 'text-warning fs-13',
|
|
|
'远端备份已完整保存并可恢复,但源宿主机的临时工作区仍待清理;清理不会重复上传或修改备份对象。'));
|
|
|
if (backup.can_cleanup_workspace === true) {
|
|
|
const cleanupActions = el('div', 'd-flex justify-content-end mb-3');
|
|
|
cleanupActions.append(backupWorkspaceCleanupButton(vmId, backup));
|
|
|
body.append(cleanupActions);
|
|
|
}
|
|
|
}
|
|
|
if (backup.state === 'uncertain') {
|
|
|
body.append(el('p', 'alert alert-warning fs-13 mb-0',
|
|
|
'备份效果尚未确认。系统会保留任务和对象边界,请勿重复创建或恢复,先完成任务核对。'));
|
|
|
} else if (backup.state === 'delete_uncertain' || backup.state === 'deleting') {
|
|
|
body.append(el('p', 'alert alert-warning fs-13',
|
|
|
'删除结果尚未确认。系统会在两次间隔核对确认同一对象后创建新的删除代次。'));
|
|
|
if (backup.can_delete === true) {
|
|
|
const deleteActions = el('div', 'd-flex justify-content-end');
|
|
|
deleteActions.append(backupDeleteButton(vmId, backup)); body.append(deleteActions);
|
|
|
}
|
|
|
} else if (backup.state === 'delete_attention') {
|
|
|
body.append(el('p', 'alert alert-danger fs-13 mb-0',
|
|
|
'对象清理已达到自动重试上限,请在“对象存储 -> 对象清理异常”中核查并手动恢复。'));
|
|
|
} else if (backup.state === 'ready') {
|
|
|
const targets = backupTargets(payload, backup);
|
|
|
if (targets.length) body.append(restoreForm(vmId, backup, targets,
|
|
|
payload?.can_restore === false || payload?.active_job?.blocks_mutation === true));
|
|
|
else body.append(el('p', 'text-warning fs-13 mb-0',
|
|
|
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
|
|
|
}
|
|
|
if (['ready', 'failed'].includes(backup.state) && backup.can_delete === true) {
|
|
|
const deleteActions = el('div', 'd-flex justify-content-end mt-3');
|
|
|
deleteActions.append(backupDeleteButton(vmId, backup)); body.append(deleteActions);
|
|
|
}
|
|
|
card.append(body); panel.append(card);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function loadBackups(vmId, force = false) {
|
|
|
if (state.detailId !== String(vmId)) return;
|
|
|
if (!force && state.backupLoadedFor === String(vmId)) return;
|
|
|
state.backupRequest?.abort('replaced');
|
|
|
const controller = new AbortController();
|
|
|
const serial = state.backupSerial;
|
|
|
state.backupRequest = controller;
|
|
|
const panel = byId('instance-panel-backups');
|
|
|
panel.replaceChildren(el('p', 'text-muted py-3', '正在读取对象存储备份…'));
|
|
|
try {
|
|
|
const payload = await api(
|
|
|
`/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.backupSerial
|
|
|
|| state.detailId !== String(vmId)) return;
|
|
|
state.backupLoadedFor = String(vmId);
|
|
|
renderBackups(payload, String(vmId));
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial === state.backupSerial) {
|
|
|
panel.replaceChildren(el('p', 'alert alert-danger', `${error.message} 请刷新后重试。`));
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.backupRequest === controller) state.backupRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function libraryNotice(message, error = false) {
|
|
|
const node = byId('backup-library-notice');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message;
|
|
|
node.className = error ? 'alert alert-danger' : 'alert alert-info';
|
|
|
node.textContent = message || '';
|
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function renderBackupLibrary(payload) {
|
|
|
const container = byId('backup-library-items');
|
|
|
container.replaceChildren();
|
|
|
const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
const canManage = payload?.can_manage === true;
|
|
|
if (!items.length) {
|
|
|
container.append(el('p', 'text-muted py-3', '备份库中暂无对象。'));
|
|
|
}
|
|
|
for (const backup of items) {
|
|
|
const source = backup?.source && typeof backup.source === 'object'
|
|
|
? backup.source : {};
|
|
|
const vmId = String(source.instance_id || '');
|
|
|
const card = el('article', 'card mb-3');
|
|
|
const body = el('div', 'card-body');
|
|
|
const heading = el('div', 'd-flex align-items-start justify-content-between gap-2 flex-wrap');
|
|
|
heading.append(el('h3', 'h6 fw-semibold mb-0', text(backup.name, `备份 #${backup.id}`)));
|
|
|
const [label, tone] = backupStatus(backup.state);
|
|
|
heading.append(el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, label));
|
|
|
const sourceLabel = source.deleted === true ? '源实例已删除'
|
|
|
: `源实例 ${text(source.name, `#${vmId}`)}`;
|
|
|
body.append(heading, infoList([
|
|
|
['来源', `${sourceLabel} · ID ${text(vmId)} · 用户 ${text(source.user_id)}`],
|
|
|
['源宿主机', `${text(source.host_name, `#${source.host_id}`)}${source.region ? ` · ${source.region}` : ''}`],
|
|
|
['一致性', backupConsistency(backup.consistency)],
|
|
|
['对象大小', bytes(backup.object_size_bytes)],
|
|
|
['虚拟磁盘容量', bytes(backup.virtual_size_bytes)],
|
|
|
['创建时间', date(backup.created_at)],
|
|
|
]));
|
|
|
if (source.deleted === true) {
|
|
|
body.append(el('p', 'alert alert-warning fs-13',
|
|
|
'源实例已删除;该备份仍由独立目录保留,可恢复为新实例或确认删除。'));
|
|
|
}
|
|
|
if (backup.cleanup_pending === true) {
|
|
|
body.append(el('p', 'text-warning fs-13',
|
|
|
'远端备份可恢复,但源宿主机的临时工作区仍需核对。'));
|
|
|
if (backup.can_cleanup_workspace === true) {
|
|
|
const cleanupActions = el('div', 'd-flex justify-content-end mb-3');
|
|
|
cleanupActions.append(backupWorkspaceCleanupButton(vmId, backup, true));
|
|
|
body.append(cleanupActions);
|
|
|
}
|
|
|
}
|
|
|
if (backup.error) body.append(el('p', 'text-danger fs-13', backup.error));
|
|
|
const targets = backupTargets(payload, backup);
|
|
|
if (backup.state === 'ready') {
|
|
|
if (targets.length) {
|
|
|
body.append(restoreForm(vmId, backup, targets, !canManage, true));
|
|
|
} else {
|
|
|
body.append(el('p', 'text-warning fs-13',
|
|
|
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
|
|
|
}
|
|
|
}
|
|
|
if (backup.can_delete === true) {
|
|
|
const actions = el('div', 'd-flex justify-content-end mt-3');
|
|
|
actions.append(backupDeleteButton(vmId, backup, true));
|
|
|
body.append(actions);
|
|
|
} else if (!canManage && ['ready', 'failed', 'deleting', 'delete_uncertain', 'delete_attention'].includes(backup.state)) {
|
|
|
body.append(el('p', 'text-muted fs-12 mb-0',
|
|
|
'当前管理员仅可查看,超级管理员才可以恢复或删除备份。'));
|
|
|
}
|
|
|
card.append(body); container.append(card);
|
|
|
}
|
|
|
const pagination = payload?.pagination || {};
|
|
|
state.libraryPagination = {
|
|
|
page: Number(pagination.page) || 1,
|
|
|
total_pages: Number(pagination.total_pages) || 1,
|
|
|
total: Number(pagination.total) || 0,
|
|
|
};
|
|
|
state.libraryPage = state.libraryPagination.page;
|
|
|
byId('backup-library-page').textContent = `第 ${state.libraryPagination.page} / ${state.libraryPagination.total_pages} 页 · 共 ${state.libraryPagination.total} 个`;
|
|
|
byId('backup-library-previous').disabled = state.libraryPagination.page <= 1;
|
|
|
byId('backup-library-next').disabled = state.libraryPagination.page >= state.libraryPagination.total_pages;
|
|
|
}
|
|
|
|
|
|
async function loadBackupLibrary(page = 1, force = false) {
|
|
|
const dialog = byId('backup-library');
|
|
|
if (!dialog?.open) return;
|
|
|
const normalizedPage = Math.max(1, Number(page) || 1);
|
|
|
if (!force && state.libraryRequest) return;
|
|
|
state.libraryRequest?.abort('replaced');
|
|
|
const controller = new AbortController();
|
|
|
const serial = state.librarySerial;
|
|
|
state.libraryRequest = controller;
|
|
|
libraryNotice('正在读取有界分页的对象存储备份目录…');
|
|
|
try {
|
|
|
const payload = await api(
|
|
|
`/api/v1/admin/backups?page=${encodeURIComponent(normalizedPage)}&per_page=20`,
|
|
|
controller,
|
|
|
);
|
|
|
if (controller.signal.aborted || serial !== state.librarySerial || !dialog.open) return;
|
|
|
renderBackupLibrary(payload);
|
|
|
libraryNotice('');
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial === state.librarySerial) libraryNotice(`${error.message} 请稍后重试。`, true);
|
|
|
} finally {
|
|
|
if (state.libraryRequest === controller) state.libraryRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function cancelLibraryActivity(reason = 'cancelled') {
|
|
|
state.librarySerial += 1;
|
|
|
state.libraryRequest?.abort(reason);
|
|
|
state.libraryRequest = null;
|
|
|
state.backupMutationRequest?.abort(reason);
|
|
|
state.backupMutationRequest = null;
|
|
|
state.libraryObserver?.stop(reason);
|
|
|
state.libraryObserver = null;
|
|
|
}
|
|
|
|
|
|
function finishLibraryClose() {
|
|
|
state.libraryClosing = false;
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.scroll) {
|
|
|
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
|
|
|
state.scroll = null;
|
|
|
}
|
|
|
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
|
|
|
state.opener = null;
|
|
|
}
|
|
|
|
|
|
function closeBackupLibrary() {
|
|
|
if (state.libraryClosing || !byId('backup-library')?.open) return;
|
|
|
cancelLibraryActivity('closed');
|
|
|
state.libraryClosing = true;
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(byId('backup-library')).then(closed => {
|
|
|
if (closed) finishLibraryClose();
|
|
|
else state.libraryClosing = false;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function openBackupLibrary(opener) {
|
|
|
if (state.libraryClosing) return;
|
|
|
state.opener = opener;
|
|
|
state.libraryPage = 1;
|
|
|
const dialog = byId('backup-library');
|
|
|
const body = dialog.querySelector('.admin-instance-drawer-body');
|
|
|
if (body) body.scrollTop = 0;
|
|
|
byId('backup-library-items').replaceChildren();
|
|
|
libraryNotice('正在读取备份库…');
|
|
|
if (!dialog.open) {
|
|
|
lockDetailScroll();
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
}
|
|
|
void loadBackupLibrary(1, true);
|
|
|
}
|
|
|
|
|
|
function settingsFormValues(form) {
|
|
|
const hostname = String(form.elements.namedItem('hostname')?.value || '').trim().toLowerCase();
|
|
|
const password = String(form.elements.namedItem('root_password')?.value || '');
|
|
|
const confirmation = String(form.elements.namedItem('root_password_confirmation')?.value || '');
|
|
|
const publicKey = String(form.elements.namedItem('ssh_public_key')?.value || '').trim();
|
|
|
if (!hostname && !password && !publicKey) throw new Error('请至少填写一项要修改的实例设置。');
|
|
|
if (hostname && !/^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/.test(hostname)) {
|
|
|
throw new Error('主机名只能包含英文、数字、连字符和点,每段不能以连字符开头或结尾,最多 253 个字符。');
|
|
|
}
|
|
|
if (password || confirmation) {
|
|
|
if (!password) throw new Error('请输入新的实例密码。');
|
|
|
if (password !== confirmation) throw new Error('两次输入的实例密码不一致。');
|
|
|
if (password.length < 12 || password.length > 128 || !/^[\x21-\x7e]+$/.test(password)
|
|
|
|| !/[A-Z]/.test(password) || !/[a-z]/.test(password)
|
|
|
|| !/[0-9]/.test(password) || !/[^A-Za-z0-9]/.test(password)) {
|
|
|
throw new Error('实例密码需为 12 至 128 位可打印字符,并包含大写、小写、数字和符号。');
|
|
|
}
|
|
|
}
|
|
|
if (publicKey) {
|
|
|
if (publicKey.length > 16384 || /[\r\n\x00-\x1f\x7f]/.test(publicKey)) {
|
|
|
throw new Error('SSH 公钥必须是一行且不能包含控制字符。');
|
|
|
}
|
|
|
if (!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521)\s+[A-Za-z0-9+/]+={0,3}(?:\s+[^\r\n]*)?$/.test(publicKey)) {
|
|
|
throw new Error('请输入有效的单行 OpenSSH 公钥,不要粘贴私钥。');
|
|
|
}
|
|
|
}
|
|
|
const body = { confirm_restart: true };
|
|
|
if (hostname) body.hostname = hostname;
|
|
|
if (password) body.root_password = password;
|
|
|
if (publicKey) body.ssh_public_key = publicKey;
|
|
|
return body;
|
|
|
}
|
|
|
|
|
|
function settingsSetBusy(form, busy) {
|
|
|
for (const control of form.querySelectorAll('input, textarea, button')) {
|
|
|
control.disabled = busy;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function unlockSettingsForm(form, activeJob = false) {
|
|
|
if (!form) return;
|
|
|
for (const control of form.querySelectorAll('input, textarea, button')) {
|
|
|
control.disabled = activeJob;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function pollSettingsJob(vm, section, result) {
|
|
|
const serial = state.settingsSerial;
|
|
|
const jobId = result?.task_id ?? '';
|
|
|
announceTaskAccepted(result, { title: '修改实例设置' });
|
|
|
const handle = observeTask(result, {
|
|
|
onUpdate: () => {
|
|
|
if (serial === state.settingsSerial && state.detailId === String(vm.id)) {
|
|
|
setSettingsFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted');
|
|
|
}
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return;
|
|
|
state.settingsObserver = null;
|
|
|
void (async () => {
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
const message = succeeded
|
|
|
? `实例设置任务 #${jobId} 已成功。`
|
|
|
: taskFailureMessage(task, `任务 #${jobId} 执行失败。`);
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(message, !succeeded);
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.settingsObserver === handle) state.settingsObserver = null;
|
|
|
if (reason === 'pagehide' || serial !== state.settingsSerial) return;
|
|
|
void (async () => {
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(`任务 #${jobId} 自动观察已停止,已按服务端最新状态更新设置入口;请在任务记录刷新最终结果。`, true);
|
|
|
})();
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
setSettingsFeedback(section, '任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。', 'danger');
|
|
|
return;
|
|
|
}
|
|
|
state.settingsObserver = handle;
|
|
|
}
|
|
|
|
|
|
function settingsEditor(vm) {
|
|
|
const template = byId('admin-instance-settings-controls');
|
|
|
const controls = template?.content?.cloneNode(true);
|
|
|
const section = controls?.querySelector('[data-instance-settings]');
|
|
|
if (!section) return el('section');
|
|
|
const form = section.querySelector('[data-instance-settings-form]');
|
|
|
const current = section.querySelector('[data-settings-current-hostname]');
|
|
|
if (current) current.textContent = `当前主机名:${text(vm.guest_hostname, vm.hostname, '未记录')}`;
|
|
|
if (!form) return section;
|
|
|
if (vm.instance_settings_supported !== true) {
|
|
|
form.remove();
|
|
|
const description = section.querySelector('.admin-instance-settings-heading p');
|
|
|
if (description) {
|
|
|
description.className = 'text-warning fs-13 mb-0';
|
|
|
description.textContent = vm.instance_status && vm.instance_status !== 'active'
|
|
|
? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能修改主机名、密码或 SSH 公钥。`
|
|
|
: '当前实例缺少已验证的面板云镜像元数据,暂不能修改主机名、密码或 SSH 公钥。请先核对实例元数据。';
|
|
|
}
|
|
|
return section;
|
|
|
}
|
|
|
const mutationBlocked = vm.active_job?.blocks_mutation === true;
|
|
|
if (mutationBlocked) {
|
|
|
unlockSettingsForm(form, true);
|
|
|
setSettingsFeedback(section, mutationBlockMessage(vm.active_job, '修改实例设置'), 'warning');
|
|
|
}
|
|
|
const submit = async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.settingsRequest || mutationBlocked) return;
|
|
|
let body;
|
|
|
try {
|
|
|
body = settingsFormValues(form);
|
|
|
if (!form.elements.namedItem('confirm_restart')?.checked) {
|
|
|
throw new Error('请先确认实例会重启。');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
setSettingsFeedback(section, error.message, 'danger');
|
|
|
return;
|
|
|
}
|
|
|
const controller = new AbortController();
|
|
|
state.settingsRequest = controller;
|
|
|
settingsSetBusy(form, true);
|
|
|
setSettingsFeedback(section, '正在创建实例设置任务,请勿重复提交…', 'muted');
|
|
|
try {
|
|
|
const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/settings`, body, controller);
|
|
|
const jobId = result?.task_id;
|
|
|
form.elements.namedItem('root_password').value = '';
|
|
|
form.elements.namedItem('root_password_confirmation').value = '';
|
|
|
form.elements.namedItem('ssh_public_key').value = '';
|
|
|
form.elements.namedItem('confirm_restart').checked = false;
|
|
|
setSettingsFeedback(section, `任务 #${jobId || '—'} 已接收,运行中的实例将在后台重启并应用设置。`, 'muted');
|
|
|
detailNotice(`实例设置任务已接收,可在任务记录查看结果。`);
|
|
|
pollSettingsJob(vm, section, result);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
setSettingsFeedback(section, error.message, 'danger');
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(error.message, true);
|
|
|
} else unlockSettingsForm(form);
|
|
|
} finally {
|
|
|
if (state.settingsRequest === controller) state.settingsRequest = null;
|
|
|
}
|
|
|
};
|
|
|
form.addEventListener('submit', submit);
|
|
|
form.addEventListener('reset', () => {
|
|
|
window.setTimeout(() => setSettingsFeedback(section, ''), 0);
|
|
|
});
|
|
|
for (const control of form.querySelectorAll('input, textarea')) {
|
|
|
control.addEventListener('input', () => {
|
|
|
const feedback = section.querySelector('[data-settings-feedback]');
|
|
|
if (feedback && feedback.classList.contains('text-danger')) setSettingsFeedback(section, '');
|
|
|
});
|
|
|
}
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
function networkOptionsView(section, options) {
|
|
|
const summary = networkOptionSummary(options);
|
|
|
const status = section.querySelector('[data-network-options-status]');
|
|
|
if (status) {
|
|
|
status.textContent = options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。';
|
|
|
status.className = 'text-muted fs-12 mb-0';
|
|
|
}
|
|
|
const values = section.querySelector('[data-network-options-values]');
|
|
|
if (!values) return;
|
|
|
values.replaceChildren();
|
|
|
[
|
|
|
['地址池', summary.pool],
|
|
|
['虚拟机前缀', summary.prefix],
|
|
|
['网关', summary.gateway],
|
|
|
['DNS', summary.dns],
|
|
|
['可用地址', summary.available],
|
|
|
].forEach(([label, value]) => {
|
|
|
values.append(el('dt', '', label), el('dd', 'admin-mono', value));
|
|
|
});
|
|
|
const select = section.querySelector('[name="public_ip_cidr"]');
|
|
|
const submit = section.querySelector('button[type="submit"]');
|
|
|
const hasAvailable = options.available_ip_options?.length > 0;
|
|
|
const canChange = options.can_change === true && options.configuration_state === 'ready' && hasAvailable;
|
|
|
if (select instanceof HTMLSelectElement) {
|
|
|
select.replaceChildren(new Option(
|
|
|
hasAvailable ? '请选择新的公网 IP' : '当前没有可用公网 IP', ''));
|
|
|
const poolsByKey = new Map((options.pools || [])
|
|
|
.map(pool => [pool.public_pool_key, pool]));
|
|
|
for (const value of options.available_ip_options || []) {
|
|
|
const pool = poolsByKey.get(value.public_pool_key);
|
|
|
const label = options.pools?.length > 1 && pool?.pool_cidr
|
|
|
? `${value.public_ip_cidr} · ${pool.pool_cidr}` : value.public_ip_cidr;
|
|
|
const option = new Option(label, value.public_ip_cidr);
|
|
|
option.dataset.publicPoolKey = value.public_pool_key;
|
|
|
select.add(option);
|
|
|
}
|
|
|
select.disabled = !canChange;
|
|
|
if (!hasAvailable || !canChange) select.setAttribute('aria-describedby', 'network-options-empty');
|
|
|
else select.removeAttribute('aria-describedby');
|
|
|
}
|
|
|
if (submit instanceof HTMLButtonElement) submit.disabled = !canChange;
|
|
|
const empty = section.querySelector('[data-network-options-empty]');
|
|
|
if (empty) {
|
|
|
empty.id = 'network-options-empty';
|
|
|
const blockingJob = options.active_job?.blocks_mutation === true ? options.active_job : null;
|
|
|
empty.textContent = blockingJob
|
|
|
? mutationBlockMessage(blockingJob, '更换公网 IP')
|
|
|
: (!hasAvailable
|
|
|
? '当前没有可用地址,无法提交更换;请先检查地址池和占用记录。'
|
|
|
: (!canChange ? ({
|
|
|
invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。',
|
|
|
drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。',
|
|
|
}[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。')
|
|
|
: '只显示该宿主机当前未分配的公网 IP。'));
|
|
|
empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function networkOptionsErrorView(section, message) {
|
|
|
section._networkOptions = null;
|
|
|
section.querySelector('[data-network-options-values]')?.replaceChildren();
|
|
|
const status = section.querySelector('[data-network-options-status]');
|
|
|
if (status) {
|
|
|
status.textContent = message;
|
|
|
status.className = 'text-warning fs-12 mb-0';
|
|
|
}
|
|
|
const edit = section.querySelector('[data-network-edit="open"]');
|
|
|
if (edit instanceof HTMLButtonElement) {
|
|
|
edit.disabled = true;
|
|
|
edit.setAttribute('aria-expanded', 'false');
|
|
|
edit.title = message;
|
|
|
}
|
|
|
const form = section.querySelector('.admin-instance-network-form');
|
|
|
if (form) form.hidden = true;
|
|
|
}
|
|
|
|
|
|
async function loadNetworkOptions(vm, section) {
|
|
|
const serial = state.networkSerial;
|
|
|
const controller = new AbortController();
|
|
|
state.networkOptionsRequest = controller;
|
|
|
let options;
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network-options`, controller);
|
|
|
if (serial !== state.networkSerial || controller.signal.aborted) return;
|
|
|
options = networkOptionsPayload(payload, vm);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial !== state.networkSerial) return;
|
|
|
const message = error.status === 409
|
|
|
? error.message : '无法读取宿主机地址池,暂不能选择新的公网 IP。';
|
|
|
if (state.detailId === String(vm.id)) networkOptionsErrorView(section, message);
|
|
|
return;
|
|
|
} finally {
|
|
|
if (state.networkOptionsRequest === controller) state.networkOptionsRequest = null;
|
|
|
}
|
|
|
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
|
|
|
section._networkOptions = options;
|
|
|
networkOptionsView(section, options);
|
|
|
}
|
|
|
|
|
|
function targetNetworkValue(section, vm) {
|
|
|
const options = section._networkOptions || networkOptionsFromVm(vm);
|
|
|
const input = section.querySelector('[name="public_ip_cidr"]');
|
|
|
if (options.can_change === false || options.configuration_state !== 'ready') {
|
|
|
throw new Error('宿主机网络配置尚未就绪,暂不能更换公网 IP。');
|
|
|
}
|
|
|
if (!Array.isArray(options.available_ip_options) || options.available_ip_options.length === 0) {
|
|
|
throw new Error('当前宿主机没有可用公网 IP,请先补充地址池或释放地址后重试。');
|
|
|
}
|
|
|
if (!input?.value) throw new Error('请选择新的公网 IP。');
|
|
|
const selectedOption = input instanceof HTMLSelectElement ? input.selectedOptions[0] : null;
|
|
|
const selectedPoolKey = publicPoolKey(selectedOption?.dataset.publicPoolKey);
|
|
|
const selectedPool = (options.pools || [])
|
|
|
.find(pool => pool.public_pool_key === selectedPoolKey);
|
|
|
const parsed = normalizeCidr(input.value, selectedPool?.guest_prefix);
|
|
|
const available = parsed && options.available_ip_options.some(option => (
|
|
|
option.public_ip_cidr === parsed.value && option.public_pool_key === selectedPoolKey
|
|
|
));
|
|
|
if (!parsed || !selectedPool || !available) {
|
|
|
throw new Error('请选择列表中的可用公网 IP,不支持手动填写。');
|
|
|
}
|
|
|
if (parsed.prefix !== Number(selectedPool.guest_prefix)) {
|
|
|
throw new Error(`地址前缀必须为 /${selectedPool.guest_prefix},请不要修改宿主机分配的前缀。`);
|
|
|
}
|
|
|
if (!cidrContains(selectedPool.pool_cidr, parsed.address)) {
|
|
|
throw new Error(`目标地址不在宿主机地址池 ${selectedPool.pool_cidr} 内。`);
|
|
|
}
|
|
|
const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, parsed.prefix);
|
|
|
if (current?.value === parsed.value) throw new Error('新公网 IP 与当前配置相同。');
|
|
|
const blocked = [selectedPool.gateway, ...(selectedPool.dns_servers || [])]
|
|
|
.map(value => parseIPv4(value)?.join('.')).filter(Boolean);
|
|
|
if (blocked.includes(parsed.address)) throw new Error('目标地址是网关、DNS 或保留地址,不能分配给虚拟机。');
|
|
|
return {
|
|
|
public_ip_cidr: parsed.value,
|
|
|
public_pool_key: selectedPoolKey,
|
|
|
pool: selectedPool,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function makeNetworkConfirmation(section, vm, target, options) {
|
|
|
const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, options.guest_prefix || 24)?.value || '未记录';
|
|
|
const confirmation = section.querySelector('[data-network-confirmation]');
|
|
|
const summary = confirmation?.querySelector('[data-network-confirm-summary]');
|
|
|
const check = confirmation?.querySelector('[data-network-confirm-check]');
|
|
|
const submit = confirmation?.querySelector('[data-network-confirm-submit]');
|
|
|
if (!confirmation || !summary || !check || !submit) return null;
|
|
|
const network = networkOptionSummary(options, target.pool);
|
|
|
summary.textContent = `公网地址将从 ${current} 更换为 ${target.public_ip_cidr}。运行中的实例会受控关机并重新启动,已关机实例保持关机;地址池 ${network.pool}、网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`;
|
|
|
check.checked = false;
|
|
|
submit.disabled = true;
|
|
|
confirmation.hidden = false;
|
|
|
return { confirmation, check, submit };
|
|
|
}
|
|
|
|
|
|
async function refreshDetail(id) {
|
|
|
if (state.detailId !== String(id)) return;
|
|
|
state.detailRequest?.abort('refresh');
|
|
|
const controller = new AbortController();
|
|
|
state.detailRequest = controller;
|
|
|
detailNotice('正在刷新实例详情…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(id)}`, controller);
|
|
|
if (controller.signal.aborted || state.detailId !== String(id)) return;
|
|
|
cancelNetworkActivity('detail-refresh');
|
|
|
cancelSettingsActivity('detail-refresh');
|
|
|
renderDetail(payload);
|
|
|
detailNotice('');
|
|
|
const vm = payload.instance;
|
|
|
const item = state.items.find(entry => String(entry.id) === String(id));
|
|
|
if (item && vm) {
|
|
|
item.public_ip = vm.public_ip || String(vm.public_ip_cidr || '').split('/', 1)[0];
|
|
|
item.public_ip_cidr = vm.public_ip_cidr;
|
|
|
const rowNode = Array.from(byId('instances-body').rows).find(row => row.dataset.instanceId === String(id));
|
|
|
const ipNode = rowNode?.querySelector('.admin-instance-ip');
|
|
|
if (ipNode) {
|
|
|
ipNode.replaceChildren(el('span', 'admin-mono', text(item.public_ip, '未记录')));
|
|
|
if (item.public_ip) ipNode.append(copyButton(item.public_ip, '复制公网 IP'));
|
|
|
}
|
|
|
}
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (state.detailId === String(id)) detailNotice(`${error.message} 当前任务结果请在任务记录中核对。`, true);
|
|
|
} finally {
|
|
|
if (state.detailRequest === controller) state.detailRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function pollNetworkJob(vm, section, result) {
|
|
|
const serial = state.networkSerial;
|
|
|
const jobId = result?.task_id ?? '';
|
|
|
announceTaskAccepted(result, { title: '更换实例网络' });
|
|
|
const handle = observeTask(result, {
|
|
|
onUpdate: () => {
|
|
|
if (serial === state.networkSerial && state.detailId === String(vm.id)) {
|
|
|
setNetworkFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted');
|
|
|
}
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
|
|
|
state.networkObserver = null;
|
|
|
void (async () => {
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
const message = succeeded
|
|
|
? `网络变更任务 #${jobId} 已成功。`
|
|
|
: taskFailureMessage(task, `任务 #${jobId} 执行失败。`);
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(message, !succeeded);
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.networkObserver === handle) state.networkObserver = null;
|
|
|
if (reason === 'pagehide' || serial !== state.networkSerial) return;
|
|
|
void (async () => {
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(`任务 #${jobId} 自动观察已停止,已按服务端最新状态更新网络入口;请在任务记录刷新最终结果。`, true);
|
|
|
})();
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
setNetworkFeedback(section, '任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。', 'danger');
|
|
|
return;
|
|
|
}
|
|
|
state.networkObserver = handle;
|
|
|
}
|
|
|
|
|
|
function networkEditor(vm) {
|
|
|
const section = el('section', 'admin-instance-network-settings mt-4');
|
|
|
section.setAttribute('aria-labelledby', 'instance-network-title');
|
|
|
const heading = el('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap');
|
|
|
const copy = el('div');
|
|
|
const title = el('h3', 'h6 fw-semibold mb-1', '网络配置');
|
|
|
title.id = 'instance-network-title';
|
|
|
copy.append(title, el('p', 'text-muted fs-13 mb-0', '运行中的实例会受控重启,已关机实例保持关机;地址池、网关和 DNS 由宿主机最终校验。'));
|
|
|
heading.append(copy);
|
|
|
const template = byId('admin-instance-network-controls');
|
|
|
const controls = template?.content?.cloneNode(true);
|
|
|
const edit = controls?.querySelector('[data-network-edit="open"]');
|
|
|
if (edit && vm.network_change_supported === true) heading.append(edit);
|
|
|
section.append(heading);
|
|
|
|
|
|
const current = el('div', 'admin-instance-network-current mt-3');
|
|
|
const currentValue = el('span', 'admin-instance-network-current-value');
|
|
|
currentValue.append(el('strong', 'admin-mono', text(vm.public_ip_cidr, vm.public_ip, '未记录')));
|
|
|
if (vm.public_ip) currentValue.append(copyButton(vm.public_ip, '复制当前公网 IP'));
|
|
|
current.append(el('span', 'text-muted fs-13', '当前公网地址'), currentValue);
|
|
|
section.append(current);
|
|
|
|
|
|
if (!edit) {
|
|
|
if (controls) section.append(controls);
|
|
|
return section;
|
|
|
}
|
|
|
if (vm.network_change_supported !== true) {
|
|
|
section.append(el('p', 'text-warning fs-13 mt-3 mb-0',
|
|
|
vm.instance_status && vm.instance_status !== 'active'
|
|
|
? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能更换公网 IP。`
|
|
|
: '当前实例缺少已验证的面板云镜像元数据,暂不能更换公网 IP。请先核对实例元数据。'));
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
const optionsBox = el('div', 'admin-instance-network-options-box mt-3');
|
|
|
optionsBox.append(el('p', 'text-muted fs-13 mb-2', '宿主机网络约束'));
|
|
|
const optionsValues = el('dl', 'admin-instance-network-options');
|
|
|
optionsValues.dataset.networkOptionsValues = '';
|
|
|
optionsBox.append(optionsValues, el('p', 'text-muted fs-12 mb-0', '正在读取地址池配置…'));
|
|
|
optionsBox.lastChild.dataset.networkOptionsStatus = '';
|
|
|
optionsBox.lastChild.setAttribute('role', 'status');
|
|
|
section.append(optionsBox);
|
|
|
|
|
|
if (controls) section.append(controls);
|
|
|
const form = section.querySelector('.admin-instance-network-form');
|
|
|
if (!form) return section;
|
|
|
const input = form.elements.namedItem('public_ip_cidr');
|
|
|
const feedback = section.querySelector('.admin-instance-network-feedback');
|
|
|
const submit = form.querySelector('button[type="submit"]');
|
|
|
const cancel = form.querySelector('[data-network-edit="cancel"]');
|
|
|
input.value = '';
|
|
|
input.disabled = true;
|
|
|
submit.disabled = true;
|
|
|
|
|
|
const confirmation = el('div', 'admin-instance-network-confirmation mt-3');
|
|
|
confirmation.hidden = true;
|
|
|
confirmation.dataset.networkConfirmation = '';
|
|
|
confirmation.setAttribute('role', 'alertdialog');
|
|
|
confirmation.setAttribute('aria-labelledby', `network-confirm-title-${vm.id}`);
|
|
|
confirmation.append(el('h4', 'h6 fw-semibold mb-2', '确认更换公网 IP'));
|
|
|
confirmation.lastChild.id = `network-confirm-title-${vm.id}`;
|
|
|
const summary = el('p', 'text-muted fs-13 mb-2');
|
|
|
summary.dataset.networkConfirmSummary = '';
|
|
|
confirmation.append(summary);
|
|
|
const checkLabel = el('label', 'admin-instance-network-confirm-check');
|
|
|
const check = document.createElement('input');
|
|
|
check.type = 'checkbox'; check.dataset.networkConfirmCheck = '';
|
|
|
checkLabel.append(check, document.createTextNode('我确认运行中的实例会短暂重启(已关机实例保持关机),并确认目标公网 IP 无误。'));
|
|
|
confirmation.append(checkLabel);
|
|
|
const confirmActions = el('div', 'd-flex justify-content-end gap-2 flex-wrap mt-3');
|
|
|
const back = el('button', 'btn btn-light btn-sm', '返回修改');
|
|
|
back.type = 'button'; back.dataset.networkConfirmCancel = '';
|
|
|
const confirmSubmit = el('button', 'btn btn-primary btn-sm', '确认并提交');
|
|
|
confirmSubmit.type = 'button'; confirmSubmit.dataset.networkConfirmSubmit = ''; confirmSubmit.disabled = true;
|
|
|
confirmActions.append(back, confirmSubmit); confirmation.append(confirmActions);
|
|
|
section.append(confirmation);
|
|
|
|
|
|
const mutationBlocked = vm.active_job?.blocks_mutation === true;
|
|
|
if (mutationBlocked && edit) {
|
|
|
edit.disabled = true;
|
|
|
edit.title = mutationBlockMessage(vm.active_job, '更换公网 IP');
|
|
|
setNetworkFeedback(section, edit.title, 'warning');
|
|
|
}
|
|
|
|
|
|
const showValidationError = message => {
|
|
|
setNetworkFeedback(section, message, 'danger');
|
|
|
input.focus();
|
|
|
};
|
|
|
form.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
if (state.networkRequest || mutationBlocked) return;
|
|
|
let target;
|
|
|
try { target = targetNetworkValue(section, vm); }
|
|
|
catch (error) { showValidationError(error.message); return; }
|
|
|
const options = section._networkOptions || networkOptionsFromVm(vm);
|
|
|
form.hidden = true;
|
|
|
if (edit) edit.hidden = true;
|
|
|
setNetworkFeedback(section, '');
|
|
|
makeNetworkConfirmation(section, vm, target, options);
|
|
|
section._networkTarget = target;
|
|
|
section.querySelector('[data-network-confirm-check]')?.focus();
|
|
|
});
|
|
|
input.addEventListener('input', () => { if (!feedback.hidden) setNetworkFeedback(section, ''); });
|
|
|
cancel?.addEventListener('click', () => {
|
|
|
form.hidden = true;
|
|
|
confirmation.hidden = true;
|
|
|
if (edit) { edit.hidden = false; edit.setAttribute('aria-expanded', 'false'); }
|
|
|
input.value = '';
|
|
|
setNetworkFeedback(section, '');
|
|
|
});
|
|
|
check.addEventListener('change', () => { confirmSubmit.disabled = !check.checked; });
|
|
|
back.addEventListener('click', () => {
|
|
|
confirmation.hidden = true; form.hidden = false; if (edit) edit.hidden = false;
|
|
|
edit?.setAttribute('aria-expanded', 'true'); input.focus();
|
|
|
});
|
|
|
confirmSubmit.addEventListener('click', async () => {
|
|
|
if (!check.checked || state.networkRequest || mutationBlocked) return;
|
|
|
const target = section._networkTarget;
|
|
|
const controller = new AbortController();
|
|
|
state.networkRequest = controller;
|
|
|
check.disabled = true; confirmSubmit.disabled = true; back.disabled = true;
|
|
|
setNetworkFeedback(section, '正在创建网络变更任务,请勿重复提交…', 'muted');
|
|
|
try {
|
|
|
const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, {
|
|
|
public_ip_cidr: target.public_ip_cidr,
|
|
|
public_pool_key: target.public_pool_key,
|
|
|
confirm_restart: true,
|
|
|
}, controller);
|
|
|
const jobId = result?.task_id;
|
|
|
confirmation.hidden = true;
|
|
|
setNetworkFeedback(section, `任务 #${jobId || '—'} 已接收,实例将在后台重启并应用新地址。`, 'muted');
|
|
|
detailNotice('网络变更任务已接收,可在任务记录查看结果。');
|
|
|
if (edit) { edit.hidden = true; edit.disabled = true; }
|
|
|
state.networkRequest = null;
|
|
|
pollNetworkJob(vm, section, result);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
setNetworkFeedback(section, error.message, 'danger');
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
await refreshDetail(vm.id);
|
|
|
detailNotice(error.message, true);
|
|
|
} else {
|
|
|
confirmation.hidden = false; check.disabled = false; confirmSubmit.disabled = !check.checked; back.disabled = false;
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.networkRequest === controller) state.networkRequest = null;
|
|
|
}
|
|
|
});
|
|
|
void loadNetworkOptions(vm, section);
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
function renderDetail(payload) {
|
|
|
const vm = payload.instance;
|
|
|
if (!vm || String(vm.id) !== state.detailId) throw new Error('实例详情与请求不一致,请重新打开。');
|
|
|
byId('instance-detail-title').textContent = text(vm.name, `实例 #${vm.id}`);
|
|
|
const uuid = el('span', 'admin-instance-ip text-break');
|
|
|
uuid.append(el('span', 'admin-mono', text(vm.uuid)));
|
|
|
if (vm.uuid) uuid.append(copyButton(vm.uuid, '复制 UUID'));
|
|
|
const basic = byId('instance-panel-basic');
|
|
|
basic.replaceChildren(infoList([
|
|
|
['实例编号', `#${vm.id}`], ['UUID', uuid], ['Agent 标识', text(vm.agent_name, '未记录')],
|
|
|
['生命周期', vm.display?.lifecycle], ['所属用户', text(vm.user_name, `用户 #${vm.user_id}`)],
|
|
|
['用户 ID', vm.user_id], ['宿主机', text(vm.host_name)], ['地区', text(vm.region, '未记录')],
|
|
|
['操作系统', text(vm.os_name, '未记录')], ['配置', vm.display?.configuration],
|
|
|
['公网地址', text(vm.public_ip_cidr, vm.public_ip, '未记录')], ['网关', text(vm.gateway, '未记录')],
|
|
|
['DNS', Array.isArray(vm.dns_servers) ? text(vm.dns_servers.join('、'), '未记录') : text(vm.dns_servers, '未记录')],
|
|
|
['带宽上限', vm.bandwidth_mbps ? `${vm.bandwidth_mbps} Mbps` : '未记录'],
|
|
|
['创建时间', date(vm.created_at)],
|
|
|
]), networkEditor(vm), settingsEditor(vm));
|
|
|
byId('instance-panel-service').replaceChildren(infoList([
|
|
|
['套餐', text(vm.plan_name, '无关联套餐')], ['服务状态', vm.display?.service], ['网络状态', vm.display?.network],
|
|
|
['服务到期', vm.service_status === 'exempt' ? '免计费' : date(vm.service_expires_at)],
|
|
|
['剩余期限', vm.display?.expiry], ['本周期用量', vm.display?.traffic],
|
|
|
['下载流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_download_bytes) : '未采集'],
|
|
|
['上传流量', Number(vm.traffic_synced_at) > 0 ? bytes(vm.traffic_upload_bytes) : '未采集'],
|
|
|
['采集时间', date(vm.traffic_synced_at)], ['当前周期开始', date(vm.current_period_started_at)],
|
|
|
['当前周期结束', date(vm.current_period_ends_at)],
|
|
|
['续费价格', vm.renewal_price !== null && vm.renewal_price !== undefined ? `$${Number(vm.renewal_price).toFixed(2)}` : '不适用'],
|
|
|
['续费周期', vm.renewal_days ? `${vm.renewal_days} 天` : '不适用'],
|
|
|
['续费流量', vm.service_status === 'exempt' ? '不适用' : bytes(vm.renewal_traffic_bytes)],
|
|
|
]));
|
|
|
const jobs = byId('instance-panel-jobs');
|
|
|
jobs.replaceChildren();
|
|
|
for (const job of payload.jobs || []) {
|
|
|
const card = el('article', 'card mb-3');
|
|
|
const body = el('div', 'card-body');
|
|
|
body.append(el('h3', 'h6', `#${job.id} · ${text(job.kind_label || job.action_label || job.kind, '操作任务')} · ${jobStatus(job)}`),
|
|
|
infoList([['尝试次数', job.attempts ?? 0], ['阶段', text(job.phase, '未记录')],
|
|
|
['开始时间', date(job.created_at)], ['更新时间', date(job.updated_at)]]));
|
|
|
if (job.error) body.append(el('p', 'text-danger text-break mb-0', job.error));
|
|
|
card.append(body); jobs.append(card);
|
|
|
}
|
|
|
if (!payload.jobs?.length) jobs.append(el('p', 'text-muted py-3', '暂无任务记录。'));
|
|
|
if (payload.jobs_truncated) jobs.append(el('p', 'text-muted fs-12', '仅展示最近的任务记录。'));
|
|
|
const invoices = byId('instance-panel-invoices');
|
|
|
invoices.replaceChildren();
|
|
|
for (const invoice of payload.invoices || []) {
|
|
|
const card = el('article', 'card mb-3');
|
|
|
const body = el('div', 'card-body');
|
|
|
const purpose = ({
|
|
|
provision: '实例开通',
|
|
|
renewal: '实例续费',
|
|
|
upgrade: '实例升级',
|
|
|
})[invoice.purpose] || text(invoice.purpose, '账单');
|
|
|
const status = ({ open: '待支付', paid: '已支付', overdue: '已逾期', refunded: '已退款', expired: '已失效', void: '已作废' })[invoice.status] || text(invoice.status);
|
|
|
body.append(el('h3', 'h6', `账单 #${invoice.id} · ${purpose}`),
|
|
|
el('p', 'mb-2', `$${Number(invoice.amount).toFixed(2)} · ${status}`),
|
|
|
el('p', 'text-muted fs-12', date(invoice.created_at)));
|
|
|
if (invoice.detail_url) body.append(safeLink(invoice.detail_url, '查看账单', 'btn btn-light btn-sm'));
|
|
|
card.append(body); invoices.append(card);
|
|
|
}
|
|
|
if (!payload.invoices?.length) invoices.append(el('p', 'text-muted py-3', '暂无关联账单;导入或免计费实例可能没有开通账单。'));
|
|
|
if (payload.invoices_truncated) invoices.append(el('p', 'text-muted fs-12', '仅展示最近的关联账单。'));
|
|
|
const control = byId('instance-control-link');
|
|
|
if (control instanceof HTMLAnchorElement && vm.detail_url) {
|
|
|
const link = safeLink(vm.detail_url, '');
|
|
|
if (link instanceof HTMLAnchorElement) {
|
|
|
control.href = link.href;
|
|
|
control.hidden = false;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function lockDetailScroll() {
|
|
|
state.scroll = { x: window.scrollX, y: window.scrollY };
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
}
|
|
|
|
|
|
function finishDetailClose() {
|
|
|
state.detailClosing = false;
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.scroll) {
|
|
|
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
|
|
|
state.scroll = null;
|
|
|
}
|
|
|
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
|
|
|
state.opener = null;
|
|
|
}
|
|
|
|
|
|
function closeDetail() {
|
|
|
const dialog = byId('instance-detail');
|
|
|
if (state.detailClosing || !dialog?.open) return;
|
|
|
state.detailRequest?.abort();
|
|
|
state.detailRequest = null;
|
|
|
cancelNetworkActivity('closed');
|
|
|
cancelSettingsActivity('closed');
|
|
|
cancelBackupActivity('closed');
|
|
|
state.detailId = null;
|
|
|
state.detailClosing = true;
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (closed) finishDetailClose();
|
|
|
else state.detailClosing = false;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function openDetail(id, opener) {
|
|
|
if (!/^[1-9][0-9]*$/.test(id) || state.detailClosing) return;
|
|
|
state.detailRequest?.abort();
|
|
|
cancelNetworkActivity('detail-switch');
|
|
|
cancelSettingsActivity('detail-switch');
|
|
|
cancelBackupActivity('detail-switch');
|
|
|
state.detailId = id;
|
|
|
state.opener = opener;
|
|
|
const dialog = byId('instance-detail');
|
|
|
const drawerBody = dialog.querySelector('.admin-instance-drawer-body');
|
|
|
if (drawerBody) drawerBody.scrollTop = 0;
|
|
|
const controller = new AbortController();
|
|
|
state.detailRequest = controller;
|
|
|
byId('instance-detail-title').textContent = `实例 #${id}`;
|
|
|
const control = byId('instance-control-link');
|
|
|
if (control) control.hidden = true;
|
|
|
tabs.forEach(tab => byId(`instance-panel-${tab}`).replaceChildren());
|
|
|
chooseTab('basic');
|
|
|
detailNotice('正在读取详情…');
|
|
|
if (!dialog.open) {
|
|
|
lockDetailScroll();
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
}
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/instances/${id}`, controller);
|
|
|
if (controller.signal.aborted || state.detailId !== id) return;
|
|
|
renderDetail(payload);
|
|
|
detailNotice('');
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (state.detailId === id) detailNotice(`${error.message} 请关闭后重试。`, true);
|
|
|
} finally { if (state.detailRequest === controller) state.detailRequest = null; }
|
|
|
}
|
|
|
|
|
|
async function copy(value) {
|
|
|
try {
|
|
|
if (!navigator.clipboard?.writeText) throw new Error('Clipboard unavailable');
|
|
|
await navigator.clipboard.writeText(value);
|
|
|
notice('已复制。');
|
|
|
if (byId('instance-detail').open) detailNotice('已复制。');
|
|
|
} catch {
|
|
|
const message = '复制失败,请长按或选中文本手动复制。';
|
|
|
notice(message, true);
|
|
|
if (byId('instance-detail').open) detailNotice(message, true);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if (root) {
|
|
|
let bootstrapped = false;
|
|
|
try { applyPayload(JSON.parse(byId('admin-instances-bootstrap').textContent), false); bootstrapped = true; }
|
|
|
catch { notice('初始数据读取失败,正在重试…', true); }
|
|
|
byId('instances-filter').addEventListener('submit', event => { event.preventDefault(); void loadPage(formUrl()); });
|
|
|
byId('instances-reset').addEventListener('click', event => {
|
|
|
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
|
|
event.preventDefault(); void loadPage(new URL(location.pathname, location.origin));
|
|
|
});
|
|
|
byId('instances-refresh').addEventListener('click', () => { void loadPage(new URL(location.href), 'none'); });
|
|
|
byId('instances-backup-library').addEventListener('click', event => {
|
|
|
openBackupLibrary(event.currentTarget);
|
|
|
});
|
|
|
byId('instances-previous').addEventListener('click', () => { void loadPage(formUrl(state.pagination.page - 1)); });
|
|
|
byId('instances-next').addEventListener('click', () => { void loadPage(formUrl(state.pagination.page + 1)); });
|
|
|
root.addEventListener('click', event => {
|
|
|
const detail = event.target.closest('[data-instance-detail]');
|
|
|
if (detail) void openDetail(detail.dataset.instanceDetail, detail);
|
|
|
const button = event.target.closest('[data-copy]');
|
|
|
if (button) void copy(button.dataset.copy);
|
|
|
});
|
|
|
const dialog = byId('instance-detail');
|
|
|
const libraryDialog = byId('backup-library');
|
|
|
byId('instance-detail-close').addEventListener('click', closeDetail);
|
|
|
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
|
|
|
dialog.addEventListener('click', event => {
|
|
|
if (event.target === dialog) {
|
|
|
const rect = dialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
|
|
|
}
|
|
|
const tab = event.target.closest('[data-instance-tab]');
|
|
|
if (tab) chooseTab(tab.dataset.instanceTab);
|
|
|
const networkAction = event.target.closest('[data-network-edit]');
|
|
|
if (networkAction) {
|
|
|
const section = networkAction.closest('.admin-instance-network-settings');
|
|
|
const form = section?.querySelector('.admin-instance-network-form');
|
|
|
const input = form?.elements?.namedItem('public_ip_cidr');
|
|
|
const feedback = section?.querySelector('.admin-instance-network-feedback');
|
|
|
if (form && networkAction.dataset.networkEdit === 'open') {
|
|
|
form.hidden = false; networkAction.setAttribute('aria-expanded', 'true');
|
|
|
feedback.hidden = true; input?.focus();
|
|
|
} else if (form && networkAction.dataset.networkEdit === 'cancel') {
|
|
|
form.hidden = true;
|
|
|
const opener = section.querySelector('[data-network-edit="open"]');
|
|
|
opener?.setAttribute('aria-expanded', 'false');
|
|
|
if (input) form.reset();
|
|
|
if (feedback) feedback.hidden = true;
|
|
|
}
|
|
|
}
|
|
|
const button = event.target.closest('[data-copy]');
|
|
|
if (button) void copy(button.dataset.copy);
|
|
|
const link = event.target.closest('a[href]');
|
|
|
if (link && !event.defaultPrevented && event.button === 0 && !event.ctrlKey && !event.metaKey
|
|
|
&& !event.shiftKey && !event.altKey && (!link.target || link.target === '_self')) closeDetail();
|
|
|
});
|
|
|
dialog.addEventListener('keydown', event => {
|
|
|
if (!event.target.matches('[data-instance-tab]')) return;
|
|
|
const index = tabs.indexOf(event.target.dataset.instanceTab);
|
|
|
const next = ({ ArrowRight: (index + 1) % tabs.length, ArrowLeft: (index + tabs.length - 1) % tabs.length, Home: 0, End: tabs.length - 1 })[event.key];
|
|
|
if (next !== undefined) { event.preventDefault(); chooseTab(tabs[next], true); }
|
|
|
});
|
|
|
byId('backup-library-close').addEventListener('click', closeBackupLibrary);
|
|
|
byId('backup-library-previous').addEventListener('click', () => {
|
|
|
void loadBackupLibrary(state.libraryPagination.page - 1, true);
|
|
|
});
|
|
|
byId('backup-library-next').addEventListener('click', () => {
|
|
|
void loadBackupLibrary(state.libraryPagination.page + 1, true);
|
|
|
});
|
|
|
libraryDialog.addEventListener('cancel', event => {
|
|
|
event.preventDefault(); closeBackupLibrary();
|
|
|
});
|
|
|
libraryDialog.addEventListener('click', event => {
|
|
|
if (event.target !== libraryDialog) return;
|
|
|
const rect = libraryDialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right
|
|
|
|| event.clientY < rect.top || event.clientY > rect.bottom) {
|
|
|
closeBackupLibrary();
|
|
|
}
|
|
|
});
|
|
|
// Native modal dialog traps focus; background scrolling is locked separately for iOS.
|
|
|
window.addEventListener('popstate', () => { closeDetail(); closeBackupLibrary(); void loadPage(new URL(location.href), 'none'); });
|
|
|
document.addEventListener('visibilitychange', () => { if (document.hidden) stopStatuses(); else void refreshStatuses(); });
|
|
|
window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); cancelNetworkActivity('pagehide'); cancelSettingsActivity('pagehide'); cancelBackupActivity('pagehide'); cancelLibraryActivity('pagehide'); });
|
|
|
window.addEventListener('pageshow', event => { state.active = true; if (event.persisted) { closeDetail(); closeBackupLibrary(); void loadPage(new URL(location.href), 'none'); } });
|
|
|
if (bootstrapped) void refreshStatuses();
|
|
|
else void loadPage(new URL(location.href), 'none');
|
|
|
}
|