|
|
const runtimeUrl = new URL('/cloud/runtime.js', location.origin);
|
|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion);
|
|
|
const {
|
|
|
VM_DETAIL_TABS, api, bindPageCleanup, byId, clearCredential,
|
|
|
clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential,
|
|
|
drawVmTrafficDaily, hydrateVmDetailBootstrap, loadVmMetrics, loadVmStatus,
|
|
|
loadVmTrafficDaily, renderVmDetail, renderVmMetrics,
|
|
|
selectedVm, setVmDetailTab, showError, state, stopVmMetrics,
|
|
|
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,
|
|
|
} = await import(runtimeUrl.href);
|
|
|
|
|
|
const VM_METADATA_FIELDS = Object.freeze([
|
|
|
'region', 'location', 'created_at', 'os_source', 'os_name',
|
|
|
'install_iso', 'guest_hostname', 'public_ip_cidr', 'public_ip', 'login_name', 'vcpu',
|
|
|
'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib',
|
|
|
'engine_metadata_version',
|
|
|
]);
|
|
|
|
|
|
let metadataRequest = null;
|
|
|
let operationLogsRequest = null;
|
|
|
let operationLogsLoadedVmId = null;
|
|
|
let operationLogsPage = 1;
|
|
|
let operationLogsPageCount = 1;
|
|
|
let displayNameSaving = false;
|
|
|
let displayNameStatusTimer = null;
|
|
|
const DISPLAY_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
|
|
|
|
|
|
function setDisplayNameStatus(message = '', kind = '') {
|
|
|
const status = byId('vm-detail-name-status');
|
|
|
if (!status) return;
|
|
|
window.clearTimeout(displayNameStatusTimer);
|
|
|
displayNameStatusTimer = null;
|
|
|
status.textContent = message;
|
|
|
status.className = `vm-detail-name-status${kind ? ` ${kind}` : ''}`;
|
|
|
status.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function syncDisplayNameInputSize(input) {
|
|
|
const length = Array.from(input.value || '').length;
|
|
|
input.size = Math.max(1, Math.min(63, length || 1));
|
|
|
}
|
|
|
|
|
|
function setDisplayNameEditing(editing) {
|
|
|
const display = byId('vm-detail-name-display');
|
|
|
const form = byId('vm-detail-name-form');
|
|
|
const trigger = byId('vm-detail-name-trigger');
|
|
|
if (!display || !form || !trigger) return;
|
|
|
display.hidden = editing;
|
|
|
form.hidden = !editing;
|
|
|
trigger.setAttribute('aria-expanded', editing ? 'true' : 'false');
|
|
|
if (editing) {
|
|
|
const input = byId('vm-detail-name-input');
|
|
|
input.value = String(selectedVm()?.name || '');
|
|
|
syncDisplayNameInputSize(input);
|
|
|
setDisplayNameStatus();
|
|
|
window.requestAnimationFrame(() => { input.focus(); input.select(); });
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindDisplayNameEditor(vmId) {
|
|
|
const trigger = byId('vm-detail-name-trigger');
|
|
|
const form = byId('vm-detail-name-form');
|
|
|
const input = byId('vm-detail-name-input');
|
|
|
const save = byId('vm-detail-name-save');
|
|
|
const cancel = byId('vm-detail-name-cancel');
|
|
|
if (!trigger || !form || !input || !save || !cancel) return;
|
|
|
|
|
|
trigger.addEventListener('click', () => setDisplayNameEditing(true));
|
|
|
input.addEventListener('input', () => syncDisplayNameInputSize(input));
|
|
|
cancel.addEventListener('click', () => {
|
|
|
if (displayNameSaving) return;
|
|
|
setDisplayNameEditing(false);
|
|
|
setDisplayNameStatus();
|
|
|
trigger.focus();
|
|
|
});
|
|
|
input.addEventListener('keydown', event => {
|
|
|
if (event.key !== 'Escape' || displayNameSaving) return;
|
|
|
event.preventDefault();
|
|
|
setDisplayNameEditing(false);
|
|
|
setDisplayNameStatus();
|
|
|
trigger.focus();
|
|
|
});
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (displayNameSaving) return;
|
|
|
const name = input.value.trim();
|
|
|
if (!DISPLAY_NAME_PATTERN.test(name)) {
|
|
|
setDisplayNameStatus('名称需以英文或数字开头,可包含英文、数字、点、下划线和连字符,最多 63 个字符。', 'error');
|
|
|
input.focus();
|
|
|
return;
|
|
|
}
|
|
|
const vm = selectedVm();
|
|
|
if (!vm) {
|
|
|
setDisplayNameStatus('实例信息已失效,请刷新页面后重试。', 'error');
|
|
|
return;
|
|
|
}
|
|
|
if (name === String(vm.name || '')) {
|
|
|
setDisplayNameEditing(false);
|
|
|
trigger.focus();
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
displayNameSaving = true;
|
|
|
save.disabled = true;
|
|
|
cancel.disabled = true;
|
|
|
input.disabled = true;
|
|
|
save.textContent = '保存中…';
|
|
|
setDisplayNameStatus('正在保存名称…');
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/display-name`, {
|
|
|
method: 'PATCH', body: { name },
|
|
|
});
|
|
|
if (!result || typeof result.name !== 'string'
|
|
|
|| !DISPLAY_NAME_PATTERN.test(result.name)) {
|
|
|
throw new Error('服务返回的实例名称无效,请刷新页面确认。');
|
|
|
}
|
|
|
const current = selectedVm();
|
|
|
if (current && String(current.api_id) === String(vmId)) current.name = result.name;
|
|
|
byId('vm-detail-name-value').textContent = result.name;
|
|
|
input.value = result.name;
|
|
|
syncDisplayNameInputSize(input);
|
|
|
setDisplayNameEditing(false);
|
|
|
setDisplayNameStatus('名称已保存。', 'success');
|
|
|
trigger.focus();
|
|
|
void loadVmStatus(vmId, { force: true });
|
|
|
displayNameStatusTimer = window.setTimeout(() => setDisplayNameStatus(), 2600);
|
|
|
} catch (error) {
|
|
|
setDisplayNameStatus(error?.message || '名称保存失败,请稍后重试。', 'error');
|
|
|
window.requestAnimationFrame(() => input.focus());
|
|
|
} finally {
|
|
|
displayNameSaving = false;
|
|
|
save.disabled = false;
|
|
|
cancel.disabled = false;
|
|
|
input.disabled = false;
|
|
|
save.textContent = '保存';
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
const OPERATION_STATUS_LABELS = Object.freeze({
|
|
|
queued: ['排队中', 'queued'], running: ['执行中', 'running'],
|
|
|
succeeded: ['已完成', 'succeeded'], completed: ['已完成', 'succeeded'],
|
|
|
failed: ['失败', 'failed'], uncertain: ['待核查', 'uncertain'],
|
|
|
cancelled: ['已取消', 'cancelled'], canceled: ['已取消', 'cancelled'],
|
|
|
});
|
|
|
|
|
|
function operationLogElement(tag, className, value = '') {
|
|
|
const element = document.createElement(tag);
|
|
|
if (className) element.className = className;
|
|
|
if (value !== '') element.textContent = String(value);
|
|
|
return element;
|
|
|
}
|
|
|
|
|
|
function operationKindLabel(entry) {
|
|
|
return entry?.kind_label || entry?.action_label || entry?.display?.kind || '实例操作';
|
|
|
}
|
|
|
|
|
|
function operationStatusInfo(value) {
|
|
|
const key = String(value || '').toLowerCase();
|
|
|
return OPERATION_STATUS_LABELS[key] || [value || '未知状态', 'unknown'];
|
|
|
}
|
|
|
|
|
|
function operationTime(value) {
|
|
|
const timestamp = Number(value);
|
|
|
if (!Number.isFinite(timestamp) || timestamp <= 0) return '时间未记录';
|
|
|
return new Date(timestamp * 1000).toLocaleString('zh-CN', {
|
|
|
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
|
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function renderOperationLogs(items, pagination = {}) {
|
|
|
const list = byId('vm-operation-log-list');
|
|
|
const status = byId('vm-operation-log-status');
|
|
|
const empty = byId('vm-operation-log-empty');
|
|
|
const footer = byId('vm-operation-log-footer');
|
|
|
const summary = byId('vm-operation-log-summary');
|
|
|
const pageLabel = byId('vm-operation-log-page');
|
|
|
const previous = byId('vm-operation-log-prev');
|
|
|
const next = byId('vm-operation-log-next');
|
|
|
if (!list || !status) return;
|
|
|
list.replaceChildren();
|
|
|
const total = Math.max(0, Number(pagination.total) || 0);
|
|
|
const page = Math.max(1, Number(pagination.page) || 1);
|
|
|
const totalPages = Math.max(1, Number(pagination.total_pages) || 1);
|
|
|
operationLogsPage = page;
|
|
|
operationLogsPageCount = totalPages;
|
|
|
if (!items.length && total === 0) {
|
|
|
status.className = 'vm-operation-log-status';
|
|
|
status.hidden = true;
|
|
|
if (empty) empty.hidden = false;
|
|
|
} else if (!items.length) {
|
|
|
status.className = 'vm-operation-log-status warning';
|
|
|
status.hidden = false;
|
|
|
status.textContent = '当前页没有记录,请返回上一页。';
|
|
|
if (empty) empty.hidden = true;
|
|
|
} else {
|
|
|
status.hidden = true;
|
|
|
if (empty) empty.hidden = true;
|
|
|
}
|
|
|
for (const entry of items) {
|
|
|
const item = operationLogElement('div', 'vm-operation-log-row');
|
|
|
item.setAttribute('role', 'row');
|
|
|
const operation = operationLogElement('span', 'vm-operation-log-cell operation', operationKindLabel(entry));
|
|
|
operation.setAttribute('role', 'cell');
|
|
|
const [statusLabel, statusClass] = operationStatusInfo(entry.status);
|
|
|
const submitted = operationLogElement('span', 'vm-operation-log-cell submitted', operationTime(entry.created_at));
|
|
|
submitted.setAttribute('role', 'cell');
|
|
|
submitted.title = operationTime(entry.created_at);
|
|
|
const result = operationLogElement('span', `vm-operation-log-cell result ${statusClass}`, statusLabel);
|
|
|
result.setAttribute('role', 'cell');
|
|
|
if (entry.error) result.title = entry.error;
|
|
|
item.append(operation, submitted, result);
|
|
|
list.append(item);
|
|
|
}
|
|
|
if (footer) footer.hidden = false;
|
|
|
if (summary) summary.textContent = `共 ${total} 条记录`;
|
|
|
if (pageLabel) pageLabel.textContent = `${page} / ${totalPages}`;
|
|
|
if (previous) previous.disabled = page <= 1;
|
|
|
if (next) next.disabled = page >= totalPages;
|
|
|
}
|
|
|
|
|
|
async function loadOperationLogs(vmId, force = false, page = operationLogsPage) {
|
|
|
const requestedPage = Math.max(1, Number(page) || 1);
|
|
|
if (!force && operationLogsLoadedVmId === String(vmId) && operationLogsPage === requestedPage) return;
|
|
|
if (operationLogsRequest) return operationLogsRequest;
|
|
|
const status = byId('vm-operation-log-status');
|
|
|
if (status) {
|
|
|
status.hidden = false;
|
|
|
status.className = 'vm-operation-log-status';
|
|
|
status.textContent = '正在读取操作日志…';
|
|
|
}
|
|
|
byId('vm-operation-log-footer')?.setAttribute('hidden', '');
|
|
|
operationLogsRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/operations?page=${requestedPage}`);
|
|
|
const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
if (String(selectedVm()?.api_id || '') !== String(vmId)) return;
|
|
|
operationLogsLoadedVmId = String(vmId);
|
|
|
renderOperationLogs(items, payload?.pagination || {});
|
|
|
} catch (error) {
|
|
|
operationLogsLoadedVmId = null;
|
|
|
if (status) {
|
|
|
status.hidden = false;
|
|
|
status.className = 'vm-operation-log-status warning';
|
|
|
status.textContent = error.message || '操作日志读取失败,请稍后重试。';
|
|
|
}
|
|
|
byId('vm-operation-log-footer')?.setAttribute('hidden', '');
|
|
|
byId('vm-operation-log-list')?.replaceChildren();
|
|
|
byId('vm-operation-log-empty')?.setAttribute('hidden', '');
|
|
|
} finally {
|
|
|
operationLogsRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return operationLogsRequest;
|
|
|
}
|
|
|
|
|
|
function hasMetadataText(value) {
|
|
|
return value !== null && value !== undefined && String(value).trim() !== '';
|
|
|
}
|
|
|
|
|
|
function needsVmMetadata(vm) {
|
|
|
if (Number(vm?.engine_metadata_version) >= 1) return false;
|
|
|
const source = hasMetadataText(vm?.os_source) ? String(vm.os_source).trim() : '';
|
|
|
if (!source) return true;
|
|
|
if (source === 'cloud_template') {
|
|
|
return !hasMetadataText(vm.public_ip_cidr || vm.public_ip)
|
|
|
|| !hasMetadataText(vm.os_name) || !hasMetadataText(vm.login_name);
|
|
|
}
|
|
|
if (source === 'iso') return !hasMetadataText(vm.install_iso);
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* The SSR snapshot deliberately avoids libvirt. Fetch the immutable host
|
|
|
* metadata once after first paint, while keeping the recurring poll on the
|
|
|
* much smaller /status endpoint. Identity and permissions always remain
|
|
|
* authoritative from the actor-scoped PHP bootstrap.
|
|
|
*/
|
|
|
async function loadVmMetadata(vmId, force = false) {
|
|
|
if (!force && !needsVmMetadata(selectedVm())) return selectedVm();
|
|
|
if (metadataRequest) return metadataRequest;
|
|
|
metadataRequest = (async () => {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/metadata`);
|
|
|
const update = payload?.vm && typeof payload.vm === 'object' ? payload.vm : payload;
|
|
|
const current = selectedVm();
|
|
|
if (!current || !update || typeof update !== 'object') {
|
|
|
throw new Error('实例静态信息格式无效。');
|
|
|
}
|
|
|
const currentUuid = String(current.uuid || '').toLowerCase();
|
|
|
const updateUuid = String(update.uuid || '').toLowerCase();
|
|
|
if (!updateUuid || updateUuid !== currentUuid) {
|
|
|
throw new Error('实例静态信息标识不匹配。');
|
|
|
}
|
|
|
const merged = { ...current };
|
|
|
for (const field of VM_METADATA_FIELDS) {
|
|
|
if (Object.prototype.hasOwnProperty.call(update, field)) merged[field] = update[field];
|
|
|
}
|
|
|
state.vms = [merged];
|
|
|
state.selectedVmId = current.uuid;
|
|
|
renderVmDetail(merged);
|
|
|
return merged;
|
|
|
})();
|
|
|
try {
|
|
|
return await metadataRequest;
|
|
|
} finally {
|
|
|
metadataRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function refreshMetadataAndStatus(vmId, notifyFailure = false, forceMetadata = false, liveStatus = false) {
|
|
|
let metadataError = null;
|
|
|
// These requests intentionally run independently. Metadata does not share
|
|
|
// the status request coordinator, and each merge starts from selectedVm(),
|
|
|
// so a slow host XML read cannot delay the lightweight state refresh.
|
|
|
await Promise.all([
|
|
|
loadVmMetadata(vmId, forceMetadata).catch(error => { metadataError = error; }),
|
|
|
loadVmStatus(vmId, liveStatus ? { live: true, force: true } : {}),
|
|
|
]);
|
|
|
if (metadataError && notifyFailure) {
|
|
|
toast(`${metadataError.message || '实例静态信息刷新失败。'} 实时状态已继续更新。`, 'error');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function detailBootstrap() {
|
|
|
const source = byId('vm-detail-bootstrap');
|
|
|
if (!source) throw new Error('实例详情初始数据缺失,请刷新后重试。');
|
|
|
try {
|
|
|
return JSON.parse(source.textContent || '{}');
|
|
|
} catch {
|
|
|
throw new Error('实例详情初始数据无法解析,请刷新后重试。');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindDetailTabs(vmId) {
|
|
|
document.querySelectorAll('[data-detail-tab]').forEach(button => {
|
|
|
button.addEventListener('click', () => {
|
|
|
const tab = button.dataset.detailTab;
|
|
|
setVmDetailTab(tab);
|
|
|
if (tab === 'operations-log') void loadOperationLogs(vmId);
|
|
|
const url = new URL(location.href);
|
|
|
if (tab === 'operations') url.searchParams.delete('tab');
|
|
|
else url.searchParams.set('tab', tab);
|
|
|
history.replaceState(null, '', url);
|
|
|
});
|
|
|
button.addEventListener('keydown', event => {
|
|
|
const current = VM_DETAIL_TABS.indexOf(button.dataset.detailTab);
|
|
|
let next = current;
|
|
|
if (event.key === 'ArrowRight') next = (current + 1) % VM_DETAIL_TABS.length;
|
|
|
else if (event.key === 'ArrowLeft') next = (current - 1 + VM_DETAIL_TABS.length) % VM_DETAIL_TABS.length;
|
|
|
else if (event.key === 'Home') next = 0;
|
|
|
else if (event.key === 'End') next = VM_DETAIL_TABS.length - 1;
|
|
|
else return;
|
|
|
event.preventDefault();
|
|
|
setVmDetailTab(VM_DETAIL_TABS[next], true);
|
|
|
});
|
|
|
});
|
|
|
}
|
|
|
|
|
|
const INSTANCE_SETTING_LABELS = Object.freeze({
|
|
|
hostname: '主机名', password: 'root 密码', ssh_key: 'SSH 公钥',
|
|
|
firewall: '防火墙', snapshots: '在线快照',
|
|
|
});
|
|
|
const INSTANCE_SETTING_TABS = Object.freeze(['hostname', 'password', 'ssh_key', 'firewall', 'snapshots']);
|
|
|
const FIREWALL_RULE_LIMIT = 50;
|
|
|
const FIREWALL_PENDING_STATES = new Set(['pending', 'queued', 'applying', 'running']);
|
|
|
const FIREWALL_UNCERTAIN_STATES = new Set(['uncertain', 'needs_attention']);
|
|
|
const SNAPSHOT_LIMIT = 2;
|
|
|
const SNAPSHOT_STATE_LABELS = Object.freeze({
|
|
|
ready: ['可恢复', 'ready'], available: ['可恢复', 'ready'],
|
|
|
queued: ['排队中', 'pending'], pending: ['排队中', 'pending'], starting: ['正在开始', 'pending'],
|
|
|
creating: ['正在创建', 'pending'], running: ['正在处理', 'pending'],
|
|
|
restoring: ['正在恢复', 'pending'], deleting: ['正在删除', 'pending'],
|
|
|
failed: ['失败', 'failed'], cancelled: ['已取消', 'failed'], canceled: ['已取消', 'failed'],
|
|
|
uncertain: ['待核查', 'uncertain'], needs_attention: ['待核查', 'uncertain'],
|
|
|
});
|
|
|
const SNAPSHOT_ACTIVE_STATES = new Set([
|
|
|
'queued', 'pending', 'starting', 'creating', 'running', 'restoring', 'deleting',
|
|
|
]);
|
|
|
const SNAPSHOT_UNCERTAIN_STATES = new Set(['uncertain', 'needs_attention']);
|
|
|
let snapshotRequest = null;
|
|
|
let snapshotLoadedVmId = null;
|
|
|
let snapshotPayload = null;
|
|
|
let snapshotMutation = null;
|
|
|
let snapshotPollGeneration = 0;
|
|
|
let snapshotBlockedUncertain = false;
|
|
|
let firewallRequest = null;
|
|
|
let firewallLoadedVmId = null;
|
|
|
let firewallPayload = null;
|
|
|
let firewallSaving = false;
|
|
|
let firewallDirty = false;
|
|
|
let firewallPollGeneration = 0;
|
|
|
let firewallPolling = false;
|
|
|
|
|
|
function setInstanceSettingTab(tab, focus = false) {
|
|
|
const selected = INSTANCE_SETTING_TABS.includes(tab) ? tab : INSTANCE_SETTING_TABS[0];
|
|
|
document.querySelectorAll('[data-instance-setting-tab]').forEach(button => {
|
|
|
const active = button.dataset.instanceSettingTab === selected;
|
|
|
button.classList.toggle('active', active);
|
|
|
button.setAttribute('aria-selected', String(active));
|
|
|
button.tabIndex = active ? 0 : -1;
|
|
|
if (active && focus) button.focus();
|
|
|
});
|
|
|
document.querySelectorAll('[data-instance-setting-panel]').forEach(panel => {
|
|
|
panel.hidden = panel.dataset.instanceSettingPanel !== selected;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function activateInstanceSettingTab(vmId, tab, focus = false) {
|
|
|
setInstanceSettingTab(tab, focus);
|
|
|
if (tab === 'firewall') {
|
|
|
settingStatus();
|
|
|
void loadVmFirewall(vmId);
|
|
|
} else if (tab === 'snapshots') {
|
|
|
settingStatus();
|
|
|
void loadVmSnapshots(vmId, true);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindInstanceSettingTabs(vmId) {
|
|
|
const buttons = Array.from(document.querySelectorAll('[data-instance-setting-tab]'));
|
|
|
if (!buttons.length) return;
|
|
|
const navigation = document.querySelector('.vm-settings-navigation');
|
|
|
const compactLayout = window.matchMedia('(max-width: 740px)');
|
|
|
const syncOrientation = () => navigation?.setAttribute(
|
|
|
'aria-orientation', compactLayout.matches ? 'horizontal' : 'vertical'
|
|
|
);
|
|
|
syncOrientation();
|
|
|
compactLayout.addEventListener?.('change', syncOrientation);
|
|
|
buttons.forEach(button => {
|
|
|
button.addEventListener('click', () => activateInstanceSettingTab(vmId, button.dataset.instanceSettingTab));
|
|
|
button.addEventListener('keydown', event => {
|
|
|
const current = INSTANCE_SETTING_TABS.indexOf(button.dataset.instanceSettingTab);
|
|
|
let next = current;
|
|
|
if ((compactLayout.matches && event.key === 'ArrowRight') || (!compactLayout.matches && event.key === 'ArrowDown')) next = (current + 1) % INSTANCE_SETTING_TABS.length;
|
|
|
else if ((compactLayout.matches && event.key === 'ArrowLeft') || (!compactLayout.matches && event.key === 'ArrowUp')) next = (current - 1 + INSTANCE_SETTING_TABS.length) % INSTANCE_SETTING_TABS.length;
|
|
|
else if (event.key === 'Home') next = 0;
|
|
|
else if (event.key === 'End') next = INSTANCE_SETTING_TABS.length - 1;
|
|
|
else return;
|
|
|
event.preventDefault();
|
|
|
activateInstanceSettingTab(vmId, INSTANCE_SETTING_TABS[next], true);
|
|
|
});
|
|
|
});
|
|
|
setInstanceSettingTab(INSTANCE_SETTING_TABS[0]);
|
|
|
}
|
|
|
|
|
|
function firewallPolicy(payload) {
|
|
|
const source = payload?.firewall && typeof payload.firewall === 'object'
|
|
|
? payload.firewall : payload?.policy && typeof payload.policy === 'object'
|
|
|
? payload.policy : payload || {};
|
|
|
const rules = Array.isArray(source.rules) ? source.rules.slice(0, FIREWALL_RULE_LIMIT) : [];
|
|
|
const desiredRevision = Math.max(0, Number(source.desired_revision ?? source.revision) || 0);
|
|
|
const appliedRevision = Math.max(0, Number(source.applied_revision) || 0);
|
|
|
let syncState = String(source.sync_state || source.status || '').toLowerCase();
|
|
|
if (!syncState) syncState = source.enabled ? 'active' : 'disabled';
|
|
|
if (syncState === 'active' && !source.enabled) syncState = 'disabled';
|
|
|
return {
|
|
|
enabled: source.enabled === true,
|
|
|
desired_revision: desiredRevision,
|
|
|
applied_revision: appliedRevision,
|
|
|
sync_state: syncState,
|
|
|
can_mutate: source.can_mutate !== false,
|
|
|
last_success_at: source.last_success_at || null,
|
|
|
last_failure_at: source.last_failure_at || null,
|
|
|
last_error_code: String(source.last_error_code || source.error_code || ''),
|
|
|
rules,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function firewallStateInfo(policy) {
|
|
|
const state = String(policy?.sync_state || '').toLowerCase();
|
|
|
if (FIREWALL_UNCERTAIN_STATES.has(state)) return ['待核对', 'uncertain'];
|
|
|
if (['pending', 'queued'].includes(state)) return ['待应用', 'pending'];
|
|
|
if (['applying', 'running'].includes(state)) return ['正在应用', 'pending'];
|
|
|
if (['failed', 'error'].includes(state)) return ['应用失败', 'failed'];
|
|
|
if (!policy?.enabled || state === 'disabled') return ['未启用', 'disabled'];
|
|
|
if (['active', 'applied', 'succeeded', 'completed'].includes(state)) return ['已生效', 'active'];
|
|
|
return ['状态未知', 'unknown'];
|
|
|
}
|
|
|
|
|
|
function firewallTime(value) {
|
|
|
if (value === null || value === undefined || value === '') return '未记录';
|
|
|
let date;
|
|
|
if (typeof value === 'number' || /^\d+$/.test(String(value))) {
|
|
|
const timestamp = Number(value);
|
|
|
date = new Date(timestamp > 100000000000 ? timestamp : timestamp * 1000);
|
|
|
} else date = new Date(String(value));
|
|
|
if (Number.isNaN(date.getTime())) return '未记录';
|
|
|
return date.toLocaleString('zh-CN', {
|
|
|
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
|
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function setFirewallStatus(message = '', type = '') {
|
|
|
const target = byId('vm-firewall-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-firewall-status${type ? ` ${type}` : ''}`;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function setFirewallFormError(message = '') {
|
|
|
const target = byId('vm-firewall-form-error');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function firewallElement(tag, className = '', text = '') {
|
|
|
const element = document.createElement(tag);
|
|
|
if (className) element.className = className;
|
|
|
if (text !== '') element.textContent = String(text);
|
|
|
return element;
|
|
|
}
|
|
|
|
|
|
function firewallPortText(rule) {
|
|
|
const from = Number(rule?.port_from);
|
|
|
const to = Number(rule?.port_to);
|
|
|
if (!Number.isInteger(from) || from < 1 || from > 65535) return '';
|
|
|
return Number.isInteger(to) && to !== from ? `${from}-${to}` : String(from);
|
|
|
}
|
|
|
|
|
|
function firewallRuleCell(label, control, className = '') {
|
|
|
const cell = firewallElement('label', `vm-firewall-cell${className ? ` ${className}` : ''}`);
|
|
|
cell.setAttribute('role', 'cell');
|
|
|
cell.append(firewallElement('span', 'vm-firewall-cell-label', label), control);
|
|
|
return cell;
|
|
|
}
|
|
|
|
|
|
function renderFirewallRule(rule = {}, controlsDisabled = false) {
|
|
|
const row = firewallElement('div', 'vm-firewall-rule vm-firewall-rule-item');
|
|
|
row.setAttribute('role', 'row');
|
|
|
|
|
|
const protocol = document.createElement('select');
|
|
|
protocol.name = 'protocol';
|
|
|
protocol.setAttribute('aria-label', '协议');
|
|
|
for (const value of ['TCP', 'UDP', 'ICMP']) {
|
|
|
const option = document.createElement('option');
|
|
|
option.value = value;
|
|
|
option.textContent = value;
|
|
|
protocol.append(option);
|
|
|
}
|
|
|
protocol.value = ['TCP', 'UDP', 'ICMP'].includes(String(rule.protocol || '').toUpperCase())
|
|
|
? String(rule.protocol).toUpperCase() : 'TCP';
|
|
|
|
|
|
const source = document.createElement('input');
|
|
|
source.name = 'source_cidr';
|
|
|
source.type = 'text';
|
|
|
source.maxLength = 18;
|
|
|
source.autocomplete = 'off';
|
|
|
source.spellcheck = false;
|
|
|
source.placeholder = '例如 203.0.113.8/32';
|
|
|
source.value = String(rule.source_cidr || rule.source || '');
|
|
|
source.setAttribute('aria-label', '来源 IPv4 或 CIDR');
|
|
|
|
|
|
const port = document.createElement('input');
|
|
|
port.name = 'ports';
|
|
|
port.type = 'text';
|
|
|
port.maxLength = 11;
|
|
|
port.autocomplete = 'off';
|
|
|
port.placeholder = '22 或 8000-8080';
|
|
|
port.value = protocol.value === 'ICMP' ? '' : firewallPortText(rule);
|
|
|
port.setAttribute('aria-label', '端口或端口范围');
|
|
|
|
|
|
const description = document.createElement('input');
|
|
|
description.name = 'description';
|
|
|
description.type = 'text';
|
|
|
description.maxLength = 100;
|
|
|
description.autocomplete = 'off';
|
|
|
description.placeholder = '可选说明';
|
|
|
description.value = String(rule.description || '');
|
|
|
description.setAttribute('aria-label', '规则描述');
|
|
|
|
|
|
const remove = firewallElement('button', 'button button-outline small danger', '删除');
|
|
|
remove.type = 'button';
|
|
|
remove.setAttribute('aria-label', '删除这条规则');
|
|
|
const action = firewallElement('div', 'vm-firewall-cell action');
|
|
|
action.setAttribute('role', 'cell');
|
|
|
action.append(firewallElement('span', 'vm-firewall-cell-label', '操作'), remove);
|
|
|
|
|
|
const syncProtocol = () => {
|
|
|
const icmp = protocol.value === 'ICMP';
|
|
|
port.disabled = controlsDisabled || icmp;
|
|
|
port.placeholder = icmp ? 'ICMP 无需端口' : '22 或 8000-8080';
|
|
|
if (icmp) port.value = '';
|
|
|
};
|
|
|
protocol.disabled = controlsDisabled;
|
|
|
source.disabled = controlsDisabled;
|
|
|
description.disabled = controlsDisabled;
|
|
|
remove.disabled = controlsDisabled;
|
|
|
syncProtocol();
|
|
|
protocol.addEventListener('change', () => { syncProtocol(); markFirewallDirty(); });
|
|
|
source.addEventListener('input', markFirewallDirty);
|
|
|
port.addEventListener('input', markFirewallDirty);
|
|
|
description.addEventListener('input', markFirewallDirty);
|
|
|
remove.addEventListener('click', () => {
|
|
|
row.remove();
|
|
|
markFirewallDirty();
|
|
|
});
|
|
|
row.append(
|
|
|
firewallRuleCell('协议', protocol, 'protocol'),
|
|
|
firewallRuleCell('来源 IPv4 / CIDR', source, 'source'),
|
|
|
firewallRuleCell('端口', port, 'ports'),
|
|
|
firewallRuleCell('描述', description, 'description'),
|
|
|
action,
|
|
|
);
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
function firewallControlsBlocked(policy = firewallPayload) {
|
|
|
const state = String(policy?.sync_state || '').toLowerCase();
|
|
|
return firewallSaving || !policy || policy.can_mutate === false
|
|
|
|| FIREWALL_PENDING_STATES.has(state) || FIREWALL_UNCERTAIN_STATES.has(state);
|
|
|
}
|
|
|
|
|
|
function updateFirewallEditorState() {
|
|
|
const list = byId('vm-firewall-rules');
|
|
|
const enabled = byId('vm-firewall-enabled');
|
|
|
const empty = byId('vm-firewall-empty');
|
|
|
const warning = byId('vm-firewall-empty-warning');
|
|
|
const count = byId('vm-firewall-count');
|
|
|
const save = byId('vm-firewall-save');
|
|
|
const add = byId('vm-firewall-add-rule');
|
|
|
if (!list || !enabled || !save) return;
|
|
|
const total = list.querySelectorAll('.vm-firewall-rule-item').length;
|
|
|
const blocked = firewallControlsBlocked();
|
|
|
if (empty) empty.hidden = total !== 0;
|
|
|
if (warning) warning.hidden = !enabled.checked || total !== 0;
|
|
|
if (count) count.textContent = `${total} / ${FIREWALL_RULE_LIMIT} 条`;
|
|
|
enabled.disabled = blocked;
|
|
|
if (add) add.disabled = blocked || total >= FIREWALL_RULE_LIMIT;
|
|
|
document.querySelectorAll('[data-firewall-preset]').forEach(button => {
|
|
|
button.disabled = blocked || total >= FIREWALL_RULE_LIMIT;
|
|
|
});
|
|
|
list.querySelectorAll('select,input,button').forEach(control => {
|
|
|
const row = control.closest('.vm-firewall-rule-item');
|
|
|
const protocol = row?.querySelector('[name="protocol"]')?.value;
|
|
|
control.disabled = blocked || (control.name === 'ports' && protocol === 'ICMP');
|
|
|
});
|
|
|
save.disabled = blocked || !firewallDirty;
|
|
|
if (firewallSaving) save.textContent = '正在提交…';
|
|
|
else if (FIREWALL_UNCERTAIN_STATES.has(String(firewallPayload?.sync_state || ''))) save.textContent = '等待人工核对';
|
|
|
else if (FIREWALL_PENDING_STATES.has(String(firewallPayload?.sync_state || ''))) save.textContent = '正在应用';
|
|
|
else save.textContent = '应用全部规则';
|
|
|
}
|
|
|
|
|
|
function markFirewallDirty() {
|
|
|
firewallDirty = true;
|
|
|
setFirewallFormError();
|
|
|
updateFirewallEditorState();
|
|
|
}
|
|
|
|
|
|
function renderVmFirewall(payload) {
|
|
|
const policy = firewallPolicy(payload);
|
|
|
firewallPayload = policy;
|
|
|
const list = byId('vm-firewall-rules');
|
|
|
const enabled = byId('vm-firewall-enabled');
|
|
|
if (!list || !enabled) return policy;
|
|
|
const [stateLabel, stateClass] = firewallStateInfo(policy);
|
|
|
const state = byId('vm-firewall-state');
|
|
|
if (state) {
|
|
|
state.textContent = stateLabel;
|
|
|
state.className = `vm-firewall-state ${stateClass}`;
|
|
|
}
|
|
|
const revisions = byId('vm-firewall-revisions');
|
|
|
if (revisions) revisions.textContent = `${policy.desired_revision || '—'} / ${policy.applied_revision || '—'}`;
|
|
|
const success = byId('vm-firewall-last-success');
|
|
|
if (success) success.textContent = firewallTime(policy.last_success_at);
|
|
|
const failure = byId('vm-firewall-last-failure');
|
|
|
if (failure) {
|
|
|
const failedAt = firewallTime(policy.last_failure_at);
|
|
|
failure.textContent = policy.last_error_code
|
|
|
? `${failedAt} · ${policy.last_error_code}` : failedAt;
|
|
|
failure.title = policy.last_error_code || '';
|
|
|
}
|
|
|
enabled.checked = policy.enabled;
|
|
|
const blocked = firewallControlsBlocked(policy);
|
|
|
list.replaceChildren(...policy.rules.map(rule => renderFirewallRule(rule, blocked)));
|
|
|
firewallDirty = false;
|
|
|
setFirewallFormError();
|
|
|
updateFirewallEditorState();
|
|
|
|
|
|
const syncState = String(policy.sync_state || '').toLowerCase();
|
|
|
if (FIREWALL_UNCERTAIN_STATES.has(syncState)) {
|
|
|
setFirewallStatus('上一次应用结果待核对,编辑已冻结。确认宿主机真实规则前请勿重复提交。', 'warning');
|
|
|
} else if (FIREWALL_PENDING_STATES.has(syncState)) {
|
|
|
setFirewallStatus('防火墙策略正在排队或应用,完成前不能再次编辑。');
|
|
|
} else if (['failed', 'error'].includes(syncState)) {
|
|
|
const suffix = policy.last_error_code ? `(${policy.last_error_code})` : '';
|
|
|
setFirewallStatus(`新策略应用失败${suffix};上一份已确认策略仍然生效,可修正规则后重试。`, 'error');
|
|
|
} else if (policy.can_mutate === false) {
|
|
|
setFirewallStatus('当前实例状态或服务状态不允许修改防火墙。', 'warning');
|
|
|
} else if (policy.enabled) {
|
|
|
setFirewallStatus('防火墙已启用,未列出的新 IPv4 入站连接会被拒绝。', 'success');
|
|
|
} else {
|
|
|
setFirewallStatus('防火墙未启用,当前入站访问不受用户规则限制;反欺骗保护仍然有效。');
|
|
|
}
|
|
|
return policy;
|
|
|
}
|
|
|
|
|
|
async function loadVmFirewall(vmId, force = false, replaceDraft = false) {
|
|
|
if (!byId('vm-settings-section-firewall')) return null;
|
|
|
if (firewallDirty && !replaceDraft) {
|
|
|
setFirewallStatus('存在尚未应用的防火墙修改;应用或刷新页面前不会覆盖当前编辑。', 'warning');
|
|
|
return firewallPayload;
|
|
|
}
|
|
|
if (!force && firewallLoadedVmId === String(vmId) && firewallPayload) return firewallPayload;
|
|
|
if (firewallRequest) return firewallRequest;
|
|
|
setFirewallStatus('正在读取防火墙策略…');
|
|
|
firewallRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/firewall`);
|
|
|
if (String(selectedVm()?.api_id || '') !== String(vmId)) return null;
|
|
|
firewallLoadedVmId = String(vmId);
|
|
|
const policy = renderVmFirewall(payload);
|
|
|
if (FIREWALL_PENDING_STATES.has(policy.sync_state) && !firewallPolling) {
|
|
|
void pollVmFirewall(vmId);
|
|
|
}
|
|
|
return policy;
|
|
|
} catch (error) {
|
|
|
firewallLoadedVmId = null;
|
|
|
setFirewallStatus(error?.message || '防火墙策略读取失败,请稍后重试。', 'error');
|
|
|
return null;
|
|
|
} finally {
|
|
|
firewallRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return firewallRequest;
|
|
|
}
|
|
|
|
|
|
async function pollVmFirewall(vmId) {
|
|
|
if (firewallPolling) return;
|
|
|
firewallPolling = true;
|
|
|
const generation = ++firewallPollGeneration;
|
|
|
try {
|
|
|
for (let attempt = 0; attempt < 150 && generation === firewallPollGeneration; attempt += 1) {
|
|
|
await new Promise(resolve => setTimeout(resolve, document.hidden ? 1000 : 2000));
|
|
|
if (document.hidden) { attempt -= 1; continue; }
|
|
|
const policy = await loadVmFirewall(vmId, true, true);
|
|
|
if (!policy) continue;
|
|
|
if (!FIREWALL_PENDING_STATES.has(policy.sync_state)) return;
|
|
|
}
|
|
|
if (generation === firewallPollGeneration) {
|
|
|
setFirewallStatus('防火墙任务仍在后台处理,请稍后刷新核对;不要重复提交。', 'warning');
|
|
|
}
|
|
|
} finally {
|
|
|
if (generation === firewallPollGeneration) firewallPolling = false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function addFirewallRule(rule = {}) {
|
|
|
const list = byId('vm-firewall-rules');
|
|
|
if (!list || firewallControlsBlocked()) return;
|
|
|
if (list.querySelectorAll('.vm-firewall-rule-item').length >= FIREWALL_RULE_LIMIT) {
|
|
|
setFirewallFormError(`每台实例最多允许 ${FIREWALL_RULE_LIMIT} 条规则。`);
|
|
|
return;
|
|
|
}
|
|
|
const row = renderFirewallRule(rule, false);
|
|
|
list.append(row);
|
|
|
markFirewallDirty();
|
|
|
row.querySelector('[name="source_cidr"]')?.focus();
|
|
|
}
|
|
|
|
|
|
function validFirewallCidr(value) {
|
|
|
const [address, prefix, ...rest] = String(value).trim().split('/');
|
|
|
if (rest.length || !address) return false;
|
|
|
const octets = address.split('.');
|
|
|
if (octets.length !== 4 || octets.some(part => !/^(?:0|[1-9]\d{0,2})$/.test(part)
|
|
|
|| Number(part) < 0 || Number(part) > 255)) return false;
|
|
|
return prefix === undefined
|
|
|
|| (/^(?:0|[1-9]\d?)$/.test(prefix) && Number(prefix) <= 32);
|
|
|
}
|
|
|
|
|
|
function firewallPortRange(value) {
|
|
|
const match = String(value).trim().match(/^(\d{1,5})(?:\s*-\s*(\d{1,5}))?$/);
|
|
|
if (!match) return null;
|
|
|
const from = Number(match[1]);
|
|
|
const to = Number(match[2] || match[1]);
|
|
|
if (from < 1 || from > 65535 || to < from || to > 65535) return null;
|
|
|
return [from, to];
|
|
|
}
|
|
|
|
|
|
function invalidFirewallControl(control, message) {
|
|
|
control.setAttribute('aria-invalid', 'true');
|
|
|
setFirewallFormError(message);
|
|
|
control.focus();
|
|
|
return null;
|
|
|
}
|
|
|
|
|
|
function collectFirewallRules() {
|
|
|
const rows = Array.from(document.querySelectorAll('#vm-firewall-rules .vm-firewall-rule-item'));
|
|
|
if (rows.length > FIREWALL_RULE_LIMIT) {
|
|
|
setFirewallFormError(`每台实例最多允许 ${FIREWALL_RULE_LIMIT} 条规则。`);
|
|
|
return null;
|
|
|
}
|
|
|
const rules = [];
|
|
|
const unique = new Set();
|
|
|
for (const [index, row] of rows.entries()) {
|
|
|
row.querySelectorAll('[aria-invalid="true"]').forEach(control => control.removeAttribute('aria-invalid'));
|
|
|
const protocolControl = row.querySelector('[name="protocol"]');
|
|
|
const sourceControl = row.querySelector('[name="source_cidr"]');
|
|
|
const portControl = row.querySelector('[name="ports"]');
|
|
|
const descriptionControl = row.querySelector('[name="description"]');
|
|
|
const protocol = String(protocolControl?.value || '').toUpperCase();
|
|
|
const sourceCidr = String(sourceControl?.value || '').trim();
|
|
|
const description = String(descriptionControl?.value || '').trim();
|
|
|
if (!['TCP', 'UDP', 'ICMP'].includes(protocol)) {
|
|
|
return invalidFirewallControl(protocolControl, `第 ${index + 1} 条规则的协议无效。`);
|
|
|
}
|
|
|
if (!validFirewallCidr(sourceCidr)) {
|
|
|
return invalidFirewallControl(sourceControl, `第 ${index + 1} 条规则需要有效的 IPv4 或 CIDR。`);
|
|
|
}
|
|
|
let portFrom = null;
|
|
|
let portTo = null;
|
|
|
if (protocol !== 'ICMP') {
|
|
|
const range = firewallPortRange(portControl?.value || '');
|
|
|
if (!range) {
|
|
|
return invalidFirewallControl(portControl, `第 ${index + 1} 条规则需要 1-65535 的端口或端口范围。`);
|
|
|
}
|
|
|
[portFrom, portTo] = range;
|
|
|
}
|
|
|
const key = `${protocol}|${sourceCidr}|${portFrom || ''}|${portTo || ''}`;
|
|
|
if (unique.has(key)) {
|
|
|
return invalidFirewallControl(sourceControl, `第 ${index + 1} 条规则与已有规则重复。`);
|
|
|
}
|
|
|
unique.add(key);
|
|
|
rules.push({
|
|
|
protocol, source_cidr: sourceCidr,
|
|
|
port_from: portFrom, port_to: portTo, description,
|
|
|
});
|
|
|
}
|
|
|
return rules;
|
|
|
}
|
|
|
|
|
|
function firewallIdempotencyKey() {
|
|
|
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replaceAll('-', '');
|
|
|
if (globalThis.crypto?.getRandomValues) {
|
|
|
const bytes = new Uint8Array(16);
|
|
|
globalThis.crypto.getRandomValues(bytes);
|
|
|
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
|
|
}
|
|
|
return `${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`.padEnd(32, '0').slice(0, 32);
|
|
|
}
|
|
|
|
|
|
function firewallTransportUncertain(error) {
|
|
|
const status = Number(error?.status);
|
|
|
return (Number.isFinite(status) && status >= 500)
|
|
|
|| /failed to fetch|network|load failed|timeout|timed out|abort/i.test(String(error?.message || ''));
|
|
|
}
|
|
|
|
|
|
async function saveVmFirewall(vmId) {
|
|
|
if (firewallSaving || firewallControlsBlocked()) return;
|
|
|
const rules = collectFirewallRules();
|
|
|
if (!rules) return;
|
|
|
const enabled = byId('vm-firewall-enabled')?.checked === true;
|
|
|
firewallSaving = true;
|
|
|
setFirewallFormError();
|
|
|
setFirewallStatus('正在提交整张防火墙策略…');
|
|
|
updateFirewallEditorState();
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/firewall`, {
|
|
|
method: 'PUT',
|
|
|
body: {
|
|
|
expected_revision: Number(firewallPayload?.desired_revision) || 0,
|
|
|
idempotency_key: firewallIdempotencyKey(),
|
|
|
enabled,
|
|
|
rules,
|
|
|
},
|
|
|
});
|
|
|
firewallDirty = false;
|
|
|
const policy = result?.firewall ? renderVmFirewall(result.firewall)
|
|
|
: result?.sync_state ? renderVmFirewall(result)
|
|
|
: await loadVmFirewall(vmId, true, true);
|
|
|
if (result?.job_id || FIREWALL_PENDING_STATES.has(policy?.sync_state)) {
|
|
|
setFirewallStatus('防火墙策略已进入队列,确认宿主机生效前不能再次编辑。');
|
|
|
void pollVmFirewall(vmId);
|
|
|
}
|
|
|
} catch (error) {
|
|
|
if (firewallTransportUncertain(error)) {
|
|
|
firewallDirty = false;
|
|
|
firewallPayload = {
|
|
|
...firewallPayload, enabled, rules, sync_state: 'uncertain', can_mutate: false,
|
|
|
};
|
|
|
renderVmFirewall(firewallPayload);
|
|
|
setFirewallStatus('连接中断,面板无法确认策略是否已提交;编辑已冻结,请刷新核对,切勿重复应用。', 'warning');
|
|
|
void loadVmFirewall(vmId, true, true);
|
|
|
} else {
|
|
|
firewallDirty = true;
|
|
|
setFirewallFormError(error?.message || '防火墙策略提交失败,请修正规则后重试。');
|
|
|
setFirewallStatus('防火墙策略未提交,当前已生效策略没有改变。', 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
firewallSaving = false;
|
|
|
updateFirewallEditorState();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindFirewallControls(vmId) {
|
|
|
const form = byId('vm-firewall-form');
|
|
|
if (!form) return;
|
|
|
byId('vm-firewall-enabled')?.addEventListener('change', markFirewallDirty);
|
|
|
byId('vm-firewall-add-rule')?.addEventListener('click', () => addFirewallRule());
|
|
|
document.querySelectorAll('[data-firewall-preset]').forEach(button => {
|
|
|
button.addEventListener('click', () => {
|
|
|
const presets = {
|
|
|
ssh: { protocol: 'TCP', source_cidr: '0.0.0.0/0', port_from: 22, port_to: 22, description: 'SSH' },
|
|
|
http: { protocol: 'TCP', source_cidr: '0.0.0.0/0', port_from: 80, port_to: 80, description: 'HTTP' },
|
|
|
https: { protocol: 'TCP', source_cidr: '0.0.0.0/0', port_from: 443, port_to: 443, description: 'HTTPS' },
|
|
|
};
|
|
|
addFirewallRule(presets[button.dataset.firewallPreset] || {});
|
|
|
});
|
|
|
});
|
|
|
form.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
void saveVmFirewall(vmId);
|
|
|
});
|
|
|
window.addEventListener('pagehide', () => { firewallPollGeneration += 1; });
|
|
|
updateFirewallEditorState();
|
|
|
}
|
|
|
|
|
|
function snapshotState(snapshot) {
|
|
|
const jobStatus = String(snapshot?.job_status || '').toLowerCase();
|
|
|
if (SNAPSHOT_UNCERTAIN_STATES.has(jobStatus) || SNAPSHOT_ACTIVE_STATES.has(jobStatus)) return jobStatus;
|
|
|
return String(snapshot?.state || snapshot?.status || jobStatus || '').toLowerCase();
|
|
|
}
|
|
|
|
|
|
function snapshotStateInfo(snapshot) {
|
|
|
const value = snapshotState(snapshot);
|
|
|
return SNAPSHOT_STATE_LABELS[value] || [value || '状态未知', 'unknown'];
|
|
|
}
|
|
|
|
|
|
function snapshotItems(payload = snapshotPayload) {
|
|
|
if (Array.isArray(payload?.snapshots)) return payload.snapshots.slice(0, SNAPSHOT_LIMIT);
|
|
|
if (Array.isArray(payload?.items)) return payload.items.slice(0, SNAPSHOT_LIMIT);
|
|
|
return [];
|
|
|
}
|
|
|
|
|
|
function snapshotKey(snapshot) {
|
|
|
const value = String(snapshot?.snapshot_key || snapshot?.key || '');
|
|
|
return /^[a-f0-9]{32}$/i.test(value) ? value : '';
|
|
|
}
|
|
|
|
|
|
function snapshotTime(value) {
|
|
|
if (value === null || value === undefined || value === '') return '时间未记录';
|
|
|
const numeric = Number(value);
|
|
|
const date = Number.isFinite(numeric)
|
|
|
? new Date(numeric < 1e12 ? numeric * 1000 : numeric)
|
|
|
: new Date(String(value));
|
|
|
if (!Number.isFinite(date.getTime())) return '时间未记录';
|
|
|
return date.toLocaleString('zh-CN', {
|
|
|
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
|
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function snapshotSize(value) {
|
|
|
const bytes = Number(value);
|
|
|
if (!Number.isFinite(bytes) || bytes <= 0) return '';
|
|
|
const gib = bytes / (1024 ** 3);
|
|
|
if (gib >= 1) return `${gib.toFixed(gib >= 10 ? 1 : 2)} GiB`;
|
|
|
return `${(bytes / (1024 ** 2)).toFixed(1)} MiB`;
|
|
|
}
|
|
|
|
|
|
function snapshotConsistency(value) {
|
|
|
const normalized = String(value || '').toLowerCase();
|
|
|
if (normalized === 'filesystem') return '文件系统一致';
|
|
|
if (normalized === 'crash') return '崩溃一致';
|
|
|
return '一致性未知';
|
|
|
}
|
|
|
|
|
|
function snapshotFriendlyError(error, fallback = '快照操作失败,请稍后重试。') {
|
|
|
const message = String(error?.message || fallback);
|
|
|
if (/qemu[ -]?guest[ -]?agent|\bqga\b|guest agent|访客代理/i.test(message)) {
|
|
|
return 'QEMU Guest Agent(QGA)不可用,无法安全冻结文件系统;本次没有创建可恢复快照。请确认实例内 qemu-guest-agent 已安装并运行后重试。';
|
|
|
}
|
|
|
if (/snapshot.*limit|limit.*snapshot|最多.*快照|快照.*上限/i.test(message)) {
|
|
|
return '每台实例最多保留 2 份在线快照,请先删除不再需要的快照。';
|
|
|
}
|
|
|
return message;
|
|
|
}
|
|
|
|
|
|
function snapshotTransportUncertain(error) {
|
|
|
const status = Number(error?.status);
|
|
|
return (Number.isFinite(status) && status >= 500)
|
|
|
|| /failed to fetch|network|load failed|timeout|timed out|abort/i.test(String(error?.message || ''));
|
|
|
}
|
|
|
|
|
|
function setSnapshotStatus(message = '', type = '') {
|
|
|
const target = byId('vm-snapshot-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-snapshot-status${type ? ` ${type}` : ''}`;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function snapshotElement(tag, className = '', text = '') {
|
|
|
const element = document.createElement(tag);
|
|
|
if (className) element.className = className;
|
|
|
if (text !== '') element.textContent = String(text);
|
|
|
return element;
|
|
|
}
|
|
|
|
|
|
function snapshotActionLabel(action) {
|
|
|
return { create: '创建快照', restore: '恢复快照', delete: '删除快照' }[action] || '快照操作';
|
|
|
}
|
|
|
|
|
|
function snapshotName(snapshot) {
|
|
|
return String(snapshot?.name || '在线快照');
|
|
|
}
|
|
|
|
|
|
function snapshotUsedSlots(payload, items) {
|
|
|
const reported = Number(payload?.used_slots ?? payload?.total);
|
|
|
if (Number.isFinite(reported) && reported >= 0) return Math.min(SNAPSHOT_LIMIT, Math.floor(reported));
|
|
|
return Math.min(SNAPSHOT_LIMIT, items.length);
|
|
|
}
|
|
|
|
|
|
function snapshotHasUncertain(items) {
|
|
|
return items.some(snapshot => SNAPSHOT_UNCERTAIN_STATES.has(snapshotState(snapshot)));
|
|
|
}
|
|
|
|
|
|
function snapshotPendingItem(items) {
|
|
|
return items.find(snapshot => SNAPSHOT_ACTIVE_STATES.has(snapshotState(snapshot)) && snapshot?.job_id);
|
|
|
}
|
|
|
|
|
|
function renderSnapshotRow(vmId, snapshot, controlsDisabled = false) {
|
|
|
const row = snapshotElement('article', 'vm-snapshot-row');
|
|
|
const main = snapshotElement('div', 'vm-snapshot-main');
|
|
|
const heading = snapshotElement('div', 'vm-snapshot-heading');
|
|
|
const title = snapshotElement('strong', 'vm-snapshot-title', snapshotName(snapshot));
|
|
|
const [stateLabel, stateClass] = snapshotStateInfo(snapshot);
|
|
|
const statePill = snapshotElement('span', `vm-snapshot-state ${stateClass}`, stateLabel);
|
|
|
heading.append(title, statePill);
|
|
|
const metadata = [
|
|
|
snapshotTime(snapshot?.created_at),
|
|
|
snapshotConsistency(snapshot?.consistency),
|
|
|
snapshotSize(snapshot?.size_bytes),
|
|
|
].filter(Boolean).join(' · ');
|
|
|
main.append(heading, snapshotElement('span', 'vm-snapshot-meta', metadata));
|
|
|
|
|
|
const actions = snapshotElement('div', 'vm-snapshot-actions');
|
|
|
const restore = snapshotElement('button', 'button button-outline small', '恢复');
|
|
|
restore.type = 'button';
|
|
|
const remove = snapshotElement('button', 'button button-outline small danger', '删除');
|
|
|
remove.type = 'button';
|
|
|
const key = snapshotKey(snapshot);
|
|
|
const ready = ['ready', 'available'].includes(snapshotState(snapshot));
|
|
|
const disabled = !key || !ready || controlsDisabled || snapshotBlockedUncertain;
|
|
|
restore.disabled = disabled;
|
|
|
remove.disabled = disabled;
|
|
|
if (!key) {
|
|
|
restore.title = '快照标识无效,请刷新后核查。';
|
|
|
remove.title = restore.title;
|
|
|
} else if (!ready) {
|
|
|
restore.title = '仅已就绪的快照可以恢复。';
|
|
|
remove.title = '快照任务完成后才能删除。';
|
|
|
}
|
|
|
restore.addEventListener('click', () => void restoreVmSnapshot(vmId, snapshot));
|
|
|
remove.addEventListener('click', () => void deleteVmSnapshot(vmId, snapshot));
|
|
|
actions.append(restore, remove);
|
|
|
row.append(main, actions);
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
function renderVmSnapshots(vmId, payload = snapshotPayload) {
|
|
|
const list = byId('vm-snapshot-list');
|
|
|
const empty = byId('vm-snapshot-empty');
|
|
|
const summary = byId('vm-snapshot-summary');
|
|
|
const create = byId('vm-snapshot-create');
|
|
|
const name = byId('vm-snapshot-name');
|
|
|
const consistency = byId('vm-snapshot-consistency');
|
|
|
if (!list || !empty || !summary || !create) return;
|
|
|
const items = snapshotItems(payload);
|
|
|
const used = snapshotUsedSlots(payload, items);
|
|
|
const activeJobPresent = Boolean(payload?.active_job);
|
|
|
const activeJobStatus = String(payload?.active_job?.status || '').toLowerCase();
|
|
|
const busy = Boolean(snapshotMutation)
|
|
|
|| (activeJobPresent && !SNAPSHOT_UNCERTAIN_STATES.has(activeJobStatus))
|
|
|
|| items.some(item => SNAPSHOT_ACTIVE_STATES.has(snapshotState(item)));
|
|
|
const operationsUnavailable = payload?.can_mutate === false
|
|
|
&& !busy && !snapshotBlockedUncertain;
|
|
|
const canCreate = payload?.can_create !== false && used < SNAPSHOT_LIMIT
|
|
|
&& !busy && !snapshotBlockedUncertain;
|
|
|
|
|
|
summary.textContent = `已使用 ${used} / ${SNAPSHOT_LIMIT} 份`;
|
|
|
list.replaceChildren(...items.map(item => renderSnapshotRow(
|
|
|
vmId, item, busy || operationsUnavailable
|
|
|
)));
|
|
|
empty.hidden = items.length !== 0;
|
|
|
create.disabled = !canCreate;
|
|
|
if (name) name.disabled = !canCreate;
|
|
|
if (consistency) consistency.disabled = !canCreate;
|
|
|
if (snapshotBlockedUncertain) create.textContent = '等待人工核查';
|
|
|
else if (snapshotMutation) create.textContent = `${snapshotActionLabel(snapshotMutation.action)}中…`;
|
|
|
else if (busy) create.textContent = '实例任务执行中';
|
|
|
else if (used >= SNAPSHOT_LIMIT) create.textContent = '已达到 2 份上限';
|
|
|
else if (operationsUnavailable) create.textContent = '当前不可操作';
|
|
|
else create.textContent = '创建在线快照';
|
|
|
|
|
|
if (snapshotBlockedUncertain) {
|
|
|
setSnapshotStatus('存在结果待核查的实例任务,需要管理员人工处理。确认真实结果前,创建、恢复和删除均已停用,请勿重复提交。', 'warning');
|
|
|
} else if (snapshotMutation) {
|
|
|
setSnapshotStatus(`${snapshotActionLabel(snapshotMutation.action)}任务正在后台执行,请勿重复提交。`);
|
|
|
} else if (busy) {
|
|
|
setSnapshotStatus(`实例还有${payload?.active_job?.kind_label || '其他任务'}正在执行,完成后才能操作快照。`, 'warning');
|
|
|
} else if (operationsUnavailable) {
|
|
|
setSnapshotStatus('当前实例状态或服务状态不允许快照操作,请刷新实例详情后重试。', 'warning');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadVmSnapshots(vmId, force = false) {
|
|
|
if (!byId('vm-settings-section-snapshots')) return;
|
|
|
if (!force && snapshotLoadedVmId === String(vmId) && snapshotPayload) return;
|
|
|
if (snapshotRequest) return snapshotRequest;
|
|
|
setSnapshotStatus('正在读取在线快照…');
|
|
|
snapshotRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/snapshots`);
|
|
|
if (String(selectedVm()?.api_id || '') !== String(vmId)) return;
|
|
|
snapshotLoadedVmId = String(vmId);
|
|
|
snapshotPayload = payload || {};
|
|
|
const items = snapshotItems(snapshotPayload);
|
|
|
const activeJobStatus = String(snapshotPayload?.active_job?.status || '').toLowerCase();
|
|
|
snapshotBlockedUncertain = snapshotHasUncertain(items)
|
|
|
|| SNAPSHOT_UNCERTAIN_STATES.has(activeJobStatus);
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
const pending = snapshotPendingItem(items);
|
|
|
if (!snapshotBlockedUncertain && !snapshotMutation && pending) {
|
|
|
const pendingState = snapshotState(pending);
|
|
|
const action = pendingState === 'restoring' ? 'restore' : pendingState === 'deleting' ? 'delete' : 'create';
|
|
|
snapshotMutation = { action, jobId: String(pending.job_id) };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
void pollSnapshotJob(vmId, pending.job_id, action);
|
|
|
} else if (!snapshotBlockedUncertain && !snapshotMutation) {
|
|
|
setSnapshotStatus();
|
|
|
}
|
|
|
} catch (error) {
|
|
|
snapshotLoadedVmId = null;
|
|
|
setSnapshotStatus(snapshotFriendlyError(error, '在线快照读取失败,请稍后重试。'), 'error');
|
|
|
} finally {
|
|
|
snapshotRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return snapshotRequest;
|
|
|
}
|
|
|
|
|
|
async function pollSnapshotJob(vmId, jobId, action) {
|
|
|
const generation = ++snapshotPollGeneration;
|
|
|
const label = snapshotActionLabel(action);
|
|
|
let attempt = 0;
|
|
|
while (generation === snapshotPollGeneration) {
|
|
|
if (document.visibilityState === 'hidden') {
|
|
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
|
continue;
|
|
|
}
|
|
|
attempt += 1;
|
|
|
try {
|
|
|
const job = await api(`/api/v1/jobs/${encodeURIComponent(jobId)}`);
|
|
|
if (generation !== snapshotPollGeneration) return;
|
|
|
const status = String(job?.status || '').toLowerCase();
|
|
|
if (['completed', 'succeeded', 'done'].includes(status)) {
|
|
|
snapshotMutation = null;
|
|
|
await loadVmSnapshots(vmId, true);
|
|
|
if (action === 'create' && byId('vm-snapshot-name')) byId('vm-snapshot-name').value = '';
|
|
|
setSnapshotStatus(`${label}已完成。`, 'success');
|
|
|
toast(`${label}已完成。`, 'success');
|
|
|
return;
|
|
|
}
|
|
|
if (SNAPSHOT_UNCERTAIN_STATES.has(status)) {
|
|
|
snapshotBlockedUncertain = true;
|
|
|
snapshotMutation = { action, jobId: String(jobId), uncertain: true };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
return;
|
|
|
}
|
|
|
if (['failed', 'cancelled', 'canceled'].includes(status)) {
|
|
|
snapshotMutation = null;
|
|
|
const message = snapshotFriendlyError(
|
|
|
{ message: job?.error || job?.message || `${label}失败,请核查后重试。` }
|
|
|
);
|
|
|
await loadVmSnapshots(vmId, true);
|
|
|
setSnapshotStatus(message, 'error');
|
|
|
return;
|
|
|
}
|
|
|
setSnapshotStatus(`${label}任务${job?.phase || '正在后台执行'},请勿重复提交。`);
|
|
|
} catch (error) {
|
|
|
if (generation !== snapshotPollGeneration) return;
|
|
|
setSnapshotStatus(`${label}仍在后台执行,但任务状态暂时无法读取;页面会自动重试:${snapshotFriendlyError(error)}`, 'warning');
|
|
|
}
|
|
|
const delay = attempt < 30 ? 2000 : attempt < 120 ? 5000 : 15000;
|
|
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function defaultSnapshotName() {
|
|
|
const now = new Date();
|
|
|
const part = value => String(value).padStart(2, '0');
|
|
|
return `snapshot-${now.getFullYear()}${part(now.getMonth() + 1)}${part(now.getDate())}-${part(now.getHours())}${part(now.getMinutes())}${part(now.getSeconds())}`;
|
|
|
}
|
|
|
|
|
|
async function startSnapshotMutation(vmId, action, path, body) {
|
|
|
if (snapshotMutation || snapshotBlockedUncertain) return;
|
|
|
snapshotMutation = { action };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
try {
|
|
|
const result = await api(path, { method: action === 'delete' ? 'DELETE' : 'POST', body });
|
|
|
const jobId = result?.job_id;
|
|
|
if (!jobId) {
|
|
|
snapshotBlockedUncertain = true;
|
|
|
snapshotMutation = { action, uncertain: true };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(`${snapshotActionLabel(action)}已提交但任务编号缺失,结果未知;请勿重复操作。`, 'warning');
|
|
|
return;
|
|
|
}
|
|
|
snapshotMutation = { action, jobId: String(jobId) };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
void pollSnapshotJob(vmId, jobId, action);
|
|
|
} catch (error) {
|
|
|
snapshotMutation = null;
|
|
|
const transportUncertain = snapshotTransportUncertain(error);
|
|
|
if (transportUncertain) snapshotBlockedUncertain = true;
|
|
|
const message = transportUncertain
|
|
|
? '网络连接中断,面板未能确认快照请求结果;请先刷新并核查状态,在结果明确前不要重复操作。'
|
|
|
: snapshotFriendlyError(error);
|
|
|
await loadVmSnapshots(vmId, true);
|
|
|
if (transportUncertain) snapshotBlockedUncertain = true;
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(message, snapshotBlockedUncertain ? 'warning' : 'error');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function restoreVmSnapshot(vmId, snapshot) {
|
|
|
const key = snapshotKey(snapshot);
|
|
|
if (!key || snapshotMutation || snapshotBlockedUncertain) return;
|
|
|
const name = snapshotName(snapshot);
|
|
|
if (!window.confirm(`确认恢复到“${name}”?系统盘会回到快照创建时;账单、服务周期和公网 IP 不会回滚。`)) return;
|
|
|
const confirmationName = String(selectedVm()?.name || '');
|
|
|
await startSnapshotMutation(
|
|
|
vmId, 'restore',
|
|
|
`/api/v1/vms/${encodeURIComponent(vmId)}/snapshots/${encodeURIComponent(key)}/restore`,
|
|
|
{ confirmation_name: confirmationName }
|
|
|
);
|
|
|
}
|
|
|
|
|
|
async function deleteVmSnapshot(vmId, snapshot) {
|
|
|
const key = snapshotKey(snapshot);
|
|
|
if (!key || snapshotMutation || snapshotBlockedUncertain) return;
|
|
|
const name = snapshotName(snapshot);
|
|
|
if (!window.confirm(`确认删除快照“${name}”?删除后无法使用它恢复系统盘。`)) return;
|
|
|
const confirmationName = String(selectedVm()?.name || '');
|
|
|
await startSnapshotMutation(
|
|
|
vmId, 'delete',
|
|
|
`/api/v1/vms/${encodeURIComponent(vmId)}/snapshots/${encodeURIComponent(key)}`,
|
|
|
{ confirmation_name: confirmationName }
|
|
|
);
|
|
|
}
|
|
|
|
|
|
function bindSnapshotControls(vmId) {
|
|
|
const form = byId('vm-snapshot-create-form');
|
|
|
if (!form) return;
|
|
|
form.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
if (snapshotMutation || snapshotBlockedUncertain) return;
|
|
|
const name = String(form.elements.name?.value || '').trim() || defaultSnapshotName();
|
|
|
const consistencyMode = String(form.elements.consistency_mode?.value || 'filesystem');
|
|
|
void startSnapshotMutation(
|
|
|
vmId, 'create', `/api/v1/vms/${encodeURIComponent(vmId)}/snapshots`,
|
|
|
{ name, consistency_mode: consistencyMode === 'crash' ? 'crash' : 'filesystem' }
|
|
|
);
|
|
|
});
|
|
|
window.addEventListener('pagehide', () => { snapshotPollGeneration += 1; });
|
|
|
}
|
|
|
|
|
|
function settingError(form, message = '') {
|
|
|
const target = form.querySelector('[data-instance-setting-error]');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function settingStatus(message = '', type = '') {
|
|
|
const target = byId('vm-settings-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status ${type}`.trim();
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
async function pollInstanceSettingJob(vmId, jobId, kind) {
|
|
|
const label = INSTANCE_SETTING_LABELS[kind] || '实例设置';
|
|
|
try {
|
|
|
for (let attempt = 0; attempt < 600; attempt += 1) {
|
|
|
if (document.visibilityState === 'hidden') {
|
|
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
|
}
|
|
|
const job = await api(`/api/v1/jobs/${encodeURIComponent(jobId)}`);
|
|
|
const status = String(job?.status || '').toLowerCase();
|
|
|
if (['completed', 'succeeded', 'done'].includes(status)) {
|
|
|
settingStatus(`${label}已完成,实例正在使用新的设置。`, 'success');
|
|
|
if (kind === 'password') {
|
|
|
setGeneratedPasswordNote('密码重置任务已完成。请将密码保存到安全位置;关闭此卡片不会删除面板中的加密凭据。');
|
|
|
}
|
|
|
toast(`${label}修改完成。`, 'success');
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
return;
|
|
|
}
|
|
|
if (['failed', 'cancelled', 'needs_attention', 'uncertain'].includes(status)) {
|
|
|
const message = job?.error || job?.message || `${label}任务失败,请核查实例状态。`;
|
|
|
settingStatus(`${label}任务未确认成功:${message}`, 'error');
|
|
|
if (kind === 'password') setGeneratedPasswordNote('任务未确认成功,此密码可能尚未生效,请勿直接使用。');
|
|
|
return;
|
|
|
}
|
|
|
settingStatus(`${label}任务${job?.phase || '正在后台执行'};运行中的实例会短暂重启。`);
|
|
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
|
}
|
|
|
settingStatus(`${label}任务仍在处理,可稍后刷新实例状态;请勿重复提交。`, 'warning');
|
|
|
} catch (error) {
|
|
|
settingStatus(`${label}任务状态读取失败:${error.message}`, 'warning');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function setGeneratedPasswordNote(message) {
|
|
|
const note = byId('vm-detail-password-card-note');
|
|
|
if (note) note.textContent = message;
|
|
|
}
|
|
|
|
|
|
function clearGeneratedPassword() {
|
|
|
const card = byId('vm-detail-password-result');
|
|
|
const value = byId('vm-detail-generated-password');
|
|
|
if (value) value.textContent = '';
|
|
|
if (card) card.hidden = true;
|
|
|
}
|
|
|
|
|
|
function showGeneratedPassword(password) {
|
|
|
const card = byId('vm-detail-password-result');
|
|
|
const value = byId('vm-detail-generated-password');
|
|
|
if (!card || !value || !password) return;
|
|
|
value.textContent = password;
|
|
|
setGeneratedPasswordNote('密码会在任务成功后生效;关闭此卡片不会取消后台任务。');
|
|
|
card.hidden = false;
|
|
|
card.focus({ preventScroll: true });
|
|
|
}
|
|
|
|
|
|
function bindInstanceSettings(vmId) {
|
|
|
bindInstanceSettingTabs(vmId);
|
|
|
bindFirewallControls(vmId);
|
|
|
bindSnapshotControls(vmId);
|
|
|
const forms = document.querySelectorAll('[data-instance-setting-form]');
|
|
|
if (!forms.length) return;
|
|
|
let submitting = false;
|
|
|
forms.forEach(form => form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (submitting) return;
|
|
|
const kind = form.dataset.instanceSettingForm || '';
|
|
|
const body = { confirm_restart: true };
|
|
|
if (kind === 'hostname') {
|
|
|
const value = form.elements.hostname?.value?.trim() || '';
|
|
|
if (!value) return settingError(form, '请输入新的主机名。');
|
|
|
body.hostname = value;
|
|
|
} else if (kind === 'password') {
|
|
|
body.reset_password = true;
|
|
|
} else if (kind === 'ssh_key') {
|
|
|
const value = form.elements.ssh_key_id?.value || '';
|
|
|
if (!value) return settingError(form, '请选择一个已保存的 SSH 公钥。');
|
|
|
body.ssh_key_id = value;
|
|
|
} else return;
|
|
|
const button = form.querySelector('button[type="submit"]');
|
|
|
const checkbox = form.elements.confirm_restart;
|
|
|
settingError(form);
|
|
|
submitting = true;
|
|
|
if (button) { button.disabled = true; button.dataset.originalText = button.textContent; button.textContent = '正在提交…'; }
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/settings`, { method: 'POST', body });
|
|
|
const label = INSTANCE_SETTING_LABELS[kind] || '实例设置';
|
|
|
if (kind === 'password' && typeof result?.initial_password === 'string') {
|
|
|
showGeneratedPassword(result.initial_password);
|
|
|
}
|
|
|
if (checkbox) checkbox.checked = false;
|
|
|
form.elements.hostname && (form.elements.hostname.value = kind === 'hostname' ? body.hostname : form.elements.hostname.value);
|
|
|
settingStatus(`${label}任务已提交;运行中的实例会短暂重启,任务成功后设置才会生效。`);
|
|
|
toast(`${label}修改任务已提交。`, 'success');
|
|
|
if (result?.job_id) void pollInstanceSettingJob(vmId, result.job_id, kind);
|
|
|
else settingStatus(`${label}已提交,但任务编号缺失,请刷新实例详情核查。`, 'warning');
|
|
|
} catch (error) {
|
|
|
settingError(form, error.message || '设置提交失败,请稍后重试。');
|
|
|
settingStatus(`${INSTANCE_SETTING_LABELS[kind] || '实例设置'}提交失败。`, 'error');
|
|
|
} finally {
|
|
|
submitting = false;
|
|
|
if (button) { button.disabled = false; button.textContent = button.dataset.originalText || '提交'; }
|
|
|
}
|
|
|
}));
|
|
|
byId('vm-detail-generated-password-copy')?.addEventListener('click', async () => {
|
|
|
const value = byId('vm-detail-generated-password')?.textContent || '';
|
|
|
if (!value) return;
|
|
|
try { await copyText(value); toast('新密码已复制,请妥善保存。', 'success'); }
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
});
|
|
|
byId('vm-detail-generated-password-close')?.addEventListener('click', clearGeneratedPassword);
|
|
|
byId('vm-detail-generated-password-saved')?.addEventListener('click', clearGeneratedPassword);
|
|
|
}
|
|
|
|
|
|
function bindConsole() {
|
|
|
byId('console-modal')?.querySelector('[data-close-modal]')?.addEventListener('click', closeConsole);
|
|
|
byId('console-cad')?.addEventListener('click', () => state.rfb?.sendCtrlAltDel());
|
|
|
byId('console-fullscreen')?.addEventListener('click', () => {
|
|
|
byId('console-stage')?.requestFullscreen?.().catch(error => toast(error.message, 'error'));
|
|
|
});
|
|
|
byId('console-password-form')?.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
state.rfb?.sendCredentials({ password: byId('console-password').value });
|
|
|
byId('console-password').value = '';
|
|
|
byId('console-password-form').hidden = true;
|
|
|
});
|
|
|
window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); });
|
|
|
}
|
|
|
|
|
|
export async function initialize() {
|
|
|
try {
|
|
|
const vm = hydrateVmDetailBootstrap(detailBootstrap());
|
|
|
bindPageCleanup();
|
|
|
const vmId = vm.api_id;
|
|
|
const requestedTab = new URLSearchParams(location.search).get('tab');
|
|
|
const initialTab = requestedTab === 'traffic' ? 'performance' : requestedTab;
|
|
|
state.detailTab = VM_DETAIL_TABS.includes(initialTab) ? initialTab : 'operations';
|
|
|
clearVmMetrics('打开“使用记录”页签后加载性能数据。');
|
|
|
clearVmTrafficDaily('打开“使用记录”页签后加载最近 30 天流量数据。');
|
|
|
renderVmDetail(vm);
|
|
|
setVmDetailTab(state.detailTab);
|
|
|
if (state.detailTab === 'operations-log') void loadOperationLogs(vmId);
|
|
|
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
|
|
|
|
|
|
byId('vm-detail-refresh-button')?.addEventListener('click', async () => {
|
|
|
await refreshMetadataAndStatus(vmId, true, true, true);
|
|
|
if (trafficDailyViewVisible()) await loadVmTrafficDaily(true);
|
|
|
if (state.detailTab === 'operations-log') await loadOperationLogs(vmId, true);
|
|
|
if (!byId('vm-settings-section-firewall')?.hidden) await loadVmFirewall(vmId, true);
|
|
|
if (!byId('vm-settings-section-snapshots')?.hidden) await loadVmSnapshots(vmId, true);
|
|
|
});
|
|
|
byId('vm-detail-ip-copy')?.addEventListener('click', async () => {
|
|
|
try { await copyText(vmIp(selectedVm())); toast('公网 IP 已复制。'); }
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
});
|
|
|
byId('vm-detail-password-reveal')?.addEventListener('click', () => credential());
|
|
|
byId('vm-detail-password-copy')?.addEventListener('click', () => credential(true));
|
|
|
byId('vm-metrics-range')?.addEventListener('change', () => {
|
|
|
state.metricsRange = byId('vm-metrics-range').value;
|
|
|
state.metricsRequest?.controller.abort();
|
|
|
state.metricsRequest = null;
|
|
|
void loadVmMetrics();
|
|
|
});
|
|
|
byId('vm-operation-log-refresh')?.addEventListener('click', () => void loadOperationLogs(vmId, true, operationLogsPage));
|
|
|
byId('vm-operation-log-prev')?.addEventListener('click', () => {
|
|
|
if (operationLogsPage > 1) void loadOperationLogs(vmId, true, operationLogsPage - 1);
|
|
|
});
|
|
|
byId('vm-operation-log-next')?.addEventListener('click', () => {
|
|
|
if (operationLogsPage < operationLogsPageCount) void loadOperationLogs(vmId, true, operationLogsPage + 1);
|
|
|
});
|
|
|
bindDetailTabs(vmId);
|
|
|
bindDisplayNameEditor(vmId);
|
|
|
bindInstanceSettings(vmId);
|
|
|
bindConsole();
|
|
|
window.addEventListener('resize', () => {
|
|
|
clearTimeout(state.metricsResizeTimer);
|
|
|
clearTimeout(state.trafficDailyResizeTimer);
|
|
|
state.metricsResizeTimer = setTimeout(() => {
|
|
|
if (state.metricsPayload) renderVmMetrics(state.metricsPayload);
|
|
|
}, 150);
|
|
|
state.trafficDailyResizeTimer = setTimeout(() => {
|
|
|
if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId) {
|
|
|
drawVmTrafficDaily(state.trafficDailyPayload);
|
|
|
}
|
|
|
}, 150);
|
|
|
});
|
|
|
let timer = null;
|
|
|
let stopped = false;
|
|
|
const poll = async () => {
|
|
|
timer = null;
|
|
|
if (stopped || document.hidden) return;
|
|
|
await loadVmStatus(vmId);
|
|
|
if (!stopped && !document.hidden) timer = window.setTimeout(poll, 20000);
|
|
|
};
|
|
|
const startPolling = () => {
|
|
|
stopped = false;
|
|
|
if (timer !== null) window.clearTimeout(timer);
|
|
|
timer = window.setTimeout(poll, 20000);
|
|
|
};
|
|
|
const stopPolling = () => {
|
|
|
stopped = true;
|
|
|
if (timer !== null) window.clearTimeout(timer);
|
|
|
timer = null;
|
|
|
};
|
|
|
startPolling();
|
|
|
void refreshMetadataAndStatus(vmId, false, false, true);
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
stopPolling();
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (!event.persisted) return;
|
|
|
void loadVmStatus(vmId, { live: true, force: true });
|
|
|
setVmDetailTab(state.detailTab);
|
|
|
if (!byId('vm-settings-section-firewall')?.hidden) {
|
|
|
firewallPolling = false;
|
|
|
void loadVmFirewall(vmId, true);
|
|
|
}
|
|
|
if (!byId('vm-settings-section-snapshots')?.hidden) {
|
|
|
snapshotMutation = null;
|
|
|
void loadVmSnapshots(vmId, true);
|
|
|
}
|
|
|
startPolling();
|
|
|
});
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
|
if (document.hidden) { stopPolling(); clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); }
|
|
|
else { void loadVmStatus(vmId, { live: true, force: true }); setVmDetailTab(state.detailTab); startPolling(); }
|
|
|
});
|
|
|
} catch (error) { showError('cloud-page-error', error.message); }
|
|
|
}
|