|
|
|
|
|
const root = document.querySelector('[data-admin-instances]');
|
|
|
|
|
|
const byId = id => document.getElementById(id);
|
|
|
|
|
|
const columns = ['实例', '用户', '所在位置', '公网 IP', '配置', '状态', '用量与期限', '操作'];
|
|
|
|
|
|
const tabs = ['basic', 'service', '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,
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
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' ? '未配置' : '提交时由引擎校验')));
|
|
|
|
|
|
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) {
|
|
|
|
|
|
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: 'PATCH',
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
Accept: 'application/json',
|
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
|
'X-CSRF-Token': window.ADMIN_CSRF_TOKEN || '',
|
|
|
|
|
|
},
|
|
|
|
|
|
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;
|
|
|
|
|
|
}
|
|
|
|
|
|
return payload;
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
|
|
|
|
|
|
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(value) {
|
|
|
|
|
|
return ({ queued: '已排队', pending: '待处理', running: '执行中', uncertain: '待核对',
|
|
|
|
|
|
succeeded: '已完成', completed: '已完成', failed: '失败', cancelled: '已取消' })[value] || text(value);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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) statuses.append(el('span', 'text-warning fs-12', `任务 #${vm.active_job.id} · ${jobStatus(vm.active_job.status)}`));
|
|
|
|
|
|
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();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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.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.settingsSerial += 1;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function waitForSettingsPoll(ms, serial) {
|
|
|
|
|
|
return new Promise(resolve => {
|
|
|
|
|
|
clearTimeout(state.settingsPollTimer);
|
|
|
|
|
|
state.settingsPollResolve = resolve;
|
|
|
|
|
|
state.settingsPollTimer = setTimeout(() => {
|
|
|
|
|
|
state.settingsPollTimer = null;
|
|
|
|
|
|
state.settingsPollResolve = null;
|
|
|
|
|
|
resolve(serial === state.settingsSerial);
|
|
|
|
|
|
}, ms);
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function settingsJobState(job) {
|
|
|
|
|
|
return String(job?.status || job?.job?.status || '').toLowerCase();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function settingsStatusPath(jobId, statusUrl) {
|
|
|
|
|
|
return typeof statusUrl === 'string' && statusUrl.startsWith('/api/v1/')
|
|
|
|
|
|
? statusUrl : `/api/v1/jobs/${encodeURIComponent(jobId)}`;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async function pollSettingsJob(vm, section, jobId, statusUrl) {
|
|
|
|
|
|
const serial = state.settingsSerial;
|
|
|
|
|
|
const path = settingsStatusPath(jobId, statusUrl);
|
|
|
|
|
|
for (let attempt = 0; attempt < 150; attempt += 1) {
|
|
|
|
|
|
if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return;
|
|
|
|
|
|
const controller = new AbortController();
|
|
|
|
|
|
state.settingsPollRequest = controller;
|
|
|
|
|
|
try {
|
|
|
|
|
|
const job = await api(path, controller);
|
|
|
|
|
|
if (serial !== state.settingsSerial || state.detailId !== String(vm.id)) return;
|
|
|
|
|
|
const status = settingsJobState(job);
|
|
|
|
|
|
const phase = job?.phase || job?.job?.phase;
|
|
|
|
|
|
if (['succeeded', 'completed', 'done'].includes(status)) {
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId} 已完成,正在刷新实例设置…`, 'success');
|
|
|
|
|
|
detailNotice(`实例设置任务 #${jobId} 已完成,正在刷新详情。`);
|
|
|
|
|
|
state.settingsPollRequest = null;
|
|
|
|
|
|
clearTimeout(state.settingsPollTimer);
|
|
|
|
|
|
state.settingsPollTimer = null;
|
|
|
|
|
|
await refreshDetail(vm.id);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (['failed', 'cancelled'].includes(status)) {
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId}${phase ? `:${phase}` : '执行失败'},请修正设置后重试。`, 'danger');
|
|
|
|
|
|
section.dataset.settingsRetry = 'true';
|
|
|
|
|
|
unlockSettingsForm(section.querySelector('[data-instance-settings-form]'));
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (status === 'uncertain') {
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId} 状态待核对,不能重复提交;请先在任务记录确认结果。`, 'warning');
|
|
|
|
|
|
unlockSettingsForm(section.querySelector('[data-instance-settings-form]'), true);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId} ${jobStatus(status || 'queued')}${phase ? ` · ${phase}` : ''}…`, 'muted');
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
|
|
|
if (serial !== state.settingsSerial) return;
|
|
|
|
|
|
setSettingsFeedback(section, `${error.message},将继续等待任务结果。`, 'warning');
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
if (state.settingsPollRequest === controller) state.settingsPollRequest = null;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!await waitForSettingsPoll(Math.min(10000, 2000 + attempt * 250), serial)) return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId} 仍在执行,请稍后刷新任务记录;不要重复提交。`, 'warning');
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
const activeJob = Boolean(vm.active_job && ['queued', 'running', 'uncertain'].includes(String(vm.active_job.status)));
|
|
|
|
|
|
if (activeJob) {
|
|
|
|
|
|
unlockSettingsForm(form, true);
|
|
|
|
|
|
setSettingsFeedback(section, `实例已有任务 #${vm.active_job.id}(${jobStatus(vm.active_job.status)}),完成前不能修改实例设置。`, 'warning');
|
|
|
|
|
|
}
|
|
|
|
|
|
const submit = async event => {
|
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
|
if (state.settingsRequest || (activeJob && section.dataset.settingsRetry !== 'true')) 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;
|
|
|
|
|
|
delete section.dataset.settingsRetry;
|
|
|
|
|
|
settingsSetBusy(form, true);
|
|
|
|
|
|
setSettingsFeedback(section, '正在创建实例设置任务,请勿重复提交…', 'muted');
|
|
|
|
|
|
try {
|
|
|
|
|
|
const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/settings`, body, controller);
|
|
|
|
|
|
const jobId = result?.job_id ?? result?.job?.id;
|
|
|
|
|
|
const resultStatus = settingsJobState(result);
|
|
|
|
|
|
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;
|
|
|
|
|
|
if (!jobId && ['succeeded', 'completed', 'done'].includes(resultStatus)) {
|
|
|
|
|
|
setSettingsFeedback(section, '实例设置已应用,正在刷新详情…', 'success');
|
|
|
|
|
|
detailNotice('实例设置已应用,正在刷新详情。');
|
|
|
|
|
|
await refreshDetail(vm.id);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!jobId) throw new Error('服务器未返回实例设置任务编号,请在任务记录中核对。');
|
|
|
|
|
|
setSettingsFeedback(section, `任务 #${jobId} 已创建,运行中的实例将在后台重启并应用设置…`, 'muted');
|
|
|
|
|
|
detailNotice(`实例设置任务 #${jobId} 已创建,正在等待执行结果。`);
|
|
|
|
|
|
void pollSettingsJob(vm, section, jobId, result?.status_url);
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
|
|
|
setSettingsFeedback(section, error.message, 'danger');
|
|
|
|
|
|
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 networkJobState(job) {
|
|
|
|
|
|
return String(job?.status || job?.job?.status || '').toLowerCase();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function networkOptionsView(section, options, fallback = false, fallbackMessage = '') {
|
|
|
|
|
|
const summary = networkOptionSummary(options);
|
|
|
|
|
|
const status = section.querySelector('[data-network-options-status]');
|
|
|
|
|
|
if (status) {
|
|
|
|
|
|
status.textContent = fallback
|
|
|
|
|
|
? (fallbackMessage || '地址池详情暂不可用,暂不能选择新的公网 IP。')
|
|
|
|
|
|
: (options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。');
|
|
|
|
|
|
status.className = `text-muted fs-12 mb-0${fallback ? ' text-warning' : ''}`;
|
|
|
|
|
|
}
|
|
|
|
|
|
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 activeJob = options.active_job;
|
|
|
|
|
|
empty.textContent = activeJob
|
|
|
|
|
|
? `实例已有任务 #${activeJob.id || ''}(${jobStatus(activeJob.status)}),请等待完成后再更换。`
|
|
|
|
|
|
: (!hasAvailable
|
|
|
|
|
|
? '当前没有可用地址,无法提交更换;请先检查地址池和占用记录。'
|
|
|
|
|
|
: (!canChange ? ({
|
|
|
|
|
|
invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。',
|
|
|
|
|
|
drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。',
|
|
|
|
|
|
}[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。')
|
|
|
|
|
|
: '只显示该宿主机当前未分配的公网 IP。'));
|
|
|
|
|
|
empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async function loadNetworkOptions(vm, section) {
|
|
|
|
|
|
const serial = state.networkSerial;
|
|
|
|
|
|
const controller = new AbortController();
|
|
|
|
|
|
state.networkOptionsRequest = controller;
|
|
|
|
|
|
let options = networkOptionsFromVm(vm);
|
|
|
|
|
|
let fallback = true;
|
|
|
|
|
|
let fallbackMessage = '';
|
|
|
|
|
|
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);
|
|
|
|
|
|
fallback = false;
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
|
|
|
if (serial !== state.networkSerial) return;
|
|
|
|
|
|
// The options endpoint is additive. Older deployments can still use the
|
|
|
|
|
|
// existing detail fields while the engine remains the final validator.
|
|
|
|
|
|
options = networkOptionsFromVm(vm);
|
|
|
|
|
|
fallbackMessage = error.status === 409
|
|
|
|
|
|
? error.message : '无法读取宿主机地址池,暂不能选择新的公网 IP。';
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
if (state.networkOptionsRequest === controller) state.networkOptionsRequest = null;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
|
|
|
|
|
|
section._networkOptions = options;
|
|
|
|
|
|
networkOptionsView(section, options, fallback, fallbackMessage);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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 };
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function waitForNetworkPoll(ms, serial) {
|
|
|
|
|
|
return new Promise(resolve => {
|
|
|
|
|
|
clearTimeout(state.networkPollTimer);
|
|
|
|
|
|
state.networkPollResolve = resolve;
|
|
|
|
|
|
state.networkPollTimer = setTimeout(() => {
|
|
|
|
|
|
state.networkPollTimer = null;
|
|
|
|
|
|
state.networkPollResolve = null;
|
|
|
|
|
|
resolve(serial === state.networkSerial);
|
|
|
|
|
|
}, ms);
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async function pollNetworkJob(vm, section, jobId, statusUrl) {
|
|
|
|
|
|
const serial = state.networkSerial;
|
|
|
|
|
|
const path = typeof statusUrl === 'string' && statusUrl.startsWith('/api/v1/')
|
|
|
|
|
|
? statusUrl : `/api/v1/jobs/${encodeURIComponent(jobId)}`;
|
|
|
|
|
|
for (let attempt = 0; attempt < 150; attempt += 1) {
|
|
|
|
|
|
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
|
|
|
|
|
|
const controller = new AbortController();
|
|
|
|
|
|
state.networkPollRequest = controller;
|
|
|
|
|
|
try {
|
|
|
|
|
|
const job = await api(path, controller);
|
|
|
|
|
|
if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return;
|
|
|
|
|
|
const status = networkJobState(job);
|
|
|
|
|
|
const phase = job?.phase || job?.job?.phase || job?.error;
|
|
|
|
|
|
if (status === 'succeeded' || status === 'completed' || status === 'done') {
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId} 已完成,正在刷新实例网络配置…`, 'success');
|
|
|
|
|
|
detailNotice(`网络变更任务 #${jobId} 已完成,正在刷新当前公网 IP。`);
|
|
|
|
|
|
state.networkPollRequest = null;
|
|
|
|
|
|
clearTimeout(state.networkPollTimer);
|
|
|
|
|
|
state.networkPollTimer = null;
|
|
|
|
|
|
await refreshDetail(vm.id);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (status === 'failed' || status === 'cancelled') {
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId}${phase ? `:${phase}` : '执行失败'}。请确认地址池后修改并重试。`, 'danger');
|
|
|
|
|
|
const form = section.querySelector('.admin-instance-network-form');
|
|
|
|
|
|
form?.removeAttribute('hidden');
|
|
|
|
|
|
const edit = section.querySelector('[data-network-edit="open"]');
|
|
|
|
|
|
if (edit) { edit.hidden = false; edit.disabled = false; edit.setAttribute('aria-expanded', 'true'); }
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (status === 'uncertain') {
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId} 状态待核对,不能重复提交;请先在任务记录确认宿主机结果。`, 'warning');
|
|
|
|
|
|
const form = section.querySelector('.admin-instance-network-form');
|
|
|
|
|
|
const select = form?.elements?.namedItem('public_ip_cidr');
|
|
|
|
|
|
const submit = form?.querySelector('button[type="submit"]');
|
|
|
|
|
|
form?.removeAttribute('hidden');
|
|
|
|
|
|
if (select) select.disabled = true;
|
|
|
|
|
|
if (submit) submit.disabled = true;
|
|
|
|
|
|
const edit = section.querySelector('[data-network-edit="open"]');
|
|
|
|
|
|
if (edit) { edit.hidden = false; edit.disabled = true; edit.title = '任务待核对,请先确认任务结果'; }
|
|
|
|
|
|
const feedback = section.querySelector('.admin-instance-network-feedback');
|
|
|
|
|
|
if (feedback && !feedback.querySelector('[data-network-refresh]')) {
|
|
|
|
|
|
const refresh = el('button', 'btn btn-light btn-sm mt-2', '刷新任务状态');
|
|
|
|
|
|
refresh.type = 'button'; refresh.dataset.networkRefresh = '';
|
|
|
|
|
|
refresh.addEventListener('click', () => { refresh.disabled = true; void refreshDetail(vm.id); });
|
|
|
|
|
|
feedback.append(document.createElement('br'), refresh);
|
|
|
|
|
|
}
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId} ${jobStatus(status || 'queued')}${phase ? ` · ${phase}` : ''}…`, 'muted');
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
|
|
|
if (serial !== state.networkSerial) return;
|
|
|
|
|
|
setNetworkFeedback(section, `${error.message},将继续等待任务结果。`, 'warning');
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
if (state.networkPollRequest === controller) state.networkPollRequest = null;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (!await waitForNetworkPoll(Math.min(10000, 2000 + attempt * 250), serial)) return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId} 仍在执行,请稍后刷新任务记录;不要重复提交。`, 'warning');
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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) 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);
|
|
|
|
|
|
|
|
|
|
|
|
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 activeJob = vm.active_job && ['queued', 'running', 'uncertain'].includes(String(vm.active_job.status));
|
|
|
|
|
|
if (activeJob && edit) {
|
|
|
|
|
|
edit.disabled = true;
|
|
|
|
|
|
edit.title = `实例已有任务 #${vm.active_job.id},请等待任务结束`;
|
|
|
|
|
|
setNetworkFeedback(section, `实例已有任务 #${vm.active_job.id}(${jobStatus(vm.active_job.status)}),完成前不能更换公网 IP。`, 'warning');
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const showValidationError = message => {
|
|
|
|
|
|
setNetworkFeedback(section, message, 'danger');
|
|
|
|
|
|
input.focus();
|
|
|
|
|
|
};
|
|
|
|
|
|
form.addEventListener('submit', event => {
|
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
|
if (state.networkRequest || activeJob) 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 || activeJob) 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?.job_id ?? result?.job?.id ?? result?.operation_id;
|
|
|
|
|
|
if (!jobId) throw new Error('服务器未返回网络变更任务编号,请在任务记录中核对。');
|
|
|
|
|
|
confirmation.hidden = true;
|
|
|
|
|
|
setNetworkFeedback(section, `任务 #${jobId} 已创建,实例将在后台重启并应用新地址…`, 'muted');
|
|
|
|
|
|
detailNotice(`网络变更任务 #${jobId} 已创建,正在等待执行结果。`);
|
|
|
|
|
|
if (edit) { edit.hidden = true; edit.disabled = true; }
|
|
|
|
|
|
state.networkRequest = null;
|
|
|
|
|
|
void pollNetworkJob(vm, section, jobId, result.status_url);
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
|
|
|
setNetworkFeedback(section, error.message, 'danger');
|
|
|
|
|
|
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], ['引擎标识', text(vm.engine_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.status)}`),
|
|
|
|
|
|
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: '实例续费' })[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() {
|
|
|
|
|
|
if (state.detailClosing) return;
|
|
|
|
|
|
state.detailRequest?.abort();
|
|
|
|
|
|
state.detailRequest = null;
|
|
|
|
|
|
cancelNetworkActivity('closed');
|
|
|
|
|
|
cancelSettingsActivity('closed');
|
|
|
|
|
|
state.detailId = null;
|
|
|
|
|
|
const dialog = byId('instance-detail');
|
|
|
|
|
|
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');
|
|
|
|
|
|
state.detailId = id;
|
|
|
|
|
|
state.opener = opener;
|
|
|
|
|
|
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 (!byId('instance-detail').open) {
|
|
|
|
|
|
lockDetailScroll();
|
|
|
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(byId('instance-detail'));
|
|
|
|
|
|
}
|
|
|
|
|
|
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-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');
|
|
|
|
|
|
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); }
|
|
|
|
|
|
});
|
|
|
|
|
|
// Native modal dialog traps focus; background scrolling is locked separately for iOS.
|
|
|
|
|
|
window.addEventListener('popstate', () => { closeDetail(); 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'); });
|
|
|
|
|
|
window.addEventListener('pageshow', event => { state.active = true; if (event.persisted) { closeDetail(); void loadPage(new URL(location.href), 'none'); } });
|
|
|
|
|
|
if (bootstrapped) void refreshStatuses();
|
|
|
|
|
|
else void loadPage(new URL(location.href), 'none');
|
|
|
|
|
|
}
|